<template>
  <z-paging
    ref="paging"
    v-model="likeProdData"
    :refresher-enabled="false"
    :safe-area-inset-bottom="false"
    :paging-style="{'top': '0','background': '#f2f3f7'}"
    @query="onGetLikeProdList"
  >
    <view
      class="Mall4j page-cart"
      :class="{ 'edit-cart': isEditCart }"
    >
      <!-- 购物车头部 -->
      <view class="cart-top">
        <view
          class="address"
          @tap="toAddressList"
        >
          <view class="img">
            <image src="/static/images/local.png" />
          </view>
          <view class="text">
            配送至：{{ defaultAddrStr || '暂无地址' }}
          </view>
        </view>
        <view
          v-if="shopCarts.length || expiryProdList.length"
          class="edit"
          @tap="onEditCart"
        >
          {{ isEditCart ? '完成' : '编辑' }}
        </view>
      </view>
      <view class="cart-con">
        <view class="con-box">
          <block
            v-for="(shopItem, shopIndex) in shopCarts"
            :key="shopIndex"
          >
            <view class="shop-item">
              <!-- 店铺信息 -->
              <view class="shop-info">
                <checkbox
                  color="#fff"
                  :class="{'checked':shopItem.checked}"
                  :checked="shopItem.checked"
                  @tap="onHandleShopSelect(shopIndex)"
                />
                <view class="info">
                  <view class="icon">
                    <image src="/static/images/shop.png" />
                  </view>
                  <view
                    class="name text-arrow"
                    @tap="onToShopIndex(shopItem.shopId)"
                  >
                    {{ shopItem.shopName }}
                  </view>
                </view>
              </view>
              <!-- 商品 -->
              <block
                v-for="(shopCartItemDiscount, discountIndex) in shopItem.shopCartItemDiscounts"
                :key="discountIndex"
              >
                <view class="item-box">
                  <view :class="['prod-item', shopCartItemDiscount.chooseDiscountItem ? 'discount-prod' : '']">
                    <!-- 活动信息 -->
                    <view
                      v-if="shopCartItemDiscount.chooseDiscountItem"
                      class="discount-info"
                    >
                      <view class="d-name">
                        {{ shopCartItemDiscount.chooseDiscountItem.discountRule===0?'满减':'满折' }}
                      </view>
                      <view
                        v-if="shopCartItemDiscount.chooseDiscountItem.discountRule===0"
                        class="d-des"
                      >
                        满{{ wxs.parsePrice(shopCartItemDiscount.chooseDiscountItem.needAmount)[0] }}.{{ wxs.parsePrice(shopCartItemDiscount.chooseDiscountItem.needAmount)[1] }}元减{{ wxs.parsePrice(shopCartItemDiscount.chooseDiscountItem.discount)[0] }}.{{ wxs.parsePrice(shopCartItemDiscount.chooseDiscountItem.discount)[1] }}元
                      </view>
                      <view
                        v-else
                        class="d-des"
                      >
                        满{{ wxs.parsePrice(shopCartItemDiscount.chooseDiscountItem.needAmount)[0] }}件享{{ wxs.parsePrice(shopCartItemDiscount.chooseDiscountItem.discount)[0] }}.{{ wxs.parsePrice(shopCartItemDiscount.chooseDiscountItem.discount)[1] }}折
                      </view>
                      <view class="d-reduce">
                        <view
                          v-if="shopCartItemDiscount.chooseDiscountItem.reduceAmount"
                          class="d-reduce-amount"
                        >
                          活动优惠 ￥{{ wxs.parsePrice(shopCartItemDiscount.chooseDiscountItem.reduceAmount)[0] }}.{{ wxs.parsePrice(shopCartItemDiscount.chooseDiscountItem.reduceAmount)[1] }}
                        </view>
                        <view
                          v-else
                          class="d-button"
                          @tap="onToDiscountDetail(shopCartItemDiscount.chooseDiscountItem.discountId)"
                        >
                          <view>去凑单</view>
                          <image
                            class="img"
                            src="@/static/images/more.png"
                          />
                        </view>
                      </view>
                    </view>
                    <!-- 套装提示 -->
                    <view
                      v-if="shopCartItemDiscount.chooseComboItemVo"
                      class="discount-tips"
                    >
                      <view class="combo-item">
                        <text class="text-block">
                          套餐
                        </text>
                        <text class="text-list combo-name">
                          {{ shopCartItemDiscount.chooseComboItemVo.name }}
                        </text>
                      </view>
                      <view class="combo-item">
                        <text class="text-list reduce-amount">
                          已优惠￥{{ (shopCartItemDiscount.chooseComboItemVo.preferentialAmount/100).toFixed(2) }}
                        </text>
                      </view>
                    </view>
                    <!-- 产品信息 -->
                    <view
                      v-for="(prodItem, prodIndex) in shopCartItemDiscount.shopCartItems"
                      :key="prodIndex"
                      class="prod-box"
                    >
                      <view
                        class="prod-info-box"
                      >
                        <checkbox
                          color="#fff"
                          :class="['check',prodItem.comboId && prodItem.parentCartItemId!==null? 'hide' : '',prodItem.checked? 'checked' : '']"
                          :checked="prodItem.checked"
                          @tap.stop="onHandleProdItemSelect(shopIndex,discountIndex,prodIndex)"
                        />
                        <view class="prod-img">
                          <img-show
                            :src="prodItem.imgUrl"
                            img-mode="aspectFit"
                            @handle-tap="()=>onToProdDetail(prodItem.spuId)"
                          />
                        </view>
                        <view class="prod-info">
                          <view
                            class="name"
                            @tap="onToProdDetail(prodItem.spuId)"
                          >
                            {{ prodItem.spuName }}
                          </view>
                          <view class="sku-con">
                            <view
                              v-if="prodItem.skuName"
                              class="sku"
                              @tap.stop="onShowSkuPopup(shopIndex,discountIndex,prodIndex,prodItem.skuId)"
                            >
                              {{ prodItem.skuName }}
                            </view>
                          </view>
                          <view class="sku-con">
                            <view
                              v-if="prodItem.discounts&&prodItem.discounts.length&&!shopCartItemDiscount.chooseComboItemVo"
                              class="activity"
                              @tap.stop="onChooseDiscount(shopIndex,discountIndex,prodIndex)"
                            >
                              {{ wxs.getCurrDiscountName(prodItem.discountId,prodItem.discounts,'zh_CN') }}
                            </view>
                          </view>
                          <view class="price-number">
                            <view class="price">
                              <view class="symbol">
                                ￥
                              </view>
                              <view class="big">
                                {{ wxs.parsePrice(prodItem.comboId?prodItem.matchingPrice:prodItem.skuPriceFee)[0] }}
                              </view>
                              <view class="symbol">
                                .{{ wxs.parsePrice(prodItem.comboId?prodItem.matchingPrice:prodItem.skuPriceFee)[1] }}
                              </view>
                            </view>
                            <view
                              v-if="prodItem.comboId"
                              class="num"
                            >
                              x {{ prodItem.count }}
                            </view>

                            <view
                              v-if="!prodItem.comboId"
                              class="number-box"
                            >
                              <view
                                class="minus"
                                @tap.stop="onChangeNumber(shopIndex,discountIndex,prodIndex,-1)"
                              />
                              <input
                                v-model="prodItem.count"
                                type="number"
                                class="number"
                                @focus="onHandleInputFocus"
                                @blur="onHandleInputBlur($event, shopIndex, discountIndex, prodIndex)"
                              >
                              <view
                                class="plus"
                                @tap.stop="onChangeNumber(shopIndex,discountIndex,prodIndex,1)"
                              />
                            </view>
                          </view>
                        </view>
                      </view>

                      <view
                        v-if="prodItem.comboShopCartItems"
                        class="gift-con"
                      >
                        <view
                          v-for="(comboItem, comboIndex) in prodItem.comboShopCartItems"
                          :key="comboIndex"
                          class="gift-item"
                          @tap.stop="onToProdDetail(comboItem.spuId)"
                        >
                          <view class="gift-name">
                            【组合】{{ comboItem.spuName }}{{ comboItem.skuName ? (' ' + comboItem.skuName) : '' }}
                          </view>
                          <view class="gift-count">
                            <view>x {{ comboItem.count }}</view>
                            <image
                              src="@/static/images/more.png"
                            />
                          </view>
                        </view>
                      </view>

                      <view
                        v-if="prodItem.giveawayShopCartItemList"
                        class="gift-con"
                      >
                        <view
                          v-for="(giveawayItem, giveawayIndex) in prodItem.giveawayShopCartItemList"
                          :key="giveawayIndex"
                          class="gift-item"
                          @tap.stop="onToProdDetail(giveawayItem.spuId)"
                        >
                          <view class="gift-name">
                            【赠品】{{ giveawayItem.spuName }}
                          </view>
                          <view class="gift-count">
                            <view>x {{ giveawayItem.count }}</view>
                            <image
                              src="@/static/images/more.png"
                            />
                          </view>
                        </view>
                      </view>
                    </view>

                    <!-- 套餐的数量 -->
                    <view
                      v-if="shopCartItemDiscount.chooseComboItemVo && shopCartItemDiscount.chooseComboItemVo.comboId"
                      class="combo-oper"
                    >
                      <view class="combo-price">
                        <text>套餐价￥</text>
                        <text class="combo-amount">
                          {{ wxs.parsePrice(shopCartItemDiscount.chooseComboItemVo.comboTotalAmount)[0] }}.
                        </text>
                        <text>{{ wxs.parsePrice(shopCartItemDiscount.chooseComboItemVo.comboTotalAmount)[1] }}</text>
                      </view>
                      <view class="combo-count">
                        <view class="m-numSelector">
                          <view class="number-box">
                            <view
                              class="minus"
                              @tap.stop="onChangeNumber(shopIndex,discountIndex,null,-1)"
                            />
                            <input
                              v-model="shopCartItemDiscount.chooseComboItemVo.comboCount"
                              type="number"
                              class="number"
                            >
                            <view
                              class="plus"
                              @tap.stop="onChangeNumber(shopIndex,discountIndex,null,1)"
                            />
                          </view>
                        </view>
                      </view>
                    </view>
                  </view>
                </view>
              </block>
            </view>
          </block>
          <!-- 失效商品 -->
          <view
            v-if="expiryProdList.length"
            class="shop-item invalid"
          >
            <view class="tit">
              <view class="text">
                失效商品
              </view>
              <view
                class="clear"
                @tap="onClearExpiryItems"
              >
                清空失效商品
              </view>
            </view>
            <view class="item-box">
              <view
                v-for="(expiryItem, expiryIndex) in expiryProdList"
                :key="expiryIndex"
                class="prod-item"
              >
                <view
                  class="prod-box"
                  style="flex-direction: row;"
                >
                  <view class="invalid-icon">
                    失效
                  </view>
                  <checkbox
                    color="#fff"
                    class="check"
                    :class="{'checked':expiryItem.checked}"
                    :checked="expiryItem.checked"
                    @tap="onSelectExpiryItem(expiryIndex)"
                  />
                  <view class="prod-img">
                    <img-show
                      :src="expiryItem.imgUrl"
                      img-mode="aspectFit"
                      :img-style="{
                        width: '180rpx',
                        height: '180rpx'
                      }"
                    />
                  </view>
                  <view class="prod-info">
                    <view class="name">
                      {{ expiryItem.spuName }}
                    </view>
                    <view class="expiry-sku">
                      {{ expiryItem.skuName || '' }}
                    </view>
                    <view class="price-number">
                      <view class="price">
                        <view class="symbol">
                          ￥
                        </view>
                        <view class="big">
                          {{ wxs.parsePrice(expiryItem.skuPriceFee)[0] }}
                        </view>
                        <view class="symbol">
                          .{{ wxs.parsePrice(expiryItem.skuPriceFee)[1] }}
                        </view>
                      </view>
                    </view>
                  </view>
                </view>
                <view
                  v-if="expiryItem.giveaway"
                  class="gift-con"
                >
                  <view
                    v-for="(giveawayItem, giveawayIndex) in expiryItem.giveaway.giveawaySpus"
                    :key="giveawayIndex"
                    class="gift-item"
                    @tap.stop="onToProdDetail(giveawayItem.spuId)"
                  >
                    <view class="gift-name">
                      【赠品】{{ giveawayItem.spuName }}<text
                        v-if="giveawayItem.skuName"
                        class="gift-sku"
                      >
                        {{ giveawayItem.skuName || '' }}
                      </text>
                    </view>
                    <view class="gift-count">
                      <view>x {{ giveawayItem.giveawayNum }}</view>
                      <image src="@/static/images/more.png" />
                    </view>
                  </view>
                </view>
              </view>
            </view>
          </view>
          <!-- 数据为空 -->
          <view class="shop-cart-empty">
            <empty-all-tips
              v-if="isLoaded || !isLogin"
              :empty-img="5"
              :is-empty="!shopCarts.length && !expiryProdList.length"
              empty-tips="购物车空空的，去逛逛吧"
            />
          </view>

          <!-- 猜你喜欢 -->
          <view
            v-if="likeProdData && likeProdData.length > 0"
            class="guess-like"
          >
            <view class="tit">
              <view class="bg">
                <image src="/static/images/tit-bg.png" />
              </view>
              <view class="text">
                你可能还喜欢
              </view>
              <view class="bg">
                <image src="/static/images/tit-bg.png" />
              </view>
            </view>
            <view class="prods">
              <view
                v-for="(prodItem, prodIndex) in likeProdData"
                :key="prodIndex"
                class="item"
                @tap="onToProdDetail(prodItem.spuId)"
              >
                <view class="img">
                  <img-show
                    :src="prodItem.mainImgUrl"
                    img-mode="aspectFit"
                  />
                </view>
                <view class="text-box">
                  <view class="name">
                    {{ prodItem.spuName }}
                  </view>
                  <view class="sku">
                    {{ prodItem.sellingPoint || '' }}
                  </view>
                  <view class="price-box">
                    <view class="price">
                      <view class="symbol">
                        ￥
                      </view>
                      <view class="big">
                        {{ wxs.parsePrice(prodItem.priceFee)[0] }}
                      </view>
                      <view class="symbol">
                        .{{ wxs.parsePrice(prodItem.priceFee)[1] }}
                      </view>
                    </view>
                  </view>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
      <!-- 底部 -->
      <view
        v-show="footerShow"
        v-if="shopCarts.length || expiryProdList.length"
        class="settlement"
      >
        <view
          v-if="shopCarts.length"
          class="all-check"
          @tap="onHandleSelectAll"
        >
          <checkbox
            color="#fff"
            :class="{'checked':allChecked}"
            :checked="allChecked"
            @tap="onHandleSelectAll"
          />
          <view class="text">
            全选
          </view>
        </view>
        <view
          class="price-box"
          @tap="showPriceDetPopup"
        >
          <view class="total">
            <view class="text">
              总计：
            </view>
            <view class="price">
              <view class="symbol">
                ￥
              </view>
              <view class="big">
                {{ wxs.parsePrice(finalMoney)[0] }}
              </view>
              <view class="symbol">
                .{{ wxs.parsePrice(finalMoney)[1] }}
              </view>
            </view>
          </view>
          <view
            v-if="subtractMoney"
            class="discount"
          >
            已优惠￥{{ wxs.parsePrice(subtractMoney)[0] }}.{{ wxs.parsePrice(subtractMoney)[1] }}
          </view>
        </view>
        <view class="btn-box">
          <view
            class="gray-btn add-collection"
            @tap="onHandleEditOper(1)"
          >
            添加收藏
          </view>
          <view
            class="gray-btn"
            @tap="onHandleEditOper(-1)"
          >
            删除所选
          </view>
        </view>
        <view
          class="btn"
          @tap="submitOrder"
        >
          去结算({{ selectedCounts>99? '99+' : selectedCounts }})
        </view>
      </view>

      <!-- 优惠活动弹窗 -->
      <view
        class="popup"
        :class="{ 'show': isShowDiscountPopup }"
      >
        <view
          class="popup-mask"
          @tap="onClosePopup"
        />
        <view class="popup-con-bottom check-discount">
          <view class="popup-tit">
            <view class="tit-text">
              {{ operBasketItem && operBasketItem.checked? '选择':'' }}促销活动
            </view>
            <view
              class="close"
              @tap="onClosePopup"
            >
              <image src="/static/images/close.png" />
            </view>
          </view>
          <view class="con-box">
            <radio-group @change="onRadioChange">
              <label
                v-for="(item, index) in prodDiscounts"
                :key="index"
              >
                <view class="discount-item cart-discount-pop">
                  <radio
                    color="#e43130"
                    :value="String(item.discountId)"
                    :checked="item.discountId===discountId"
                  />
                  <view class="text">{{ item.discountName }}</view>
                </view>
              </label>
              <label>
                <view class="discount-item cart-discount-pop">
                  <radio
                    color="#e43130"
                    value="-1"
                    :checked="discountId===-1"
                  />
                  <view class="text">不参与促销</view>
                </view>
              </label>
            </radio-group>
          </view>
          <view
            class="btn-box"
          >
            <view
              class="btn"
              @tap="onConfirmChangeDiscount"
            >
              确定
            </view>
          </view>
        </view>
      </view>

      <!-- 选择sku弹窗 -->
      <view
        class="popup"
        :class="{ 'show': isShowSkuPopup }"
      >
        <view
          class="popup-mask"
          @tap="onClosePopup"
        />
        <view class="popup-con-bottom check-discount check-sku">
          <view
            v-if="isShowSkuPopup"
            class="goods-box"
          >
            <view class="img">
              <img-show :src="defaultSku && defaultSku.imgUrl ? defaultSku.imgUrl : defaultSku.mainImgUrl" />
            </view>
            <view class="info">
              <view class="name">
                {{ pordName }}
              </view>
              <view class="price">
                <view class="symbol">
                  ￥
                </view>
                <view class="big">
                  {{ wxs.parsePrice(defaultSku.priceFee)[0] }}
                </view>
                <view class="symbol">
                  .{{ wxs.parsePrice(defaultSku.priceFee)[1] }}
                </view>
              </view>
            </view>
            <view
              class="close"
              @tap="onClosePopup"
            >
              <image src="/static/images/close.png" />
            </view>
          </view>

          <view
            v-if="isShowSkuPopup"
            class="sku-con-box"
          >
            <!-- 组合商品详情 -->
            <combine-card-list
              v-if="spuMold === 2"
              :new-sku="newSku"
              :sku-id="newSku.skuId"
              :spu-id="spuId"
            />
            <block
              v-for="(skuGroupItem, skuGroupItemIndex) in skuGroupList"
              :key="skuGroupItemIndex"
            >
              <view class="sku-item">
                <block
                  v-for="(skuLine, key) in skuGroupItem"
                  :key="key"
                >
                  <view class="item-tit">
                    {{ key }}
                  </view>
                  <view class="item-box">
                    <view
                      v-for="skuLineItem in skuLine"
                      :key="skuLineItem"
                      :class="['item-item',selectedPropNew.indexOf(key + skuLineItem) !== -1?'active':'', onIsSkuLineItemNotOptional(allProperties, selectedPropObj, key, skuLineItem, propKeys)? 'cannot' : '']"
                      @tap="onToChooseItem(skuGroupItemIndex, skuLineItem, key)"
                    >
                      {{ skuLineItem }}
                    </view>
                  </view>
                </block>
              </view>
            </block>
          </view>
          <view
            v-if="isShowSkuPopup"
            class="sku-btn-box"
          >
            <view
              :class="['btn',findSku?'':'gray']"
              class=""
              @tap="onSkuPopupConfirm"
            >
              确定
            </view>
          </view>
        </view>
      </view>

      <!-- 金额明细弹窗 -->
      <view
        v-show="priceDetShow"
        class="popup price-detail"
        :class="{ 'show': isShowPriceDetPopup }"
      >
        <view
          class="popup-mask"
          @tap="onClosePopup"
        />
        <view
          class="popup-con-bottom"
          style="min-height: 30%;"
        >
          <view class="popup-tit">
            <view class="tit-text">
              金额明细
            </view>
            <view
              class="close"
              @tap="onClosePopup"
            >
              <image src="/static/images/close.png" />
            </view>
          </view>
          <view class="con-box">
            <view class="price-item">
              <view class="text">
                商品总额
              </view>
              <view class="price color-black">
                ￥{{ wxs.parsePrice(totalMoney)[0] }}.{{ wxs.parsePrice(totalMoney)[1] }}
              </view>
            </view>
            <view
              v-if="subtractMoney"
              class="price-item"
            >
              <view class="text">
                促销立减
              </view>
              <view class="price">
                -￥{{ wxs.parsePrice(subtractMoney)[0] }}.{{ wxs.parsePrice(subtractMoney)[1] }}
              </view>
            </view>
            <view
              v-if="freightAmount"
              class="price-item"
            >
              <view class="text">
                运费
              </view>
              <view class="price color-black">
                ￥{{ wxs.parsePrice(freightAmount)[0] }}.{{ wxs.parsePrice(freightAmount)[1] }}
              </view>
            </view>
            <view
              v-if="freeTransfee"
              class="price-item"
            >
              <view class="text">
                减免运费
              </view>
              <view class="price">
                -￥{{ wxs.parsePrice(freeTransfee)[0] }}.{{ wxs.parsePrice(freeTransfee)[1] }}
              </view>
            </view>
          </view>
        </view>
      </view>
      <confirm-pop
        :show-pop="showPop"
        :pop-content="popContent"
        @handle-pop-cancel="popCancel"
        @handle-pop-confirm="onPopConfirm"
      />
    </view>
  </z-paging>
