<template>
  <view class="Mall4j submit-order page-submit-score-order">
    <view v-if="!isMap">
      <!-- 邮寄到家 -->
      <!-- 当前的收货地址信息 -->
      <view class="address-box">
        <view
          class="current-address"
          @tap="goSelAddress"
        >
          <view class="addr-icon">
            <image src="@/package-user/static/images/icon_addr.png" />
          </view>
          <view
            v-if="userAddr && userAddr.addrId"
            class="addr-info"
          >
            <view class="c-address">
              {{ userAddr.province + userAddr.city + userAddr.area + userAddr.addr }}
            </view>
            <view class="c-user">
              <text class="name">
                {{ userAddr.consignee }}
              </text>
              <text class="phone">
                {{ userAddr.mobile }}
              </text>
            </view>
          </view>
          <view
            v-else
            class="empty-addr-info"
          >
            请先填写收货人信息
          </view>
          <view class="c-right">
            <image src="@/package-user/static/images/arrow-right.png" />
          </view>
        </view>
      </view>
      <!-- /邮寄到家 -->
      <blockquote v-if="!isAllUnmeet">
        <blockquote
          v-for="(shopItem, shopIndex) in shopCartOrders"
          :key="shopIndex"
        >
          <!-- 店铺信息 -->
          <view class="shop-item">
            <view class="shop-box">
              <view class="shop-icon">
                <image src="@/static/images/shop.png" />
              </view>
              <view class="shop-name">
                {{ shopItem.shopName }}
              </view>
            </view>
            <!-- /店铺信息 -->
            <blockquote
              v-for="(shopCartItemDiscount, shopCartItemDiscountIndex) in shopItem.shopCartItemDiscounts"
              :key="'1'+shopCartItemDiscountIndex"
            >
              <!-- 店铺商品明细 -->
              <view class="shop-prods">
                <view
                  :class="['prod-item', shopCartItemDiscount.chooseDiscountItem ?
                    'discount-prod' : '', shopItem.shopCartItemDiscounts.length===1 ||
                    shopCartItemDiscountIndex===shopItem.shopCartItemDiscounts.length-1? 'no-border': '']"
                >
                  <blockquote
                    v-for="(shopCartItem, index) in shopCartItemDiscount.shopCartItems"
                    :key="index"
                  >
                    <view class="prod-item">
                      <view class="single-prod">
                        <view class="pic">
                          <img-show
                            :src="shopCartItem.imgUrl"
                            img-mode="aspectFit"
                          />
                        </view>
                        <view class="info">
                          <view>
                            <view class="info-item">
                              <view class="name">
                                {{ shopCartItem.spuName }}
                              </view>
                            </view>
                            <view class="sku">
                              <view class="sku-text">
                                {{ shopCartItem.skuName || '' }}
                              </view>
                              <view
                                v-if="orderType === orderTypeConstant.SCORE + ''"
                                class="activity-logo"
                              >
                                {{ orderType === orderTypeConstant.SCORE + '' ? '积分' : '' }}
                              </view>
                            </view>
                          </view>
                          <view class="price-box">
                            <view class="price">
                              <view class="symbol">
                                {{ shopCartItem.scorePrice / totalCount }}积分
                              </view>
                              <text
                                v-if="shopCartItem.skuPriceFee"
                                class="symbol"
                              >
                                +
                              </text>
                              <text
                                v-if="shopCartItem.skuPriceFee"
                                class="symbol"
                              >
                                {{ wxs.parsePrice(shopCartItem.skuPriceFee)[0] }}
                              </text>
                              <text
                                v-if="shopCartItem.skuPriceFee"
                                class="symbol"
                              >
                                .{{ wxs.parsePrice(shopCartItem.skuPriceFee)[1] }}元
                              </text>
                            </view>
                            <view class="count">
                              ×{{ shopCartItem.count }}
                            </view>
                          </view>
                        </view>
                      </view>
                    </view>
                  </blockquote>
                </view>
              </view>
            </blockquote>
            <!-- 店铺优惠、留言、运费 -->
            <view class="msg-item">
              <view class="item">
                <view class="item-tit">
                  配送费用
                </view>
                <view class="free-box">
                  <view class="price black">
                    <blockquote v-if="shopItem.transfee">
                      <text class="symbol">
                        ￥
                      </text>
                      <text class="big-num">
                        {{ wxs.parsePrice(shopItem.transfee)[0] }}
                      </text>
                      <text class="small-num">
                        .{{ wxs.parsePrice(shopItem.transfee)[1] }}
                      </text>
                    </blockquote>
                    <text v-else>
                      免运费
                    </text>
                  </view>
                </view>
              </view>
              <view class="item">
                <view class="item-tit">
                  买家留言
                </view>
                <input
                  v-model="shopItem.remarks"
                  class="input"
                  placeholder="选填，给商家留言"
                >
              </view>
            </view>
          </view>
        </blockquote>
      </blockquote>

      <!-- 不满足当前收货地址的商品 -->
      <view
        v-if="unmeetAddrProdList.length"
        class="useless"
      >
        <view class="u-reason">
          以下商品（共{{ unmeetAddrProdList.length }}件）在当前地址不支持配送
        </view>
        <view class="u-box">
          <scroll-view
            :scroll-x="true"
            class="u-scroll-box"
          >
            <view
              v-for="(item,index) in unmeetAddrProdList"
              :key="index"
              class="u-prods"
            >
              <img-show :src="item.imgUrl" />
              <text class="u-buy-tag">
                不可购买
              </text>
            </view>
          </scroll-view>
          <view class="text-arrow u-total a-rignt-6">
            共{{ unmeetAddrProdList.length }}件
          </view>
        </view>
      </view>

      <!-- 总金额计算 -->
      <view
        v-if="!isAllUnmeet"
        class="msg-item"
      >
        <view class="item">
          <view class="item-tit">
            商品总价
          </view>
          <view class="price black">
            <text class="big-num">
              ￥{{ wxs.parsePrice(total || 0)[0] }}
            </text>
            <text class="small-num">
              .{{ wxs.parsePrice(total || 0)[1] }}
            </text>
          </view>
        </view>
        <view class="item">
          <view class="item-tit">
            积分抵扣
          </view>
          <view class="price black">
            <text class="score">
              {{ usableScore }}积分
            </text>
          </view>
        </view>

        <!-- 运费 -->
        <view class="item">
          <view class="item-tit">
            应付运费
          </view>
          <view class="price black">
            <text class="symbol">
              ￥
            </text>
            <text class="big-num">
              {{ wxs.parsePrice(totalTransfee)[0] }}
            </text>
            <text class="small-num">
              .{{ wxs.parsePrice(totalTransfee)[1] }}
            </text>
          </view>
        </view>

        <!-- 平台开启会员包邮(运费减免) -->
        <view
          v-if="freeTransfee"
          class="item"
        >
          <view class="item-tit">
            会员包邮
          </view>
          <view class="price">
            <text class="symbol">
              -￥
            </text>
            <text class="big-num">
              {{ wxs.parsePrice(freeTransfee)[0] }}
            </text>
            <text class="small-num">
              .{{ wxs.parsePrice(freeTransfee)[1] }}
            </text>
          </view>
        </view>

        <!-- 会员积分 -->
        <view
          v-if="!orderType && maxUsableScore"
          class="item"
          @tap="showIntegralPopup"
        >
          <view class="item-tit">
            积分抵扣
          </view>
          <view class="number text-arrow">
            <view
              v-if="totalScoreAmount"
              class="price"
            >
              <text class="symbol">
                -￥
              </text>
              <text class="big-num">
                {{ wxs.parsePrice(totalScoreAmount)[0] }}
              </text>
              <text class="small-num">
                .{{ wxs.parsePrice(totalScoreAmount)[1] }}
              </text>
            </view>
            <text
              v-else
              class="text"
            >
              不使用积分抵扣
            </text>
          </view>
        </view>

        <!-- 会员等级折扣 -->
        <view
          v-if="totalLevelAmount"
          class="item"
        >
          <view class="item-tit">
            会员折扣
          </view>
          <view class="price">
            <text class="symbol">
              -￥
            </text>
            <text class="big-num">
              {{ wxs.parsePrice(totalLevelAmount)[0] }}
            </text>
            <text class="small-num">
              .{{ wxs.parsePrice(totalLevelAmount)[1] }}
            </text>
          </view>
        </view>

        <!-- 秒杀/团购金额优惠 -->
        <view
          v-if="orderType==='1' || orderType==='2'"
          class="item"
        >
          <view class="item-tit">
            {{ orderType === '1' ? '团购优惠' : '秒杀优惠' }}
          </view>
          <view class="price">
            <text class="symbol">
              -￥
            </text>
            <text class="big-num">
              {{ wxs.parsePrice(orderReduce)[0] }}
            </text>
            <text class="small-num">
              .{{ wxs.parsePrice(orderReduce)[1] }}
            </text>
          </view>
        </view>

        <!-- 店铺优惠（满减、满折等） -->
        <view
          v-if="orderShopReduce && !orderType"
          class="item"
        >
          <view class="item-tit">
            店铺优惠
          </view>
          <view class="price">
            <text class="symbol">
              -￥
            </text>
            <text class="big-num">
              {{ wxs.parsePrice(orderShopReduce)[0] }}
            </text>
            <text class="small-num">
              .{{ wxs.parsePrice(orderShopReduce)[1] }}
            </text>
          </view>
        </view>
      </view>

      <view class="submit-footer">
        <view class="price-info">
          <view class="total">
            <view class="text">
              合计：
            </view>
            <view class="price">
              <text class="symbol">
                {{ usableScore }}积分
              </text>
              <text
                v-if="actualTotal"
                class="symbol"
              >
                +
              </text>
              <text
                v-if="actualTotal"
                class="symbol"
              >
                {{ wxs.parsePrice(actualTotal)[0] }}
              </text>
              <text
                v-if="actualTotal"
                class="symbol"
              >
                .{{ wxs.parsePrice(actualTotal)[1] }}元
              </text>
            </view>
          </view>
        </view>
        <view
          v-if="!isAllUnmeet"
          class="btn"
          @tap="toPay"
        >
          提交订单
        </view>
        <view
          v-else
          class="disabled-btn"
        >
          提交订单
        </view>
      </view>
    </view>

    <!-- 选择配送方式弹窗 -->
    <view
      class="popup"
      :class="{ show: isShowDistributionPopup }"
    >
      <view
        class="popup-mask"
        @tap="closePopup"
      />
      <view class="popup-con-bottom check-address h40">
        <view class="popup-tit">
          <view class="tit-text">
            选择配送方式
          </view>
          <view
            class="close"
            @tap="closePopup"
          >
            <image src="@/package-user/static/images/icon_close.png" />
          </view>
        </view>
        <radio-group class="con-box-min">
          <label class="address-item">
            <radio
              color="#fff"
              :checked="true"
              value="1"
            />
            <view class="text-box">
              <view class="address">快递配送</view>
            </view>
          </label>
          <label class="address-item">
            <radio
              color="#fff"
              value="4"
            />
            <view class="text-box">
              <view class="address">同城配送</view>
            </view>
          </label>
        </radio-group>
        <view class="btn-box">
          <view class="btn">
            确定
          </view>
        </view>
      </view>
    </view>

    <!-- 新建收货地址弹窗 -->
    <view
      class="popup"
      :class="{ show: isEditAddress }"
    >
      <view
        class="popup-mask"
        @tap="closePopup"
      />
      <view class="popup-con-bottom check-address">
        <view class="popup-tit">
          <view class="tit-text">
            新建收货地址
          </view>
          <view
            class="close"
            @tap="closePopup"
          >
            <image src="@/package-user/static/images/icon_close.png" />
          </view>
        </view>
        <view class="addr-item input-item-start">
          <text class="label">
            收货人
          </text>
          <view class="input-box">
            <view :class="['input-con',isSaveAddrClick && !consignee ?'addr-error':'']">
              <input
                v-model="consignee"
                type="text"
                maxlength="20"
                placeholder-class="inp-palcehoder"
                :placeholder="'请输入收货人姓名'"
              >
            </view>
            <view
              v-if="isSaveAddrClick && !consignee"
              class="error-text"
            >
              请填写收货人
            </view>
          </view>
        </view>
        <view class="addr-item">
          <text class="label">
            手机号
          </text>
          <view class="input-box">
            <view :class="['input-con',isSaveAddrClick && !mobile ?'addr-error':'']">
              <input
                v-model="mobile"
                type="number"
                maxlength="11"
                placeholder-class="inp-palcehoder"
                :placeholder="'请输入手机号'"
              >
            </view>
            <view
              v-if="isSaveAddrClick && !mobile"
              class="error-text"
            >
              请填写手机号
            </view>
          </view>
        </view>
        <view class="addr-item">
          <text class="label">
            所在地区
          </text>
          <view class="input-box">
            <view :class="['input-con',isSaveAddrClick && !province ?'addr-error':'']">
              <view
                class="area-box"
                @tap="showPicker=true"
              >
                <text
                  v-if="province"
                  class="text"
                >
                  {{ province }} {{ city }} {{ area }}
                </text>
                <text
                  v-else
                  class="inp-palcehoder"
                >
                  请选择省市区
                </text>
              </view>
              <view
                class="icon-right"
                @tap="showPicker=true"
              >
                <image src="@/package-user/static/images/arrow-right.png" />
              </view>
            </view>
            <view
              v-if="isSaveAddrClick && !province"
              class="error-text"
            >
              请选择所在地区
            </view>
          </view>
          <address-picker
            v-if="showPicker"
            :show-picker="showPicker"
            :addr-ids="addrIds"
            @set-address-info="addressPickerConfirm"
          />
        </view>
        <view class="addr-item">
          <text class="label">
            详细地址
          </text>
          <view class="input-box">
            <view :class="['input-con',isSaveAddrClick && !addr ?'addr-error':'']">
              <textarea
                v-model="addr"
                data-type="username"
                placeholder-class="inp-palcehoder"
                auto-height
                :placeholder="'小区楼栋、门牌号、村等'"
              />
              <view class="location-btn">
                <view class="addr-icon-loc">
                  <image src="@/package-user/static/images/icon_addr_loc.png" />
                </view>
                <text
                  class="loc-name"
                  @tap="selLocation"
                >
                  定位
                </text>
              </view>
            </view>
            <view
              v-if="isSaveAddrClick && !addr"
              class="error-text"
            >
              请填写详细地址
            </view>
          </view>
        </view>
        <view
          class="btn-box"
          :style="showPicker?'z-index:0;':''"
        >
          <view
            class="btn"
            @tap="saveAndUse"
          >
            保存
          </view>
        </view>
      </view>
    </view>

    <!-- 可用地址弹窗 -->
    <view
      class="popup"
      :class="{ show: isShowAddressListPopup }"
    >
      <view
        class="popup-mask"
        @tap="closePopup"
      />
      <view class="popup-con-bottom check-address">
        <view class="popup-tit">
          <view class="tit-text">
            可选用地址
          </view>
          <view
            class="close"
            @tap="closePopup"
          >
            <image src="@/static/images/close.png" />
          </view>
        </view>
        <radio-group
          class="con-box-min"
          @change="addrRadioChange"
        >
          <blockquote
            v-for="(addressItem, addressIndex) in addressList"
            :key="addressIndex"
          >
            <label class="address-item">
              <view class="text-box">
                <view class="address">
                  <text
                    v-if="addressItem.isDefault"
                    class="default"
                  >默认
                  </text>
                  {{ addressItem.province + addressItem.city + addressItem.area + addressItem.addr }}
                </view>
                <view class="user">
                  <view class="name">{{ addressItem.consignee }}</view>
                  <view class="phone">{{ addressItem.mobile }}</view>
                </view>
              </view>
              <radio
                color="#fc1b35"
                :value="String(addressItem.addrId)"
                :checked="addressItem.addrId === addrId"
              />
            </label>
          </blockquote>
        </radio-group>
        <view class="btn-box">
          <view
            class="btn"
            @tap="confirmChangeAddr"
          >
            确定
          </view>
        </view>
      </view>
    </view>
    <!-- 确认弹窗 -->
    <confirm-pop
      :show-pop="showPop"
      :pop-content="popContent"
      :show-cancel="false"
      @handle-pop-confirm="popConfirm"
    />
    <invoiceEdit
      v-if="isShowInvoicePopup"
      :invoice-data-from="invoiceDataFrom"
      :shop-id="invoiceShopId"
      :invoice-id="invoiceId"
      @close-popup="closePopup"
      @get-invoice-data="getInvoiceData"
    />

    <!-- #ifdef APP-PLUS -->
    <!-- 腾讯地图组件 -->
    <view
      v-if="isMap"
      class="map"
    >
      <web-map
        v-if="isMap"
        @on-get-location="onGetLocation"
      />
    </view>
    <!-- end 腾讯地图组件 -->
    <!--  #endif -->
  </view>
