import {Component, Prop, Watch, Vue} from 'vue-property-decorator';
import TableModal from '../TableModal/index.vue';
import couponColumn from './columns/coupon.column';
import { cloneDeep } from 'lodash';
import operationApi from '@api/operation.api';

@Component({ components: { TableModal }, name: 'CouponTableModal' })
export default class CouponTableModal extends Vue {
  @Prop({ default: () => ([]), type: Array }) value;
  @Prop({ default: () => ([]), type: Array }) formControl;

  coupon: object[] = cloneDeep(this.value);
  templates: object[] = [];
  table: object[] = [
    {
      title: '选择优惠券',
      type: 'coupon',
      multiple: true,
      columns: couponColumn,
      query: this.query
    }
  ];

  @Watch('coupon')
  onFormChange(newVal) {
    this.$emit('input', newVal);
  }

  async query(data) {
    // receiverType 领取方式 1：主动领取 2：自动发放 3：不限
    const res = await operationApi.couponList({ ...data });
    const couponInfoList = res?.couponInfoList?.map(item => {
      item.receiverTime = `${item.receiverStartTime.slice(0, 10)}--${item.receiverEndTime.slice(0, 10)}`;
      item.useTime = item.useTimeStart
        ? `${item.useTimeStart}-${item.useTimeEnd}`
        : item.validHours
        ? `自领取后有效${item.validHours}小时`
        : `自领取${item.receiverDaysValid}天后生效，有效天数${item.validDays}天`;
      // item.useTime = item.useTimeStart ? `${item.useTimeStart}-${item.useTimeEnd}` : `自领取${item.receiverDaysValid}天后生效，有效天数${item.validDays}天`;
      const selections = this.templates.length ? this.templates : this.coupon;
      console.log('query', selections, this.templates, this.coupon);
      if (selections.some(v => v === item.id)) {
        item._checked = true;
      }
      return item;
    });

    return { data: couponInfoList || [], total: res?.pageInfo?.totalCount };
  }
}