</template>

<script setup>
import * as cartCount from '@/utils/cart-count'
import CombineCardList from '@/pages/detail/components/combine-card-list/index.vue'

const wxs = number()

const shopCartsLoaded = ref(false) // 用户购物车列表是否加载完成
const expiryProdListLoaded = ref(false) // 失效商品列表是否加载完成
const isLoaded = computed(() => {
  return shopCartsLoaded.value && expiryProdListLoaded.value
})

const popContent = reactive({
  content: '确认要删除选中商品吗？'
})

const isEditCart = ref(false) // 编辑购物车
const likeProdData = ref([])

// 是否登录
const isLogin = ref(false)
const shopCarts = ref([])
const expiryProdList = ref([])
const finalMoney = ref(0)
// 用户默认地址的地区信息
const defaultAddrStr = ref('')
const totalMoney = ref(0)
// 运费
const freightAmount = ref(0)
const selectedCounts = ref(0)
/**
 * 生命周期函数--监听页面显示
 */
onShow(() => {
  uni.pageScrollTo({
    scrollTop: 0,
    duration: 0
  })
  if (!uni.getStorageSync('cloudToken')) {
    isLogin.value = false
    shopCarts.value = []
    expiryProdList.value = []
    finalMoney.value = 0
    defaultAddrStr.value = ''
    totalMoney.value = 0
    freightAmount.value = 0
    selectedCounts.value = 0
  } else {
    isLogin.value = true
    // 请求数据
    onQueryPageData()
  }

  /* #ifdef H5 */
  // window.onresize监听页面高度的变化
  window.addEventListener('resize', onWindowResize)
  /* #endif */
})

