<template>
  <view class="footer-wrap">
    <view :class="['footer', { between: manageCartState }]">
      <view class="footer-check" @click="allSelect">
        <radio color="#EC1500" class="footer-allS" :checked="isSelectedAll" />
        <view class="footer-check-label">全选</view>
      </view>
      <view v-if="!manageCartState" class="footer-detail">
        <text class="footer-total"
          >合计：<text class="footer-total-num">{{ calcFeeInfo.totalPayFee || "0.00" }}</text></text
        >
        <view v-if="calcFeeInfo.totalSkuFee" class="footer-discounts" @click="openDisCountsDialog">
          <template v-if="calcFeeInfo.totalCouponFee">
            已优惠：
            <text class="footer-total-discounts">{{ calcFeeInfo.totalCouponFee }}</text> </template
          ><text class="footer-total-discounts-detail">
            优惠明细
            <text
              :class="[
                'iconfont',
                { 'icon-arrow-down': showDisCountsDislog },
                { 'icon-arrow-up': !showDisCountsDislog }
              ]"/></text
        ></view>
      </view>
      <button
        v-if="!manageCartState"
        class="footer-button-settle"
        type="default"
        @click="orderSettle"
      >
        结算{{ selectedNumText }}
      </button>
      <view v-if="manageCartState">
        <button class="footer-button-del" type="default" @click="delGoods">
          删除
        </button>
      </view>
    </view>
    <good-discounts v-model="showDisCountsDislog" @close="closeDisCountsDialog" />
    <good-del-dialog :show="showGoodDelDialog" @close="showGoodDelDialog = false" />
    <GoodLimitPopup v-model="isShowLimit" :list="limitGoods" @continueBuy="onContinueBuy" />
  </view>
</template>
<script>
import { throtte } from "@/utils";
import { saTrackEvent } from "@/utils/sa";
import { orderConfirm, beforeConfirmCheck } from "@/api/shopCart.api";
import { mapActions, mapState, mapGetters } from "../shopCartModules";
import goodDiscounts from "./goodDiscounts.vue";
import GoodDelDialog from "./goodDelConfirm";
import GoodLimitPopup from "./goodLimitPopup.vue";
export default {
  components: {
    GoodDelDialog,
    goodDiscounts,
    GoodLimitPopup
  },
  data() {
    return {
      isFree: false,
      isShowLimit: false,
      limitGoods: [],
      showGoodDelDialog: false,
      showDisCountsDislog: false
    };
  },
  computed: {
    ...mapState(["manageCartState", "calcFeeInfo"]),
    ...mapGetters(["isSelectedAll", "selectedList"]),
    selectedNumText: function() {
      return this.selectedList.length ? `(${this.selectedList.length})` : "";
    }
  },
  methods: {
    ...mapActions({
      selectAllCartGood: "select_all_cart_good",
      delCartGood: "del_cart_good"
    }),
    openDisCountsDialog() {
      this.showDisCountsDislog = !this.showDisCountsDislog;
    },
    closeDisCountsDialog({ show }) {
      this.showDisCountsDislog = show;
    },
    allSelect() {
      saTrackEvent("MINI_ShoppingCartPageSelectAllBtnClick", { check_or_not: !this.isSelectedAll });
      this.$nextTick(() => {
        this.selectAllCartGood(!this.isSelectedAll);
      });
    },
    delGoods() {
      if (!this.selectedList.length) {
        uni.showToast({
          title: "您还没有选择要删除的商品哦！",
          icon: "none"
        });
        return;
      }
      this.showGoodDelDialog = true;
    },
    orderSettle: throtte(function() {
      if (!this.selectedList.length) {
        uni.showToast({
          title: "您还没有选择商品哦",
          icon: "none"
        });
        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);
        }
      });
      sku_nos = JSON.stringify(sku_nos);
      saTrackEvent("MINI_ShoppingCartPageBalanceBtnClick", { sku_nos });
      if (pros.length > 0) {
        this.limitGoods = pros;
        this.isShowLimit = true;
      } else {
        this.onSettle();
      }
    }, 2000),
    // 继续购买
    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.activityType && arr[i].product.activityType == 8) {
            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() {
      // 检查新人专享商品允许下单情况
      if (await this.checkActivityForNewUserBreakOff()) {
        return;
      }
      const [data] = await orderConfirm({ selectedSkuList: this.selectedList });
      if (data) {
        const that = this;
        setTimeout(() => {
          uni.navigateTo({
            url: `/pages/order/createOrder`,
            success: function(res) {
              res.eventChannel.emit("onDetailConfirmInfo", {
                addrReceiverId: data.addrReceiverInfo?.addrReceiverId,
                selectedSkuList: that.selectedList,
                defaultUseCoupon: true,
                defaultUseFreightFeeCoupon: true,
                defaultUseCashCoupon: true,
                defaultUseActivityCoupon: true,
                defaultUseGiftCard: true,
                couponActivityUseIdList: []
              });
            }
          });
        }, 200);
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.footer-wrap {
  height: 120rpx;
  width: 100vw;
  position: fixed;
  left: 0;
  bottom: 0;
  z-index: 1;
  .footer {
    width: 100%;
    height: 100%;
    display: flex;
    position: relative;
    z-index: 98;
    align-items: center;
    color: $text-color-n1;
    background-color: $white;
    font-size: $uni-font-size-sm;
    padding: $padding-md 24rpx;
    border-top: 1rpx solid $border-color-gray;
    &-allS {
      transform: scale(0.7);
    }
    .iconfont {
      font-size: $uni-font-size-base;
      vertical-align: bottom;
    }
    &-detail {
      flex: 1;
      text-align: right;
      padding-right: $padding-md;
    }
    &-total {
      color: $font-color-dark;
      &-num {
        font-size: $uni-font-size-lg;
        font-weight: bold;
        color: $font-color-search;
        &::before {
          content: "¥";
          font-size: $uni-font-size-base;
        }
      }
      &-discounts {
        color: $font-color-search;
        display: inline-block;
        &::before {
          content: "¥";
        }
      }
      &-discounts-detail {
        padding-left: $margin-md;
        color: $font-color-search;
      }
    }
    &-button-settle {
      width: 260rpx;
      background: $background-primary !important;
      border-radius: $uni-border-radius-xl;
      font-size: $line-height-md;
      color: $white;
      border: none;
    }
    &-button-del {
      width: 174rpx;
      background: $white !important;
      border-radius: $uni-border-radius-xl;
      font-size: $line-height-md;
      color: $font-color-search;
      border: 2rpx solid;
    }
  }
  .between {
    justify-content: space-between;
  }
  .footer-check {
    position: relative;
    height: 42rpx;
    display: flex;
    align-items: center;
    &-label {
      position: absolute;
      z-index: 1;
      left: 0;
      top: 0;
      padding-left: 50rpx;
      width: 100rpx;
      height: 42rpx;
      box-sizing: border-box;
      display: flex;
      align-items: center;
    }
  }
}
</style>
