<template v-if="reqFinished">
  <cr-popup
    v-model="isShow"
    closeable
    round
    position="bottom"
    :style="{ height: '80vh', overflowY: 'unset !important' }"
    @close="handleClose"
  >
    <div v-if="extObj != null" class="popup-container">
      <div class="coupon-title">{{ extObj.popTitle }}</div>
      <div class="coupon-content">
        <!--         优惠券-->
        <cr-tabs
          v-if="couponType === COMB_COUPON"
          v-model="active"
          v-bind="tabsConfig"
          :border="true"
          title-bg-color="#fff"
          title-active-color="#EC1500"
          title-inactive-color="#999999"
        >
          <cr-tab :title="showTabs[0]"
            ><coupon-panel :data-list="list" :coupon-type="couponType"
          /></cr-tab>
          <cr-tab :title="showTabs[1]"
            ><coupon-panel :data-list="invalidCoupons" type="invalidCoupons"
          /></cr-tab>
        </cr-tabs>
        <!--         礼品卡 运费券 优惠活动-->
        <coupon-panel v-else v-bind="couponPanelConfig" :data-list="list" />
      </div>
      <div v-if="showBottom" class="coupon-bottom">
        <button @click="handleRadioSubmit">确定</button>
      </div>
    </div>
  </cr-popup>
</template>
<script>
import { getCouponChooseList } from '@/api/home.api';
import {
  COMB_COUPON,
  DISCOUNT,
  FREIGHT,
  GIFT,
  HAS_DISCOUNT,
  REDUCTION,
  CASH
} from '@/constants/order';
import CouponPanel from './couponPanel/index.vue';
import { handlerSelectApi } from '@/views/orders/createOrderAdapter';