</template>

<script setup>
import number from '@/wxs/number'
import util from '@/utils/util'
import { ProdType, PayType, PayEntry } from '@/utils/constant'
import * as locTrans from '@/utils/locTrans'
import invoiceEdit from '@/package-user/components/invoice-edit/index.vue'
import Pay from '@/utils/pay'

const wxs = number()

// 订单类型常量
const orderTypeConstant = ref(ProdType)

const invoiceId = ref('') // 发票id
const invoiceShopId = ref('')

// 1为立即购买,否则为从购物车提交
let orderEntry = ''
// 订单类型
const orderType = ref('')
// 凑团的团队id
let groupTeamId = 0
let seckillOrderPath = ''
const isEditAddress = ref(false) // 编辑地址
let dvyTypes = []
// 当前订单选择的地址id
const addrId = ref(0)
// 当前订单选择的用户地址
const userAddr = ref({})
/**
 * 生命周期函数--监听页面加载
 */
onLoad((options) => {
  const savePageInfo = uni.getStorageSync('cloudSavePageInfo')
  uni.removeStorageSync('cloudSavePageInfo')
  orderEntry = options.orderEntry || ''
  orderType.value = options.orderType || ''
  groupTeamId = options.groupTeamId || savePageInfo.groupTeamId || 0
  seckillOrderPath = options.seckillOrderPath || savePageInfo.seckillOrderPath || ''
  isEditAddress.value = savePageInfo.isEditAddress || false
  const shopCartItem = uni.getStorageSync('cloudShopCartItem') ? JSON.parse(uni.getStorageSync('cloudShopCartItem')) : {}
  if (shopCartItem) {
    dvyTypes = [{ shopId: shopCartItem.shopId, dvyType: 1 }]
  }
  // 是否已选择的可配送地址
  const deliveryAddrInfo = uni.getStorageSync('cloudDeliveryAddrInfo')
  if (deliveryAddrInfo) {
    addrId.value = deliveryAddrInfo.addrId
    userAddr.value = deliveryAddrInfo
  } else {
    // 获取用户地址列表
    getAddressList()
  }

  if (options.module === 'locationPicker') {
    afterLoc(options)
  }

  // 加载订单
  loadOrder(true)
})

