<template>
  <view class="container" :class="[`${themeInfo.theme}-theme`, `${themeInfo.language}`]">

    <view class="selectSite card" @click="goSite">
      <view class="left">
        <image src="/static/home/address.svg" mode="heightFix" class="icon"></image>
        <text class="address">{{ unitTypeData[0]?.city }}·{{ unitTypeData[0]?.district }}</text>
      </view>
      <view class="right">
        <text class="more">更多分店</text><image src="/static/home/jiantou.svg" style="width: 24rpx;height: 24rpx;" class="icon"></image>
      </view>
    </view>
    <template v-if="state.siteId">
      <view class="siteInfo card">
        <!-- 顶部：左中右布局 -->
        <view class="top">
          <view class="left">
            <image src="/static/home/siteicon.svg" class="icon"></image>
            <view class="title-wrap">
              <text class="title font36 fontb">{{ unitTypeData[0]?.sitdName }}</text>
              <!-- <view class="tag font16 fontb">距离最近</view> -->
            </view>
          </view>
          <view class="right" v-if="siteDistance">
            <text class="distance font28 fontb">{{ siteDistance }}KM</text>
          </view>
        </view>
        <!-- 底部：地址 -->
        <view class="bottom">
          <image src="/static/home/siteicon2.svg" class="icon"></image>
          <text class="address font26 fontb textGary">{{ unitTypeData[0]?.sitdAddress }}</text>
        </view>
      </view>
      <view class="unitType card">
        <view class="title font32 fontb mgb20">
          仓型选择
        </view>
        <view class="swiper">
          <view class="info">
            <view class="left arrow">
              <view class="arrowIcon" @click="prev" v-if="unitTypeData.length > 1">
                <image src="/static/home/jiantouleft.svg" style="width: 64rpx;height: 64rpx;" class="icon"></image>
              </view>
            </view>
            <view class="swiper-container">
              <swiper class="warehouse-detail" circular style="height: 300rpx;" :indicator-dots="false"
                :autoplay="false" @change="changeMove" :current="state.active">
                <swiper-item v-for="(item, index) in unitTypeData" :key="index">
                  <view class="warehouse-detail-items">
                    <image class="warehouse-detail-right" @click="showImage(baseImageUrl + item.imgUrl)"
                      :src="baseImageUrl + item.imgUrl" mode="widthFix"></image>
                  </view>
                </swiper-item>
              </swiper>
            </view>
            <view class="right arrow">
              <view class="arrowIcon" @click="next" v-if="unitTypeData.length > 1">
                 <image src="/static/home/jiantouright.svg" style="width: 64rpx;height: 64rpx;" class="icon"></image>
              </view>
            </view>
          </view>
        </view>
        <view class="bottom" v-if="unitTypeData.length">
          <view class="font32 fontb name">
            {{ unitTypeData[state.active].name }}
          </view>
          <view class="font26 fontb textGary" style="padding: 0 28rpx;">
            {{ unitTypeData[state.active].volumeRange }}
          </view>
          <view class="font26 fontb textGary">（{{ unitTypeData[state.active].description }}）</view>
        </view>
      </view>
      <view class="orderInfo sflist card" v-if="unitTypeData.length">
        <ul>
          <li @click="showUnitPopup">
            <view class="left"><text class="font32 fontb">体积</text> 
              <!-- <text style="font-size: 26rpx;margin-left: 10rpx;"
                v-if="state.selectUnitRow?.name">（仓号：{{ state.selectUnitRow?.name }}）</text> -->
              </view>
            <view class="right font26 fontb textGary"><text
                :style="{ color: state.selectUnitRow?.name ? '#A8AAAC' : '#FB322E' }">{{
                  state.selectUnitRow?.name ? `${state.selectUnitRow?.volume}m³ ` : "请选择" }} </text>
              <image src="/static/home/jiantou.svg"  style="width: 44rpx;height: 24rpx;" class="icon"></image>
            </view>
          </li>
          <li @click="showMonthPopup">
            <view class="left"><text class="font32 fontb">租期</text></view>
            <view class="right font26 fontb textGary"><text>{{ state.month }}个月</text>
              <image src="/static/home/jiantou.svg" style="width: 44rpx;height: 24rpx;" class="icon"></image>
            </view>
          </li>
          <li>
            <view class="left"><text class="font32 fontb">租金</text></view>
            <view class="right font26 fontb textGary"><text>{{ state.priceData?.price ? `￥ ${state.priceData?.price}` :
              '--'
                }} </text>
            </view>
          </li>
          <li @click="goVaild">
            <view class="left"><text class="font32 fontb">实名验证</text></view>
            <view class="right font26 fontb textGary"><text
                :style="{ color: state.hasVerify ? '#1E9B00' : '#FB322E' }">{{
                  state.hasVerify ? '已验证' : '未验证' }}</text>
                <image src="/static/home/jiantou.svg" v-if="!state.hasVerify" style="width: 44rpx;height: 24rpx;" class="icon"></image>
            </view>
          </li>
        </ul>
      </view>
      <view class="toOrder card font28" v-if="unitTypeData.length">
        <view class="left " >
          <text class="price fontb" :class="{ overMaxFont: String(state.priceData?.expense).length>6 }"> {{ state.priceData.expense ? `￥ ${state.priceData.expense}` : '￥--'
            }}</text>
            <view class="detail" v-if="state.priceData.expense" @click="showPayPopup"><text style="margin-right: 10rpx;font-weight: 600;" :class="{ overMaxFont:String(state.priceData?.expense).length>6  }" v-if="state.priceData?.expense">￥{{ state.priceData.leaseOriginalPrice }}</text><text>明细</text>
            <image src="/static/home/jiantouup.svg" style="height: 12rpx;margin-left: 10rpx;" mode="heightFix" class="icon"></image>
          </view>
        </view>
        <view class="right">
          
          <uv-button :customStyle="{
            height: '86rpx',
            color: '#fff',
          }" :textStyle="{
            fontSize: '32rpx',
            fontWeight: 'bold',
          }" shape="circle" color="#FB322E" :disabled="!state.lockerId || !state.month" @click="goOrder"
            class="goOrder">下单</uv-button>
        </view>
      </view>
      <view class="empt font32 fontb" v-if="unitTypeData.length === 0" style="text-align: center;margin-top: 20rpx;">
        暂无可用仓型，请选择其他门店～
      </view>
      <view class="agreed" v-if="unitTypeData.length" @click="changeCheck">
        <view class="check-wrap" :class="{ checked: state.checked }">
          <uv-radio-group v-model="state.checked"  activeColor="#fb322e" size="40rpx" inactiveColor="#D8D8D8">
            <uv-radio activeColor="#fb322e" :key="0" :name="true">
            </uv-radio></uv-radio-group>
        </view>
        <view style="display: flex;align-items: center;">
          <text class="stress" @click="openAgreement">阅读并同意《电子租赁条款》</text>
        </view>
      </view>
    </template>
    <template v-else>
      <!-- <view style="margin-top: 40vh;" @click="goSite">
        <uv-button :customStyle="{
          height: '86rpx',
          width: '560rpx',
          color: '#2979ff',
          fontSize: '32rpx',
        }" shape="circle">选择门店</uv-button>
      </view> -->
       <view class="empt font32 fontb" @click="goSite" style="text-align: center;margin-top: 20rpx;">
        请选择其他门店～
      </view>
    </template>
    <div class="footer">
      <myCustomtTabBar direction="horizontal" :show-icon="true" :selected="0" @onTabItemTap="onTabItemTap">
      </myCustomtTabBar>
    </div>
    <uv-popup ref="unitPopupRef" mode="bottom" zIndex="999" round="24px">
      <view class="unitPopupBox">
        <view class="title font36 fontb">
          体积选择
        </view>
        <view class="info">
          <uv-radio-group v-model="state.radiovalue" activeColor="#fb322e" size="40rpx" inactiveColor="#D8D8D8">
            <view class="list" v-for="(item, index) in LockerList">
              <view class="left">
                <view class="volume mgb10 font28 fontb">
                  体积: {{ item.volume }}m³
                </view>
                <view class="unit textGary font28 fontb mgb10">
                  仓号: {{ item.name }}
                </view>
                <view class="site textGary font28 fontb mgb10">
                  尺寸: 长{{ item.length }}m*宽{{ item.width }}m*高{{ item.height }}m
                </view>
              </view>
              <view class="right">
                <view class="radioBox">
                  <uv-radio :key="item.lockerId" :name="item.lockerId" size="40rpx">
                  </uv-radio>
                </view>
                <view class="price mgb10">
                  <text class="font28 textGary fontb" style="text-decoration: line-through #000;padding-right: 20rpx;">￥ {{
                    item.price
                  }}/月</text>
                  <text class="font28 fontb" style="color: #D2021B;">￥ {{ item.currentPrice }}/月</text>
                </view>
              </view>
            </view>
          </uv-radio-group>
        </view>
        <view class="btn" style="display: flex;justify-content: center;">
          <uv-button @click="confirmUnit" :customStyle="{
            height: '86rpx',
            color: '#fff',
            fontSize: '32rpx',
            width: '630rpx',
          }" color="#FB322E" shape="circle">
            确定
          </uv-button>
        </view>
      </view>
    </uv-popup>
    <uv-popup ref="monthPopupRef" mode="bottom" zIndex="999" round="24px">
      <view class="unitPopupBox">
        <view class="title font36 fontb">
          租期选择
        </view>
        <view class="info">
          <uv-radio-group v-model="state.radioMonthvalue" activeColor="#fb322e" size="40rpx" inactiveColor="#D8D8D8">
            <view class="list" v-for="item in state.lockData?.discountList">
              <view class="left">
                <view class="volume mgb10 font28 fontb">
                  租期: {{ item.month }}个月
                </view>
                <view class="unit mgb10 textRed font28 fontb">
                  优惠: 享受{{ (item.discount * 100) / 10 }}折优惠
                </view>
              </view>
              <view class="right">
                <view class="radioBox">
                  <uv-radio :key="item.month" :name="item.month">
                  </uv-radio>
                </view>
              </view>
            </view>
            <view class="list">
              <view class="left">
                <view class="volume mgb10 font28 fontb zuqi" style="display: flex;">
                  自定义租期: &nbsp;
                  <!-- <uv-number-box  v-model="state.selfMonth" buttonSize="26" color="#000" bgColor="#EBEBEB"
                   :min="1" :max="24" :step="1" iconStyle="color: #fff"></uv-number-box> -->
                  <uv-number-box v-model="state.selfMonth"  :min="1" :max="24" :step="1">
                <template v-slot:minus>
                  <view class="minus">
                    <uv-icon name="minus" size="20rpx">
                    </uv-icon>
                  </view>
                </template>
                <template v-slot:input>
                  <text style="width: 50px;text-align: center;color: #000;" class="input">
                    {{state.selfMonth}}
                  </text>
                </template>
                <template v-slot:plus>
                  <view class="plus">
                    <uv-icon name="plus" color="#FFFFFF" size="20rpx">
                    </uv-icon>
                  </view>
                </template>
              </uv-number-box>
                   &nbsp;个月
                </view>
                <view class="unit mgb10 textRed font28 fontb" v-if="selfDiscount !== 1">
                  优惠: 享受{{ selfDiscount * 100 / 10 }}折优惠
                </view>
                <view class="unit mgb10 textRed font28 fontb" v-else>
                  优惠: --
                </view>
                <!-- <view class="site textGary mgb10">
                  尺寸: 120cm*100cm*100cm
                </view> -->
              </view>
              <view class="right">
                <view class="radioBox">
                  <uv-radio :key="0" :name="-1">
                  </uv-radio>
                </view>
              </view>
            </view>
          </uv-radio-group>
        </view>
        <view class="btn" @click="confirmMonth" style="display: flex;justify-content: center;" >
          <uv-button :customStyle="{
            height: '86rpx',
            color: '#fff',
            fontSize: '32rpx',
            width: '630rpx',
          }" color="#FB322E" shape="circle">
            确定
          </uv-button>
        </view>
      </view>
    </uv-popup>
    <uv-popup ref="payPopupRef" mode="bottom" zIndex="999" round="24px">
      <view class="unitPopupBox payPopupBox">
        <view class="title font36 fontb">
          租赁费用详情
        </view>
        <view class="garyBox font28 card20">
          （体积月费 x 租期 + 押金）- 优惠
        </view>
        <view class="title2 font32 fontb">
          <text>租赁体积</text> <text>{{ `${state.selectUnitRow?.volume}m³` }}</text>
        </view>
        <view class="garyBox font28 card20">
          <view class="mgb10">
            仓号: {{ state.selectUnitRow?.name }}
          </view>
          <view class="">
            尺寸: {{ state.selectUnitRow?.['length'] }}m*{{ state.selectUnitRow?.width }}m*{{ state.selectUnitRow?.height
            }}m
          </view>
        </view>
        <view class="title2 font32 fontb">
          <text>租金总价</text> <text>￥ {{ state.priceData?.lockerExpense }}</text>
        </view>
        <view class="title2 textGary2 fontb font28">
          <text>租金月费</text> <text> ￥ {{ state.priceData?.lockerPrice }}</text>
        </view>
        <view class="title2 textGary2 fontb font28">
          <text>租期时长</text> <text> {{ state.month }}个月</text>
        </view>
        <view class="title2 font32 fontb">
          <text>押金费用</text> <text>￥ {{ state.priceData.securityDeposit }}</text>
        </view>
        <view class="title2 textGary2 fontb font28">
          <text>租赁押金在租期结束后给予归还</text>
        </view>
        <view class="title2 font32 fontb">
          <text>优惠信息</text> <text style="color: #FB322E;">-￥ {{ state.priceData.favorable }}</text>
        </view>
        <view class="title2 textGary2 fontb font28">
          <text>租期优惠（{{state.month}}个月长租）</text><text style="color: #FB322E;">-￥ {{ state.priceData.leaseDiscount }}</text>
        </view>
        <view class="toOrder card font28">
          <view class="left font28">
            <text class="price fontb" :class="{ overMaxFont: String(state.priceData?.expense).length>6 }"> {{ state.priceData.expense ? `￥ ${state.priceData.expense}` : '--'
              }}</text>
            <view class="detail" v-if="state.priceData.expense" @click="hidePayPopup"><text style="margin-right: 10rpx;font-weight: 600;" :class="{ overMaxFont: String(state.priceData?.expense).length>6  }" v-if="state.priceData?.expense">￥{{ state.priceData.leaseOriginalPrice }}</text><text class="font28">明细</text>
              <image src="/static/home/jiantouup.svg" style="height: 12rpx;margin-left: 10rpx;" mode="heightFix" class="icon"></image>
            </view>
          </view>
          <view class="right">
            <uv-button :customStyle="{
              height: '86rpx',
              color: '#fff',
            }" :textStyle="{
              fontSize: '32rpx',
              fontWeight: 'bold',
            }" color="#FB322E" :disabled="!state.lockerId && !state.month" @click="goOrder" shape="circle"
              class="goOrder">下单</uv-button>
          </view>
        </view>
        <view class="agreed" @click="changeCheck">
          <view class="check-wrap" :class="{ checked: state.checked }">
            <uv-radio-group v-model="state.checked" activeColor="#fb322e" size="40rpx" inactiveColor="#D8D8D8">
              <uv-radio activeColor="#fb322e" :key="0" :name="true">
              </uv-radio></uv-radio-group>
          </view>
          <view  style="display: flex;align-items: center;">
            <text class="stress" @click="openAgreement">阅读并同意《电子租赁条款》</text>
          </view>
        </view>
      </view>
    </uv-popup>
    <uv-popup ref="agreementRef" mode="bottom" :closeOnClickOverlay="false" width="750rpx" zIndex="999" round="24px">
      <view class="agreement-wrap">
        <view class="agreement-top">
          <view class="name">{{ $t("detail.agreement") }}</view>
          <uv-icon name="close" size="20" @click="closeAgreement"></uv-icon>
        </view>
        <scroll-view class="agreement-content" :scroll-top="state.scrollTop" scroll-y="true"
          @scrolltolower="handleScrollBottom" @scroll="handleScroll">
          <!-- themeInfo.language === 'en_lang' ? state.enAgreementContent : state.agreementContent -->
          <uv-parse :content="state.agreementContent"></uv-parse>
          <view style="margin-top: 200rpx;">
            <uv-loading-icon v-if="!state.agreementContent" :vertical="true"
              :text="$t('common.loading')"></uv-loading-icon>
          </view>
        </scroll-view>
        <view class="roll-btn" @click="handleRoll">
          <uv-icon name="arrow-down" size="24" color="#FFFFFF"></uv-icon>
        </view>
        <view class="bottom-read agree" v-if="state.isRead" @click="handleAgree">{{ $t("detail.agreeTerm") }}</view>
        <view class="bottom-read" v-else>{{ $t("detail.scrollRead") }}</view>
      </view>
    </uv-popup>
  </view>