const reqItemList = ref([]) // 勾选的项目
/**
 * 生命周期函数--监听页面隐藏
 */
onHide(() => {
  onClosePopup()
  reqItemList.value = []

  /* #ifdef H5 */
  window.removeEventListener('resize', onWindowResize)
  /* #endif */
})

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

/* #ifdef H5 */
const documentHeight = document.documentElement.clientHeight // 默认屏幕高度
/* #endif */
// 顶部结算盒显示控制
const footerShow = ref(true)
// 金额明细弹窗显示控制
const priceDetShow = ref(true)
/**
 * 处理键盘弹出顶起
 */
const onWindowResize = () => {
  if (documentHeight > document.documentElement.clientHeight) {
    uni.hideTabBar()
    footerShow.value = false
    priceDetShow.value = false
  } else {
    uni.showTabBar()
    footerShow.value = true
    priceDetShow.value = true
  }
}

/**
 * 跳转到满减活动详情
 * @param {Number} discountId 满减活动id
 */
const onToDiscountDetail = (discountId) => {
  uni.navigateTo({
    url: '/package-activities/pages/discount-detail/discount-detail?discountId=' + discountId
  })
}

/**
 * 请求页面数据
 */
const onQueryPageData = () => {
  // 获取购物车数字
  cartCount.getCartCount()
  // 获取用户购物车信息
  onGetCartInfo()
  // 获取失效商品列表
  onGetExpiryProdList()
  onGetDefaultAddrStr()
}

