<template>
  <view class="Mall4j submit-order page-submit-order">
    <view v-if="!isMap">
      <!-- 当商品为虚拟商品时，隐藏收货地址信息 -->
      <blockquote v-if="spuMold !== 1">
        <view class="address-box">
          <!-- 邮寄到家 -->
          <!-- 当前的收货地址信息 -->
          <blockquote v-if="dvyType !== 2">
            <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>
          </blockquote>
          <!-- /邮寄到家 -->

          <!-- 门店自提 -->
          <!-- 当前的自提点信息 -->
          <view
            v-if="isUserPickUp && dvyType === 2"
            class="store-box"
          >
            <view
              v-show="!isGetStationLoaded"
              class="mask-layer"
              :class="{ 'me-bg-loading': !isGetStationLoaded }"
            />
            <view
              :class="['current-address', 'current-station']"
              @tap="goSelStation"
            >
              <view
                v-if="stationInfo"
                class="addr-icon"
              >
                <image
                  mode="aspectFit"
                  :src="util.addDomain(stationInfo.selStationItem?.imgUrl) || shopStoreIcon"
                  @error="stationInfo.selStationItem.imgUrl = ''"
                />
              </view>
              <view
                v-if="stationInfo.stationStockStatus === 2 && isGetStationLoaded && isHaveStation"
                class="addr-info"
              >
                <view v-if="stationInfo.stationStockStatus === 2">
                  <view class="c-address">
                    {{ stationInfo.selStationItem?.stationName }}
                  </view>
                  <view class="c-user">
                    <text class="name">
                      {{ stationInfo?.userInfo?.name }}
                    </text>
                    <text class="phone">
                      {{ stationInfo?.userInfo?.userMobile }}
                    </text>
                  </view>
                </view>
              </view>
              <view
                v-else-if="stationInfo.stationStockStatus === 1 && isGetStationLoaded && !isHaveStation"
                class="addr-info"
              >
                <view class="c-address">
                  当前区域暂无库存
                </view>
              </view>
              <view
                v-else-if="isGetStationLoaded && !isHaveStation"
                class="addr-info"
              >
                <view class="c-address">
                  当前区域暂无门店
                </view>
              </view>
              <view
                v-else
                class="empty-addr-info"
              />
              <view
                v-if="!(isGetStationLoaded && !isHaveStation)"
                class="c-right"
              >
                <image src="@/package-user/static/images/arrow-right.png" />
              </view>
            </view>
          </view>
          <!-- 门店自提开关 -->
          <view
            v-if="isUserPickUp && (stationInfo.selStationItem?.stationId || (userAddr && userAddr.addrId))"
            class="station-box"
          >
            <view class="station-name">
              <text class="name">
                门店自提
              </text>
            </view>
            <switch
              class="station-switch"
              style="transform:scale(0.7)"
              :checked="dvyType === 2"
              color="#F81A1A"
              @change="stationChange"
            />
          </view>
          <!-- /门店自提 -->
        </view>
      </blockquote>

      <blockquote v-if="!isAllUnmeet">
        <blockquote
          v-for="(shopItem, shopIndex) in shopCartOrders"
          :key="shopIndex"
        >
          <!-- 店铺信息 -->
          <view
            class="shop-item"
            :class="{'virtual': spuMold === 1}"
          >
            <view class="shop-box">
              <view class="shop-icon">
                <image src="@/static/images/shop.png" />
              </view>
              <view class="shop-name">
                <text>{{ shopItem.shopName }}</text>
              </view>
            </view>
            <!-- /店铺信息 -->
            <blockquote
              v-for="(shopCartItemDiscount, shopCartItemDiscountIndex) in shopItem.shopCartItemDiscounts"
              :key="shopCartItemDiscountIndex"
            >
              <!-- 店铺商品明细 -->
              <view class="shop-prods">
                <view
                  :class="['shop-prods-item',shopCartItemDiscount.chooseDiscountItem ||
                    shopCartItemDiscount.chooseComboItemVo ? 'discount-prod' : '', shopItem.shopCartItemDiscounts.length===1 ||
                    shopCartItemDiscountIndex===shopItem.shopCartItemDiscounts.length-1? 'no-border': '']"
                >
                  <!-- 活动信息 -->
                  <view
                    v-if="shopCartItemDiscount.chooseDiscountItem"
                    class="discount-info"
                  >
                    <view class="d-name">
                      {{ shopCartItemDiscount.chooseDiscountItem.discountRule === 0 ? '满减' : '满折' }}
                    </view>
                    <view class="d-des">
                      {{ shopCartItemDiscount.chooseDiscountItem.discountName }}
                    </view>
                    <view class="d-reduced">
                      <view class="text">
                        已减
                      </view>
                      <view class="price">
                        ￥{{ wxs.parsePrice(shopCartItemDiscount.chooseDiscountItem.reduceAmount)[0] }}.
                        {{ wxs.parsePrice(shopCartItemDiscount.chooseDiscountItem.reduceAmount)[1] }}
                      </view>
                    </view>
                  </view>

                  <view
                    v-if="shopCartItemDiscount.chooseComboItemVo"
                    class="discount-tips"
                    :hidden="!shopCartItemDiscount.chooseComboItemVo"
                  >
                    <text class="text-block">
                      套餐
                    </text>
                    <text class="text-list">
                      {{ shopCartItemDiscount.chooseComboItemVo.name }}
                    </text>
                    <text class="reduce-amount">
                      已优惠 ￥{{ (shopCartItemDiscount.chooseComboItemVo.preferentialAmount / 100).toFixed(2) }}
                    </text>
                  </view>

                  <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 class="info-top">
                            <!-- 商品名称和价格 -->
                            <view class="info-item">
                              <view class="name">
                                {{ shopCartItem.spuName }}
                              </view>
                            </view>
                            <!-- 商品信息 -->
                            <view class="sku">
                              <view class="sku-act-info">
                                <view class="sku-text">
                                  {{ shopCartItem.skuName || '' }}
                                </view>
                                <view class="act-or-pre">
                                  <view
                                    v-if="orderType==orderTypeConstant.GROUP || orderType==orderTypeConstant.SECOND"
                                    class="activity-logo"
                                  >
                                    {{ orderType == orderTypeConstant.GROUP ? '拼团' : '秒杀' }}
                                  </view>
                                  <!-- 预售 -->
                                  <view
                                    v-if="shopCartItem.preSaleType === 1 || shopCartItem.preSaleType === 0"
                                    class="presale-logo"
                                  >
                                    <view class="activity-logo logo">
                                      预售
                                    </view>
                                    <view v-if="shopCartItem.preSaleDeliveryType !== -1">
                                      {{
                                        ['付款成功后', '尾款支付'][shopCartItem.preSaleType] + shopCartItem.preSaleDeliveryType + "天开始发货"
                                      }}
                                    </view>
                                    <view v-else>
                                      {{ moment(shopCartItem.preSaleDeliveryTime).format('M[月]D[日]') }} 开始发货
                                    </view>
                                  </view>
                                </view>
                              </view>
                            </view>
                          </view>

                          <view class="price-box">
                            <view class="price">
                              <text class="symbol">
                                ￥
                              </text>
                              <text class="big">
                                {{ wxs.parsePrice(shopCartItem.matchingPrice || shopCartItem.skuPriceFee)[0] }}
                              </text>
                              <text class="symbol">
                                .{{ wxs.parsePrice(shopCartItem.matchingPrice || shopCartItem.skuPriceFee)[1] }}
                              </text>
                            </view>
                            <view class="count">
                              ×{{ shopCartItem.count }}
                            </view>
                          </view>
                        </view>
                      </view>
                    </view>

                    <!-- 虚拟商品留言 start -->
                    <view
                      v-if="shopCartItem.virtualRemarkList && shopCartItem.virtualRemarkList.length"
                      class="virtual-goods-msg"
                    >
                      <view
                        v-for="(msgItem, msgIndex) in shopCartItem.virtualRemarkList"
                        :key="msgIndex"
                        class="v-msg-item"
                      >
                        <view class="v-msg-tit">
                          {{ msgItem.name }}
                          <text
                            v-if="msgItem.isRequired"
                            class="stress"
                          >
                            *
                          </text>
                        </view>
                        <view class="v-msg-con">
                          <input
                            v-model="msgItem.value"
                            class="v-msg-input"
                            placeholder-class="ph-class"
                            :placeholder="`请输入${msgItem.name}`"
                            maxlength="20"
                            @blur="handleInputBlur(msgItem.value, {
                              msgIndex: msgIndex,
                              prodIndex: index,
                              discIndex: shopCartItemDiscountIndex,
                              shopIndex: shopIndex
                            })"
                          >
                        </view>
                      </view>
                    </view>
                    <!-- 虚拟商品留言 end -->

                    <!-- 组合信息 -->
                    <view
                      v-if="shopCartItem.comboShopCartItems"
                      class="gift-con"
                    >
                      <view
                        v-for="(comboItem, comboIndex) in shopCartItem.comboShopCartItems"
                        :key="comboIndex"
                        class="gift-item"
                      >
                        <view class="gift-name">
                          【组合】{{ comboItem.spuName }}{{ comboItem.skuName ? (' ' + comboItem.skuName) : '' }}
                        </view>
                        <view class="gift-count">
                          ×{{ comboItem.count }}
                        </view>
                      </view>
                    </view>

                    <!-- 赠品信息 -->
                    <view
                      v-if="shopCartItem.giveawayShopCartItemList"
                      class="gift-con"
                    >
                      <view
                        v-for="(giveawayItem, giveawayIndex) in shopCartItem.giveawayShopCartItemList"
                        :key="giveawayIndex"
                        class="gift-item"
                      >
                        <view class="gift-name">
                          【赠品】{{ giveawayItem.spuName }}
                        </view>
                        <view class="gift-count">
                          ×{{ giveawayItem.count }}
                        </view>
                      </view>
                    </view>

                    <!-- 预售 -->
                    <view
                      v-if="preSaleType === 1"
                      class="presale-steps"
                    >
                      <steps
                        :active="0"
                        direction="column"
                        active-color="#000"
                        :options="[
                          {
                            title:'定金(待支付)',
                            desc: (totalDepositReduceAmount?
                              `(可抵￥${ wxs.parsePrice(totalDepositReduceAmount+shopCartItem.actualDepositAmount)[0]
                                +'.'+wxs.parsePrice(totalDepositReduceAmount+shopCartItem.actualDepositAmount)[1]})`:'')
                              +'￥'+ wxs.parsePrice(shopCartItem.actualDepositAmount)[0]+'.'+wxs.parsePrice(shopCartItem.actualDepositAmount)[1]
                          },
                          {
                            title:'尾款(未支付)',
                            desc:'￥'+wxs.parsePrice(shopCartItem.actualBalanceAmount)[0]+'.'+wxs.parsePrice(shopCartItem.actualBalanceAmount)[1]
                          }
                        ]"
                      />
                      <view
                        v-if="shopCartItem.balanceStartTime?(new Date(shopCartItem.balanceStartTime.replace(/-/g, '/')).getTime()>Date.now()):null"
                      >
                        {{ moment(shopCartItem.balanceStartTime).format('M[月]D[日] HH:mm:ss') }} 开始支付尾款
                      </view>
                      <view v-else-if="shopCartItem.balanceEndTime">
                        {{ moment(shopCartItem.balanceEndTime).format('M[月]D[日] HH:mm:ss') }} 尾款停止支付
                      </view>
                    </view>
                  </blockquote>
                </view>
              </view>
            </blockquote>
            <view
              v-if="dvyType === 2 && unUserPickUpList.length"
              class="un-user-pickup"
            >
              <view class="tips">
                以下商品不支持 到店自提，请选择其他配送方式
              </view>
              <view
                v-for="(prodItem,prodInx) in unUserPickUpList"
                :key="prodInx"
                class="img"
              >
                <img-show :src="prodItem.imgUrl" />
              </view>
            </view>
            <!-- 店铺优惠、留言、运费 -->
            <view class="msg-item">
              <view
                v-if="spuMold !== 1 && dvyType !== 2"
                class="item"
                @tap="showDistributionPopup(shopItem,shopIndex)"
              >
                <view class="item-tit">
                  配送服务
                </view>
                <view class="text-arrow a-rignt-6">
                  <view class="arrow-text-col">
                    <text v-if="shopItem.dvyType===1">
                      快递配送
                    </text>
                    <text v-else-if="shopItem.dvyType === 4">
                      同城配送
                    </text>
                  </view>
                </view>
              </view>
              <view
                v-if="spuMold !== 1 && shopItem.dvyType === 4"
                class="item"
              >
                <view class="item-tit">
                  起送费
                </view>
                <view class="price black">
                  <text class="symbol">
                    ￥
                  </text>
                  <text class="big-num">
                    {{ wxs.parsePrice(shopItem.startDeliveryFee)[0] }}
                  </text>
                  <text class="small-num">
                    .{{ wxs.parsePrice(shopItem.startDeliveryFee)[1] }}
                  </text>
                </view>
              </view>
              <view
                v-if="spuMold !== 1 && dvyType !== 2"
                class="item"
              >
                <view class="item-tit">
                  配送费用
                </view>
                <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
                v-if="preSaleType===1"
                class="item"
              >
                <view class="item-tit">
                  定金优惠金额
                </view>
                <view class="price black">
                  <text class="symbol">
                    ￥
                  </text>
                  <text class="big-num">
                    {{ wxs.parsePrice(totalDepositReduceAmount)[0] }}
                  </text>
                  <text class="small-num">
                    .{{ wxs.parsePrice(totalDepositReduceAmount)[1] }}
                  </text>
                </view>
              </view>
              <view
                v-if="!orderType"
                class="item"
                @tap="showCouponPopup(shopIndex)"
              >
                <view class="item-tit">
                  店铺优惠
                </view>
                <view class="number text-arrow a-rignt-6">
                  <view
                    v-if="!shopItem.shopCoupons.canUseLength"
                    class="text"
                  >
                    暂无可用
                  </view>
                  <view
                    v-if="shopItem.couponReduce"
                    class="price"
                  >
                    <text class="symbol">
                      -￥
                    </text>
                    <text class="big-num">
                      {{ wxs.parsePrice(shopItem.couponReduce)[0] }}
                    </text>
                    <text class="small-num">
                      .{{ wxs.parsePrice(shopItem.couponReduce)[1] }}
                    </text>
                  </view>
                  <view
                    v-if="shopItem.shopCoupons.canUseLength && !shopItem.couponReduce"
                    class="text"
                  >
                    {{ shopItem.shopCoupons.canUseLength }}张可用
                  </view>
                </view>
              </view>
              <view class="item">
                <view class="item-tit">
                  订单备注
                </view>
                <input
                  v-model="shopItem.remarks"
                  class="input text-arrow a-rignt-6"
                  placeholder="选填，给商家留言"
                >
              </view>
              <block v-if="shopItem.actualTotal">
                <view
                  v-if="!shopItem.invoiceDataFrom || shopItem.invoiceDataFrom.invoiceType === 2"
                  class="item"
                  @tap="showInvoicePopup(shopItem.shopId,shopItem.invoiceDataFrom)"
                >
                  <view class="item-tit">
                    开具发票
                  </view>
                  <view class="invoice-box text-arrow a-rignt-6 color9">
                    本次不开具发票
                  </view>
                </view>
                <view
                  v-else
                  class="item"
                  @tap="showInvoicePopup(shopItem.shopId,shopItem.invoiceDataFrom)"
                >
                  <view class="item-tit">
                    开具发票
                  </view>
                  <view class="invoice-box text-arrow a-rignt-6">
                    <view class="header-name">
                      电子(商品明细-
                    </view>
                    <view class="header-name">
                      {{ shopItem.invoiceDataFrom.headerName || '个人' }}
                    </view>
                    <view class="header-name">
                      )
                    </view>
                  </view>
                </view>
              </block>
            </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
          v-if="!orderType"
          class="item"
          @tap="showCouponPopup(-1)"
        >
          <view class="item-tit">
            平台优惠
          </view>
          <view class="number text-arrow a-rignt-6">
            <view
              v-if="platformCoupons&&platformCoupons.couponAmount"
              class="price"
            >
              <text class="symbol">
                -￥
              </text>
              <text class="big-num">
                {{ wxs.parsePrice(platformCoupons.couponAmount)[0] }}
              </text>
              <text class="small-num">
                .{{ wxs.parsePrice(platformCoupons.couponAmount)[1] }}
              </text>
            </view>
            <view
              v-if="platformCoupons&&!platformCoupons.canUseCoupons.length"
              class="text"
            >
              暂无可用
            </view>
            <view
              v-if="platformCoupons&&!platformCoupons.couponAmount && platformCoupons.canUseCoupons.length"
              class="text"
            >
              {{ platformCoupons.canUseCoupons.length }} 张可用
            </view>
          </view>
        </view>

        <!-- 会员积分 -->
        <view
          v-if="!orderType && maxUsableScore && preSaleType!==1 "
          class="item"
          @tap="showIntegralPopup"
        >
          <view class="item-tit">
            积分抵扣
          </view>
          <view class="number score-box">
            <blockquote v-if="totalScoreAmount">
              <text class="text">
                {{ usableScore > maxUsableScore ? maxUsableScore : usableScore }}积分抵
              </text>
              <text class="text">
                ￥{{ wxs.parsePrice(totalScoreAmount)[0] }}
              </text>
              <text class="text u-score-text">
                .{{ wxs.parsePrice(totalScoreAmount)[1] }}
              </text>
            </blockquote>
            <text
              v-else
              class="text u-score-text"
            >
              不使用积分抵扣
            </text>
            <view :class="['score-flag',isScorePay === 1?'check':'']" />
          </view>
        </view>

        <!-- 商品总价 -->
        <view class="item">
          <view class="item-tit">
            商品总价
          </view>
          <view class="price black">
            <text class="symbol">
              ￥
            </text>
            <text class="big-num">
              {{ wxs.parsePrice(total)[0] }}
            </text>
            <text class="small-num">
              .{{ wxs.parsePrice(total)[1] }}
            </text>
          </view>
        </view>

        <!-- 运费 -->
        <view
          v-if="spuMold !== 1 && dvyType!==2"
          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="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')&&orderReduce>0"
          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">
          <blockquote v-if="preSaleType===1">
            <view class="total">
              <view class="text">
                定金：
              </view>
              <view class="price">
                <text class="symbol">
                  ￥
                </text>
                <text class="big">
                  {{ wxs.parsePrice(totalDepositAmount)[0] }}
                </text>
                <text class="symbol">
                  .{{ wxs.parsePrice(totalDepositAmount)[1] }}
                </text>
              </view>
            </view>
          </blockquote>
          <blockquote v-else>
            <view class="total">
              <view class="text">
                合计：
              </view>
              <view class="price">
                <text class="symbol">
                  ￥
                </text>
                <text class="big">
                  {{ wxs.parsePrice(actualTotal)[0] }}
                </text>
                <text class="symbol">
                  .{{ wxs.parsePrice(actualTotal)[1] }}
                </text>
                <text v-if="usableScore > 0">
                  +
                </text>
                <text
                  v-if="usableScore > 0"
                  class="big"
                >
                  {{ usableScore > maxUsableScore ? maxUsableScore : usableScore }}
                </text>
                <text
                  v-if="usableScore > 0"
                  class="symbol"
                >
                  积分
                </text>
              </view>
            </view>
          </blockquote>
        </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"
          @change="distributionChange"
        >
          <label class="address-item">
            <view class="text-box">
              <view class="address">快递配送</view>
            </view>
            <radio
              color="#fc1b35"
              :checked="curShopDvyType === 1"
              value="1"
            />
          </label>
          <label
            v-if="isHasCityDelivery"
            class="address-item"
          >
            <view class="text-box">
              <view class="address">同城配送</view>
            </view>
            <radio
              color="#fc1b35"
              :checked="curShopDvyType === 4"
              value="4"
            />
          </label>
        </radio-group>
        <view class="btn-box">
          <view
            class="btn"
            @tap="confirmDistribution"
          >
            确定
          </view>
        </view>
      </view>
    </view>

    <!-- 新建收货地址弹窗 -->
    <view
      class="popup"
      :class="{ show: isEditAddress }"
    >
      <view
        class="popup-mask"
        @tap="closePopup"
      />
      <view class="popup-con-bottom check-address add-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="content-wrap">
          <!-- 表单内容 -->
          <view class="addr-item-wrap">
            <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.trim()"
                  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.trim()"
                  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 addr-detail-placeholder"
                    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.trim()"
                  class="error-text"
                >
                  请填写详细地址
                </view>
              </view>
            </view>
          </view>
          <!-- 保存按钮 -->
          <view
            class="btn-box"
            :style="showPicker?'z-index:0;':''"
          >
            <view
              class="btn"
              @tap="saveAndUse"
            >
              保存
            </view>
          </view>
        </view>
      </view>
    </view>

    <view
      class="popup"
      :class="{ 'show': isShowCouponPopup }"
    >
      <view
        class="popup-mask"
        @tap="closePopup"
      />
      <view class="popup-con-bottom check-coupon">
        <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="con-box">
          <view class="coupon-tit">
            <text class="tit-text">
              可用优惠券
            </text>
            <text class="tit-des">
              （已领取且满足该商品）
            </text>
          </view>
          <CouponCheck
            v-for="(canUseItem, canUseIndex) in showCoupons.canUseCoupons"
            :key="canUseIndex"
            :item="canUseItem"
            :index="canUseIndex"
            :is-plat="isPlat"
            :can-use="isCanUse"
            @check-coupon="checkCoupon"
          />
          <!-- 空 -->
          <view
            v-if="!showCoupons.canUseCoupons.length"
            class="empty"
            style="padding: 20rpx 0;"
          >
            <view
              class="text"
              style="text-align:left;"
            >
              暂无可用优惠券
            </view>
          </view>
          <view class="coupon-tit">
            <text class="tit-text">
              不可用优惠券
            </text>
            <text class="tit-des">
              （已领取但不满足当前商品）
            </text>
          </view>
          <view
            v-if="!showCoupons.unCanUseCoupons.length"
            class="empty"
            style="padding: 20rpx 0;"
          >
            <view
              class="text"
              style="text-align:left;"
            >
              暂无优惠券
            </view>
          </view>
          <coupon-check
            v-for="(unCanUseItem, unCanUseIndex) in showCoupons.unCanUseCoupons"
            :key="'un'+unCanUseIndex"
            :item="unCanUseItem"
            :is-plat="isPlat"
            :can-use="!isCanUse"
          />
        </view>
        <view class="btn-box">
          <view
            class="btn"
            @tap="choosedCoupon"
          >
            确定
          </view>
        </view>
      </view>
    </view>

    <!-- 查看留言（虚拟商品） -->
    <view
      class="popup"
      :class="{ 'show': showViewMsg }"
    >
      <view
        class="popup-mask"
        @tap="closePopup"
      />
      <view class="popup-con-bottom check-coupon">
        <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="con-box">
          <view class="coupon-tit">
            <view
              v-for="(item, index) in virtualRemarkList"
              :key="index"
              class="msg-item"
            >
              <view class="tit-text">
                {{ item.name }}
              </view>
              <view class="tit-des">
                {{ item.value }}
              </view>
            </view>
          </view>
        </view>
        <view class="btn-box">
          <view
            class="btn"
            @tap="choosedCoupon"
          >
            我知道了
          </view>
        </view>
      </view>
    </view>

    <!-- 预售定金不退款协议 -->
    <view
      v-if="preSaleType === 1"
      class="presaleAgreement"
    >
      <label class="radio">
        <radio
          color="#fc1b35"
          :checked="presaleAgreement"
          @click="presaleAgreement=!presaleAgreement"
        > 我同意预售商品定金不退协议
          <view
            class="warn-icon"
            @tap.stop="presaleAgreementTip"
          >
            !
          </view>
        </radio>
      </label>
    </view>

    <!-- 积分抵扣弹窗 -->
    <view
      class="popup"
      :class="{ show: isShowIntegralPopup }"
    >
      <view
        class="popup-mask"
        @tap="closePopupHide"
      />
      <view class="popup-con-bottom use-integral">
        <view class="popup-tit">
          <view class="tit-text">
            积分抵扣
          </view>
          <view
            class="close"
            @tap="closePopupHide"
          >
            <image src="@/package-user/static/images/icon_close.png" />
          </view>
        </view>
        <view class="con-box-min">
          <view class="my-integral">
            <view class="number">
              我的积分：
              <text class="bold">
                {{ userHasScore }}
              </text>
            </view>
            <view
              v-if="totalScoreAmount"
              class="used"
            >
              已抵扣：
              <text class="price">
                ￥
                <text class="big-num">
                  {{ wxs.parsePrice(totalScoreAmount)[0] }}
                </text>
                <text class="small-num">
                  .{{ wxs.parsePrice(totalScoreAmount)[1] }}
                </text>
              </text>
            </view>
            <view
              class="not-use"
              @tap="dontUseScore"
            >
              不使用积分抵扣
            </view>
          </view>
          <input
            v-model="userUseScore"
            class="input"
            type="number"
            :placeholder="`请输入积分数量，最多可用 ${maxUsableScore} 积分`"
            @input="inputUserUseScore"
          >
        </view>
        <view class="btn-box">
          <view
            class="btn"
            @tap="useScoreConfirm"
          >
            确定
          </view>
        </view>
      </view>
    </view>
    <!-- 区域没有门店弹窗 -->
    <view
      class="popup"
      :class="{ show: isShowNotStationPopup }"
    >
      <view
        class="popup-mask"
        @tap="closePopup"
      />
      <view class="popup-con-bottom">
        <view class="not-search-empty">
          <view
            class="close"
            @tap="closePopup"
          >
            <image src="@/package-user/static/images/icon_close_gray.png" />
          </view>
          <view class="img">
            <image
              src="@/static/empty-img/search-empty.png"
              mode="aspectFit"
            />
          </view>
          <text class="ntxt">
            {{ stationInfo.stationStockStatus === 1 ? '当前区域暂无库存' : '当前区域暂无门店' }}
          </text>
        </view>
        <view class="btn-box">
          <view
            class="btn"
            @tap="closePopup"
          >
            我知道了
          </view>
        </view>
      </view>
    </view>

    <!-- 确认弹窗 -->
    <confirm-pop
      :class="{showPop:!showPop}"
      :show-pop="showPop"
      :pop-content="popContent"
      :show-cancel="false"
      @handle-pop-confirm="popConfirm"
    />

    <invoice-edit
      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 * as locTrans from '@/utils/locTrans'