</template>

<script setup>
import { ref, computed, nextTick, watch } from "vue";
import { onTabItemTap, getDistance, makePhoneCall, mergeFiveGoatStores, parseUrlParams } from "/utils/common.js";
import myCustomtTabBar from "@/components/myCustomtTabBar.vue";
import wxNavbar from "@/components/wxNavbar.vue";
import siteDetail from '@/components/siteDetail.vue';
import { onLoad, onShow, onShareAppMessage, onUnload } from "@dcloudio/uni-app";
import { baseImageUrl, projectInfo, isKingKong, setOrderDays } from "@/config/index.js";
import { useLoginApi } from "/Apis/home.js";
import myPopup from "@/components/myPopup.vue";
import { navigateTo } from '@/utils/navigateTo';
// 主题色配置
import { useMainStore } from "@/store/index.js";
import { navbarHeightAndStatusBarHeight, shareParam } from "@/utils/common.js";
import { couponApi } from "@/Apis/coupon.js";
import { useLocation } from "@/hooks/useLocation";
import { useLoginApi as useLoginApi2 } from "@/Apis/login";
import { useSiteApi } from "@/Apis/site.js";
import { authInfoApi } from "@/Apis/validInfo.js";
import { ClientSite } from "@/Apis/book.js";
import { useLockApi } from '@/Apis/lock.js';
import { useOrderApi } from "@/Apis/order.js";
import { useI18n } from "vue-i18n";
import dayjs from 'dayjs';
const getOrderApi = useOrderApi();
const getAuthApi = authInfoApi();
const getCouponApi = couponApi();
const { themeInfo, storeState, getUserInfo } = useMainStore();
// 国际化配置
const { t, locale } = useI18n();
const getApi = useLoginApi();
const { getLocation, locationState } = useLocation();
const getLockApi = useLockApi()
const getSiteApi = useSiteApi();
const getApi2 = useLoginApi2();
const getClientSiteApi = ClientSite();