export default {
  name: 'CouponList',
  components: {
    CouponPanel
  },
  props: {
    value: {
      type: Boolean,
      default: false
    },
    couponId: {
      type: [String, Number],
      default: 0
    },
    // 选中的券集合
    couponIds: {
      type: Array,
      default: () => []
    },

    hasCouponActivity: {
      type: Number,
      default: 0
    },
    couponType: [String, Number],
    currency: {
      type: String,
      default: '¥'
    },
    goodsInfo: {
      type: Array,
      default: () => []
    },
    extObj: {
      type: Object,
      default: () => null
    },
    couponActivityInfoList: {
      type: Array,
      default: () => []
    },
    selectActivityInfo: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      list: null,
      reqFinished: false, // 标记网络请求是否完成
      invalidCoupons: null, // 不可用的优惠券
      isShow: false,
      GIFT, // 礼品卡
      REDUCTION, // 活动
      DISCOUNT, // 优惠券
      COMB_COUPON, // 组合优惠券
      FREIGHT, // 运费
      CASH,
      active: 0,
      tabsConfig: {
        'title-inactive-color': '#333333',
        'title-bg-color': '#fff',
        color: '#fff'
      }
    };
  },
  computed: {
    //couponPanel 配置参数
    couponPanelConfig() {
      let couponPanelConfig = {
        compName: '',
        couponType: this.couponType
      };
      switch (this.couponType) {
        case REDUCTION:
          couponPanelConfig.compName = 'ActivityItem';
          couponPanelConfig.emptyText = '好像没有发现什么';
          break;
        case GIFT:
          couponPanelConfig.compName = 'GiftCardItem';
          break;
        case FREIGHT:
          couponPanelConfig.compName = 'CouponItem';
          break;
      }
      return couponPanelConfig;
    },
    selectedCoupon() {
      return this.list.filter(l => {
        if (l.isSelect) return l;
      });
    },
    showBottom() {
      return !(this.couponType === COMB_COUPON && this.active === 1);
    },
    showTabs() {
      return [
        `可用优惠券(${this.list?.length || 0})`,
        `不可用优惠券(${this.invalidCoupons?.length || 0})`
      ];
    }
  },
  watch: {
    value(v) {
      if (v) {
        v &&
          this.getCouponChooseList(() => {
            this.isShow = v;
          });
      } else {
        this.isShow = v;
      }
    }
  },
  methods: {
    // 关闭弹窗
    handleClose() {
      this.$emit('input', false);
    },
    // 点击确定
    handleRadioSubmit() {
      this.$emit('coupon-select', this.getCouponUserIdList(this.selectedCoupon));
    },
    // TODO 对数据进行加工,确定哪些是选中的,改方法建议调整位置，待优化
    getCouponUserIdList() {
      // 本次选中的
      const current = this.list.reduce((result, item) => {
        if (item.isSelect) {
          result.push({
            couponActivityType: item?.couponActivityType || item?.couponCategory || this.couponType, // 礼品卡没有类型，需要补充
            couponActivityUseId: item?.pickupId || item?.id // id 礼品卡 pickupId 优惠券
          });
        }
        return result;
      }, []);
      // 非本次选中
      const oldList = this.couponActivityInfoList.reduce((result, item) => {
        // 有值，并且不是本次操作的类型集合
        if (
          item?.couponActivityUseId &&
          !this.extObj.targetKeys.includes(item.couponActivityType)
        ) {
          result.push(item);
        }
        return result;
      }, []);
      return [...oldList, ...current];
    },
    async getCouponChooseList(cb) {
      if (!this.goodsInfo.length) return;
      this.list = [];
      // 获取下单的商品
      const selectedSkuList = this.goodsInfo.map(item => {
        const { count: skuNum, skuId } = item;
        return {
          skuId,
          skuNum
        };
      });

      const cartInfo = [];
      // 商品详情过来的时候
      cartInfo.push({
        skus: selectedSkuList
      });
      const [res] = await getCouponChooseList({
        cartInfo, // 选择的sku信息
        couponActivityType: this.couponType, // 多活动需要对参数进行适配
        selectedCouponActivityList: this.selectActivityInfo // 之前选中的活动id
      });
      if (res) {
        let _list = res.coupons || [];
        let _id_name = 'pickupId';
        if (this.couponType === GIFT) {
          if (HAS_DISCOUNT === this.hasCouponActivity && res.userCardInfoVoList) {
            _list = res.userCardInfoVoList;
          } else {
            _list = [];
          }
          _id_name = 'id';
        } else if (this.couponType === REDUCTION) {
          _list = res.activityList || [];
          _id_name = 'activityId';
        }
        _list.forEach(d => {
          d.id = d[_id_name];
          d.isSelect = this.couponIds.includes(d[_id_name]);
        });
        this.list = handlerSelectApi(_list, this.couponType, this.couponIds);
        console.log('jhb', this.list, _list);
        // 不可选中优惠券查看
        this.invalidCoupons = res?.invalidCoupons || [];
      }
      cb && cb();
    }
  }
};
</script>
<style lang="less" scoped>
::v-deep .cr-tabs__line {
  background: red !important;
}
::v-deep .cr-hairline--top-bottom {
  &::after {
    border-top: 0 !important;
    border-color: #f2f3f5 !important;
  }
}
.popup-container {
  display: flex;
  flex-direction: column;
  width: 100%;
  position: relative;
  height: 100%;
  z-index: -1;
}
.coupon-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  padding: 0 12px;
}
.coupon-title {
  height: 48px;
  display: flex;
  align-items: center;
  justify-content: center;
  .text-size(16);
}
.coupon-bottom {
  height: 60px;
  width: 100vw;
  background: #fff;
  position: absolute;
  left: 0;
  bottom: 0;
  display: flex;
  justify-content: center;
  align-items: flex-end;
  button {
    width: 335px;
    margin-bottom: 12px;
    background-image: linear-gradient(269deg, #ff5d00 12%, #ff1900 86%);
    border-radius: 80px;
    height: 40px;
    .text-size(14);
    line-height: 40px;
    color: #fff;
  }
}
.coupon-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  padding: 0 12px;
  .scroll-wrap {
    height: calc(80vh - 48px); /* 去掉头部和底部的高度 */
    overflow: auto; /* 垂直滚动条 */
  }
}
.coupon-list {
  &__item {
    position: relative;
    display: flex;
    align-items: center;
    background: #ffece6;
    border-radius: 6px;
    padding: 18px 10px;
    margin-bottom: 10px;

    &--disabled {
      -webkit-filter: grayscale(100%) opacity(0.8); /* Chrome, Safari, Opera */
      filter: grayscale(100%) opacity(0.8);

      .cr-coupon-list__right {
        display: none;
      }
    }
  }
  &__tag {
    position: absolute;
    top: 0;
    left: 0;
    width: 44px;
    height: 16px;
  }
  &__left {
    text-align: center;
    color: #ec3333;
  }

  &__amount {
    font-size: 30px;
    font-weight: 500;
    line-height: 36px;
    margin: 0;

    text {
      font-size: 16px;
      line-height: 22px;
    }
  }

  &__limit {
    .text-size(12);
    color: #ec3333;
    line-height: 17px;
    margin: 0;
  }

  &__content {
    padding: 0 18px;
  }

  &__desc {
    .text-size(14);
    line-height: 20px;
    font-weight: 500;
    color: #333;
    margin-bottom: 3px;
  }

  &__date {
    .text-size(12);
    color: #666666;
    line-height: 17px;
  }

  &__right {
    margin-left: auto;
    .radio {
      width: 30px;
      height: 30px;
      display: block;
      transform: scale(0.8);
      background-color: red !important;
    }
  }
}

::v-deep .cr-icon {
  line-height: 28px;
}
.minus-list {
  &__list {
    padding: 10px 10px 0;
    overflow-y: scroll;
    overflow-x: hidden;
    height: 62vh;
  }
  &__item {
    position: relative;
    display: flex;
    align-items: center;
    justify-content: space-between;
    border-radius: 6px;
    padding: 6px 10px;
    margin-bottom: 10px;
  }
  &__left {
    .text-size(14);
    span {
      color: @font-color-base;
      .text-size(12);
    }
  }
}
</style>