import { ProdType } from '@/utils/constant'
import invoiceEdit from '@/package-user/components/invoice-edit/index.vue'
import CouponCheck from '@/package-user/components/coupon-check/index.vue'
import moment from 'moment'
import shopStoreIcon from '@/package-user/static/images/shop-store-icon.png'

const wxs = number()

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

const isCanUse = ref(true)
const invoiceId = ref('') // 发票id

// 留言（虚拟商品）
const virtualRemarkList = ref([])

// orderEntry 1为立即购买,否则为从购物车提交
let orderEntry = ''
let seckillOrderPath = 0
const isEditAddress = ref(false) // 编辑地址
// 1 虚拟商品
const spuMold = ref('')
// 当前订单选择的地址id
let addrId = 0
// 当前订单选择的用户地址
const userAddr = ref({})
let dvyTypes = [] // 各店铺的配送方式
// 凑团的团队id
let groupTeamId = 0
// 订单类型
const orderType = ref('')
// 配送类型 1:快递 2:自提 3：无需快递 4.同城配送
const dvyType = ref(1)
let deliveryType = 1
/**
 * 生命周期函数--监听页面加载
 */
onLoad((options) => {
  const savePageInfo = uni.getStorageSync('cloudSavePageInfo')
  orderEntry = options.orderEntry || savePageInfo.orderEntry
  orderType.value = options.orderType || ''
  groupTeamId = options.groupTeamId || savePageInfo.groupTeamId || 0
  seckillOrderPath = options.seckillOrderPath || savePageInfo.seckillOrderPath || ''
  isEditAddress.value = savePageInfo.isEditAddress || false
  spuMold.value = Number(options.spuMold)
  if (savePageInfo.dvyType) {
    deliveryType = Number(savePageInfo.dvyType)
  } else {
    deliveryType = Number(options.deliveryType) || 1
  }
  if (deliveryType === 2) {
    isUserPickUp.value = true
    dvyType.value = 2
  }

  // 是否前往编辑定位的id
  const editLocationAddrId = uni.getStorageSync('cloudLocationAddrId')
  if (editLocationAddrId) {
    addrId = editLocationAddrId
    uni.removeStorageSync('cloudLocationAddrId')
  } else {
    // 是否已选择的可配送地址
    const deliveryAddrInfo = uni.getStorageSync('cloudDeliveryAddrInfo')
    if (deliveryAddrInfo) {
      addrId = deliveryAddrInfo.addrId
      userAddr.value = deliveryAddrInfo
    } else {
      // 获取用户地址列表
      getAddressList()
    }
  }

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

  const shopCartItem = uni.getStorageSync('cloudShopCartItem') ? JSON.parse(uni.getStorageSync('cloudShopCartItem')) : {}
  // 各店铺的配送方式
  const dvyTypesPar = uni.getStorageSync('cloudDvyTypes')
  dvyTypes = []
  if (dvyTypesPar) {
    dvyTypes = dvyTypesPar
  } else {
    if (orderEntry === '1') {
      dvyTypes = [{ shopId: shopCartItem.shopId, dvyType: deliveryType }]
    } else {
      const selectedShopIds = uni.getStorageSync('cloudSelectedShopIds')
      if (selectedShopIds) {
        selectedShopIds.forEach(shopId => {
          dvyTypes.push({ shopId, dvyType: 1 })
        })
      }
    }
  }
  if (!savePageInfo) uni.removeStorageSync('cloudSelStationInfo')
  // 加载订单
  if (deliveryType !== 2) {
    loadOrder(true)
  } else {
    // 获取当前位置信息
    // #ifdef APP-PLUS
    util.getUserAuth(getCurrentLocation)
    // #endif
    // #ifndef APP-PLUS
    getCurrentLocation()
    // #endif
  }
})