const unitPopupRef = ref(null);
const monthPopupRef = ref(null);
const payPopupRef = ref(null);
// 导航栏高度
const navHeight = ref(0);
const language = ref("");
const agreementRef = ref();
const today = dayjs()
  .set("hour", 0)
  .set("minute", 0)
  .set("second", 0)
  .set("millisecond", 0);
// 生成当天一个月后的日期
let oneMonthLater = today.add(setOrderDays, "day");
const state = ref({
  active: 0,
  id: "",
  radiovalue: 0,
  radioMonthvalue: 24,
  checkAgreementUrlTime: 0,
  agreementContent: "无",
  enAgreementContent: "无",
  scrollTop: 0,
  oldScrollTop: 0,
  isRead: false,
  checked: false,
  siteId: "",
  unitTypeId: "",
  lockerId: "",
  selectUnitRow: {},
  month: 24,
  selfMonth: 1,
  lockData: {
    discountList: []
  },
  startDate: today.format("YYYY/MM/DD"),
  minDate: today.format("YYYY/MM/DD"),
  maxDate: oneMonthLater.format("YYYY/MM/DD"), // 日期选择器最大日期
  zhuangxiuzhong: false,
  priceData: {},
  hasVerify: false,
});

const goOrder = async () => {
  if (!state.value.lockerId) {
    return uni.showToast({
      title: '请选择体积',
      icon: 'none',
      duration: 3000
    })
  }
  if (!state.value.month) {
    return uni.showToast({
      title: '租期',
      icon: 'none',
      duration: 3000
    }
    )
  } 
    uni.showLoading({mask: true})
    await getVerifyStatus
    uni.hideLoading();
  
  if (!state.value.hasVerify) {
    return uni.showToast({
      title: '请先验证实名信息!',
      icon: 'none',
      duration: 3000
    })
  }
  if (!state.value.checked) {
    openAgreement();
    return uni.showToast({
      title: '请勾选协议!',
      icon: 'none',
      duration: 3000
    })
  }
  let source = window.sf.isSfApp() ? 2 : 1;
  let startTime = dayjs(state.value.startDate).format("YYYY-MM-DDTHH:mm:ssZ");
  uni.showLoading({
    title: '支付中',
    mask: true
  })
  getOrderApi
    .AddOrder2({
      lockerId: state.value.lockerId,
      startTime,
      month: state.value.month,
      source
    })
    .then((res) => {
      uni.hideLoading();
      if (res.code === 200) {
        let path = window.location.pathname;
          if (!path.endsWith('/')) {
            path = path + '/';
          }
          const returnUrl = `${window.location.origin}${path}#/pages/unlock/index`;
          const failUrl = `${window.location.origin}${path}#/pages/index/index`;
        if (window.sf.isSfApp()) {
          window.sf.goPay({
            partnerId: res.data.partnerId, //商户id
            prepayId: res.data.package, // 预支付id
            nonceStr: res.data.nonceStr, //随机字符串
            timeStamp: res.data.timeStamp, //时间戳
            sign: res.data.paySign, //签名
            package: `prepay_id=${res.data.package}`,
            payChannel: 'payByWeChat' // app微信支付
          }).then(res => {
            const { channelType, status, message, channelResult } = res && res.result || {}
            if (status === 0) {
              uni.showToast({
                title: '支付成功',
                icon: 'none',
                duration: 3000
              })
              reset();
              goUnlock();
            } else {
              uni.showToast({
                title: '支付失败',
                icon: 'none',
                duration: 3000
              })
            }
          }).catch(err => console.log(err))
        } else {
          window.sf.goPay({
            timeStamp: res.data.timeStamp, // 从服务器获取的时间戳
            nonceStr: res.data.nonceStr, // 从服务器获取的随机字符串
            package: `prepay_id=${res.data.package}`, // 从服务器获取的预支付交易会话标识
            signType: res.data.signType, // 签名方式
            paySign: res.data.paySign, // 从服务器获取的签名
            successUrl: returnUrl,
            failUrl: failUrl
          }).then(res => { }).catch(err => console.log(err))
        }
      } else {
        if(res.code === 206){
          uni.showModal({
            title: t('common.title'),
            content: "仓位已出租，请重新选择",
            showCancel: false,
            success: function () {
               reset();
            },
          })
        }
        if (res.code === 1001) {
          uni.showModal({
            title: t('common.title'),
            content: t('common.unpaidOrderTips'),
            showCancel: false,
            success: function () {
              uni.switchTab({
                url: '/pages/unlock/index',
              })
            },
          })
          return
        }
      }
    });
}
const reset = () => {
  state.value.lockerId = null;
  state.value.priceData = {};
  state.value.selectUnitRow = {};
  state.value.lockData = {
    discountList: []
  }
  state.priceData = {};
}