/**
 * 生命周期函数--监听页面显示
 */
onShow(() => {
  // 切换收货地址
  const addrInfo = uni.getStorageSync('cloudStationAddress')
  if (addrInfo) {
    addrId.value = addrInfo.addrId
    loadOrder()
    uni.removeStorageSync('cloudStationAddress')
  }
})

/**
 * 用户点击右上角分享(勿删)
 */
onShareAppMessage(() => {})

// 选择地址
const goSelAddress = () => {
  // 没有地址时让其添加地址
  if (!userAddr.value || !userAddr.value.addrId) {
    isEditAddress.value = true
    return
  }
  uni.navigateTo({
    url: '/package-user/pages/address-list/address-list?selectAddress=1'
  })
}

const consignee = ref('')
const mobile = ref('')
const addr = ref('')
let provinceId = 0
let cityId = 0
let areaId = 0
const province = ref('')
const city = ref('')
const area = ref('')
let lat = ''
let lng = ''
const isMap = ref(false)
const key = import.meta.env.VITE_APP_MAP_KEY
/**
 * 获取到定位后的回调
 * loc 定位信息
 */
const afterLoc = (loc) => {
  const cloudAddrInfo = uni.getStorageSync('cloudAddrInfo')
  addrId.value = cloudAddrInfo.addrId
  mobile.value = cloudAddrInfo.mobile
  consignee.value = cloudAddrInfo.consignee
  uni.removeStorageSync('cloudAddrInfo')
  if (loc && loc.module === 'locationPicker') { // 防止其他应用也会向该页面post信息，需判断module是否为'locationPicker'
    addr.value = loc.addr
    lat = loc.latng.split(',')[0]
    lng = loc.latng.split(',')[1]
    isMap.value = false
    util.area(loc.addr, loc.name).then(res => {
      if (!res) return
      const addrReplacrstr = res[0].name + res[1].name + res[2].name
      addr.value = addr.value.replace(addrReplacrstr, '') || loc.name
      province.value = res[0].name
      city.value = res[1].name
      area.value = res[2].name
      provinceId = res[0].areaId
      cityId = res[1].areaId
      areaId = res[2].areaId
    })
  }
}