/**
 * 失效商品勾选
 */
const onSelectExpiryItem = (index) => {
  const checked = expiryProdList.value[index].checked
  expiryProdList.value[index].checked = !checked
  // 检查全选状态
  onCheckAllSelected()
  // 检查是否勾选了失效商品
  onCheckHaveExpiry()
}

let haveExpiryProd = false // 勾选的商品中是否有失效的商品
/**
 * 检查是否勾选了失效商品
 */
const onCheckHaveExpiry = () => {
  for (let i = 0; i < expiryProdList.value.length; i++) {
    if (expiryProdList.value[i].checked) {
      haveExpiryProd = true
      break
    } else {
      haveExpiryProd = false
    }
  }
}

/**
 * 清空失效商品
 */
const onClearExpiryItems = () => {
  const ids = []
  expiryProdList.value.forEach((el) => {
    ids.push(el.cartItemId)
  })
  const params = {
    url: '/mall4cloud_product/shop_cart/delete_item',
    method: 'PUT',
    data: ids
  }
  http.request(params).then(() => {
    onGetExpiryProdList()
    haveExpiryProd = false
  })
}

/**
 * 获取失效的商品列表
 */
const onGetExpiryProdList = () => {
  expiryProdListLoaded.value = false
  const params = {
    url: '/mall4cloud_product/shop_cart/expiry_prod_list',
    method: 'GET',
    data: {}
  }
  http.request(params).then(res => {
    expiryProdListLoaded.value = true
    res.forEach((el) => {
      el.checked = false
    })
    expiryProdList.value = res
  })
}

const discountId = ref(0)
/**
 * 切换满减活动
 */
const onRadioChange = (e) => {
  discountId.value = +e.detail.value
}

/**
 * 提交满减活动
 */
const onConfirmChangeDiscount = () => {
  onChangeNumber()
  onClosePopup()
}
// 当前选中的店铺数量(店铺内部分商品勾选也算)
const selectedShopsLength = ref(0)
const selectedShopIds = ref([])
/**
 * 提交订单
 */
const submitOrder = () => {
  if (!selectedCounts.value) {
    uni.showToast({
      title: '请选择商品！',
      duration: 2000,
      icon: 'none'
    })
    return
  }
  if (selectedShopsLength.value > 10) {
    uni.showToast({
      title: '购物车仅支持10个店铺同时结算',
      duration: 2000,
      icon: 'none'
    })
    return
  }
  uni.setStorageSync('cloudSelectedShopIds', selectedShopIds.value)
  uni.navigateTo({
    url: '/package-user/pages/submit-order/submit-order?orderEntry=0' + '&dvyType=1' // dvyType 配送类型 1:快递 2:自提 3：无需快递 4:同城配送
  })
}

const operType = ref(null)
// 编辑购物车时选中的购物车商品项id
const selectedCartItemIds = ref([])
// 编辑购物车时选中的商品id
const selectedCartSpuIds = ref([])
// 确认弹窗
const showPop = ref(false)
/**
 * 编辑状态的操作
 * @param operTypePar {Number} 1添加收藏  -1删除
 */
const onHandleEditOper = (operTypePar) => {
  const selectedCartItemIdsPar = []
  const selectedCartSpuIdsPar = []
  const shopCartPar = shopCarts.value
  shopCartPar.forEach(shopItem => {
    shopItem.shopCartItemDiscounts.forEach(shopCartItemDiscount => {
      shopCartItemDiscount.shopCartItems.forEach(prodItem => {
        if (prodItem.checked) {
          selectedCartItemIdsPar.push(prodItem.cartItemId)
          selectedCartSpuIdsPar.push(prodItem.spuId)
        }
      })
    })
  })
  expiryProdList.value.forEach((el) => {
    if (el.checked) {
      selectedCartItemIdsPar.push(el.cartItemId)
      if (operTypePar !== -1) {
        selectedCartSpuIdsPar.push(el.spuId)
      }
    }
  })

  if (!selectedCartItemIdsPar.length) {
    uni.showToast({
      title: `请选择要${operTypePar === 1 ? '收藏' : '删除'}的商品`,
      icon: 'none',
      mask: true
    })
    return
  }
  operType.value = operTypePar
  selectedCartItemIds.value = selectedCartItemIdsPar
  selectedCartSpuIds.value = selectedCartSpuIdsPar
  if (operTypePar === -1) {
    showPop.value = true
  } else {
    onDeleteOrCollect()
  }
}