const selfDiscount = computed(() =>
  state.value.lockData.discountList
    .sort((a, b) => b.month - a.month)
    .find(item => state.value.selfMonth >= item.month)?.discount ?? 1
)


const siteDistance = computed(() => {
  if (storeState.location.latitude && storeState.location.longitude && unitTypeData.value[0]?.latitude && unitTypeData.value[0]?.longitude) {
    return getDistance(storeState.location.latitude,
      storeState.location.longitude, unitTypeData.value[0]?.latitude, unitTypeData.value[0]?.longitude).distance;
  } else {
    return 0
  }

})

const changeCheck = () => {
  if (state.value.checkAgreementUrlTime == 0) {
    uni.showToast({
      title: t("common.checkAgreementUrl"),
      icon: "none",
      duration: 2000,
    })
    openAgreement();
    return
  }
  state.value.checked = !state.value.checked;
};

const showPayPopup = () => {
   if (!state.value.lockerId) {
    return uni.showToast({
      title: '请选择体积',
      icon: 'none',
      duration: 3000
    })
  }
  if (!state.value.month) {
    return uni.showToast({
      title: '租期',
      icon: 'none',
      duration: 3000
    }
    )
  } 
  payPopupRef.value.open();
};
const hidePayPopup = () => {
  payPopupRef.value.close();
}

