<template>
  <div class="footer-wrap">
    <div :class="['footer', { between: manageCartState }]">
      <div class="footer-radio">
        <cr-radio color="#EC1500" :value="isSelectedAll"
          ><span class="footer-allS">全选</span></cr-radio
        >
        <div class="footer-radio__select" @click="allSelect" />
      </div>
      <div v-show="!manageCartState" class="footer-detail">
        <span class="footer-total"
          >合计：<span class="footer-total-num">{{ calcFeeInfo.totalPayFee || '0.00' }}</span></span
        >
        <div v-if="calcFeeInfo.totalSkuFee" class="footer-discounts" @click="openDisCountsDialog">
          <template v-if="calcFeeInfo.totalCouponFee">
            已优惠：
            <span class="footer-total-discounts">{{ calcFeeInfo.totalCouponFee }}</span> </template
          ><span class="footer-total-discounts-detail">
            优惠明细
            <span
              :class="[
                'iconfont',
                { 'icon-arrow-down': showDisCountsDislog },
                { 'icon-arrow-up': !showDisCountsDislog }
              ]"
          /></span>
        </div>
      </div>
      <cr-button
        v-show="!manageCartState"
        class="footer-button-settle"
        type="primary"
        shape="circle"
        @click="orderSettle"
      >
        结算{{ selectedNumText }}
      </cr-button>
      <div v-show="manageCartState">
        <cr-button class="footer-button-del" shape="circle" type="default" @click="delGoods">
          删除
        </cr-button>
      </div>
    </div>
    <good-discounts v-model="showDisCountsDislog" @close="closeDisCountsDialog" />
    <good-del-dialog :show="showGoodDelDialog" @close="showGoodDelDialog = false" />
    <!-- 新人专享限购弹框 -->
    <GoodLimitPopup v-model="isShowLimit" :list="limitGoods" @continueBuy="onContinueBuy" />
  </div>
</template>
<script>
import goodDiscounts from './goodDiscounts';
import { mapActions, mapGetters, mapState } from 'vuex';