/**
 * 选择定位信息
 */
const selLocation = () => {
  // #ifdef H5
  uni.setStorageSync('cloudAddrInfo', { addrId: addrId.value, mobile: mobile.value, consignee: consignee.value })
  const savePageInfo = {
    groupTeamId,
    seckillOrderPath,
    isEditAddress: isEditAddress.value
  }
  uni.setStorageSync('cloudSavePageInfo', savePageInfo)
  uni.setStorageSync('cloudDvyTypes', dvyTypes)

  const routes = getCurrentPages() // 获取当前打开过的页面路由数组
  const curRoute = routes[routes.length - 1].route // 获取当前页面路由，也就是最后一个打开的页面路由

  const backUrl = decodeURIComponent(`${import.meta.env.VITE_APP_DOMAIN_ADDRESS}/${curRoute}?orderEntry=${orderEntry}&orderType=${orderType.value}`)
  window.location.replace(`https://apis.map.qq.com/tools/locpicker?search=1&type=0&backurl=${backUrl}&key=${key}&referer=myapp`)
  // #endif
  // #ifdef APP-PLUS
  isMap.value = true
  // #endif
  // #ifdef MP-WEIXIN
  uni.authorize({
    scope: 'scope.userLocation',
    success: () => {
      uni.chooseLocation({
        success: (res) => {
          onGetLocation(res)
        },
        fail: (err) => {
          if (err.errMsg !== 'chooseLocation:fail cancel') {
            uni.showToast({
              title: '定位失败',
              icon: 'none'
            })
          }
        }
      })
    },
    fail: () => {
      uni.showToast({
        title: '请在「右上角」 - 「设置」授予位置信息权限',
        icon: 'none'
      })
    }
  })
  // #endif
}