const showMonthPopup = () => {
  if (state.value.lockerId) {
    getLockerById();
    monthPopupRef.value.open();
  } else {
    uni.showToast({
      title: "请选择体积仓位",
      icon: "none",
      duration: 2000,
    })
  }
};
const hideMonthPopup = () => {
  monthPopupRef.value.close();
};
const showUnitPopup = () => {
  unitPopupRef.value.open();
  getLockerBySiteId();

};
const hideUnitPopup = () => {
  unitPopupRef.value.close();
  state.value.radiovalue = null;
};

// 合同下拉
const handleRoll = () => {
  state.value.oldScrollTop += 4000;
  state.value.scrollTop = state.value.oldScrollTop;
}

// 滑动到底部了
const handleScrollBottom = () => {
  state.value.isRead = true;
}

const handleScroll = (e) => {
  state.value.oldScrollTop = e.detail.scrollTop;
}

const handleAgree = () => {
  state.value.checked = true;
  closeAgreement();
}

const openAgreement = () => {
  if (!state.value.lockerId) {
    uni.showToast({
      title: "请选择体积仓位",
      icon: "none",
      duration: 2000,
    })
    return
  }

  GetLockerAgreementHTMLById()
  state.value.scrollTop = state.value.oldScrollTop;
  agreementRef?.value.open();
};

const closeAgreement = () => {
  agreementRef?.value.close();
};

const confirmUnit = () => {
  if (!state.value.radiovalue) {
    return uni.showToast({
      title: "请选择体积仓位",
      icon: "none",
      duration: 2000,
    })
  }
  state.value.lockerId = state.value.radiovalue;
  state.value.selectUnitRow = LockerList.value.find(item => item.lockerId == state.value.lockerId);
  getLockerExpense();
  hideUnitPopup();
}

const confirmMonth = () => {
  if (state.value.radioMonthvalue === -1) {
    state.value.month = state.value.selfMonth;
  } else {
    state.value.month = state.value.radioMonthvalue;
  }
  getLockerExpense();
  hideMonthPopup();
}


// 切换到上一张
const prev = () => {
  if (state.value.active > 0) {
    state.value.active -= 1;
  } else {
    state.value.active = unitTypeData.value.length - 1; // 如果是第一张，跳到最后一张
  }
}
// 切换到下一张
const next = () => {
  if (state.value.active < unitTypeData.value.length - 1) {
    state.value.active += 1;
  } else {
    state.value.active = 0; // 如果是最后一张，跳到第一张
  }
}

onShareAppMessage((res) => {
  if (res.from === "button") {
    // 来自页面内分享按钮
    console.log(res.target);
  }
  return shareParam;
});

const goSite = () => {
  uni.navigateTo({
    url: "/pages/site/index",
  });
};
const goUnlock = () => {
  uni.navigateTo({
    url: "/pages/unlock/index",
  });
};
const LockerList = ref([]);
// 获取仓位
const getLockerBySiteId = () => {
  LockerList.value = [];
  if (state.value.siteId && state.value.unitTypeId) {
    uni.showLoading({
      mask: true
    })
    getSiteApi
      .GetLockerBySiteId({ siteId: state.value.siteId, unitTypeId: state.value.unitTypeId })
      .then((res) => {
        if (res.code == 200) {
          LockerList.value = res.data;
        }
      }).finally(() => {
        uni.hideLoading()
      })
      ;
  }
};