// 自提点信息
// stationStockStatus：自提门店状态 0: 没有门店 1:门店没有库存 2:库存充足
const stationInfo = reactive({
  selStationItem: {},
  userInfo: {},
  stationStockStatus: 0
})

const isGetStationLoaded = ref(false)
const isHaveStation = ref(false) // 该商家是否拥有门店
/**
 * 生命周期函数--监听页面显示
 */
onShow(() => {
  uni.removeStorageSync('cloudSavePageInfo')
  // 切换收货地址
  const addrInfo = uni.getStorageSync('cloudStationAddress')
  if (addrInfo) {
    addrId = addrInfo.addrId
    userAddr.value = addrInfo
    loadOrder()
    uni.removeStorageSync('cloudStationAddress')
  }
  // 选取自提点
  const stationInfoPar = uni.getStorageSync('cloudSelStationInfo')
  if (stationInfoPar) {
    stationInfo.selStationItem = stationInfoPar.selStationItem
    stationInfo.userInfo = stationInfoPar.userInfo
    stationInfo.stationStockStatus = stationInfoPar.stationStockStatus
    loadOrder()
    isGetStationLoaded.value = true
    if (stationInfo.selStationItem?.stationId) {
      isHaveStation.value = true
    }
  }
  if (uni.getStorageSync('cloudIsHaveStation')) {
    isHaveStation.value = uni.getStorageSync('cloudIsHaveStation')
    uni.removeStorageSync('cloudIsHaveStation')
  }
  // 是否前往编辑定位的id
  const editLocationAddrId = uni.getStorageSync('cloudLocationAddrId')
  if (editLocationAddrId) {
    addrId = editLocationAddrId
    loadOrder()
  }
  uni.removeStorageSync('cloudMsgList')
  uni.removeStorageSync('cloudDvyTypes')
  uni.removeStorageSync('cloudLocationAddrId')
})

