<template>
  <a-modal
    :visible="value"
    title="绑定兑换卡"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <a-form
      :form="form"
    >

      <a-form-item
        label="绑定兑换卡"
        v-bind="formItemLayout"
      >
        <a-select
          mode="multiple"
          allowClear
          @change="changeSelect"
          v-decorator="[
            'exchangeCardNos',
            {
              initialValue:formData.exchangeCardNos,
              rules: [{ required: true, message: '请选择'}]
            }
          ]"
        >
          <a-select-option
            v-for="item in exchangeCardList"
            :key="item.exchange_card_no"
            :value="item.exchange_card_no"
            :disabled="item.disabled"
          >
            {{ item.exchange_card_no }}
          </a-select-option>
        </a-select>
        <span v-show="formData.exchangeCardNos.length!==cardLimit" style="color:red">{{ `还需选择${cardLimit - formData.exchangeCardNos.length}张兑换卡` }}</span>
      </a-form-item>
      <a-form-item
        label="兑换卡批量选择"
        v-bind="formItemLayout"
      >
        <a-input-number
          v-decorator="[
            'start_no',
            {
              initialValue:formData.start_no,
            }
          ]"
          :min="0"
          :precision="0"
        /> -
        <a-input-number
          v-decorator="[
            'end_no',
            {
              initialValue:formData.end_no,
            }
          ]"
          :min="0"
        />
        <a-button
          size="small"
          style="margin-left:10px"
          type="primary"
          @click="batchBindCode"
        >
          绑定
        </a-button>
        <br>
        <span
          v-if="form.getFieldValue('end_no') && form.getFieldValue('start_no')" >{{ `当前选择${Math.abs(form.getFieldValue('end_no')- form.getFieldValue('start_no'))+1}张` }}</span>
      </a-form-item>
      <a-form-item
        label="备注"
        v-bind="formItemLayout"
      >
        <a-textarea
          v-model="formData.remark"
          :rows="4" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script>
import { getExchangeCardList } from '@/api/marketingSetting/salesUser'
import { checkConvertibleOrder, getOrderById } from '@/api/orderSetting/order'

import exchangeCardMixin from './exchangeCard/exchangeCardMixin.js'

export default {
  props: {
    currentOrder: {
      type: Object,
      default: () => null
    }
  },
  mixins: [exchangeCardMixin],
  data () {
    return {
      visible: false,
      cardLimit: 0, // 兑换卡数量限制
      exchangeCardList: [],
      formData: {
        exchangeCardNos: [],
        start_no: '',
        end_no: '',
        remark: ''
      }
    }
  },

  methods: {
    changeSelect (val) {
      this.formData.exchangeCardNos = val
      this.setCardDisabled(val)
    },
    // 设置不可选的兑换卡
    setCardDisabled (val) {
      if (val.length === this.cardLimit) {
        this.exchangeCardList = this.exchangeCardList.map(i => {
          if (val.includes(i.exchange_card_no)) {
            i.disabled = false
          } else {
            i.disabled = true
          }
          return i
        })
      } else {
        this.exchangeCardList = this.exchangeCardList.map(i => {
          i.disabled = false
          return i
        })
      }
    },
    handleOk (e) {
      console.log(e)
      e.preventDefault()
      this.form.validateFields((err, values) => {
        if (!err && values.exchangeCardNos.length === this.cardLimit) {
          const params = {
            id: this.currentOrder.id,
            active: true,
            exchangeCardNos: values.exchangeCardNos,
            remark: this.formData.remark
          }
          checkConvertibleOrder(params).then(res => {
            this.$message.success('操作成功')
            this.form.resetFields()
            this.$emit('input', false)
            this.$emit('update')
          })
        }
      })
    },
    batchBindCode () {
      const start_no = this.form.getFieldValue('start_no')
      const end_no = this.form.getFieldValue('end_no')
      if (String(start_no) && String(end_no)) {
        const batchList = this.checkNum(start_no, end_no)
        const exitIds = []
        this.exchangeCardList.forEach((i) => {
          if (batchList.includes(i.exchange_card_no)) {
            exitIds.push(i.exchange_card_no)
          }
        })
        const cardList = Array.from(new Set(this.formData.exchangeCardNos.concat(exitIds)))
        if (cardList.length > this.cardLimit) {
          this.$message.warning('选择的兑换卡数量不可大于当前订单票数')
          return false
        }
        this.setCardDisabled(cardList)
        this.formData.exchangeCardNos = cardList
        this.form.setFieldsValue({ exchangeCardNos: this.formData.exchangeCardNos })
      } else {
        this.$message.warning('批量选择请输入完整')
      }
    },
    // 获取两数之间的数组
    checkNum (min, max) {
      const arr = []
      if (min > max) {
        [min, max] = [max, min]
      }
      for (let i = min; i < max + 1; i++) {
        arr.push(i)
      }
      return arr
    },
    getExchangeCardList (userId) {
      this.loading = true
      const params = {
        status: ['WAIT_SALE'],
        pageNum: 0,
        sales_user_id: userId,
        remark: ''
      }
      getExchangeCardList(params).then(res => {
        this.loading = false
        this.exchangeCardList = res.extraInfo.list
      })
    }
  },
  watch: {
    value (val) {
      const userId = this.currentOrder.salesUser.id
      if (val) {
        this.getExchangeCardList(userId)
        getOrderById(this.currentOrder.id).then(res => {
          this.cardLimit = res.extraInfo.tickets.length
        })
      }
    }
  }

}
</script>

<style scoped>
.container>>>.ant-modal-content{
  width: 800px;
}
</style>