const getVerifyStatus = async () => {
  if (uni.getStorageSync('token')) {
    // uni.showLoading();
    await getAuthApi.GetIsCertification().then(res => {
      // uni.hideLoading();
      if (res.code == 200) state.value.hasVerify = res.data?.isPass;
    });
  }
}
// 获取门店信息
const getSiteDetail = () => {
  let list = []
  uni.showLoading();
  let city = "";
  let district = "";
  list = []
  getClientSiteApi.getSiteDetailsAll({
    city,
    district,
  }).then(res => {
    if (res.code === 200) {
      list = mergeFiveGoatStores(res.data);
      if (locationState?.latitude && locationState?.longitude) {
        const { latitude, longitude } = locationState;
        list.forEach(item => {
          const { distance, number } = getDistance(latitude, longitude, item.latitude, item.longitude);
          item.distance = distance;
          item.distanceNumber = number;
        });
        list.sort((a, b) => a.distanceNumber - b.distanceNumber);
        if (list[0]?.id) {
          state.value.siteId = list[0]?.id
          reset();
          getUnitTypeBySiteId();
        }
      } else {
        state.value.siteId = list[0]?.id
        reset();
        getUnitTypeBySiteId();
      }

    }
  }).catch(err => {

  }).finally(() => {
    setTimeout(() => {
      uni.hideLoading();
    }, 300);
  })
    ;
}
onLoad(async (params) => {
  if (params.q) {
    let urlParams = decodeURIComponent(params.q);
  } else {
  }
  if (params.Pre_ID) {
    uni.setStorageSync('Pre_ID', params.Pre_ID)
  }
  if (params.mediatorId) {
    uni.setStorageSync('mediatorId', params.mediatorId);
  }
  if (params.q) {
    const parseUrlRes = parseUrlParams(decodeURIComponent(params.q));
    if (parseUrlRes.mediatorId) uni.setStorageSync('mediatorId', parseUrlRes.mediatorId);
  }
  uni.$on('homeSiteId', (data) => {
    if (data.id) {
      state.value.siteId = data.id
      reset();
      getUnitTypeBySiteId();
    }
  });
   uni.showLoading({
        mask: true,
      })
  getLocation().then(() => {
    console.log("uni.hideLoading();");
    getSiteDetail()
  });

});
onUnload(() => {
  uni.$off('homeSiteId');

})
onShow(() => {
  uni.hideTabBar();
  getVerifyStatus();

});

const goVaild = () => {
  navigateTo('/pagesb/validationInfo/index');
}


const getLockerById = () => {
  uni.showLoading();
  getSiteApi.GetLockerById({ lockerId: state.value.lockerId }).then((res) => {
    if (res.code === 200) {
      state.value.lockData = res.data;
      if (state.value.lockData.isPreSale) {
        // 订单可以租用
        state.value.zhuangxiuzhong = true;
        const limitDate = dayjs(state.value.lockData.preSaleTime).format("YYYY/MM/DD");
        if (today.isBefore(limitDate)) {
          if (dayjs(state.value.startDate, "YYYY/MM/DD").isBefore(limitDate)) {
            state.value.startDate = limitDate;
          }
          state.value.minDate = limitDate;
          uni.showModal({
            title: t("common.title"),
            content: t("storeRenovationNotice", { limitDate }),
            showCancel: false,
            success: function () { },
          });
        }
      } else {
        state.value.startDate = today.format("YYYY/MM/DD");
        state.value.zhuangxiuzhong = false;
      }
      // res.data == null 找不到订单 isPlaceOrder 等于订单不可以租用
      if (!res.data || !res.data?.isPlaceOrder) {
        // 支付回调 会触发onshow 这个会优先出来 所有  支付成功就不弹窗 会有一个支付成功的弹窗显示
        uni.showModal({
          title: t("common.title"),
          content: t("common.cantUselocker"),
          showCancel: false,
          success: function () {
            reset();
          },
        });
        uni.hideLoading();
        return;
      }
      getLockerExpense();
    } else {
      uni.reLaunch({
        url: "/pages/index/index",
      });
    }
  }).finally(() => {
    uni.hideLoading();
  });
  ;
};

const getLockerExpense = () => {
  if (!state.value.lockerId || !state.value.month) {
    return;
  }
  uni.showLoading();
  getSiteApi
    .GetLockerExpense({
      lockerId: state.value.lockerId,
      month: state.value.month,
      // couponIds: state.value.couponItem
      //   .map((item) => item.couponDispositionId),
      // isShortTerm: false,
      // point: state.value.point,
      // serialNumber: state.value.couponOtherItem.map(x => {
      //   return {
      //     dealGroupId: x.dealGroupId,
      //     number: x.number,
      //     marketPrice: x.marketPrice,
      //     purchasePrice: x.price
      //   }
      // })
    })
    .then((res) => {
      uni.hideLoading();
      if (res.code === 200) {
        state.value.priceData = res.data;
      }
      if (res.code === 1002) {
        uni.showModal({
          title: t('common.title'),
          content: t('common.ORDER_AMOUNT_ERROR'),
          showCancel: false,
          success: function () {
            reset();
          },
        });

      }
    });
};
const GetLockerAgreementHTMLById = () => {
  uni.showLoading(
    {
      mask: true
    }
  );
  getSiteApi.GetLockerAgreementHTMLById({ lockerId: state.value.lockerId }).then((res) => {
    uni.hideLoading();
    if (res.code === 200) {
      state.value.agreementContent = res.data;
    }
  });
};
// 获取可用仓型
const getUnitTypeBySiteId = () => {
  // barNameList.value = [];
  if (state.value.siteId) {
    uni.showLoading();
    getSiteApi.GetUnitTypeBySiteId({ siteId: state.value.siteId }).then((res) => {
      if (res.code == 200) {
        unitTypeData.value = res.data.filter(item => item.hasAvailableLocker);
        state.value.active = 0
        state.value.unitTypeId = unitTypeData.value[0]?.id;
        // barNameList.value = res.data;
        // if (state.value.getDataTime <= 1 && state.value.unitTypeId) {
        //   tabIndex.value =
        //     barNameList.value.findIndex(
        //       (item) => item.id == state.value.unitTypeId
        //     ) || 0;
        // }
        // 	if(state.value.getDataTime <= 1 && !state.value.unitTypeId){
        //   const index1 = barNameList.value.findIndex(item => item.id == state.value.unitTypeId);
        //   const index2 = barNameList.value.findIndex(item => item.hasAvailableLocker);
        //   tabIndex.value = index1 !== -1 ? index1 : (index2 !== -1 ? index2 : 0);
        // }
        // getLockerBySiteId();
        // state.value.address = res.data[0]?.sitdAddress;
        // state.value.name = res.data[0]?.sitdName;
        // state.value.latitude = res.data[0]?.latitude;
        // state.value.longitude = res.data[0]?.longitude;
        // state.value.tags = res.data[0]?.tags ?? [];
      }
    }).finally(() => {
      uni.hideLoading();
    })
      ;
  }
};