const onGetLocation = (loc) => {
  let poinamePar
  // #ifdef H5 || APP-PLUS
  addr.value = loc.poiaddress
  lat = loc.latlng.lat
  lng = loc.latlng.lng
  poinamePar = loc.poiname
  isMap.value = false
  // #endif

  // #ifdef MP-WEIXIN
  const municipality = '北京市|天津市|上海市|重庆市' // 直辖市
  const rex = new RegExp(`(${municipality})+(?=${municipality})`)
  lat = loc.latitude // 纬度
  lng = loc.longitude // 经度
  addr.value = loc.address?.replace(rex, '') // 详细地址
  poinamePar = loc.name // 详细地址
  // #endif

  util.area(addr, poinamePar).then(res => {
    if (res.length === 0) return
    addr.value = addr.replace(res[0].name + res[1].name + res[2].name, '') || res.poiname
    province.value = res[0].name
    city.value = res[1].name
    area.value = res[2].name
    provinceId = res[0].areaId
    cityId = res[1].areaId
    areaId = res[2].areaId
  })
  const locationInfo = { latitude: lat, longitude: lng }
  let locationRes
  // #ifdef H5 || APP-PLUS
  locationRes = locTrans.gcj02tobd09(locTrans.wgs84togcj02(locationInfo))
  // #endif

  // #ifdef MP-WEIXIN
  locationRes = locTrans.gcj02tobd09(locationInfo)
  // #endif
  lat = locationRes.latitude
  lng = locationRes.longitude
}