/**
 * 弹窗确认
 */
const onPopConfirm = () => {
  onDeleteOrCollect()
}

/**
 * 弹窗取消
 */
const popCancel = () => {
  showPop.value = false
}

/**
 * 请求接口
 */
const onDeleteOrCollect = () => {
  const operTypePar = operType.value
  const params = {
    url: operTypePar === 1 ? '/mall4cloud_product/spu_collection/order_prod_collection_all' : '/mall4cloud_product/shop_cart/delete_item',
    method: operTypePar === 1 ? 'POST' : 'PUT',
    data: operTypePar === 1 ? selectedCartSpuIds.value : selectedCartItemIds.value
  }
  http.request(params).then(() => {
    uni.showToast({
      title: operTypePar === 1 ? '已添加收藏' : '删除成功',
      duration: 2000,
      icon: 'none'
    })
    if (operTypePar === -1) {
      onGetCartInfo()
      if (haveExpiryProd) {
        onGetExpiryProdList()
      }
    }
    cartCount.getCartCount()
  })
  showPop.value = false
}

/**
 * 由于 shopCarts 层级过深，页面渲染报错，通过该方法统一获取 shopCarts 层级下的值
 * @param shopCartsPar shopCarts数据参数
 * @param indexOne 第一层数据序号
 * @param indexTwo 第二层数据序号
 * @param indexThree 第三层数据序号
 */
const onCountCurItemValue = (shopCartsPar, indexOne, indexTwo, indexThree) => {
  let val = null
  if (!shopCartsPar[indexOne]) {
    return null
  }
  if (!shopCartsPar[indexOne].shopCartItemDiscounts[indexTwo]) {
    return null
  }
  if (!shopCartsPar[indexOne].shopCartItemDiscounts[indexTwo].shopCartItems) {
    return null
  }
  if (indexThree === 0) {
    val = shopCartsPar[indexOne].shopCartItemDiscounts[indexTwo].shopCartItems[indexThree]
  } else if (!indexThree) {
    val = shopCartsPar[indexOne].shopCartItemDiscounts[indexTwo].shopCartItems
  } else {
    if (!shopCartsPar[indexOne].shopCartItemDiscounts[indexTwo].shopCartItems[indexThree]) {
      return null
    } else {
      val = shopCartsPar[indexOne].shopCartItemDiscounts[indexTwo].shopCartItems[indexThree]
    }
  }
  return val
}

const operBasketItem = ref(null)
/**
 * 商品数量加减/修改商品满减折
 */
const onChangeNumber = util.debounce(function (shopIndex, discountIndex, prodIndex, num) {
  let curItem
  let reqData = {}
  const shopCartItemsPar = onCountCurItemValue(shopCarts.value, shopIndex, discountIndex)
  if (prodIndex === null && shopCartItemsPar[0].comboId) {
    const cartComboMatchSpuDTOS = []
    shopCartItemsPar?.forEach((el, i) => {
      if (i !== 0) {
        cartComboMatchSpuDTOS.push({
          count: num,
          spuId: el.spuId,
          skuId: el.skuId
        })
      }
    })
    curItem = onCountCurItemValue(shopCarts.value, shopIndex, discountIndex, 0)
    reqData = {
      cartComboMatchSpuDTOS,
      count: num,
      shopCartItemId: curItem.cartItemId,
      skuId: curItem.skuId,
      spuId: curItem.spuId,
      comboId: curItem.comboId
    }
  } else {
    if (num) {
      curItem = onCountCurItemValue(shopCarts.value, shopIndex, discountIndex, prodIndex)
      reqData = {
        count: num,
        shopCartItemId: curItem.cartItemId,
        skuId: curItem.skuId,
        spuId: curItem.spuId
      }
    } else {
      reqData = {
        count: 0,
        shopCartItemId: operBasketItem.value.cartItemId,
        skuId: operBasketItem.value.skuId,
        spuId: operBasketItem.value.spuId,
        discountId: discountId.value,
        checked: operBasketItem.value.checked
      }
    }
  }

  const params = {
    url: '/mall4cloud_product/shop_cart/change_item',
    method: 'POST',
    data: reqData
  }
  const callback = () => {
    onGetCartInfo()
    if (num !== 0) {
      cartCount.getCartCount()
    }
    // 加购
    if (num > 0) {
      util.tapLog(2, { n: num, bid: reqData.spuId, sid: shopCarts.value[shopIndex].shopId })
    }
  }
  const errCallBack = err => {
    if (err.msg) {
      uni.showToast({
        title: err.msg,
        icon: 'none',
        mask: true,
        success: () => {
          setTimeout(() => {
            onGetCartInfo()
          }, 1200)
        }
      })
    }
  }
  if (num === -1) {
    const chooseComboItemVo = shopCarts.value[shopIndex].shopCartItemDiscounts[discountIndex]?.chooseComboItemVo
    if ((curItem.count === 1 || (chooseComboItemVo && chooseComboItemVo.comboCount === 1))) {
      uni.showModal({
        title: '提示',
        content: '要从购物车移除此商品吗？',
        success: function (res) {
          if (res.confirm) {
            http.request(params).then(() => {
              callback()
            }).catch((err) => {
              errCallBack(err)
            })
          }
        }
      })
    } else {
      http.request(params).then(() => {
        callback()
      }).catch((err) => {
        errCallBack(err)
      })
    }
  } else {
    http.request(params).then(() => {
      callback()
    }).catch((err) => {
      errCallBack(err)
    })
  }
}, 300)

// 输入框聚焦时的数量
let curProdNum = null
/**
 * 数量输入框聚焦
 */
const onHandleInputFocus = ($event) => {
  curProdNum = parseInt($event.detail.value)
}

/**
 * 直接修改购物车数量
 */
const onHandleInputBlur = ($event, shopIndex, discountIndex, prodIndex) => {
  const changeNumberPar = $event.detail.value - curProdNum
  if (changeNumberPar === 0) {
    return
  }
  if (changeNumberPar % 1 !== 0) {
    shopCarts.value[shopIndex].shopCartItemDiscounts[discountIndex].shopCartItems[prodIndex].count = curProdNum
    uni.showToast({
      title: '请输入正确的数量',
      duration: 1200,
      icon: 'none',
      mask: true
    })
    return
  }
  if (changeNumberPar + curProdNum === 0) {
    uni.showModal({
      title: '提示',
      content: '要从购物车移除此商品吗？',
      success: (res) => {
        if (res.confirm) {
          onChangeNumber(shopIndex, discountIndex, prodIndex, changeNumberPar)
        } else if (res.cancel) {
          shopCarts.value[shopIndex].shopCartItemDiscounts[discountIndex].shopCartItems[prodIndex].count = curProdNum
        }
      }
    })
  } else {
    onChangeNumber(shopIndex, discountIndex, prodIndex, changeNumberPar)
  }
}