const showImage = (url) => {
  uni.previewImage({
    urls: [url],
  });
};
const gotoPage = (url) => {
  uni.navigateTo({
    url: `/${url}`,
  });
}

// tab
const current = ref(0);
const unitTypeData = ref([]);
const tabs = ref([]);

function changeMove(event) {
  current.value = event.detail.current;
  state.value.unitTypeId = unitTypeData.value[current.value].id;
}

</script>

<style scoped lang="scss">
@import "@/static/style/theme.scss";

.payPopupBox {
  .garyBox {
    border: 3rpx solid #F6F6F7;
    background-color: #F8F9FB;
    padding: 26rpx;
		border-radius: 12rpx;
		color: #808386;
		font-weight: 600;
  }

  .title2 {
    margin-bottom: 20rpx;
    display: flex;
    justify-content: space-between;
  }

  .toOrder {
    padding: 0;
    padding-left: 40rpx;
    border-radius: 999rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;
    background-color: #0D1118;
    color: #FFFFFF;

    .left {
      color: #E9CBA1;
      display: flex;
      align-items: center;
      font-size: 38rpx;
        .price {
        &.overMaxFont{
          font-size: 32rpx;
        }
      }

      .detail {
        display: flex;
        align-items: center;
        margin-left: 16rpx;
        color: #FFFFFF;
        font-size: 28rpx;
        .overMaxFont{
          font-size: 24rpx;
        }
        image {
          margin-left: 10rpx;
          transform: rotate(180deg);
        }
      }

    }

    .right {
      display: flex;
      align-items: center;
      margin-right: -1px;

      text {
        display: flex;
        align-items: center;
      }

      .goOrder {
        height: 86rpx;
        width: 250rpx;
        background-color: #FFFFFF;
        border-radius: 999rpx;

        :deep(.uv-button) {
          font-size: 28rpx;
          border: none;
          font-weight: 600;
        }

      }
    }
  }

}

.unitPopupBox {
  min-height: 50%;
  padding: 32rpx;
  // padding-bottom: calc(32rpx + constant(safe-area-inset-bottom));
  // padding-bottom: calc(32rpx + env(safe-area-inset-bottom));

  .title {
    margin-bottom: 20rpx;

  }

  :deep(.uv-radio-group) {
    width: 100%;
  }

  .info {
    display: flex;
    font-size: 28rpx;
    max-height: 60vh;
    overflow-y: auto;

    .list {
      display: flex;
      width: 100%;
      padding-bottom: 20rpx;
      border-bottom: 1px dashed #787B7E10;
      margin-bottom: 20rpx;

      .left {
        flex: 1;
        font-size: 28rpx;

        .zuqi{
          display: flex;
          align-items: center;
          .minus {
          width: 40rpx;
          height: 40rpx;
          border-width: 1px;
          border-color: #E6E6E6;
          border-style: solid;
          border-top-left-radius: 100px;
          border-top-right-radius: 100px;
          border-bottom-left-radius: 100px;
          border-bottom-right-radius: 100px;
          /* #ifndef APP-NVUE */
          display: flex;
          /* #endif */
          justify-content: center;
          align-items: center;
          line-height: 1;
        }
        .input {
          padding: 10rpx;
          background-color: #EBEBEB;
          border-radius: 8rpx;
          margin: 0 10rpx;
          font-weight: 600;
        }
        .plus {
          width: 40rpx;
          height: 40rpx;
          background-color: #FF0000;
          border-radius: 50%;
          /* #ifndef APP-NVUE */
          display: flex;
          /* #endif */
          justify-content: center;
          align-items: center;
          line-height: 1;
        }
        }
      }

      .right {
        display: flex;
        flex-direction: column;
        justify-content: space-between;
      }

      .radioBox {
        display: flex;
        justify-content: end;
      }
    }
  }
}

.container {
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding-bottom: 300rpx;
}

.agreement-wrap {
  position: relative;
  height: 70vh;
  padding: 20rpx 40rpx;
  // padding-bottom: 100rpx;
  border-radius: 28rpx 28rpx 0 0;
  background: #FFFFFF;

  .agreement-top {
    display: flex;
    justify-content: space-between;
    padding: 20rpx 30rpx;
    margin-bottom: 20rpx;
    font-size:36rpx;
    font-weight: 600;
    .name {
      font-size: 32rpx;
    }
  }

  .agreement-content {
    height: calc(100% - 200rpx);
    overflow: auto;
  }

  .roll-btn {
    display: flex;
    align-items: center;
    justify-content: center;
    position: absolute;
    right: 40rpx;
    bottom: 140rpx;
    width: 80rpx;
    height: 80rpx;
    border-radius: 10rpx;
    background: #FB322E;
  }

  .bottom-read {
    width: 100%;
    // margin: 30rpx 0;
    padding: 20rpx 0;
    color: var(--text-color);
    border-radius: 99rpx;
    text-align: center;
    background: #FB322E;
    opacity: 0.4;

    &.agree {
      opacity: 1;
    }
  }
}