const showPop = ref(false)
/**
 * 弹窗确认
 */
const popConfirm = () => {
  showPop.value = false
  if (orderType.value !== '0') {
    uni.navigateBack({
      delta: 1
    })
  }
}

const addrIds = ref([])
const showPicker = ref(false)
/**
 * 地区弹窗确认按钮
 */
const addressPickerConfirm = (selectedAddrInfo, isChange) => {
  if (isChange) {
    area.value = selectedAddrInfo.area
    areaId = selectedAddrInfo.areaId
    city.value = selectedAddrInfo.city
    cityId = selectedAddrInfo.cityId
    province.value = selectedAddrInfo.province
    provinceId = selectedAddrInfo.provinceId
    addrIds.value = [selectedAddrInfo.provinceId, selectedAddrInfo.cityId, selectedAddrInfo.areaId]
  }
  showPicker.value = false
}

const isSaveAddrClick = ref(false) // 是否点击了编辑地址保存按钮
/**
 * 添加新的地址并使用
 */
const saveAndUse = () => {
  isSaveAddrClick.value = true // 是否点击了保存按钮
  // 数据校验
  if (!consignee.value.trim() || !mobile.value.trim() || !area || !addr.value.trim()) {
    return
  }
  if (consignee.value.length < 2) {
    uni.showToast({
      title: '收件人姓名需在2到20个字符之间',
      icon: 'none'
    })
    return
  }
  if (!util.checkPhoneNumber(mobile.value)) {
    uni.showToast({
      title: '请输入正确的手机号',
      icon: 'none'
    })
    return
  }
  if (addr.value.length < 5) {
    uni.showToast({
      title: '请输入字数在5-50之间的详细地址',
      icon: 'none'
    })
    return
  }
  // 保存地址
  http.request({
    url: '/tmerclub_user/user_addr',
    method: 'POST',
    data: {
      addr: addr.value,
      area: area.value,
      areaId,
      city: city.value,
      cityId,
      consignee: consignee.value,
      mobile: mobile.value,
      province: province.value,
      provinceId,
      lat,
      lng
    }
  }).then(() => {
    isEditAddress.value = false
    isSaveAddrClick.value = false
    clearAddressInput()
    getAddressList('reloadOrder')
    if (!userAddr.value) {
      loadOrder()
    }
  })
}

/**
 * 选择地址
 */
const addrRadioChange = (e) => {
  addrId.value = e.detail.value
}

/**
 * 确定地址
 */
const confirmChangeAddr = () => {
  isEditAddress.value = false
  closePopup()
  loadOrder()
}

// 地址列表
const addressList = ref([])
/**
 * 获取用户地址列表
 */
const getAddressList = (reload) => {
  http.request({
    url: '/tmerclub_user/user_addr/list',
    method: 'GET',
    data: {}
  }).then((res) => {
    addressList.value = res
    if (reload) {
      addrId.value = res[0].addrId
      loadOrder()
    }
  })
}

/**
 * 清除编辑地址输入框
 */
const clearAddressInput = () => {
  consignee.value = ''
  mobile.value = ''
  addr.value = ''
  cityId = ''
  provinceId = ''
}

// 选中的优惠券id列表
let couponIds = []
// 平台券
const platformCoupons = reactive({
  canUseLength: 0,
  couponAmount: null,
  canUseCoupons: [],
  unCanUseCoupons: []
})
const setPlatformCoupons = (val) => {
  platformCoupons.canUseLength = val.canUseLength
  platformCoupons.couponAmount = val.couponAmount
  platformCoupons.canUseCoupons = val.canUseCoupons
  platformCoupons.unCanUseCoupons = val.unCanUseCoupons
}

/**
 * 分割优惠券成
 * 1. canUseCoupons 可使用优惠券列表
 * 2. unCanUseCoupons 不可使用优惠券列表
 * 3. couponAmount 选中的优惠券可优惠金额
 * 4. 将选中的优惠券ids保存起来
 * @param {*} coupons 优惠券列表
 * @param {*} couponIdsPar 选中的优惠券id
 */