const subtractMoney = ref(0)
const freeTransfee = ref(0) // 减免运费
/**
 * 获取用户购物车信息
 */
const onGetCartInfo = () => {
  shopCartsLoaded.value = false
  const params = {
    url: '/mall4cloud_product/shop_cart/info',
    method: 'GET',
    data: {}
  }
  http.request(params).then((res) => {
    shopCartsLoaded.value = true
    const shopCartsPar = res.shopCarts
    if (!reqItemList.value.length) { // 初次请求
      // 所有商品添加勾选状态
      shopCartsPar.forEach((shopItem) => {
        shopItem.shopCartItemDiscounts.forEach((shopCartItemDiscount) => {
          shopCartItemDiscount.shopCartItems.forEach((prodItem) => {
            prodItem.checked = Boolean(prodItem.isChecked)
          })
        })
      })
    } else { // 修改购物车
      const checkedLog = []
      shopCarts.value.forEach(shopItem => {
        shopItem.shopCartItemDiscounts.forEach(shopCartItemDiscount => {
          shopCartItemDiscount.shopCartItems.forEach(prodItem => {
            if (prodItem.checked) {
              checkedLog.push(prodItem.cartItemId)
            }
          })
        })
      })
      shopCartsPar.forEach(shopItem => {
        shopItem.shopCartItemDiscounts.forEach(shopCartItemDiscount => {
          shopCartItemDiscount.shopCartItems.forEach(prodItem => {
            if (prodItem.imgUrl && prodItem.imgUrl.indexOf('http') === -1) {
              prodItem.imgUrl = import.meta.env.VITE_APP_RESOURCES_URL + prodItem.imgUrl
            }
            if (checkedLog.includes(prodItem.cartItemId)) {
              prodItem.checked = true
            }
          })
        })
      })
    }
    shopCarts.value = shopCartsPar
    totalMoney.value = res.totalMoney
    finalMoney.value = res.finalMoney
    subtractMoney.value = res.subtractMoney
    freeTransfee.value = res.freeTransfee
    freightAmount.value = res.freightAmount
    onCheckAllSelected()
    onCalSelectedCounts()
    freightAmount.value = res.freightAmount
    // 当前勾选的商品的店铺数量 (部分勾选也算)
    const selectedShopIdsPar = []
    for (let i = 0; i < shopCarts.value.length; i++) {
      const shopCartItem = shopCarts.value[i]
      for (let j = 0; j < shopCartItem.shopCartItemDiscounts.length; j++) {
        const cartItems = shopCartItem.shopCartItemDiscounts[j].shopCartItems
        for (let k = 0; k < cartItems.length; k++) {
          const cartItem = cartItems[k]
          if (cartItem.checked && !selectedShopIdsPar.includes(shopCartItem.shopId)) {
            selectedShopIdsPar.push(shopCartItem.shopId)
          }
        }
      }
    }
    selectedShopIds.value = selectedShopIdsPar
    selectedShopsLength.value = selectedShopIdsPar.length
  })
}

const allChecked = ref(false) // 全选状态
/**
 * 检查全选状态
 */
const onCheckAllSelected = () => {
  let allCheckedPar = true
  const shopCartsPar = shopCarts.value
  if (shopCartsPar.length) {
    shopCartsPar.forEach(shopCart => {
      let shopChecked = true
      const shopCartItemDiscounts = shopCart.shopCartItemDiscounts
      for (let i = 0; i < shopCartItemDiscounts.length; i++) {
        const cItems = shopCartItemDiscounts[i].shopCartItems
        for (let j = 0; j < cItems.length; j++) {
          if (!cItems[j].checked) {
            shopChecked = false
            allCheckedPar = false
          }
          cItems[j].checked = !!cItems[j].checked
        }
      }
      shopCart.checked = shopChecked
    })
  }
  if (isEditCart.value) {
    if (expiryProdList.value.length) {
      for (let i = 0; i < expiryProdList.value.length; i++) {
        const element = expiryProdList.value[i]
        if (element.checked) {
          haveExpiryProd = true
        } else {
          allCheckedPar = false
        }
      }
    }
  }
  allChecked.value = !shopCartsPar.length && !isEditCart.value ? !allCheckedPar : allCheckedPar
  shopCarts.value = shopCartsPar
}

/**
 * 单个店铺的 勾选/取选
 */
const onHandleShopSelect = (shopIndex) => {
  const shopCartsPar = shopCarts.value
  const checked = shopCartsPar[shopIndex].checked // 获取该店铺当前的选中状态
  shopCartsPar[shopIndex].checked = !checked // 改变状态
  reqItemList.value = []
  shopCartsPar[shopIndex].shopCartItemDiscounts.forEach(shopCartItem => {
    const cItems = shopCartItem.shopCartItems
    for (let j = 0; j < cItems.length; j++) {
      if (cItems[j].checked !== !checked) {
        reqItemList.value.push({
          isChecked: shopCartsPar[shopIndex].checked ? 1 : 0,
          shopCartItemId: cItems[j].cartItemId
        })
      }
      cItems[j].checked = !checked
    }
  })
  shopCarts.value = shopCartsPar
  onCheckAllSelected() // 检查全选状态
  onCalTotalPrice()
}

/**
 * 每一个商品的 勾选/取选
 */
const onHandleProdItemSelect = (shopIndex, discountIndex, prodIndex) => {
  const shopCartsPar = shopCarts.value
  const cartItem = onCountCurItemValue(shopCartsPar, shopIndex, discountIndex, prodIndex)
  const checked = cartItem.checked
  reqItemList.value = []

  if (cartItem.comboId) { // 套餐
    onCountCurItemValue(shopCartsPar, shopIndex, discountIndex).forEach(item => {
      item.checked = !checked
      // 重新设置勾选列表数据
      reqItemList.value.push({
        isChecked: item.checked ? 1 : 0,
        shopCartItemId: item.cartItemId
      })
    })
  } else {
    cartItem.checked = !checked
    // 重新设置勾选列表数据
    reqItemList.value.push({
      isChecked: cartItem.checked ? 1 : 0,
      shopCartItemId: cartItem.cartItemId
    })
  }
  shopCarts.value = shopCartsPar
  onCheckAllSelected()

  onCalTotalPrice()
  onCheckHaveExpiry()
}

/**
 * 点击全选
 */
const onHandleSelectAll = util.debounce(() => {
  if (!uni.getStorageSync('cloudToken')) {
    return
  }
  let allCheckedPar = allChecked.value
  const shopCartsPar = shopCarts.value
  allCheckedPar = !allCheckedPar
  reqItemList.value = []
  if (shopCartsPar.length) {
    shopCartsPar.forEach(shopItem => {
      shopItem.checked = allCheckedPar
      shopItem.shopCartItemDiscounts.forEach(shopCartItemDiscount => {
        shopCartItemDiscount.shopCartItems.forEach(prodItem => {
          if (prodItem.checked !== allCheckedPar) {
            reqItemList.value.push({
              isChecked: allCheckedPar ? 1 : 0,
              shopCartItemId: prodItem.cartItemId
            })
          }
          prodItem.checked = allCheckedPar
        })
      })
    })
  }
  if (isEditCart.value) {
    expiryProdList.value.forEach((el) => {
      el.checked = allCheckedPar
    })
    onCheckHaveExpiry()
  }
  allChecked.value = !shopCartsPar.length && !isEditCart.value ? !allCheckedPar : allCheckedPar
  shopCarts.value = shopCartsPar
  onCalTotalPrice()
}, 100)