import GoodDelDialog from './goodDelConfirm';
import { beforeConfirmCheck } from '@/api/shopCart.api';
import localStorage from '@/service/localStorage.service';
import GoodLimitPopup from './goodLimitPopup.vue';
// import { saTrackEvent } from '@/utils/sa';
export default {
  components: {
    GoodDelDialog,
    goodDiscounts,
    GoodLimitPopup
  },
  data() {
    return {
      isFree: false,
      showGoodDelDialog: false,
      showDisCountsDislog: false,
      isShowLimit: false,
      limitGoods: []
    };
  },
  computed: {
    ...mapState('shopCart', ['manageCartState', 'calcFeeInfo']),
    ...mapGetters('shopCart', ['isSelectedAll', 'selectedList']),
    ...mapGetters('createOrderStore', ['orderInfo']),
    selectedNumText: function() {
      return this.selectedList.length ? `(${this.selectedList.length})` : '';
    }
  },
  methods: {
    ...mapActions('shopCart', {
      selectAllCartGood: 'select_all_cart_good',
      delCartGood: 'del_cart_good'
    }),
    ...mapActions('createOrderStore', ['fetchOrderInfoApi']),
    openDisCountsDialog() {
      this.showDisCountsDislog = !this.showDisCountsDislog;
    },
    closeDisCountsDialog(show) {
      this.showDisCountsDislog = show;
    },
    allSelect() {
      // saTrackEvent('MINI_ShoppingCartPageSelectAllBtnClick', { check_or_not: !this.isSelectedAll });
      this.selectAllCartGood(!this.isSelectedAll);
    },
    delGoods() {
      if (!this.selectedList.length) {
        this.$toast('您还没有选择要删除的商品哦！');
        return;
      }
      this.showGoodDelDialog = true;
    },
    // 继续购买
    async orderSettle() {
      if (!this.selectedList.length) {
        this.$toast('您还没有选择商品哦');
        return;
      }
      // 检查新人专享商品允许下单情况
      if (await this.checkActivityForNewUserBreakOff()) {
        return;
      }
      let sku_nos = [];
      let pros = [];
      this.selectedList.forEach(item => {
        sku_nos.push(item.skuId);
        if (
          typeof item.product.commonLimitCount === 'number' &&
          item.product.commonLimitCount < item.skuNum
        ) {
          pros.push(item.product);
        }
      });
      // const sku_nos = JSON.stringify(this.selectedList.map(item => item.skuId));
      // saTrackEvent('MINI_ShoppingCartPageBalanceBtnClick', { sku_nos });
      if (pros.length > 0) {
        this.limitGoods = pros;
        this.isShowLimit = true;
      } else {
        this.onSettle();
      }
    },
    onContinueBuy() {
      this.selectedList.forEach(item => {
        if (
          typeof item.product.commonLimitCount === 'number' &&
          item.product.commonLimitCount < item.skuNum
        ) {
          item.skuNum = item.product.commonLimitCount;
        }
      });
      this.onSettle();
    },
    async checkActivityForNewUserBreakOff() {
      try {
        let haveNewUserProduct = false;
        const arr = this.selectedList;
        for (let i = 0; i < arr.length; i++) {
          if (arr[i].product && arr[i].product.userType && arr[i].product.userType == 9) {
            haveNewUserProduct = true;
            break;
          } else {
            continue;
          }
        }
        if (haveNewUserProduct) {
          const [res, err] = await beforeConfirmCheck();
          if (res) {
            return false;
          }
          if (err) {
            return true;
          }
        } else {
          return false;
        }
      } catch (e) {
        return false;
      }
    },
    async onSettle() {
      const order = {
        selectedSkuList: this.selectedList,
        defaultUseCoupon: true,
        defaultUseFreightFeeCoupon: true,
        defaultUseCashCoupon: true,
        defaultUseActivityCoupon: true,
        defaultUseGiftCard: true,
        couponActivityUseIdList: []
      };
      localStorage.set('orderData', order);
      localStorage.remove('addressList');
      const data = await this.fetchOrderInfoApi();
      // 购物车跳转到确认订单页缺少异常处理，err时走默认的toast提示
      if (data) {
        setTimeout(() => {
          this.$router.push({ name: 'createOrder' });
        }, 200);
      }

      // const [data] = await orderConfirm({ selectedSkuList: this.selectedList });
      // if (data) {
      //   const order = {
      //     addrReceiverId: data.addrReceiverInfo?.addrReceiverId,
      //     selectedSkuList: this.selectedList,
      //     defaultUseCoupon: true,
      //     defaultUseFreightFeeCoupon: true,
      //     defaultUseCashCoupon: true,
      //     defaultUseActivityCoupon: true,
      //     defaultUseGiftCard: true,
      //     couponActivityUseIdList: []
      //   };
      //   localStorage.set('orderData', order);
      //   localStorage.remove('addressList');
      //
      //   // setTimeout(() => {
      //   //   this.$router.push({ name: 'createOrder' });
      //   // }, 200);
      // }
    }
  }
};
</script>
<style lang="less" scoped>
.footer-wrap {
  height: 60px;
  width: 100%;
  position: fixed;
  left: 0;
  z-index: 3;
  bottom: calc(@tab-bar-height + constant(safe-area-inset-bottom));
  bottom: calc(@tab-bar-height + env(safe-area-inset-bottom));
  .footer {
    width: 100%;
    height: 100%;
    display: flex;
    position: relative;
    z-index: 2;
    box-sizing: border-box;
    align-items: center;
    color: #999;
    background-color: @white;
    font-size: 12px;
    padding: 10px 12px;
    border-top: 1px solid #ededed;
    &-radio {
      position: relative;
      &__select {
        position: absolute;
        width: 50px;
        height: 20px;
        top: 0;
      }
    }
    &-allS {
      color: #999;
      // transform: scale(0.7);
    }
    .iconfont {
      font-size: 14px;
      vertical-align: bottom;
    }
    &-detail {
      flex: 1;
      text-align: right;
      padding-right: 10px;
    }
    &-total {
      color: #333;
      &-num {
        font-size: 16px;
        font-weight: bold;
        color: #ec1500;
        &::before {
          content: '¥';
          font-size: 14px;
        }
      }
      &-discounts {
        color: #ec1500;
        display: inline-block;
        &::before {
          content: '¥';
        }
      }
      &-discounts-detail {
        padding-left: 6px;
        color: #ec1500;
      }
    }
    &-button-settle {
      width: 130px;
      // background: linear-gradient(269deg, #ff5d00 12%, #ff1900 86%) !important;
      // border-radius: 20px;
      font-size: 17px;
      color: @white;
      // border: none;
      height: 40px;
    }
    &-button-del {
      width: 87px;
      height: 40px;
      font-size: 17px;
      color: #ec1500;
      border: 1px solid;
    }
    &-popup {
      width: 311px;
      &-content {
        padding: 24px 24px 0 24px;
      }
      &-title {
        font-size: 16px;
        text-align: center;
        color: #323233;
        line-height: 22px;
      }
      &-list {
        padding-bottom: 8px;
        max-height: 231px;
        overflow: auto;
        &-shop {
          display: flex;
          width: 100%;
          padding-top: 12px;
          img {
            width: 56px;
            height: 56px;
            border-radius: 5px;
          }
          &-right {
            width: 100%;
            position: relative;
            margin-left: 8px;
            &-title {
              font-size: 12px;
              color: #999999;
              padding-top: 5px;
              text-overflow: -o-ellipsis-lastline;
              overflow: hidden; //溢出内容隐藏
              text-overflow: ellipsis; //文本溢出部分用省略号表示
              display: -webkit-box; //特别显示模式
              -webkit-line-clamp: 2; //行数
              line-clamp: 2;
              -webkit-box-orient: vertical;
              line-height: 17px;
            }
            div {
              display: flex;
              justify-content: space-between;
              align-items: center;
              position: absolute;
              bottom: -2px;
              width: 100%;
              p {
                &:nth-child(1) {
                  color: #ec1500;
                  font-size: 12px;
                }
                &:nth-child(2) {
                  font-size: 12px;
                  color: #333333;
                }
              }
            }
          }
        }
      }
      &-btn {
        display: flex;
        align-items: center;
        justify-content: space-around;
        height: 48px;
        border-top: 1px solid #ebedf0;
        button {
          width: 50%;
          font-size: 16px;
          height: 100%;
          background: #fff;
          &:nth-child(1) {
            color: #323233;
            border-right: 1px solid #ebedf0;
          }
          &:nth-child(2) {
            color: #ec1500;
          }
        }
      }
    }
  }
  .between {
    justify-content: space-between;
  }
}
</style>