/**
 * 生命周期函数--监听页面卸载
 */
onUnload(() => {
  if (spuMold.value === 1) {
    // 清除虚拟商品留言缓存
    uni.removeStorageSync('virtualRemark')
  }
})

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

// 保存页面操作内容
const saveInfo = () => {
  const savePageInfo = {
    groupTeamId,
    seckillOrderPath,
    orderEntry,
    isEditAddress: isEditAddress.value,
    dvyType: dvyType.value
  }
  uni.setStorageSync('cloudSavePageInfo', savePageInfo)
  uni.setStorageSync('cloudDvyTypes', dvyTypes)
}

// 当前商家的配送服务
const curShopDvyType = ref(1)
const distributionChange = (e) => {
  curShopDvyType.value = +e.detail.value
}

const isShowDistributionPopup = ref(false) // 选择配送方式弹窗
// 每个店铺的订单信息
const shopCartOrders = ref([])
let curShopIndex = 0
const confirmDistribution = () => {
  isShowDistributionPopup.value = false
  shopCartOrders.value[curShopIndex].dvyType = curShopDvyType.value
  dvyTypes[curShopIndex].dvyType = curShopDvyType.value
  loadOrder()
}

// 地址列表
const mobile = ref('')
const consignee = 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 = 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, 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 = encodeURIComponent(`${import.meta.env.VITE_APP_DOMAIN_ADDRESS}/${curRoute}?orderEntry=${orderEntry}&orderType=${orderType.value}${groupTeamId ? '&groupTeamId=' + groupTeamId : ''}${seckillOrderPath ? '&seckillOrderPath=' + seckillOrderPath : ''}`)
  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
}

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

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

  util.area(addr.value, addressName).then(res => {
    if (res.length === 0) {
      // #ifdef H5 || APP-PLUS
      addr.value = loc.poiaddress
      addressName = loc.poiname
      // #endif

      // #ifdef MP-WEIXIN
      addr.value = loc.address // 详细地址
      addressName = loc.name // 详细地址
      // #endif
      return
    }
    addr.value = addr.value.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 stationChange = (e) => {
  // 切换配送方式时，重置积分抵扣
  userUseScore.value = ''
  isScorePay.value = 0

  if (e.detail.value) {
    dvyType.value = 2 // 自提
    dvyTypes[0].dvyType = dvyType.value
    // 获取当前位置信息
    // #ifdef APP-PLUS
    util.getUserAuth(getCurrentLocation)
    // #endif
    // #ifndef APP-PLUS
    getCurrentLocation()
    // #endif
  } else {
    dvyType.value = 1 // 普通快递
    dvyTypes[0].dvyType = dvyType.value
    loadOrder()
  }
}

// 输入的积分数量
const userUseScore = ref('')
// 该订单最大可用积分数量
const maxUsableScore = ref(0)
// 是否使用积分抵扣 默认否
const isScorePay = ref(0)
const isShowIntegralPopup = ref(false) // 积分抵扣弹窗
/**
 * 积分弹窗底部确定按钮
 */
const useScoreConfirm = () => {
  if (Number(userUseScore.value) > maxUsableScore.value) {
    uni.showToast({
      title: `该订单最多可使用 ${maxUsableScore.value} 积分，请重新输入`,
      duration: 2000,
      mask: true,
      icon: 'none'
    })
    return
  }
  if (!userUseScore.value.trim() || Number(userUseScore.value) < 0) {
    uni.showToast({
      title: '请输入正确的积分数量',
      duration: 2000,
      mask: true,
      icon: 'none'
    })
    return
  }
  isScorePay.value = 1
  loadOrder()
  isShowIntegralPopup.value = false
}

/**
 * 不使用积分抵扣
 */
const dontUseScore = () => {
  if (!isScorePay.value) {
    isShowIntegralPopup.value = false
    return
  }
  isScorePay.value = 0
  userUseScore.value = ''
  loadOrder()
  isShowIntegralPopup.value = false
}

const showPop = ref(false)
/**
 * 弹窗确认
 */
const popConfirm = () => {
  showPop.value = false
  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: '/mall4cloud_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 getAddressList = (reload) => {
  http.request({
    url: '/mall4cloud_user/user_addr/list',
    method: 'GET',
    data: {}
  }).then((res) => {
    if (reload) {
      for (const addrPar of res) {
        if (addrPar.isDefault) {
          addrId = addrPar.addrId
          break
        }
      }
      loadOrder()
    } else {
      for (const addrPar of res) {
        if (addrPar.isDefault) {
          userAddr.value = addrPar
          addrId = addrPar.addrId
          break
        }
      }
    }
  })
}

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

let allVirtualMsg = []
/**
 * 虚拟商品留言
 */
const handleAllVirtualMsg = () => {
  const arr1 = getValueOfArr(shopCartOrders.value, ['shopCartItemDiscounts', 'shopCartItems', 'virtualRemarkList'])
  // 存在组合商品的情况下，从comboShopCartItems中提取虚拟商品留言信息
  const arr2 = getValueOfArr(shopCartOrders.value, ['shopCartItemDiscounts', 'shopCartItems', 'comboShopCartItems', 'virtualRemarkList'])
  allVirtualMsg = arr1.concat(arr2)
  if (uni.getStorageSync('cloudMsgList')) {
    const list = JSON.parse(uni.getStorageSync('cloudMsgList'))
    allVirtualMsg.forEach((msgItem, index) => {
      if (list[index].id === msgItem.id && !msgItem.value) {
        msgItem.value = list[index].value
      }
    })
  }
}

const getValueOfArr = (data, layers) => {
  const deepGet = (item, index) => {
    return item.map(la => {
      const children = la[layers[index]]
      if (Array.isArray(children)) {
        if (layers.length === index + 1) {
          return children.map((ch, idx) => {
            ch.id = la.skuId + '_' + idx
            return ch
          })
        }
        return deepGet(children, index + 1)
      }
      return []
    }).flat(Infinity)
  }
  return deepGet(data, 0)
}

/**
 * 虚拟商品留言输入框失焦
 * 每次失焦就将该文本框的内容同步到allVirtualMsg
 */
const handleInputBlur = (value, arrIndex) => {
  const { msgIndex, prodIndex, discIndex, shopIndex, comboIndex } = arrIndex
  if (!value) {
    return
  }
  let currentItem = {}
  if (comboIndex !== null) {
    currentItem = shopCartOrders.value[shopIndex].shopCartItemDiscounts[discIndex].shopCartItems[prodIndex].comboShopCartItems[comboIndex].virtualRemarkList[msgIndex]
  } else {
    currentItem = shopCartOrders.value[shopIndex].shopCartItemDiscounts[discIndex].shopCartItems[prodIndex].virtualRemarkList[msgIndex]
  }
  allVirtualMsg.forEach(msgItem => {
    if (currentItem.id === msgItem.id) {
      msgItem.value = value
    }
  })
  uni.setStorageSync('cloudMsgList', JSON.stringify(allVirtualMsg))
}

// 选中的优惠券id列表
let couponIds = []
let isShowGeneralCouponPopup = false // 平台券弹窗
// 店铺优惠券
const showCoupons = reactive({
  canUseCoupons: [],
  unCanUseCoupons: []
})
// 平台券
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
}

/**
 * 确定选择好的优惠券
 */
const choosedCoupon = () => {
  const showCouponsPar = isShowGeneralCouponPopup ? platformCoupons : showCoupons
  if (!showCouponsPar) {
    return
  }
  const canUseCoupons = showCouponsPar.canUseCoupons
  let checkedCouponId = ''
  for (const canUseCouponIndex in canUseCoupons) {
    const coupon = canUseCoupons[canUseCouponIndex]
    if (!coupon.choose && couponIds.indexOf(coupon.couponId) !== -1) {
      couponIds.splice(couponIds.indexOf(coupon.couponId), 1)
    }
    if (coupon.choose) {
      checkedCouponId = coupon.couponId
    }
  }
  couponIds.push(checkedCouponId)
  closePopup()
  loadOrder()
}

// 用户是否改变了优惠券的选择: 1是; 0否
let userChangeCoupon = 0
/**
 * 优惠券子组件发过来
 */
const checkCoupon = (e) => {
  const showCouponsPar = isShowGeneralCouponPopup ? platformCoupons : showCoupons

  for (let i = 0; i < showCouponsPar.canUseCoupons.length; i++) {
    if (e.couponId === showCouponsPar.canUseCoupons[i].couponId && i === e.index) {
      showCouponsPar.canUseCoupons[i].choose = !showCouponsPar.canUseCoupons[i].choose
    } else {
      showCouponsPar.canUseCoupons[i].choose = false
    }
  }
  showCoupons.canUseCoupons = showCouponsPar.canUseCoupons
  showCoupons.unCanUseCoupons = showCouponsPar.unCanUseCoupons
  userChangeCoupon = 1
}

/**
 * 分割优惠券成
 * 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
  }
}

const unUserPickUpList = ref([]) // 不可自提的商品
const isUserPickUp = ref(false) // 是否自提
// 不满足收货地址的商品
const unmeetAddrProdList = ref([])
const isAllUnmeet = ref(false) // 是否全部为不满足地址的商品
// 订单优惠金额(所有店铺优惠金额)
const orderReduce = ref(0)
const orderShopReduce = ref(0) // 店铺优惠
const totalTransfee = ref(0)
const totalLevelAmount = ref(0)
const totalScoreAmount = ref(0)
const usableScore = ref(0) // 使用的积分
const userHasScore = ref(0)
const total = ref(0)
const actualTotal = ref(0)
const preSaleType = ref(0) // 预售类型 0.全款预售类型 1.定金预售
const totalDepositReduceAmount = ref(0)
const totalDepositAmount = ref(0)
// 运费减免
const freeTransfee = ref('')
const isDelivery = ref(true) // 当前地址是否可配送
const { proxy } = getCurrentInstance()
/**
 * 加载订单数据
 */
// eslint-disable-next-line max-lines-per-function
const loadOrder = (isFirst = false) => {
  isGetStationLoaded.value = false
  dvyTypes = dvyTypes.map(item => {
    const obj = item
    obj.lat = item.dvyType === 2 ? lat : null
    obj.lng = item.dvyType === 2 ? lng : null
    obj.stationId = item.dvyType === 2 ? (stationInfo.selStationItem?.stationId || null) : null
    return obj
  })
  const shopCartItem = uni.getStorageSync('cloudShopCartItem') ? JSON.parse(uni.getStorageSync('cloudShopCartItem')) : {}
  const params = {
    url: orderType.value === '1' ? '/mall4cloud_group/group_order/confirm' : orderType.value === '2' ? `/mall4cloud_seckill/seckill_order/${seckillOrderPath}/confirm` : '/mall4cloud_order/order/confirm',
    method: 'POST',
    data: {
      addrId: addrId || 0,
      dvyTypes,
      groupSkuId: shopCartItem.groupSkuId || undefined,
      seckillId: shopCartItem.seckillId || undefined,
      seckillSkuId: shopCartItem.seckillSkuId || undefined,
      shopCartItem: orderEntry === '1' ? shopCartItem : undefined,
      couponIds,
      distributionUserId: shopCartItem.distributionUserId || undefined,
      userChangeCoupon,
      isScorePay: isScorePay.value,
      userUseScore: Number(userUseScore.value)
    }
  }
  http.request(params).then((res) => {
    if (res.orderSelfStation?.stationStockStatus) {
      stationInfo.stationStockStatus = res.orderSelfStation.stationStockStatus
    }
    if (res.orderSelfStation?.stationId && res.orderSelfStation.stationName) {
      stationInfo.selStationItem = {
        stationId: res.orderSelfStation.stationId,
        stationName: res.orderSelfStation.stationName,
        imgUrl: res.orderSelfStation.stationImgUrl,
        stationType: res.orderSelfStation.stationType,
        hasStock: res.stationStockStatus === 2 ? 1 : 0
      }
      stationInfo.userInfo = {
        name: userAddr.value.consignee,
        userMobile: userAddr.value.mobile
      }
      uni.setStorageSync('cloudSelStationInfo', stationInfo)

      isGetStationLoaded.value = true
      isHaveStation.value = res.stationStockStatus !== 0
    } else if (!stationInfo.selStationItem.stationId) {
      isGetStationLoaded.value = true
      isHaveStation.value = false
    }
    isGetStationLoaded.value = true

    const shopCartOrdersPar = res.shopCartOrders || []
    const couponIdsPar = []
    const remarksList = []
    if (!isFirst) {
      shopCartOrders.value.forEach(el => {
        remarksList.push(el.remarks)
      })
    }

    // 是否可选择自提 (单店铺结算时才需要)
    if (shopCartOrdersPar.length === 1) {
      unUserPickUpList.value = []
      isUserPickUp.value = true
      for (const shopCart of shopCartOrdersPar) {
        for (const shopCartItemDiscount of shopCart.shopCartItemDiscounts) {
          for (const prodItem of shopCartItemDiscount.shopCartItems) {
            // 虚拟商品无需配送
            if (prodItem.spuMold === 1) {
              continue
            }
            // 如果是套餐商品, 需要所有商品都包含自提才能切换
            if (prodItem.comboId) {
              // eslint-disable-next-line max-depth
              if (!prodItem.deliveryModeBO.hasUserPickUp && prodItem.mold !== 1) {
                isUserPickUp.value = false
                break
              }
            } else {
              // eslint-disable-next-line max-depth
              if (prodItem.deliveryModeBO.hasUserPickUp) {
                isUserPickUp.value = true
                break
              } else {
                isUserPickUp.value = false
              }
            }
          }
        }
      }
      // 当前配送类型
      if (isFirst) {
        dvyType.value = deliveryType
      } else {
        dvyType.value = res.dvyTypes[0].dvyType
      }
      if (dvyType.value === 4) curShopDvyType.value = 4
    }
    unmeetAddrProdList.value = []
    unUserPickUpList.value = []
    if (dvyType.value === 2) {
      unUserPickUpList.value = res.filterShopItems
    } else {
      // 当前地址不可配送的商品
      unmeetAddrProdList.value = res.filterShopItems
    }
    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]
      }
      shopCart.coupons?.forEach(couponItem => {
        couponItem.shopName = shopCart.shopName
      })
      shopCart.shopCoupons = splitCouponAndPushCouponIds(shopCart.coupons, couponIdsPar)
      // 店铺配送方式
      shopCart.dvyType = (res.dvyTypes[index].dvyType === 1 && isFirst) ? deliveryType : res.dvyTypes[index].dvyType
    })
    // 平台优惠券
    const platformCouponsPar = splitCouponAndPushCouponIds(res.coupons, couponIdsPar)
    dvyTypes = res.dvyTypes
    couponIds = couponIdsPar
    shopCartOrders.value = shopCartOrdersPar
    isAllUnmeet.value = !shopCartOrders.value?.length
    setPlatformCoupons(platformCouponsPar)
    orderReduce.value = res.orderReduce
    orderShopReduce.value = res.orderShopReduce // 店铺优惠
    total.value = res.total
    actualTotal.value = res.actualTotal
    totalTransfee.value = res.totalTransfee
    totalLevelAmount.value = res.totalLevelAmount
    usableScore.value = res.usableScore
    totalScoreAmount.value = res.totalScoreAmount
    maxUsableScore.value = res.maxUsableScore > res.userHasScore ? res.userHasScore : res.maxUsableScore
    userHasScore.value = res.userHasScore
    isDelivery.value = res.isDelivery
    // 预售
    preSaleType.value = res.preSaleType
    totalDepositReduceAmount.value = res.totalDepositReduceAmount
    totalDepositAmount.value = res.totalDepositAmount
    // 平台开启会员包邮（运费减免）
    freeTransfee.value = res.freeTransfee
    spuMold.value = res.spuMold
    if (res.userAddr && spuMold.value !== 1) {
      userAddr.value = res.userAddr
      addrId = res.userAddr.addrId
      addrIds.value = [res.userAddr.provinceId, res.userAddr.cityId, res.userAddr.areaId]
    }
    proxy.$forceUpdate()

    getOrderSkuList()

    // 虚拟商品留言
    handleAllVirtualMsg()
    setOrderInvoice()
  }).catch((err) => {
    isGetStationLoaded.value = true
    errCallBackPop(err)
  })
}