/**
 * 计算购物车选中的商品项的数量
 */
const onCalSelectedCounts = () => {
  // 计算购物车勾选的项目数量
  let sum = 0
  shopCarts.value.forEach(shopItem => {
    shopItem.shopCartItemDiscounts.forEach(shopCartItemDiscount => {
      shopCartItemDiscount.shopCartItems.forEach(prodItem => {
        if (prodItem.checked) {
          sum += prodItem.count
        }
      })
    })
  })
  selectedCounts.value = sum
}

/**
 * 计算价格
 */
const onCalTotalPrice = () => {
  const params = {
    url: '/mall4cloud_product/shop_cart/check_items',
    method: 'POST',
    data: reqItemList.value
  }
  http.request(params).then(() => {
    onGetCartInfo()
  })
}

// 编辑购物车
const onEditCart = () => {
  isEditCart.value = !isEditCart.value
  if (isEditCart.value) {
    selectedCartItemIds.value = []
    for (let i = 0; i < expiryProdList.value.length; i++) {
      const element = expiryProdList.value[i]
      element.checked = false
    }
  }
  onCheckAllSelected()
}

const isShowCouponPopup = ref(false) // 优惠券弹窗显示

const prodDiscounts = ref([])
const isShowDiscountPopup = ref(false) // 活动弹窗显示
const shopIndexPar = ref(0)
const discountIndexPar = ref(0)
const prodIndexPar = ref(0)
// 显示活动弹窗
const onChooseDiscount = (shopIndex, discountIndex, prodIndex) => {
  const curItem = onCountCurItemValue(shopCarts.value, shopIndex, discountIndex, prodIndex)
  prodDiscounts.value = curItem.discounts
  discountId.value = curItem.discountId

  isShowDiscountPopup.value = true
  shopIndexPar.value = shopIndex
  discountIndexPar.value = discountIndex
  prodIndexPar.value = prodIndex
  operBasketItem.value = curItem
}

const oldSkuId = ref(null)
const spuId = ref(null)
const pordName = ref(null)
const spuMold = ref(null)
// 显示Sku弹窗
const onShowSkuPopup = (shopIndex, discountIndex, prodIndex) => {
  shopIndexPar.value = shopIndex
  discountIndexPar.value = discountIndex
  prodIndexPar.value = prodIndex
  const cartItem = onCountCurItemValue(shopCarts.value, shopIndex, discountIndex, prodIndex)
  spuId.value = cartItem.spuId
  pordName.value = cartItem.spuName
  oldSkuId.value = cartItem.skuId
  spuMold.value = cartItem.mold
  onGetProdSkuList(cartItem)
}

const findSku = ref(true)
const defaultSku = ref(null)
const isShowSkuPopup = ref(false) // sku弹窗显示
/**
 * sku弹窗确认
 */
const onSkuPopupConfirm = () => {
  if (!findSku.value) {
    uni.showToast({
      title: '所选规格无货',
      duration: 2000,
      icon: 'none'
    })
    return
  }
  if (defaultSku.value.skuId === oldSkuId.value) {
    isShowSkuPopup.value = false
    return
  }
  const cartItem = onCountCurItemValue(shopCarts.value, shopIndexPar.value, discountIndexPar.value, prodIndexPar.value)
  const params = {
    url: '/mall4cloud_product/shop_cart/change_item',
    method: 'POST',
    data: {
      isMainProd: cartItem.isMainProd || undefined,
      comboId: cartItem.comboId || undefined,
      oldSkuId: oldSkuId.value,
      shopCartItemId: cartItem.cartItemId,
      count: cartItem.count,
      skuId: defaultSku.value.skuId,
      spuId: cartItem.spuId
    }
  }
  http.request(params).then(() => {
    isShowSkuPopup.value = false
    onGetCartInfo()
  })
}

const skuList = ref([])
/**
 * 获取商品sku数据
 * @param cartItem
 */
const onGetProdSkuList = (cartItem) => {
  const params = {
    url: cartItem.comboId ? '/mall4cloud_marketing/combo_prod_sku/comboSpuSkuList' : '/mall4cloud_product/ma/spu/sku_list',
    method: cartItem.comboId ? 'POST' : 'GET',
    data: {
      spuId: cartItem.spuId,
      comboId: cartItem.comboId || undefined
    }
  }
  http.request(params).then(res => {
    if (cartItem.comboId) {
      res.forEach(el => {
        el.priceFee = el.matchingPrice
        el.imgUrl = el.pic
      })
    }
    skuList.value = res
    onGroupSkuProp(res, res[0].priceFee)
  })
}

const paging = ref(null)
// 获取猜你喜欢商品列表
const onGetLikeProdList = (pageNum, pageSize) => {
  const categoryId = uni.getStorageSync('cloudBrowseCategoryId')
  const userDetails = uni.getStorageSync('cloudUserDetails')
  let paramUrl = '/mall4cloud_search/ua/search/page'
  const paramData = {
    pageNum,
    pageSize
  }
  // prodRecommendation 0:关(新品推荐)  1:开(个性化推荐)
  if (userDetails && userDetails.prodRecommendation === 1) {
    paramUrl = '/mall4cloud_product/ma/spu/recommend_list'
    paramData.categoryId = categoryId
  } else {
    paramData.sort = 1
  }

  const params = {
    url: paramUrl,
    method: 'GET',
    data: paramData
  }
  http.request(params).then((res) => {
    // 将请求结果通过complete传给z-paging处理，同时也代表请求结束，这一行必须调用
    paging.value.complete(res.list[0].spus)
  })
}

const propKeys = ref([])
const selectedPropObj = ref({})
const selectedPropObjList = ref([])
const skuGroup = ref({})
const skuGroupList = ref([])
const allProperties = ref([])
/**
 * 组装SKU
 */
