<template>
  <view class="cart-store-list">
    <view v-if="cartStoreList.length > 0">
      <!--  购物车列表  -->
      <view class="cart-store-item" v-for="(cItem, cIdx) in cartStoreList" :key="cIdx">
        <view class="cart-checkbox-group">
          <yi-checkbox
            shape="circle"
            :active-color="primaryColor"
            v-model="cItem[0].storeAllCheck"
            @change="check('store', cIdx)"
          ></yi-checkbox>
          <view class="store-info-wrap">
            <u-cell-group>
              <u-cell-item arrow :border="false" :title="cItem[0].storeName" />
            </u-cell-group>
          </view>
        </view>
        <view class="cart-checkbox-group" v-for="(gItem, gIdx) in cItem" :key="gIdx">
          <yi-checkbox
            shape="circle"
            :active-color="primaryColor"
            v-model="gItem.checked"
            :disabled="cartEdit === false && gItem.goodDetail.stock === 0"
            @change="check('item', cIdx, gIdx)"
          ></yi-checkbox>
          <view class="goods-card-wrap">
            <yi-goods-card
              :tag="gItem.goodDetail.goods.transport === 2 ? '自提' : null"
              :price="gItem.goodDetail.price"
              :desc="gItem.name"
              :title="gItem.goodDetail.goods.nameSpu"
              :thumb="
                gItem.goodDetail.iconSku && gItem.goodDetail.iconSku !== ''
                  ? imgUrl + gItem.goodDetail.iconSku
                  : defaultGoodsIcon
              "
              thumb-mode="aspectFill"
            >
              <u-tag
                type="error"
                slot="tags"
                v-if="gItem.goodDetail.stock === 0"
                text="该商品库存为0,请重新选择其他商品."
              >
              </u-tag>
              <u-number-box
                slot="num"
                v-model="gItem.numBuy"
                :disabled="gItem.disabled"
                :min="gItem.minBuyNumber"
                :max="gItem.maxBuyNumber"
                integer
                @change="onNumBuyChange($event, cIdx, gIdx)"
              />
            </yi-goods-card>
          </view>
        </view>
      </view>
      <view class="cart-oth">
        <u-button size="mini" @click="handleEditCart">编辑</u-button>
      </view>
      <!--  去结算  -->
      <yi-submit-bar
        v-if="cartEdit === false"
        :price="totalAmount"
        :disabled="totalNumBuy === 0"
        :safe-area-inset-bottom="safeAreaInsetBottom"
        button-text="去结算"
        @submit="handleCreateOrder"
      >
        <yi-checkbox shape="circle" :active-color="primaryColor" v-model="allChecked" @change="check('all')">
          {{ allChecked ? '不全选' : '全选' }}
        </yi-checkbox>
      </yi-submit-bar>
      <!--  删除购车商品  -->
      <yi-submit-bar
        v-if="cartEdit === true"
        price-class="custom-submit-bar-price"
        bar-class="custom-bar-class"
        :disabled="totalNumBuy === 0"
        button-text="删除"
        currency=" "
        :decimal-length="0"
        :safe-area-inset-bottom="safeAreaInsetBottom"
        @submit="delCart"
      >
        <yi-checkbox shape="circle" :active-color="primaryColor" v-model="allChecked" @change="check('all')">
          {{ allChecked ? '不全选' : '全选' }}
        </yi-checkbox>
      </yi-submit-bar>
    </view>
    <u-empty v-if="cartStoreList.length === 0" mode="car"></u-empty>
  </view>
</template>

<script>
import { Setting, Utils } from '../../index';
import flattenDeep from 'lodash.flattendeep';
import cloneDeep from 'lodash.clonedeep';
import { queryCartList, delCartBunch, updateCartBunch } from '../../mall/api';
import { mapState } from 'vuex';