// 位置信息
let locationInfo = null
/**
 * 获取当前地理位置
 */
const getCurrentLocation = () => {
  if (locationInfo && lng && lat) {
    confirmLocation(locationInfo)
  } else {
    const func = () => {
      isGetStationLoaded.value = false
      uni.getLocation({
        type: 'wgs84', // 默认为 wgs84 返回 gps 坐标，gcj02 返回国测局坐标，可用于 uni.openLocation 的坐标，app平台高德SDK仅支持返回gcj02
        altitude: true,
        isHighAccuracy: true,
        highAccuracyExpireTime: 3500,
        success: (res) => {
          if (res) {
            locationInfo = res
            confirmLocation(res)
          }
        },
        fail: () => {
          loadOrder()
          uni.showToast({
            title: '获取定位失败！',
            icon: 'none',
            duration: 1500
          })
        }
      })
    }
    // 处理公众号权限关闭
    // #ifdef MP-WEIXIN
    uni.authorize({
      scope: 'scope.userLocation',
      success () {
        func()
      },
      fail: () => {
        uni.showModal({
          title: '定位权限开启',
          content: '需要打开地理位置',
          showCancel: true,
          confirmText: '去开启',
          success: ({ confirm, cancel }) => {
            if (confirm) {
              uni.openSetting({
                success (res) {
                  if (res.authSetting['scope.userLocation']) {
                    func()
                  } else {
                    uni.showToast({
                      title: '权限开启失败',
                      icon: 'none',
                      duration: 1500
                    })
                    setTimeout(() => {
                      func()
                    }, 1600)
                  }
                }
              })
            } else if (cancel) {
              func()
            }
          }
        })
      }
    })
    // #endif
    // #ifndef MP-WEIXIN
    func()
    // #endif
  }
}