.agreed {
  display: flex;
  font-weight: bold;
  width: 100%;

  .check-wrap {
    pointer-events: none;
    margin-right: 10rpx;
    :deep(.uv-radio-group){
      flex-direction: column-reverse;
    }
    // min-width: 40rpx;
    // height: 40rpx;
    // border: 6rpx solid #242a37;
    // border-radius: 50%;
    // margin: 4rpx 20rpx 0 0;
    // font-size: 26rpx;
    // color: #A8AAAC;
    // text-align: center;
    // line-height: 40rpx;
    // background-color: #242a37;
    // &.checked {
    //   background-color: var(--active-color);
    // }
  }

  .read {
    color: #323233;
  }

  .stress {
    font-size: 26rpx;
    color: #A8AAAC;
    font-weight: 600;
  }
}

.agreed {
  .check-wrap {
    display: flex;
    align-items: center;
    margin-right: 10rpx;
    // :deep(.uv-radio){
    //   zoom: 1.0;
    // }
    // min-width: 30rpx;
    // height: 30rpx;
    // border: 4rpx solid #242a37;
    // border-radius: 50%;
    // margin: 4rpx 20rpx 0 0;
    // font-size: 26rpx;
    // color: #A8AAAC;
    // &.checked {
    //   background-color: var(--active-color);
    // }
  }

  .read {
    color: #A8AAAC;
    font-size: 26rpx;
  }

  .stress {
    font-size: 26rpx;
    color: #A8AAAC;
    font-weight: 600;
  }
}

.toOrder {
  padding: 0;
  padding-left: 40rpx;
  border-radius: 999rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #0D1118;
  color: #FFFFFF;
  .left {
    color: #E9CBA1;
    display: flex;
    align-items: center;
    font-size: 38rpx;
    .price {
      &.overMaxFont{
        font-size: 32rpx;
      }
    }
    .detail {
      display: flex;
      align-items: center;
      color: #FFFFFF;
      margin-left: 16rpx;
      font-size: 28rpx;
      .overMaxFont{
      font-size: 24rpx;
    }
      image{
        margin-left: 10rpx;
      }
    }

  }

  .right {
    display: flex;
    align-items: center;
    margin-right: -1px;
    

    text {
      display: flex;
      align-items: center;
    }

    .goOrder {
      height: 86rpx;
      width: 250rpx;
      background-color: #FFFFFF;
      border-radius: 999rpx;

      :deep(.uv-button) {
        font-size: 28rpx;
        border: none;
        font-weight: 600;
      }

    }
  }
}

.orderInfo {
  padding: 0;

  ul {
    list-style: none;
    padding: 8rpx 40rpx;

    li {
      display: flex;
      align-items: center;
      padding: 32rpx 0;
      justify-content: space-between;
      border-bottom: 1px solid #a8aaac20;
      padding-left: 10rpx;
      //  &:first-child {
      //   padding-top: 0;
      // }
      // &:last-child {
      //   padding-bottom: 0;
      // }

      &:active {
        background-color: #f5f5f5;
      }

      &:last-child {
        border: none;
      }

      .right {
        display: flex;
        align-items: center;

        text {
          padding-right: 20rpx;
        }
      }
    }
  }
}

.selectSite {
  height: 75rpx; // 整体高度
  display: flex;
  justify-content: space-between; // 左右分布
  align-items: center; // 垂直居中
  background: linear-gradient(90deg, #FFE8C4 0%, #FFFFFF 100%);
  width: 100%;
  font-size: 30rpx;
}

.selectSite .left {
  display: flex;
  align-items: center; // 左侧垂直居中
}

.selectSite .left .icon {
  width: 30rpx; // 图片大小，可根据实际调整
  height: 30rpx;
  margin-right: 20rpx; // 图片和文字间距
}

.selectSite .left .address {
  font-size: 28rpx;
  word-wrap: break-word;
  word-break: break-all;
}

.selectSite .right {
  display: flex;
  align-items: center; // 右侧垂直居中
}

.selectSite .right .more {
  font-size: 28rpx;
  color: #000;
  margin-right: 8rpx; // text 和 icon 间距
}

.siteInfo {
  display: flex;
  flex-direction: column;

  image {
    width: 32rpx;
    height: 32rpx;
    margin-right: 8rpx;
  }

  /* 顶部行 */
  .top {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20rpx;

    image {
      margin-top: 6rpx;
    }

    .left {
      display: flex;
      align-items: center;
      .title-wrap {
        display: flex;
        flex-direction: row;
        align-items: center;

        .title {}
        .tag {
          background-color: $sfgrayBgColor;
          margin-left: 8rpx;
          border-radius: 8px;
          height: 35rpx;
          line-height: 35rpx;
          padding: 0 8rpx;
        }
      }
    }

    .right {
      display: flex;
      .distance {}
    }
  }

  /* 底部地址行 */
  .bottom {
    display: flex;
    image {
      margin-top: 4rpx;
    }
    .address {
      word-wrap: break-word;
    	word-break: break-all;
      flex: 1;
    }
  }
}

.info {
  display: flex;
  .right.arrow {
    justify-content: end;
    transform: translateX(20rpx);
  }
  .left.arrow{
     transform: translateX(-20rpx);
  }
  .arrow {
    width: 100rpx;
    display: flex;
    align-items: center;
    
    .arrowIcon {
      display: flex;
      justify-content: center;
      align-items: center;
      width: 64rpx;
      height: 64rpx;
      text-align: center;
      opacity: 0.4;
    }
  }

  .swiper-container {
    flex: 1;
  }
}

.swiper-container {
  height: 320rpx;
  margin-bottom: 20rpx;

  .warehouse-detail-items {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 100%;

    .warehouse-detail-right {
      // width: 250rpx;
      height: 100% !important;
      width: 100% !important;

      image {
        width: 300rpx;
      }
    }
  }
}

uni-swiper-item {
  display: flex;
  justify-content: center;
  align-items: center;
}

.unitType {
  padding: 40rpx;
  .title {
    padding-left: 10rpx;
  }
  .bottom {
    .name{
      padding-left: 10rpx;
    }
    display: flex;
    align-items: baseline;
  }
}
</style>