export default {
  name: 'CartList',
  props: {
    // 商品默认图片
    defaultGoodsIcon: {
      type: String,
      default: null,
    },
    safeAreaInsetBottom: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      imgUrl: Setting.getImgPath(),
      totalPayAmount: 0,
      disabledSubmit: true,
      totalNumBuy: 0, // 总购买数量
      allChecked: false, // 全选状态  true|false
      cartEdit: false, // 购物车编辑模式
    };
  },
  mounted() {
    console.log('%c [购车组件 mounted]: ', 'color:#1989fa;', this.$store.dispatch);
    // this.getCartList();
  },
  computed: {
    ...mapState({
      cartStoreList: state => {
        const cartStoreList = state.mall.cartStoreList;
        cartStoreList.forEach(item => {
          item.forEach(gItem => {
            gItem.minBuyNumber = 1;
            // 根据起售数量(minBuy)超出商品库存(stock) 判断最小购买量
            if (gItem.goodDetail.stock > 0) {
              if (gItem.goodDetail.goods.minBuy <= gItem.goodDetail.stock) {
                gItem.minBuyNumber = gItem.goodDetail.goods.minBuy;
              } else {
                gItem.minBuyNumber = 1;
              }
            } else {
              gItem.minBuyNumber = 0;
            }

            if (gItem.goodDetail.goods.minBuy > gItem.numBuy) {
              gItem.numBuy = gItem.goodDetail.goods.minBuy;
            }
            if (gItem.goodDetail.goods.isLimitBuy && gItem.goodDetail.goods.limitBuyCate === 'cycle') {
              gItem.maxBuyNumber = gItem.goodDetail.goods.cycleNumBuy;
            } else if (gItem.goodDetail.goods.isLimitBuy && gItem.goodDetail.goods.limitBuyCate === 'life') {
              gItem.maxBuyNumber = gItem.goodDetail.goods.lifeNumBuy;
            } else {
              gItem.maxBuyNumber = gItem.goodDetail.stock;
            }
            // 1.起售数量(minBuy)超出商品库存(stock)时,买家无法购买该商品 2.商品库存(stock)为零时,买家无法购买该商品
            if (gItem.goodDetail.goods.minBuy > gItem.goodDetail.stock || gItem.goodDetail.stock === 0) {
              gItem.disabled = true;
            } else {
              gItem.disabled = false;
            }
          });
        });
        return cartStoreList;
      },
      totalAmount: state => state.mall.totalAmount,
      primaryColor: state => (state.primaryColor ? state.primaryColor : '#ee0a24'),
    }),
  },
  methods: {
    // 获取购物车列表
    async getCartList() {
      if (this.$store && this.$store.dispatch) {
        console.log('%c [this.$store.dispatch]: ', 'color:#1989fa;', this.$store.dispatch);
        this.$store.dispatch('mall/getCartList');
      }
    },
    // 修改购买数量
    async onNumBuyChange(e, cidx, gidx) {
      // console.log('%c [修改数量]: ', 'color:#1989fa;', e.currentTarget.dataset);
      const cartStoreListCp = cloneDeep(this.cartStoreList);
      // const { cidx, gidx } = e.currentTarget.dataset;
      // console.log('%c [cIdx]: ', 'color:#1989fa;', cidx);
      // console.log('%c [gIdx]: ', 'color:#1989fa;', gidx);
      // console.log('%c [cartStoreListCp[cIdx]]: ', 'color:#1989fa;', cartStoreListCp[cidx]);
      // console.log('%c []: ', 'color:#1989fa;');
      try {
        const params = {
          form: [
            {
              gid: cartStoreListCp[cidx][gidx].gid,
              numBuy: e.value,
            },
          ],
        };
        await updateCartBunch(params);
        cartStoreListCp[cidx][gidx].numBuy = e.value;
        this.$store.commit('mall/updateState', { cartStoreList: cartStoreListCp });
        await this.calcTotal();
      } catch (e) {
        console.log('err', e);
        throw e;
      }
    },
    // 选中状态处理
    check(type, cartListIndex, index) {
      // console.log(' 选中状态处理 --> ', type, cartListIndex, index);
      if (type === 'store') {
        const _cartListByStore = cloneDeep(this.cartStoreList);
        const curStoreAllCheck = _cartListByStore[cartListIndex].every(item => item.checked === true);
        _cartListByStore[cartListIndex].forEach(item => {
          item.checked = !curStoreAllCheck;
        });
        // const cartStoreList = _cartListByStore;
        // 判断本店铺的商品是否全选
        if (_cartListByStore[cartListIndex].every(item => item.checked === true)) {
          _cartListByStore[cartListIndex][0].storeAllCheck = true;
        } else {
          _cartListByStore[cartListIndex][0].storeAllCheck = false;
        }

        this.$store.commit('mall/updateState', { cartStoreList: _cartListByStore });
      } else if (type === 'item') {
        const _cartListByStore = cloneDeep(this.cartStoreList);
        _cartListByStore[cartListIndex][index].checked = !_cartListByStore[cartListIndex][index].checked;
        // const cartListByStore = _cartListByStore;
        // 判断本店铺的商品是否全选
        if (_cartListByStore[cartListIndex].every(item => item.checked === true)) {
          _cartListByStore[cartListIndex][0].storeAllCheck = true;
        } else {
          _cartListByStore[cartListIndex][0].storeAllCheck = false;
        }
        this.$store.commit('mall/updateState', { cartStoreList: _cartListByStore });
      } else {
        // console.log(' this.allChecked 000 --> ', this.allChecked);
        // const checked = !this.allChecked;
        // console.log(' checked --> ', !this.allChecked);
        const list = cloneDeep(this.cartStoreList);
        list.forEach(item => {
          item.forEach(cartItem => {
            cartItem.checked = !this.allChecked;
          });
        });
        this.allChecked = !this.allChecked;
        // console.log(' this.allChecked 111 --> ', this.allChecked);
        // console.log(' list --> ', list);
        // this.cartStoreList = list;
        // 判断本店铺的商品是否全选
        list.forEach((_, cartListIndex) => {
          if (list[cartListIndex].every(item => item.checked === true)) {
            list[cartListIndex][0].storeAllCheck = true;
          } else {
            list[cartListIndex][0].storeAllCheck = false;
          }
        });

        this.$store.commit('mall/updateState', { cartStoreList: list });
      }
      this.calcTotal(type);
    },
    // 计算总价和总数量
    calcTotal() {
      let list = this.cartStoreList;
      if (list.length === 0) {
        this.empty = true;
        return;
      }
      let total = 0; // 总价格
      let totalNumBuy = 0; // 总购买数量
      let checked = true;
      list.forEach(item => {
        item.forEach(cartItem => {
          if (cartItem.checked === true) {
            // console.log(' 计算总价 --> ', item);
            total += cartItem.price * cartItem.numBuy;
            totalNumBuy += cartItem.numBuy;
          } else if (checked === true) {
            checked = false;
          }
        });
      });
      this.allChecked = checked;
      const totalAmount = Number(total.toFixed(2));
      this.$store.commit('mall/updateState', { totalAmount });
      this.totalNumBuy = totalNumBuy;
    },
    // 去结算
    handleCreateOrder() {
      const newCartList = flattenDeep(this.cartStoreList);
      const selectedCartList = [];
      newCartList.forEach(cartItem => {
        if (cartItem.checked === true && cartItem.goodDetail.stock > 0) {
          selectedCartList.push(cartItem);
        }
      });
      const orderForm = selectedCartList.map(cartItem => {
        const {
          gid,
          numBuy,
          acc,
          name,
          goodDetail: { goods },
        } = cartItem;
        const goodsTransport = Utils.parseTransport(goods.transport);
        return {
          gid,
          acc,
          transport: goodsTransport.indexOf(1) > -1 ? 1 : goodsTransport[0],
          address: '',
          note: '',
          numBuy,
          payMethodPick: 0, // 支付方式 0: 现金支付; >0: 混合支付,由商品支付方式决定
          name,
        };
      });
      // const createOrderUrl = `/packageMall/order/createOrder?orderForm=${JSON.stringify(orderForm)}`;
      // uni.navigateTo({
      //   url: createOrderUrl,
      // });
      this.$emit('createOrder', orderForm);
    },
    // 购物车编辑模式
    handleEditCart() {
      this.cartEdit = !this.cartEdit;
    },
    // 删除购物车商品
    async onDelCartBunch(accArr = null) {
      let form = [];
      console.log('%c [删除购物车商品]: ', 'color:#f33;', this.cartStoreList, accArr);
      if (!accArr) {
        flattenDeep(this.cartStoreList).forEach(cartItem => {
          if (cartItem.checked === true) {
            form.push(cartItem.acc);
          }
        });
      } else {
        form = accArr;
      }
      await delCartBunch({ form });
      await this.getCartList();
    },
    // 删除购物车商品二次确认弹窗
    async delCart() {
      const _this = this;
      if (this.totalNumBuy === 0) return;
      uni.showModal({
        content: '确定删除购物车商品？',
        success: async e => {
          if (e.confirm) {
            await _this.onDelCartBunch();
            this.totalNumBuy = 0;
            this.cartEdit = false;
            uni.showToast({
              title: '删除商品成功',
            });
          }
        },
      });
    },
    // 跳转页面
    navigateToPage(url) {
      console.log('跳转页面 -->', url);
      uni.navigateTo({
        url,
      });
    },
  },
};
</script>