/**
 * 转换经纬度请求自提点列表
 */
const confirmLocation = (locationRes) => {
  let locationObj
  // #ifdef APP-PLUS || MP-WEIXIN
  locationObj = locTrans.gcj02tobd09(locTrans.wgs84togcj02(locationRes))
  // #endif

  // #ifdef H5
  locationObj = locTrans.gcj02tobd09(locationRes)
  // #endif

  lat = locationObj.latitude
  lng = locationObj.longitude

  loadOrder()
}

/**
 * 获取订单规格列表
 */
const getOrderSkuList = () => {
  const stationSpuList = []
  if (shopCartOrders.value?.length > 0) {
    shopCartOrders.value.forEach(order => {
      if (order.shopCartItemDiscounts?.length > 0) {
        order.shopCartItemDiscounts.forEach(discount => {
          if (discount.shopCartItems?.length > 0) {
            discount.shopCartItems.forEach(item => {
              if (item.mold === 2) {
                if (item.comboShopCartItems?.length > 0) {
                  item.comboShopCartItems.forEach(combo => {
                    const obj = {
                      skuId: combo.skuId,
                      count: combo.count
                    }
                    stationSpuList.push(obj)
                  })
                }
              } else {
                const obj = {
                  skuId: item.skuId,
                  count: item.count
                }
                stationSpuList.push(obj)
              }
            })
          }
        })
      }
    })
    // 将订单中所选的商品规格存入缓存
    uni.setStorageSync('orderSkuList', stationSpuList)
  }
}

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