const splitCouponAndPushCouponIds = (coupons, couponIdsPar) => {
  if (!coupons || !coupons.length) {
    return {
      canUseLength: 0,
      couponAmount: 0,
      canUseCoupons: [],
      unCanUseCoupons: []
    }
  }

  const canUseCoupons = []
  const unCanUseCoupons = []
  let couponAmount = 0
  coupons.forEach(coupon => {
    if (coupon.canUse) {
      canUseCoupons.push(coupon)
    } else {
      unCanUseCoupons.push(coupon)
    }

    if (coupon.choose) {
      couponIdsPar.push(coupon.couponId)
      couponAmount = coupon.reduceAmount
    }
  })
  return {
    canUseLength: canUseCoupons.length,
    couponAmount,
    canUseCoupons,
    unCanUseCoupons
  }
}

// 用户是否改变了优惠券的选择: 1是; 0否
const userChangeCoupon = 0
// 是否使用积分抵扣 默认否
const isScorePay = 1
// 输入的积分数量
const userUseScore = ''
// 不满足收货地址的商品
const unmeetAddrProdList = ref([])
const isAllUnmeet = ref(false) // 是否全部为不满足地址的商品
const shopCartOrders = ref([])
// 订单优惠金额(所有店铺优惠金额)
const orderReduce = ref(0)
const orderShopReduce = ref(0) // 店铺优惠
const total = ref(0)
const actualTotal = ref(0)
const usableScore = ref(0) // 积分
const totalTransfee = ref(0)
const totalLevelAmount = ref(0)
const totalScoreAmount = ref(0)
// 该订单最大可用积分数量
const maxUsableScore = ref(0)
let userHasScore = 0
const totalCount = ref(1) // 商品数量
// 运费减免
const freeTransfee = ref('')
/**
 * 加载订单数据
 */
const loadOrder = (isFirst) => {
  const shopCartItem = uni.getStorageSync('cloudShopCartItem') ? JSON.parse(uni.getStorageSync('cloudShopCartItem')) : {}
  http.request({
    url: '/tmerclub_order/score_order/confirm',
    method: 'POST',
    data: {
      addrId: addrId.value || 0,
      dvyTypes,
      shopCartItem,
      couponIds,
      distributionUserId: shopCartItem.distributionUserId || undefined,
      userChangeCoupon,
      isScorePay,
      userUseScore: Number(userUseScore)
    }
  }).then((res) => {
    const shopCartOrdersPar = res.shopCartOrders
    const couponIdsPar = []

    const remarksList = []
    if (!isFirst) {
      shopCartOrdersPar.forEach(el => {
        remarksList.push(el.remarks)
      })
    }
    shopCartOrdersPar.forEach((shopCart, index) => {
      shopCart.shopCartItemDiscounts.forEach(shopCartItemDiscount => {
        shopCartItemDiscount.shopCartItems.forEach(prodItem => {
          if (prodItem.imgUrl) {
            if (prodItem.imgUrl.indexOf('http') === -1) {
              prodItem.imgUrl = import.meta.env.VITE_APP_RESOURCES_URL + prodItem.imgUrl
            }
          }
        })
      })
      if (isFirst) {
        shopCart.remarks = ''
      } else {
        remarksList.push(shopCart.remarks)
        shopCartOrdersPar[index].remarks = remarksList[index]
      }
    })
    // 平台优惠券
    const platformCouponsPar = splitCouponAndPushCouponIds(res.coupons, couponIdsPar)

    unmeetAddrProdList.value = res.filterShopItems // 当前地址不可配送的商品
    isAllUnmeet.value = !shopCartOrdersPar?.length
    couponIds = couponIdsPar
    shopCartOrders.value = shopCartOrdersPar
    setPlatformCoupons(platformCouponsPar)
    orderReduce.value = res.orderReduce
    orderShopReduce.value = res.orderShopReduce // 店铺优惠
    total.value = res.total
    actualTotal.value = res.actualTotal
    usableScore.value = res.usableScore
    totalTransfee.value = res.totalTransfee
    totalLevelAmount.value = res.totalLevelAmount
    totalScoreAmount.value = res.totalScoreAmount
    maxUsableScore.value = res.maxUsableScore > res.userHasScore ? res.userHasScore : res.maxUsableScore
    userHasScore = res.userHasScore
    totalCount.value = res.totalCount
    // 平台开启会员包邮（运费减免）
    freeTransfee.value = res.freeTransfee
    if (freeTransfee.value > 0) {
      totalTransfee.value = util.accuracyCount(totalTransfee.value, freeTransfee.value, 1)
    }
    if (res.userAddr) {
      userAddr.value = res.userAddr
      addrId.value = res.userAddr.addrId
      addrIds.value = [res.userAddr.provinceId, res.userAddr.cityId, res.userAddr.areaId]
    }
  }).catch((err) => {
    errCallBackPop(err)
  })
}

const isShowDistributionPopup = ref(false) // 选择配送方式弹窗

