<template>
  <div class="cart">
    <div class="content">
      <div class="step-box">
        <div class="left">
          <span class="img"></span>
          <span class="text">{{$t('cart.cart')}}</span>
        </div>
        <div class="steps">
          <div class="item active">
            <div class="number">step 01.</div>
            <div class="text">{{$t('cart.selectProductToBuy')}}</div>
          </div>
          <div class="item">
            <div class="number">step 02.</div>
            <div class="text">{{$t('cart.confirmOrderInformation')}}</div>
          </div>
          <div class="item">
            <div class="number">step 03.</div>
            <div class="text">{{$t('cart.payToCompleteTheOrder')}}</div>
          </div>
        </div>
      </div>
      <div class="cart-tab">
        <div class="tab-check" v-if="shopCartList.length">
          <input
            type="checkbox"
            class="checkbox default"
            :class="{ checked: allChecked, default: !allChecked }"
            @click="checkAll()"
          />
          <span class="text">{{$t('all')}}</span>
        </div>
        <div class="tab-img">&nbsp;</div>
        <div class="tab-name">{{$t('products')}}</div>
        <div class="tab-price">{{$t('priceOne')}}</div>
        <div class="tab-number">{{$t('quantity')}}</div>
        <div class="tab-total">{{$t('subtotal')}}</div>
        <div class="tab-action">{{$t('operation')}}</div>
      </div>
      <div class="empty" v-if="!shopCartList.length">
        <div class="img">
          <img src="~/assets/images/emptyPic/cart-empty.png" alt />
        </div>
        <div class="action">
          <div class="text">{{$t('cart.yourShoppingCartIsEmpty')}}</div>
          <nuxt-link :to="'/'" class="btn">{{$t('cart.goShopping')}}</nuxt-link>
        </div>
      </div>
      <div v-for="(shopCart, shopIndex) in shopCartList" :key="shopIndex">
        <div class="cart-con">
          <div class="shop-box">
            <div class="shop-msg">
              <input
                type="checkbox"
                class="checkbox default"
                :class="{ checked: shopCart.checked, default: !shopCart.checked }"
                @click="handleCheckShop(shopIndex)"
              />
              <span class="self" v-if="shopCart.shopId === 1">{{$t('prodDetail.selfEmployed')}}</span>
              <nuxt-link :to="'shopIndex?sid=' + shopCart.shopId" class="shop-name">{{
                shopCart.shopName
              }}</nuxt-link>
            </div>
          </div>
          <div class="activity-list">
            <div
              class="cart-con"
              v-for="(shopCartItem,
              shopCartItemIndex) in shopCart.shopCartItemDiscounts"
              :key="shopCartItemIndex"
            >
              <div class="activity-list">
                <div
                  class="activity-msg"
                  v-if="shopCartItem.chooseDiscountItemDto"
                >
                  <div class="a-info">
                    <div class="icon">
                      {{
                         [$t('cart.fullReduction'), $t('cart.fullPieceDiscount'), $t('cart.fullDiscount'), $t('cart.discountOnFullPieces')][
                          shopCartItem.chooseDiscountItemDto.discountRule
                        ]
                      }}
                    </div>
                    <div
                      class="text"
                      v-if="
                        shopCartItem.chooseDiscountItemDto.discountRule == 0
                      "
                    >
                      <span
                        v-if="shopCartItem.chooseDiscountItemDto.reduceAmount"
                      >
                        {{$t('cart.activeItemsAreFullyPurchased')}}￥{{
                          parsePrice(
                            shopCartItem.chooseDiscountItemDto.needAmount
                          )[0]
                        }}.{{
                          parsePrice(
                            shopCartItem.chooseDiscountItemDto.needAmount
                          )[1]
                        }}（
                        <span class="text-red"
                          >{{$t('cart.reduced')}}￥{{
                            parsePrice(
                              shopCartItem.chooseDiscountItemDto.reduceAmount
                            )[0]
                          }}.{{
                            parsePrice(
                              shopCartItem.chooseDiscountItemDto.reduceAmount
                            )[1]
                          }}</span
                        >）
                      </span>
                      <span v-else
                        >{{$t('cart.activeItemsPurchasedOver')}}￥{{
                          parsePrice(
                            shopCartItem.chooseDiscountItemDto.needAmount
                          )[0]
                        }}.{{
                          parsePrice(
                            shopCartItem.chooseDiscountItemDto.needAmount
                          )[1]
                        }}
                        {{$t('cart.getAFullDiscount')}}</span
                      >
                    </div>
                    <div
                      class="text"
                      v-if="
                        shopCartItem.chooseDiscountItemDto.discountRule == 1
                      "
                    >
                      <span
                        v-if="shopCartItem.chooseDiscountItemDto.reduceAmount"
                      >
                        {{$t('cart.activeItemsAreFullyPurchased')}}
                        {{ shopCartItem.chooseDiscountItemDto.needAmount }}件{{$t('items')}}（
                        <span class="text-red"
                          >{{$t('cart.reduced')}}￥{{
                            parsePrice(
                              shopCartItem.chooseDiscountItemDto.reduceAmount
                            )[0]
                          }}.{{
                            parsePrice(
                              shopCartItem.chooseDiscountItemDto.reduceAmount
                            )[1]
                          }}</span
                        >）
                      </span>
                      <span v-else
                        >{{$t('cart.activeItemsPurchasedOver')}}
                        {{ shopCartItem.chooseDiscountItemDto.needAmount }}
                        {{$t('items')}}{{$t('cart.getAFullDiscount')}}
                        </span
                      >
                    </div>
                    <div
                      class="text"
                      v-if="
                        shopCartItem.chooseDiscountItemDto.discountRule == 2
                      "
                    >
                      <span
                        v-if="shopCartItem.chooseDiscountItemDto.reduceAmount"
                      >
                        {{$t('cart.activeItemsAreFullyPurchased')}}￥{{
                          parsePrice(
                            shopCartItem.chooseDiscountItemDto.needAmount
                          )[0]
                        }}.{{
                          parsePrice(
                            shopCartItem.chooseDiscountItemDto.needAmount
                          )[1]
                        }}（
                        <span class="text-red"
                          >{{$t('cart.reduced')}}￥{{
                            parsePrice(
                              shopCartItem.chooseDiscountItemDto.reduceAmount
                            )[0]
                          }}.{{
                            parsePrice(
                              shopCartItem.chooseDiscountItemDto.reduceAmount
                            )[1]
                          }}</span
                        >）
                      </span>
                      <span v-else
                        >{{$t('cart.activeItemsPurchasedOver')}}￥{{
                          parsePrice(
                            shopCartItem.chooseDiscountItemDto.needAmount
                          )[0]
                        }}.{{
                          parsePrice(
                            shopCartItem.chooseDiscountItemDto.needAmount
                          )[1]
                        }}
                        {{$t('cart.enjoyAFullDiscount')}}</span
                      >
                    </div>
                    <div
                      class="text"
                      v-if="
                        shopCartItem.chooseDiscountItemDto.discountRule == 3
                      "
                    >
                      <span
                        v-if="shopCartItem.chooseDiscountItemDto.reduceAmount"
                      >
                        {{$t('cart.activeItemsAreFullyPurchased')}}
                        {{ shopCartItem.chooseDiscountItemDto.needAmount }}{{$t('items')}}（
                        <span class="text-red"
                          >{{$t('cart.reduced')}}￥{{
                            parsePrice(
                              shopCartItem.chooseDiscountItemDto.reduceAmount
                            )[0]
                          }}.{{
                            parsePrice(
                              shopCartItem.chooseDiscountItemDto.reduceAmount
                            )[1]
                          }}</span
                        >）
                      </span>
                      <span v-else
                        >{{$t('cart.activeItemsPurchasedOver')}}
                        {{ shopCartItem.chooseDiscountItemDto.needAmount }}
                        {{$t('items')}} {{$t('cart.enjoyAFullDiscount')}}</span
                      >
                    </div>
                    <nuxt-link
                      :to="
                        '/discount-detail?discountId=' +
                          shopCartItem.chooseDiscountItemDto.discountId
                      "
                      class="link"
                    >
                      {{
                        shopCartItem.chooseDiscountItemDto.reduceAmount
                          ? $t('cart.goToAdd')
                          : $t('cart.goToTheList')
                      }}
                      <span class="arr">>></span>
                    </nuxt-link>
                  </div>
                  <div class="a-price">
                    <!-- <div class="total">
                      <span>￥{{parsePrice(shopCartItem.checkedGoodsTotal)[0]}}.{{parsePrice(shopCartItem.checkedGoodsTotal)[1]}}</span>
                    </div>-->
                    <div class="discount">
                      <span
                        v-if="shopCartItem.chooseDiscountItemDto.reduceAmount"
                        >-￥{{
                          parsePrice(
                            shopCartItem.chooseDiscountItemDto.reduceAmount
                          )[0]
                        }}.{{
                          parsePrice(
                            shopCartItem.chooseDiscountItemDto.reduceAmount
                          )[1]
                        }}</span
                      >
                    </div>
                  </div>
                </div>
                <!-- 套餐提示 -->
                <div
                  v-if="shopCartItem.comboId"
                  class="combo-msg"
                >
                  <div class="combo-info">
                    <span class="combo-icon">{{$t('cart.combo')}}</span>
                    <span class="combo-name">{{shopCartItem.chooseComboItemDto.name}}</span>
                    (<span class="combo-reduce"> {{$t('cart.reduced')}} {{shopCartItem.chooseComboItemDto.preferentialAmount}} {{$t('memberCenter.yuan')}}</span>)
                  </div>
                  <div class="combo-unit-price">
                    ￥{{parsePrice(shopCartItem.chooseComboItemDto.comboAmount)[0]}}.{{parsePrice(shopCartItem.chooseComboItemDto.comboAmount)[1]}}
                  </div>
                  <div class="combo-count">
                    <span
                      class="reduce"
                      :class="{ limit: shopCartItem.chooseComboItemDto.comboCount === 1 }"
                      @click="handleChangeNum(shopCart.shopId, shopCartItem.comboId, shopCartItem.shopCartItems[0], -1)"
                      >-</span
                    >
                    <input
                      type="text"
                      class="number"
                      v-model="shopCartItem.chooseComboItemDto.comboCount"
                      readonly="true"
                    />
                    <span
                      class="increase"
                      @click="handleChangeNum(shopCart.shopId, shopCartItem.comboId, shopCartItem.shopCartItems[0], 1)"
                      >+</span
                    >
                  </div>
                  <div class="combo-total-price">￥{{ parsePrice(shopCartItem.chooseComboItemDto.comboTotalAmount)[0] }}.{{parsePrice(shopCartItem.chooseComboItemDto.comboTotalAmount)[1]}}</div>
                  <div class="combo-del-btn" @click="handleDelCombo(shopCartItem.comboId)">{{$t('delete')}}</div>
                </div>

                <div class="activity-goods"
                  v-for="(prod, prodIndex) in shopCartItem.shopCartItems"
                  :key="prodIndex">
                  <!-- 商品项 -->
                  <div
                    :class="[
                      prod.isCheck ? 'active item' : 'item',
                      (prod.discountId > 0 && shopCartItem.chooseDiscountItemDto) || shopCartItem.comboId ? 'activity-goods-checked' : '',
                    ]"
                  >
                    <div class="item-goods">
                      <div class="tab-check">
                        <input
                          v-if="!shopCartItem.comboId || (shopCartItem.comboId && !prod.parentBasketId)"
                          type="checkbox"
                          class="checkbox"
                          checkbox
                          :class="{
                            checked: prod.isCheck,
                            default: !prod.isCheck
                          }"
                          @click="handleCheckProdItem(shopIndex, shopCartItemIndex, prodIndex, prod.isCheck)"
                        />
                      </div>
                      <div class="tab-img">
                        <nuxt-link :to="'/detail/' + prod.prodId" class="img-box">
                          <img v-if="prod.pic" :src="prod.pic" alt @error="handlePicError" />
                          <img v-else src="~/assets/img/def.png" alt />
                        </nuxt-link>
                      </div>
                      <div class="tab-name">
                        <nuxt-link :to="'/detail/' + prod.prodId" class="name">{{
                          prod.prodName
                        }}</nuxt-link>
                        <!-- <span class="sku">{{ prod.skuName }}</span> -->
                        <span class="sku" @click="getSkuListByProdId(prod)">
                            <!-- :sku-list="mainProd.skuList" -->
                          <SelectSku
                            v-if="prod.skuName"
                            :sku-id="prod.skuId"
                            :sku-name="prod.skuName"
                            :prod-id="prod.prodId"
                            :combo-id="prod.comboId"
                            @getSku="handleSetSku"
                          />
                        </span>
                      </div>
                      <div class="tab-price">
                        <div class="unit-price">
                          ￥{{ parsePrice(shopCartItem.comboId ? prod.comboPrice : prod.price)[0] }}.{{
                            parsePrice(shopCartItem.comboId ? prod.comboPrice : prod.price)[1]
                          }}
                        </div>
                        <div class="promotion-box">
                          <div
                            class="p-tit"
                            v-if="prod.discountId > 0 || prod.discountId == -1"
                            :data-basketid="prod.basketId"
                            @click.prevent="onShowDisList(prod.basketId, prod.discountId)"
                          >
                            {{$t('promotion')}}
                          </div>
                          <transition name="fade">
                            <div
                              class="p-con"
                              v-if="
                                showDiscountsList &&
                                  prod.basketId == currentBasketId
                              "
                            >
                              <div class="p-items-con">
                                <div
                                class="p-item"
                                v-for="(discountItem, index) in prod.discounts"
                                :key="discountItem.discountId"
                              >
                                <input
                                  @change="setChooseDiscountId(discountItem.discountId)"
                                  :id="index"
                                  type="radio"
                                  class="radio"
                                  :name="prod.prodId"
                                  :checked="
                                    discountItem.discountId == prod.discountId
                                  "
                                />
                                <label :for="index" class="p-info">{{
                                  discountItem.discountName
                                }}</label>
                              </div>
                              <div class="p-item">
                                <input
                                  @change="setChooseDiscountId(-1)"
                                  id="nodiscount"
                                  type="radio"
                                  class="radio"
                                  :name="prod.prodId"
                                  :checked="prod.discountId == -1"
                                />
                                <label for="nodiscount" class="p-info"
                                  >{{$t('cart.noEventDiscount')}}</label
                                >
                              </div>
                              </div>
                              <div class="p-btns">
                                <a
                                  href="javascript:void(0)"
                                  class="sure"
                                  @click="onChooseDiscount(
                                      switchDiscountId,
                                      prod.basketId
                                    )"
                                  >{{$t('determine')}}</a
                                >
                                <a
                                  href="javascript:void(0)"
                                  class="cancel"
                                  @click="showDiscountsList = false"
                                  >{{$t('cancel')}}</a
                                >
                              </div>
                            </div>
                          </transition>
                        </div>
                      </div>
                      <div class="tab-number">
                        <div class="goods-number">
                          <span
                            v-if="!shopCartItem.comboId"
                            class="reduce"
                            :class="{ limit: prod.prodCount === 1 }"
                            @click="handleChangeNum(shopCart.shopId, shopCartItem.comboId, prod, -1)"
                            >-</span
                          >
                          <input
                            type="text"
                            class="number"
                            v-model="prod.prodCount"
                            readonly="true"
                          />
                          <span
                            v-if="!shopCartItem.comboId"
                            class="increase"
                            @click="handleChangeNum(shopCart.shopId, shopCartItem.comboId, prod, 1)"
                            >+</span
                          >
                        </div>
                      </div>
                      <!-- <div class="tab-total">￥{{parsePrice(prod.productTotalAmount)[0]}}.{{parsePrice(prod.productTotalAmount)[1]}}</div> -->
                      <div class="tab-total">
                        ￥{{ parsePrice(prod.prodCount * (shopCartItem.comboId ? prod.comboPrice : prod.price))[0] }}.{{
                          parsePrice(prod.prodCount * (shopCartItem.comboId ? prod.comboPrice : prod.price))[1]
                        }}
                      </div>
                      <div class="tab-action">
                        <!-- <a
                          href="JavaScript:;"
                          class="action-a collect"
                          @click="collection(index, shopCartItemIndex, prodIndex)"
                          >{{ prod.isCollection ? '取消收藏' : '移入收藏夹' }}</a
                        > -->
                        <!-- 活动商品不可收藏 -->
                        <a
                          href="JavaScript:;"
                          v-if="prod.prodType !== 5"
                          class="action-a collect"
                          :style="$t('language')=='en'?moveToFavorites:''"
                          @click="collection(shopIndex, shopCartItemIndex, prodIndex)"
                          >{{$t('cart.moveToFavorites')}}</a
                        >
                        <a
                          v-if="!shopCartItem.comboId"
                          href="JavaScript:;"
                          class="action-a del"
                          @click="openPopup(prod.basketId)"
                          >{{$t('delete')}}</a
                        >
                      </div>
                    </div>
                    <!-- 赠品展示 -->
                    <div v-if="prod.giveaway" class="gift-con">
                      <div v-for="(giveawayItem, giveawayIndex) in prod.giveaway.giveawayProds" :key="giveawayIndex" class="gift-item">
                        <nuxt-link class="gift-item-name" :to="'/detail/' + giveawayItem.prodId">
                        {{$t('cart.giveaways')}} {{giveawayItem.prodName}}
                        <span class="gift-item-sku-name">{{giveawayItem.skuName}} x{{giveawayItem.giveawayNum}}</span>
                        </nuxt-link>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="cart-bottom" v-if="shopCartList.length">
        <div class="total-box">
          <div class="check-all">
            <input
              type="checkbox"
              class="checkbox"
              :class="{ checked: allChecked, default: !allChecked }"
              @click="checkAll()"
            />
            <span class="text" @click="checkAll()">{{$t('cart.selectAll')}}</span>
          </div>
          <a href="JavaScript:;" class="del-selected" @click="openPopup()"
            >{{$t('cart.deleteSelectedProducts')}}</a
          >
        </div>
        <div class="settlement-box">
          <div class="amount">
            {{$t('cart.selected')}}
            <span class="number">{{ this.count }}</span
            >{{$t('cart.itemsProducts')}}
          </div>
          <div class="price-box">
            <div class="total-price">
              {{$t('cart.totalPrice')}}：
              <span class="text"
                >¥{{ parsePrice(this.finalMoney)[0] }}.{{
                  parsePrice(this.finalMoney)[1]
                }}</span
              >
            </div>
            <div class="discount-price">
              {{$t('cart.offers')}}：
              <span class="text"
                >-¥{{ parsePrice(this.subtractMoney)[0] }}.{{
                  parsePrice(this.subtractMoney)[1]
                }}</span
              >
            </div>
          </div>
          <a href="JavaScript:;" class="btn" @click="submit()" :style="{fontSize:$t('language')=='en'?'14px':'16px'}">{{$t('cart.goToSettlement')}}</a>
        </div>
      </div>
      <div class="popup-mask" v-if="isPopup"></div>
      <!-- 删除提示弹窗 -->
      <div class="popup-box" v-if="isPopup">
        <div class="tit">
          <div class="text">{{$t('tips')}}</div>
          <div class="close" @click="closePopup()"></div>
        </div>
        <div class="con">
          <div class="tip">
            <div class="tip-icon warning"></div>
            <div class="tip-info">
              <div class="result">{{$t('cart.deleteThisItem')}}</div>
              <div class="date">{{$t('cart.removeCart')}}</div>
              <div class="btns">
                <a href="JavaScript:;" class="btn-r" @click="handleDeletProd">{{$t('delete')}}</a>
                <a href="JavaScript:;" class="btn-g" @click="closePopup"
                  >{{$t('cancel')}}</a
                >
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { _debounce } from "~/plugins/util";   //防抖
import util from '~/plugins/util'
import SelectSku from '~/components/select-sku.vue'
export default {
  data () {
    return {
      shopCartList: [],
      allChecked: true,
      count: 0,
      finalMoney: 0,
      subtractMoney: 0,
      totalMoney: 0,
      isPopup: false,
      basketId: null,

      showDiscountsList: false, // 促销活动显隐
      currentBasketId: '',
      discountData: {},
      reqData: [],
      moveToFavorites:{
        position: "relative",
        left: "-25px"
      },
      baskets: [],
      isSwichDiscount: false,
      switchDiscountId: -1,
      // 是否显示套装商品
      isCombo: false,
      // 是否显示赠品
      showGift: false,

      // 当前修改的购物车商品项
      currentProdItem: {},
      showSkuPop: false,

      isClick: true //限制加减按钮点击
    }
  },
  components: {
    SelectSku
  },
  mounted () {
    // 设置网页标题
    document.title = this.$t('cart.cart')
    this.loadBasketData()
  },
  methods: {
    handlePicError(e){
      e.target.src=require('@/assets/img/def.png')
    },
    /**
     * 修改sku
     */
    handleSetSku(sku) {
      const currentProdItem = this.currentProdItem
      const params = {
        basketId: currentProdItem.basketId,
        comboId: currentProdItem.comboId,
        count: 0,
        shopId: currentProdItem.shopId,
        prodId: currentProdItem.prodId,
        skuId: sku.skuId,
      }
      this.updateBasket(params)
    },

    loadBasketData () {
      var shopCartIds = []
      this.$axios.post('/p/shopCart/info', this.baskets).then(({ data }) => {
        if(this.isSwichDiscount) {
          for(let i = this.baskets.length -1; i >= 0 ; i--) {
            if(!this.baskets[i].isCheck) {
              this.baskets.splice(i, 1)
            }
          }
          this.isSwichDiscount = false
        }
        var shopCartList = data
        if (data.length > 0) {
          if (shopCartIds.length == 0) {  // 初始加载
            shopCartList.forEach(shopCart => {
              shopCart.shopCartItemDiscounts.forEach(shopCartItemDiscount => {
                if (shopCartItemDiscount.comboId) {
                  shopCartItemDiscount.mainProdBasketId = shopCartItemDiscount.shopCartItems[0].basketId
                }
              })
            })
            this.shopCartList = shopCartList
          } else { // 修改购物车
            var checkedLog = []
            this.shopCartList.forEach(shopCart => {
              shopCart.shopCartItemDiscounts.forEach(shopCartItemDiscount => {
                shopCartItemDiscount.shopCartItems.forEach(shopCartItem => {
                  if (shopCartItem.checked) {
                    checkedLog.push(shopCartItem.basketId)
                  }
                })
              })
            })
            data.forEach(newShopCart => {
              newShopCart.shopCartItemDiscounts.forEach(newShopCartItemDiscount => {
                newShopCartItemDiscount.shopCartItems.forEach(shopCartItem => {
                  if (checkedLog.includes(shopCartItem.basketId)) {
                    shopCartItem.checked = true
                  }else {
                    shopCartItem.checked = false
                  }
                })
              });
            })
            this.shopCartList = data
          }
        } else {
          this.shopCartList = []
        }
        this.checkAllSelected()
        // 计算总价
        this.calTotalPrice()
        // 购物车数量
        // this.getCartCount()

        this.isClick = true
      })
    },

    /**
     * 计算购物车总额
     */
    calTotalPrice () {
      var shopCartIds = [];
      this.baskets.forEach(item => {
        if (item.isCheck) {
          shopCartIds.push(item.basketId)
        }
      })
      this.$axios.post('/p/shopCart/totalPay', shopCartIds).then(({ data }) => {
        this.count = data.count
        this.finalMoney = data.finalMoney,
          this.totalMoney = data.totalMoney,
          this.subtractMoney = data.subtractMoney
      })
    },

    //收藏商品
    collection: _debounce(function(shopIndex, shopCartItemIndex, prodIndex) {
      const item = this.shopCartList[shopIndex].shopCartItemDiscounts[shopCartItemIndex].shopCartItems[prodIndex]
      var prodId = item.prodId
      this.$axios.get('/p/user/collection/isCollection', { params: { prodId } }).then(({ data }) => {
        if (data == true) {
          this.$message({
            message: this.$t('cart.theProductIsAlreadyInTheFavorites'),
            type: 'success',
            duration: 1000
          })
        } else {
          this.$axios.post('/p/user/collection/orderProdCollectionAll', item.prodId).then(({ data }) => {
            this.$message({
              message: this.$t('prodDetail.collectionSuccess'),
              type: 'success',
              duration: 1000
            })
            // item.isCollection = true
            return
          })
        }
      })
    },500),

    /**
     * 点击套装的删除按钮
     */
    handleDelCombo (comboId) {
      for (let i = 0; i < this.shopCartList.length; i++) {
        const shop = this.shopCartList[i];
        for (let k = 0; k < shop.shopCartItemDiscounts.length; k++) {
          const shopCartItemDiscount = shop.shopCartItemDiscounts[k]
          for (let j = 0; j < shopCartItemDiscount.shopCartItems.length; j++) {
            const shopCartItem = shopCartItemDiscount.shopCartItems[j];
            if (shopCartItemDiscount.comboId === comboId && shopCartItem.parentBasketId === 0) {
              this.openPopup(shopCartItem.basketId)
              break
            }
          }
        }
      }
    },

    //打开弹窗
    openPopup (basketId) {
      this.isPopup = true
      this.basketId = basketId
    },
    //关闭弹窗
    closePopup () {
      this.isPopup = false
      this.basketId = null
    },
    // 删除购物车商品
    handleDeletProd () {
      var shopCartIds = []
      if (!this.basketId) {
        this.shopCartList.forEach(shop => {
          shop.shopCartItemDiscounts.forEach(item => {
            item.shopCartItems.forEach(shopCart => {
              if (shopCart.isCheck) {
                shopCartIds.push(shopCart.basketId);
              }
            });
          });
        });
      } else {
        shopCartIds.push(this.basketId)
      }
      if (!shopCartIds.length) {
        this.$message({
          type: 'warning',
          message: this.$t('cart.pleaseCheckTheItemsWantToDelete')
        })
        this.isPopup = false
        return
      }
      this.$axios.put('/p/shopCart/deleteItem', shopCartIds).then(({ data }) => {
        this.loadBasketData()
        this.getCartCount()
      })
      this.isPopup = false
    },

    /**
     * 每一项的选择事件
     */
    handleCheckProdItem (shopIndex, shopCartItemIndex, prodIndex,isCheck) {
      var shopCartList = this.shopCartList;
      var shopCartItemDiscounts = shopCartList[shopIndex].shopCartItemDiscounts; // 获取购物车列表
      var checked = shopCartItemDiscounts[shopCartItemIndex].shopCartItems[prodIndex].checked; // 获取当前商品的选中状态
      shopCartItemDiscounts[shopCartItemIndex].shopCartItems[prodIndex].checked = !checked; // 改变状态
      const shopCartItem = shopCartItemDiscounts[shopCartItemIndex].shopCartItems[prodIndex]
      this.generateRequestData(shopCartItem.basketId, !isCheck)
      this.loadBasketData()
      this.checkAllSelected(); //检查全选状态
    },
    isBasketPresence(prod) {
      for(let i = 0; i < this.baskets.length; i++) {
        if(prod.basketId === this.baskets[i].basketId) {
          return i
        }
      }
      return false
    },

    /**
     * 店铺勾选事件
     */
    handleCheckShop (shopIndex) {
      this.shopCartList[shopIndex].checked = !this.shopCartList[shopIndex].checked
      var checked = this.shopCartList[shopIndex].checked
      this.shopCartList[shopIndex].shopCartItemDiscounts.forEach(item => {
        item.checked = checked
        item.shopCartItems.forEach(prodItem => {
          prodItem.isCheck = checked
          this.generateRequestData(prodItem.basketId, checked)
        })
      })

      this.loadBasketData()
      this.checkAllSelected()
    },
    /**
     * 全选事件
     */
    checkAll () {
      this.handleCheckAll(this.shopCartList, !this.allChecked)
    },
    /**
     * 全选
     */
    handleCheckAll () {
      var allChecked = this.allChecked;
      allChecked = !allChecked; //改变状态
      var shopCartList = this.shopCartList;
      shopCartList.forEach(shopCart => {
        shopCart.checked = allChecked;
        var shopCartItemDiscounts = shopCart.shopCartItemDiscounts;
        for (var i = 0; i < shopCartItemDiscounts.length; i++) {
          var cItems = shopCartItemDiscounts[i].shopCartItems;
          for (var j = 0; j < cItems.length; j++) {
            cItems[j].checked = allChecked;
            if(allChecked) {
              this.generateRequestData(cItems[j].basketId, allChecked)
            } else {
              this.baskets = []
            }
          }
        }
      });
      this.allChecked = allChecked
      this.shopCartList = shopCartList
      this.loadBasketData()
      // this.calTotalPrice(); //计算总价
    },

    /**
     * 检查全选状态
     */
    checkAllSelected () {
      var allChecked = true;
      var shopCartList = this.shopCartList;
      var flag = false;
      shopCartList.forEach(shopCart => {
        var shopChecked = true;
        var shopCartItemDiscounts = shopCart.shopCartItemDiscounts;
        for (var i = 0; i < shopCartItemDiscounts.length; i++) {
          var cItems = shopCartItemDiscounts[i].shopCartItems;
          for (var j = 0; j < cItems.length; j++) {
            if (!cItems[j].isCheck) {
              shopChecked = false;
              allChecked = false;
              flag = true;
              break;
            }
          }
          if (flag) {
            break;
          }
        }
        shopCart.checked = shopChecked;
      });
      this.allChecked = allChecked
      this.shopCartList = shopCartList
    },

    /**
     * 修改购物车数量
     * @param {Number} shopId 店铺
     * @param {Number} comboId 套餐id
     * @param {Object} prod 修改的商品项
     * @param {Number} count 商品数量增量
     */
    handleChangeNum(shopId, comboId, prod, count) {
      if(!this.isClick) {
        return
      }
      this.isClick = false
      let matchingSkuIds = []
      if (comboId) {
        const shopCartList = this.shopCartList
        let shopIndex = shopCartList.findIndex(el => el.shopId === shopId)
        let shopCartItemDiscounts = shopCartList[shopIndex].shopCartItemDiscounts
        let shopCartItemIndex = shopCartItemDiscounts.findIndex(el => el.comboId === comboId && el.mainProdBasketId === prod.basketId)
        if (shopCartItemDiscounts[shopCartItemIndex].shopCartItems[0].comboCount === 1 && count === -1) {
          this.isClick = true
          return
        }
        shopCartItemDiscounts[shopCartItemIndex].shopCartItems.forEach(el => {
          if (el.parentBasketId !== 0) {
            matchingSkuIds.push(el.skuId)
          }
        })
      }
      // else {
        this.currentProdItem = prod
      // }
      const updateBasketParam = {
        basketId: prod.basketId,
        comboId: comboId,
        count: count,
        matchingSkuIds: comboId ? matchingSkuIds : undefined,
        prodId: prod.prodId,
        shopId: shopId,
        skuId: prod.skuId
      }
      this.updateBasket(updateBasketParam)
    },

    /**
     * 更新购物车
     * @param {Object} updateBasketParam 请求的参数
     */
    updateBasket: _debounce(function (updateBasketParam) {
      if (updateBasketParam.count == -1 && this.currentProdItem.prodCount == 1) {
        this.isClick = true
        return
      }
      this.$axios({
        url: updateBasketParam.count === 0 ? "/p/shopCart/changeShopCartSku" : "/p/shopCart/changeItem",
        method: updateBasketParam.count === 0 ? "PUT" : "POST",
        data: updateBasketParam
      }).then(({data})=> {
        this.getCartCount()
        this.loadBasketData()
        if (updateBasketParam.count && updateBasketParam.count >= 1) {
          const flowAnalysisLogDto = JSON.parse(localStorage.getItem('flowAnalysisLogDto'))
          flowAnalysisLogDto.bizData = updateBasketParam.prodId
          flowAnalysisLogDto.bizType = 0
          localStorage.setItem('flowAnalysisLogDto', JSON.stringify(flowAnalysisLogDto))
          util.tapLog(4, '', '', updateBasketParam.count)
        }
      })
    }, 420),

    /**
     * 去结算
     */
    submit () {
      var shopCartIds = []
      this.baskets.forEach(basket => {
        shopCartIds.push(basket.basketId);
      })
      if (shopCartIds.length < 1) {
        this.$message({
          message: this.$t('cart.pleaseSelectAtLeastOneItem'),
          type: 'error',
          duration: 1000
        })
        return
      }
      var basketIds = JSON.stringify(shopCartIds)
      sessionStorage.setItem('basketIds', basketIds);
      this.$router.push({ path: '/submit-order?orderEntry=0' })
    },
    /**
     * 价格处理
     */
    parsePrice: (value) => {
      var val = Number(value)
      if (!val) {
        val = 0;
      }
      // 截取小数点后两位，并以小数点为切割点将val转化为数组
      return val.toFixxed(2).split(".");
    },
    /**
     * 当前选中的活动id
     */
    setChooseDiscountId(discountId) {
      this.switchDiscountId = discountId
    },
    /**
     * 修改促销活动
     */
    onChooseDiscount (discountId, basketId) {
      let flag = false
      for(let i = 0; i < this.baskets.length; i++) {
        if(this.baskets[i].basketId === basketId) {
          this.baskets[i].discountId = discountId
          flag = true
          break
        }
      }
      if(!flag) {
        this.baskets.push({
          discountId,
          basketId
        })
      }
      this.submitDiscount()
    },
    /**
     * 提交促销活动修改
     */
    submitDiscount () {
      // var reqData = this.discountData
      this.loadBasketData()
      this.showDiscountsList = false
      this.isSwichDiscount = true
    },
    /**
     * 促销按钮
     */
    onShowDisList (val, discountId) {
      this.showDiscountsList = true
      this.currentBasketId = val
      this.switchDiscountId = discountId || -1
    },
    /**
     * 获取购物车商品总数
     */
    getCartCount () {
      this.$axios.get('/p/shopCart/prodCount').then(({ data }) => {
        this.$store.commit('cartNumber/changeCartNumber', data)
      })
    },

    /**
     * 生成请求购物车的数据
     * @param {Number} basketId 商品的购物车id
     * @param {Boolean} isCheck 商品的选择状态
     */
    generateRequestData(basketId, isCheck) {
      let matchingProdBasketsId = []
      for (let i = 0; i < this.shopCartList.length; i++) {
        const shopCart = this.shopCartList[i];
        for (let j = 0; j < shopCart.shopCartItemDiscounts.length; j++) {
          const cItems = shopCart.shopCartItemDiscounts[j];
          for (let k = 0; k < cItems.shopCartItems.length; k++) {
            const pItem = cItems.shopCartItems[k];
            if (cItems.comboId === pItem.comboId && pItem.parentBasketId === basketId) {
              matchingProdBasketsId.push(pItem.basketId)
            }
          }
        }
      }
      if (this.baskets.length) {
        this.setBasketsWhileNotEmpty(basketId, isCheck)
        // 套餐商品
        for (let i = 0; i < matchingProdBasketsId.length; i++) {
          this.setBasketsWhileNotEmpty(matchingProdBasketsId[i], isCheck)
        }
      } else {
        this.setBaskets(basketId, isCheck)
        // 套餐商品
        for (let i = 0; i < matchingProdBasketsId.length; i++) {
          this.setBaskets(matchingProdBasketsId[i], isCheck)
        }
      }
    },

    /**
     * 生成请求购物车的数据: 当baskets不为空时
     */
    setBasketsWhileNotEmpty (basketId, isCheck) {
      let index = this.baskets.findIndex(el => el.basketId === basketId)
      if (index > -1) {
        this.baskets[index].isCheck = isCheck
      } else {
        this.setBaskets(basketId, isCheck)
      }
    },

    /**
     * 生成请求购物车的数据: 当basketId 中未包含当前修改的商品的购物车id时
     */
    setBaskets (basketId, isCheck) {
      this.baskets.push({
        basketId: basketId,
        discountId: '',
        isCheck: isCheck
      })
    },

    /**
     * 根据商品id获取skuList
     * @param {Object} prod 当前要修改的选项
     */
    getSkuListByProdId(prod) {
      let comboList = []
      if (prod.comboId) {
        const shopCartList = this.shopCartList
        let shopIndex = shopCartList.findIndex(el => el.shopId === prod.shopId)
        let shopCartItemDiscounts = shopCartList[shopIndex].shopCartItemDiscounts
        let shopCartItemIndex = shopCartItemDiscounts.findIndex(el => el.comboId === prod.comboId)
        shopCartItemDiscounts[shopCartItemIndex].shopCartItems.forEach(el => {
          comboList.push({
            basketId: el.basketId,
            skuId: el.skuId,
            prodId: el.prodId
          })
        })
        prod.comboList = comboList
      }
      this.currentProdItem = prod
    },

    /**
     * sku
     */
    handleShowSkuPop() {
      console.log('sku弹窗显示了');
    }
  }
}
</script>
<style scoped src='~/assets/css/cart.css'>
</style>