// 选取自提点
const goSelStation = () => {
  if (isGetStationLoaded.value && !isHaveStation.value) {
    return
  }
  saveInfo() // 保存当前页面操作
  let state = 0
  if (stationInfo.selStationItem?.stationId) {
    uni.setStorageSync('cloudSelStationInfo', stationInfo)
    state = 1
  }
  const shopId = shopCartOrders.value[0].shopId
  //  重定向地址
  const fullPath = getCurrentPages()[getCurrentPages().length - 1].$page.fullPath
  uni.navigateTo({
    url: `/package-user/pages/select-store/select-store?shopId=${shopId}&addrId=${addrId}&orderEntry=${orderEntry}&state=${state}&redirect=${encodeURIComponent(fullPath)}`
  })
}

const isHasCityDelivery = ref(false) // 是否支持同城配送
// 选择配送方式弹窗
const showDistributionPopup = (shopItem, shopIndex) => {
  let cityDeliveryFlag = true
  // 是否可选同城配送 同城配送状态  1 可用 -1 不在范围内 -2 商家没有配置同城配送信息 -3 起送费不够
  if (shopItem.dvyType === 1) {
    if (dvyType.value === 2 || shopItem.shopCityStatus !== 1) {
      cityDeliveryFlag = false
    }
    // 检查当前店铺下的商品是否都支持同城
    if (cityDeliveryFlag) {
      for (const shopCartItemDiscount of shopItem.shopCartItemDiscounts) {
        for (const prodItem of shopCartItemDiscount.shopCartItems) {
          if (prodItem.spuMold !== 1 && prodItem.deliveryModeBO.hasCityDelivery) {
            cityDeliveryFlag = true
            break
          } else if (prodItem.spuMold !== 1 && !prodItem.deliveryModeBO.hasCityDelivery) {
            cityDeliveryFlag = false
          }
        }
      }
    }
  }
  isHasCityDelivery.value = cityDeliveryFlag
  isShowDistributionPopup.value = true
  curShopIndex = shopIndex
  curShopDvyType.value = shopItem.dvyType || 1
}