const onGroupSkuProp = (skuListPar) => {
  if (skuListPar.length === 1 && !skuListPar[0].properties) {
    defaultSku.value = skuListPar[0]
    findSku.value = true
    isShowSkuPopup.value = true
    return
  }
  const skuGroupListPar = []
  const skuGroupPar = {}
  const allPropertiesPar = []
  const propKeysPar = []
  const selectedPropObjPar = {}
  const selectedPropObjListPar = []
  let defaultSkuPar = null
  for (let i = 0; i < skuListPar.length; i++) {
    let isDefault = false
    if (!defaultSkuPar && skuListPar[i].skuId === oldSkuId.value) { // 找到和商品价格一样的那个SKU，作为默认选中的SKU
      defaultSkuPar = skuListPar[i]

      isDefault = true
    }
    const properties = skuListPar[i].properties // 版本:公开版;颜色:金色;内存:64GB
    allPropertiesPar.push(properties)
    const propList = properties.split(';') // ["版本:公开版","颜色:金色","内存:64GB"]
    for (let j = 0; j < propList.length; j++) {
      const index = propList[j].indexOf(':')
      const propval = [propList[j].slice(0, index), propList[j].substring(index + 1)] // ["版本","公开版"]
      let props = skuGroupPar[propval[0]] // 先取出 版本对应的值数组
      // 如果当前是默认选中的sku，把对应的属性值 组装到selectedProp
      if (isDefault) {
        propKeysPar.push(propval[0])
        selectedPropObjPar[propval[0]] = propval[1]
        const selectedPropObjItem = {}
        selectedPropObjItem[propval[0]] = propval[1]
        selectedPropObjListPar.push(selectedPropObjItem)
      }
      if (!props) {
        props = [] // 假设还没有版本，新建个新的空数组
        props.push(propval[1]) // 把 "公开版" 放进空数组
      } else {
        if (props.indexOf(propval[1]) === -1) { // 如果数组里面没有"公开版"
          props.push(propval[1]) // 把 "公开版" 放进数组
        }
      }
      skuGroupPar[propval[0]] = props // 最后把数据 放回版本对应的值
      const propListItem = {}
      propListItem[propval[0]] = props
      skuGroupListPar.push(propListItem)
    }
  }
  if (oldSkuId.value) {
    skuListPar.forEach(skuItem => {
      if (skuItem.skuId === oldSkuId.value) {
        defaultSkuPar = skuItem
      }
    })
  }
  defaultSku.value = defaultSkuPar
  propKeys.value = propKeysPar
  selectedPropObj.value = selectedPropObjPar
  selectedPropObjList.value = selectedPropObjListPar
  skuGroup.value = skuGroupPar
  skuGroupList.value = onUnique(skuGroupListPar)
  allProperties.value = allPropertiesPar
  onParseSelectedObjToVals(skuListPar)
  isShowSkuPopup.value = true
}

const selectedPropertiesNew = ref('')
const selectedPropNew = ref([])
const selectedPropShowNew = ref([])
const newSku = ref([])
/**
 * 将已选的 {key:val,key2:val2}转换成 [val,val2]
 */
const onParseSelectedObjToVals = (skuListPar) => {
  const selectedPropObjListPar = selectedPropObjList.value
  let selectedPropertiesNewPar = ''
  const selectedPropNewPar = []
  const selectedPropShowNewPar = []
  for (let i = 0; i < selectedPropObjListPar.length; i++) {
    const selectedPropObjItem = selectedPropObjListPar[i]
    for (const key in selectedPropObjItem) {
      if (Object.hasOwnProperty.call(selectedPropObjItem, key)) {
        selectedPropNewPar.push(key + selectedPropObjItem[key])
        selectedPropShowNewPar.push(selectedPropObjItem[key])
        selectedPropertiesNewPar += key + ':' + selectedPropObjItem[key] + ';'
      }
    }
  }
  selectedPropertiesNewPar = selectedPropertiesNewPar.substring(0, selectedPropertiesNewPar.length - 1)
  selectedPropNew.value = selectedPropNewPar
  selectedPropShowNew.value = selectedPropShowNewPar
  selectedPropertiesNew.value = selectedPropertiesNewPar
  selectedPropObjList.value = selectedPropObjListPar
  let findSkuPar = false
  for (let i = 0; i < skuListPar.length; i++) {
    if (skuListPar[i].properties === selectedPropertiesNewPar) {
      if (skuListPar[i].stocks > 0 || skuListPar[i].stock > 0) {
        findSkuPar = true
      }
      defaultSku.value = skuListPar[i]
      newSku.value = skuListPar[i]
      break
    }
  }
  findSku.value = findSkuPar
}

/**
 * 判断当前的规格值 是否可以选
 */
const onIsSkuLineItemNotOptional = (allProperties, selectedPropObjPar, key, item, propKeys) => {
  const selectedPropPar = Object.assign({}, selectedPropObjPar)
  let properties = ''
  selectedPropPar[key] = item
  for (let j = 0; j < propKeys.length; j++) {
    properties += propKeys[j] + ':' + selectedPropPar[propKeys[j]] + ';'
  }
  properties = properties.substring(0, properties.length - 1)
  for (let i = 0; i < allProperties.length; i++) {
    if (properties === allProperties[i]) {
      return false
    }
  }
  for (let i = 0; i < allProperties.length; i++) {
    if (allProperties[i].indexOf(item) >= 0) {
      return true
    }
  }
  return false
}

/**
 * 规格点击事件
 */
const onToChooseItem = (skuGroupItemIndex, skuLineItem, key) => {
  selectedPropObjList.value[skuGroupItemIndex][key] = skuLineItem
  selectedPropObj.value[key] = skuLineItem
  onParseSelectedObjToVals(skuList.value)
}

/**
 * 去重
 */
const onUnique = (arr) => {
  const map = {}
  arr.forEach(item => {
    const obj = {}
    Object.keys(item).sort().map((key) => {
      obj[key] = item[key]
      return key
    })
    map[JSON.stringify(obj)] = item
  })
  return Object.keys(map).map(key => JSON.parse(key))
}

/**
 * 跳转到店铺首页
 */
const onToShopIndex = (shopId) => {
  onGetShopInfo(shopId)
}

/**
* 获取店铺信息
*/
const onGetShopInfo = (shopId) => {
  const params = {
    url: '/mall4cloud_admin/ua/shop_detail/head_info',
    method: 'GET',
    data: {
      shopId,
      imgType: 0 // 图片类型：0.app(h5) 1.pc
    }
  }
  http.request(params).then((res) => {
    uni.redirectTo({
      url: res.renovationId ? '/package-shop/shop-page/feature-index/feature-index?shopId=' + res.shopId +
            '&renovationId=' + res.renovationId : '/package-shop/shop-page/shop-index/shop-index?shopId=' + shopId
    })
  })
}

const isShowPriceDetPopup = ref(false) // 金额明细弹窗显示
// 显示金额明细弹窗
const showPriceDetPopup = () => {
  isShowPriceDetPopup.value = !isShowPriceDetPopup.value
}

const isShowDistributionPopup = ref(false) // 配送方式弹窗显示

// 隐藏弹窗
const onClosePopup = () => {
  isShowDiscountPopup.value = false
  isShowCouponPopup.value = false
  isShowSkuPopup.value = false
  isShowPriceDetPopup.value = false
  isShowDistributionPopup.value = false
}

/**
 * 跳转商品详情
 */
const onToProdDetail = (spuId) => {
  uni.navigateTo({
    url: `/pages/detail/detail?spuId=${spuId}`
  })
}

/**
 * 获取默认地址的地区信息
 */
const onGetDefaultAddrStr = () => {
  const params = {
    url: '/mall4cloud_user/user_addr/list',
    method: 'GET'
  }
  http.request(params).then((res) => {
    if (!res.length) {
      return
    }
    const defaultAddr = res.filter((el) => {
      return el.isDefault
    })[0]
    defaultAddrStr.value = defaultAddr.province + defaultAddr.city + defaultAddr.area
  })
}

// 去管理地址
const toAddressList = () => {
  uni.navigateTo({
    url: '/package-user/pages/address-list/address-list'
  })
}
</script>

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