const isShowAddressListPopup = ref(false) // 历史选用地址弹窗

const isShowInvoicePopup = ref(false) // 发票弹窗
// 关闭弹窗
const closePopup = () => {
  isShowDistributionPopup.value = false
  isShowAddressListPopup.value = false
  isShowInvoicePopup.value = false
  isEditAddress.value = false
}

// 去支付
const toPay = () => {
  if (isEditAddress.value) {
    uni.showToast({
      title: '请完善地址信息',
      duration: 2000,
      mask: true,
      icon: 'none'
    })
    return
  }
  submitOrder()
}

// 配送方式
const dvyType = 1
/**
 * 提交订单
 */
const submitOrder = () => {
  if (dvyType === 1 && !userAddr.value.addrId) {
    uni.showToast({
      title: '请先添加收货地址',
      icon: 'none'
    })
    return
  }
  const shopCartOrdersPar = shopCartOrders.value
  const orderShopParam = []
  shopCartOrdersPar.forEach(shopCart => {
    orderShopParam.push({
      remarks: shopCart.remarks,
      shopId: shopCart.shopId
    })
  })
  let orderInvoiceList = [] // invoiceDataFrom
  shopCartOrdersPar.forEach((item) => {
    if (item.invoiceDataFrom && item.invoiceDataFrom.invoiceType === 1) {
      orderInvoiceList.push(item.invoiceDataFrom)
    }
  })
  if (orderInvoiceList.length === 0) {
    orderInvoiceList = null
  }
  http.request({
    url: orderType.value === '1' ? '/tmerclub_group/group_order/submit' : (orderType.value === '2' ? `/tmerclub_seckill/seckill_order/${seckillOrderPath}/submit` : '/tmerclub_order/order/submit'),
    method: 'POST',
    data: {
      groupTeamId: orderType.value === '1' ? groupTeamId : undefined,
      orderShopParam,
      orderInvoiceList
    }
  }).then((res) => {
    if (orderType.value === '2') {
      return
    }
    orderSubmitSuccessCallBack(res)
  }).catch((err) => {
    errCallBackPop(err)
  })
}

let payType = 0
// 确认支付
const surePay = (orderIds) => {
  const paymentData = {
    payType: 0,
    orderIds,
    isPurePoints: orderIds,
    dvyType,
    payEntry: PayEntry.ORDER
  }
  if (payType === PayType.SCOREPAY) {
    if (userHasScore < usableScore.value) {
      uni.showToast({
        title: '积分不足！当前积分为：' + userHasScore,
        icon: 'none',
        duration: 3000
      })
      return
    }
    uni.showModal({
      title: '提示',
      content: `确认使用${usableScore.value}积分支付吗？`,
      success: (res) => {
        if (res.confirm) {
          Pay.toOrderPay(paymentData)
        } else if (res.cancel) {
          uni.redirectTo({
            url: '/package-user/pages/order/order?orderStatus=1'
          })
        }
      }
    })
    return
  }
  if (actualTotal.value <= 0) {
    payType = 0 // 积分支付
  }
  Pay.toOrderPay(paymentData)
}

/**
 * 订单提交成功后回调
 */
const orderSubmitSuccessCallBack = (successRes) => {
  const orderIds = successRes.join(',')
  // 206:生成订单结算页id
  util.tapLog(4, { pid: 206, bid: orderIds })
  if (actualTotal.value) {
    uni.redirectTo({
      url: `/package-activities/pages/payment/payment?orderIds=${orderIds}&dvyType=1`
    })
  } else {
    surePay(orderIds)
  }
}

const popContent = reactive({
  content: ''
})
/**
 * 订单请求错误弹窗回调
 */
const errCallBackPop = (errMsg) => {
  if (errMsg.code === 'A03020') {
    popContent.content = '用户积分不足'
    showPop.value = true
    return
  }
  if (errMsg.code !== 'A00004') {
    if (errMsg.code !== 'A03002') {
      if (errMsg.code === 'A07001') {
        shopCartOrders.value.forEach((shopCart) => {
          shopCart.shopCartItemDiscounts.forEach((shopCartItemDiscount) => {
            shopCartItemDiscount.shopCartItems.forEach((prodItem) => {
              if (!prodItem.isDelivery) {
                errMsg.msg += prodItem.spuName + '、'
              }
            })
          })
        })
        errMsg.msg = errMsg.msg.substring(0, errMsg.msg.length - 1)
      }
      popContent.content = errMsg.msg
    }
    showPop.value = true
  }
}

const invoiceDataFrom = ref({})
const getInvoiceData = (data) => {
  shopCartOrders.value.forEach(item => {
    if (item.shopId === data.shopId) {
      item.invoiceDataFrom = data
    }
  })
}

</script>
<style lang="scss" scoped>
@use "submit-score-order";
@use "../../../popup";
</style>