// 是否平台优惠券
const isPlat = ref(false)
const isShowCouponPopup = ref(false) // 优惠券弹窗
// 优惠券弹窗
const showCouponPopup = (shopIndex) => {
  const isPlatPar = shopIndex + '' === '-1'
  const showCouponsPar = isPlatPar ? platformCoupons : shopCartOrders.value[shopIndex].shopCoupons

  showCoupons.canUseCoupons = showCouponsPar.canUseCoupons
  showCoupons.unCanUseCoupons = showCouponsPar.unCanUseCoupons

  isPlat.value = isPlatPar
  isShowCouponPopup.value = true
}

// 积分抵扣弹窗
const showIntegralPopup = () => {
  isShowIntegralPopup.value = true
}

const isShowInvoicePopup = ref(false) // 发票弹窗
const isShowNotStationPopup = ref(false) // 区域没有门店的弹窗控制
// 查看留言弹窗显隐
const showViewMsg = ref(false)
// 关闭弹窗
const closePopup = () => {
  isShowDistributionPopup.value = false
  isShowCouponPopup.value = false
  isShowGeneralCouponPopup = false
  isShowIntegralPopup.value = false
  isShowInvoicePopup.value = false
  showViewMsg.value = false
  isEditAddress.value = false
  isShowNotStationPopup.value = false
}

const closePopupHide = () => {
  userUseScore.value = ''
  closePopup()
}

// 预售
const presaleAgreement = ref(false) // 预售不退款协议
// 去支付
const toPay = () => {
  if (isEditAddress.value && spuMold.value !== 1) {
    uni.showToast({
      title: '请完善地址信息',
      duration: 2000,
      mask: true,
      icon: 'none'
    })
    return
  }

  // 虚拟商品留言校验
  if (allVirtualMsg.length &&
    allVirtualMsg.find(el => el.value && !el.value.trim())) {
    uni.showToast({
      title: '留言不能全为空格',
      icon: 'none'
    })
    return
  }
  if (allVirtualMsg.length &&
    allVirtualMsg.find(el => el.isRequired && !el.value)) {
    uni.showToast({
      title: '请填写带*号的必填项留言',
      icon: 'none'
    })
    return
  }

  // 预售定金协议
  if (preSaleType.value === 1 && !presaleAgreement.value) {
    uni.showToast({
      title: '请了解并同意定金不退协议，否则无法提交订单',
      duration: 2000,
      icon: 'none'
    })
    return
  }

  if ((dvyType.value === 1) && !userAddr.value.addrId && spuMold.value !== 1) {
    uni.showToast({
      title: '请先添加收货地址',
      icon: 'none'
    })
    return
  }

  if (dvyType.value === 2 && !isHaveStation.value && spuMold.value !== 1) {
    isShowNotStationPopup.value = true
    return
  }

  if (dvyType.value === 2 && !stationInfo.selStationItem?.stationId && spuMold.value !== 1) {
    uni.showToast({
      title: '请选择提货地址',
      icon: 'none'
    })
    return
  }

  for (const dvy of dvyTypes) {
    if (dvy.dvyType === 4 && (!userAddr.value.lat || !userAddr.value.lng)) {
      const con = '当配送方式存在同城配送时，用户地址信息中需包含经纬度，请前往地址页面将已选地址经纬度补充完整'
      if (!userAddr.value.addrId) {
        uni.showToast({
          title: '请先添加收货地址',
          icon: 'none'
        })
      } else {
        uni.showModal({
          title: '提示',
          content: con,
          showCancel: false,
          confirmText: '确定',
          success: (res) => {
            if (res.confirm) {
              uni.setStorageSync('cloudLocationAddrId', userAddr.value.addrId)
              uni.setStorageSync('cloudDvyTypes', dvyTypes)
              uni.navigateTo({
                url: '/package-user/pages/edit-address/edit-address?addrId=' + userAddr.value.addrId
              })
            }
          }
        })
      }
      return
    }
  }
  submitOrder()
}

/**
 * 提交订单
 */
const submitOrder = () => {
  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 && item.actualTotal) {
      orderInvoiceList.push(item.invoiceDataFrom)
    }
  })
  if (orderInvoiceList.length === 0) {
    orderInvoiceList = null
  }
  // 虚拟商品留言
  allVirtualMsg.forEach(el => {
    el.id = undefined
  })
  const orderSelfStationDto = {}
  if (dvyType.value === 2) {
    orderSelfStationDto.stationId = stationInfo.selStationItem?.stationId
    orderSelfStationDto.stationUserName = stationInfo.userInfo?.name
    orderSelfStationDto.stationUserMobile = stationInfo.userInfo?.userMobile
  }
  uni.removeStorageSync('cloudMsgList')
  http.request({
    url: orderType.value === '1' ? '/mall4cloud_group/group_order/submit' : orderType.value === '2' ? `/mall4cloud_seckill/seckill_order/${seckillOrderPath}/submit` : '/mall4cloud_order/order/submit',
    method: 'POST',
    data: {
      orderSelfStationDto, // 自提信息
      groupTeamId: orderType.value === '1' ? groupTeamId : undefined,
      orderShopParam,
      orderInvoiceList,
      virtualRemarkList: allVirtualMsg
    },
    withoutPrompting: true
  }).then((res) => {
    orderSubmitSuccessCallBack(res)
  }).catch((err) => {
    errCallBackPop(err)
  })
}

const popContent = reactive({
  content: ''
})

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

/**
 * 订单请求错误弹窗回调
 */
const errCallBackPop = (errMsg) => {
  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
    } else {
      popContent.content = '请不要重复提交订单'
    }
    showPop.value = true
  }
}

const invoiceDataFrom = ref({})
const invoiceShopId = ref('')
// 发票信息弹窗
const showInvoicePopup = (shopId, invoiceDataFromPar) => {
  if (invoiceDataFromPar) {
    invoiceDataFrom.value = invoiceDataFromPar
  } else {
    invoiceDataFrom.value = {}
  }
  invoiceShopId.value = shopId
  isShowInvoicePopup.value = true
}

const invoiceDataList = []
const getInvoiceData = (data) => {
  // invoiceDataFrom
  let flag = false
  for (let i = 0; i < invoiceDataList.length; i++) {
    if (invoiceDataList[i].shopId === data.shopId) {
      flag = true
      if (data) {
        invoiceDataList[i] = data
      }
      break
    }
  }
  if (!flag && data) {
    invoiceDataList.push(data)
  }

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

const setOrderInvoice = () => {
  invoiceDataList.forEach((invoice) => {
    shopCartOrders.value.forEach((item) => {
      if (item.shopId === invoice.shopId) {
        item.invoiceDataFrom = invoice
      }
    })
  })
}

// 验证使用积分   为整数
const inputUserUseScore = (e) => {
  const value = e.detail.value
  const str = /^[1-9]\d*$/
  if (!str.test(value)) {
    nextTick(() => {
      userUseScore.value = ''
    })
  }
}

const presaleAgreementTip = () => {
  uni.showModal({
    title: '提示',
    content: '预售定金不退款',
    showCancel: false
  })
}

</script>
<style lang="scss" scoped>
@use "../../../popup";
</style>

<style lang="scss" scoped>
@use "submit-order";
</style>