<style lang="scss">
.cart-store-list {
  background-color: #fafafa;
  min-height: 100vh;
  padding-bottom: constant(safe-area-inset-bottom);
  padding-bottom: env(safe-area-inset-bottom);

  .custom-cart-class {
    background-color: #fff !important;
  }
  .cart-store-item {
    margin-bottom: 10px;
  }
  .cart-checkbox-group {
    width: 100vw;
    display: flex;
    flex-direction: row;
    align-items: center;
    padding-left: 20rpx;
    background-color: #fff;
    border-bottom: 1px solid #f2f3f5;
    .store-info-wrap {
      padding-left: 20rpx;
      flex: 1;
      background-color: #fff;
    }
    .goods-card-wrap {
      width: 100%;
      background-color: #fff;
    }
  }

  .del-cart-bar {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    padding: 0 16px;
    -webkit-user-select: none;
    user-select: none;
    z-index: 100;
    background-color: #fff;
    height: 50px;
    .custom-del-btn-class {
      width: 110px;
      height: 40px;
    }
  }
  .custom-submit-bar-price {
    //background-color: #1bd1a5;
  }
  .custom-bar-class {
    //background-color: #f8d402;
    justify-content: space-between;
  }
  .cart-oth {
    padding-left: 30rpx;
  }
  .u-icon {
    display: flex !important;
  }
  .u-checkbox__icon-wrap--circle {
    border-radius: 50%;
  }
}
</style>
