<template>
  <a-modal
    width="800px"
    :visible="visible"
    @ok="handleSubmit"
    @cancel="visible=false"
    title="编辑票种规则"
    :confirmLoading="confirmLoading"
  >

    <a-form-model :model="form" ref="form" class="form-wrap">
      <div class="block-title">
        买票设置
      </div>

      <a-form-model-item
        label="价格"
        v-bind="formItemLayout"
        prop="price"
        :rules="[{ required: true, message: '请选择' }]"
      >
        <a-input-number
          disabled
          style="width:128px"
          :precision="2"
          :min="0"
          :formatter="value => `￥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"
          :parser="value => value.replace(/\￥\s?|(,*)/g, '')"
          v-model="form.price"
        />
      </a-form-model-item>

      <a-form-model-item
        label="可提前预定的天数"
        v-bind="formItemLayout"
        prop="book_future_days"
        :rules="[{ required: true, message: '请输入' }]"
      >
        <a-input-number
          :min="0"
          v-model="form.book_future_days"
        >
        </a-input-number>
      </a-form-model-item>
      <div v-if="data.type!=='SEAT'">
        <a-form-model-item
          label="当日库存"
          v-bind="formItemLayout"
          prop="sales_limit"
          :rules="[{ required: true, message: '请输入' }]"
        >
          <a-input-number
            :min="0"
            v-model="form.sales_limit"
          >
          </a-input-number> (0 表示不限制)
        </a-form-model-item>

        <a-form-model-item
          label="总库存"
          v-bind="formItemLayout"
          prop="total_sales_limit"
          :rules="[{ required: true, message: '请输入' }]"
        >
          <a-input-number
            :min="0"
            v-model="form.total_sales_limit"
          >
          </a-input-number> (0 表示不限制)
        </a-form-model-item>
      </div>

      <a-form-model-item
        label="当日可订"
        v-bind="formItemLayout"
        prop="is_book_today"
      >
        <a-switch
          checked-children="是"
          un-checked-children="否"
          v-model="form.is_book_today"
        />
      </a-form-model-item>

      <a-form-model-item
        v-if="form.is_book_today"
        label="当日可订截止时间"
        v-bind="formItemLayout"
        prop="book_today_endtime"
        :rules="[{ required: true, message: '请选择结束时间' }]"
      >
        <a-time-picker v-model="form.book_today_endtime"/>
      </a-form-model-item>
      <div class="block-title">
        退票设置
      </div>

      <a-form-model-item
        label="是否可退"
        v-bind="formItemLayout2"
        style="width:100%"
        prop="is_refund"
      >
        <a-switch
          disabled
          checked-children="是"
          un-checked-children="否"
          v-model="form.is_refund"
        />
      </a-form-model-item>

      <template v-if="form.is_refund">
        <a-form-model-item
          label="提前可退天数"
          v-bind="formItemLayout"
          prop="refund_advance_days"
          :rules="[{ required: true, message: '请输入' }]"
        >
          <RefundAdvanceDay v-model="form.refund_advance_days"></RefundAdvanceDay>
        </a-form-model-item>

        <a-form-model-item
          label="当日可退截止时间"
          v-bind="formItemLayout"
          prop="refund_today_endtime"
          :rules="[{ required: true, message: '请选择结束时间' }]"
        >
          <RefundDayEndtime v-model="form.refund_today_endtime"></RefundDayEndtime>
        </a-form-model-item>

        <a-form-model-item
          label="退票策略"
          v-bind="formItemLayout"
          prop="refund_strategy"
          :rules="[{ required: true, message: '请输入' }]"
        >
          <a-select v-model="form.refund_strategy.type" disabled>
            <a-select-option value="FIXED">
              固定价格
            </a-select-option>
            <a-select-option value="RATE">
              固定费率
            </a-select-option>
            <a-select-option value="TIME_RATE">
              阶梯费率
            </a-select-option>
          </a-select>
        </a-form-model-item>

        <a-form-model-item
          label="退票费率"
          v-if="form.refund_strategy.type==='RATE'"
          v-bind="formItemLayout"
          :rules="[{ required: true, message: '请输入' }]"
          prop="refund_strategy.rate"
        >
          <a-input-number
            disabled
            style="width:128px"
            :precision="2"
            :min="0"
            :max="1"
            :step="0.01"
            v-model="form.refund_strategy.rate"
          />（0 表示全额退款）
        </a-form-model-item>
      </template>
    </a-form-model>
  </a-modal>
</template>

<script>
import moment from 'moment'
import { setSalesInfo, getSalesInfo, deleteSalesInfo } from '@/api/ticketSetting/ticket'

export default {
  components: {
  },
  props: {
    currentBatch: {
      type: Object,
      default: () => {}
    },
    currentBatchPrice: {
      type: Object,
      default: () => {}
    },
    ticketList: {
      type: Array,
      default: () => []
    },
    allSeatTypeList: {
      type: Array,
      default: () => []
    }
  },
  computed: {
    seat_type_id () {
      return this.form.seat_type_id
    }
  },
  watch: {
    seat_type_id: {
      handler () {
        this.getSalesInfo(this.data, this.ticket_type_id, this.getSeatTypeId(this.seat_type_id))
      }
    }
  },
  data () {
    return {
      visible: false,
      selectTickes: [],
      seatTypeList: [],
      changeSeatTypeList: false, // 是否变动座位类型列表
      ticket_type_id: '',
      confirmLoading: false,
      data: {},
      timeRateList: [
        { timeEffect: '+',
          timeNum: '30',
          timeType: 'minute',
          rate: 0
        }
      ],
      form: {
        price: '0',
        status: '',
        is_change: true,
        is_book_today: true,
        book_future_days: 0,
        sales_limit: 0,
        total_sales_limit: 0,
        book_today_endtime: moment().endOf('day'),
        change_today_endtime: moment().endOf('day'),
        is_refund: true,
        refund_strategy: {},
        refund_advance_days: 0,
        refund_today_endtime: moment().endOf('day'),
        seat_type_id: 0
      },
      formItemLayout: {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 8 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 }
        }
      },
      formItemLayout2: {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 4 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 20 }
        }
      },
      weekDayPrice: [],
      periodPrice: []
    }
  },
  methods: {
    handleAdd () {
      let lastTimeRate
      if (this.timeRateList.length > 0) {
        lastTimeRate = JSON.parse(JSON.stringify(this.timeRateList[this.timeRateList.length - 1]))
      } else {
        lastTimeRate = { seconds: '', rate: '' }
      }
      this.timeRateList.push({
        ...lastTimeRate
      })
    },
    getNewArea () {
      this.changeSeatTypeList = true
      this.getSalesInfo(this.data, this.ticket_type_id)
    },
    getSeatTypeId (e) {
      if (this.seatTypeList.find(i => i.id === e)) {
        return e
      } else {
        return this.seatTypeList[0].id || null
      }
    },
    handleDeleteStrategy (index) {
      this.timeRateList.splice(index, 1)
    },
    // 删除座位类型
    handleDelete (seat_type_id) {
      const params = {}
      params.ticket_type_id = this.ticket_type_id
      params.batch_type_id = this.data.id
      params.seat_type_id = seat_type_id
      params.type = (this.data.type === 'SEAT' ? 'BATCH_SEAT' : 'BATCH')
      this.deleteSalesInfo(params)
      this.$refs.form.resetFields()
      this.seatTypeList = this.seatTypeList.filter(i => i.id !== seat_type_id)
    },
    deleteSalesInfo (params) {
      if (this.seatTypeList.length > 0) {
        this.loading = true
        deleteSalesInfo({ params }).then(res => {
          this.$message.success('删除成功')
          this.loading = false
          this.$emit('updateBatch')
          if (this.seatTypeList.length === 0) {
            this.visible = false
          }
        })
      }
    },
    // 获取售卖信息
    getSalesInfo (data, id, seat_type_id) {
      const params = {}
      params.batch_type_id = data.id
      params.seat_type_id = seat_type_id || 0
      params.ticket_type_id = id
      params.type = (data.type === 'SEAT' ? 'BATCH_SEAT' : 'BATCH')
      getSalesInfo({ params }).then(res => {
        this.bindBatches = res.extraInfo.items
        this.seatTypeList = this.changeSeatTypeList ? res.extraInfo.seat_types : this.seatTypeList
        this.$nextTick(() => {
          const formData = JSON.parse(JSON.stringify(this.bindBatches[0]))
          formData.is_refund = !!formData.is_refund
          formData.is_book_today = !!formData.is_book_today
          formData.is_change = !!formData.is_change

          formData.change_today_endtime = moment(formData.change_today_endtime || '23:59:59', 'HH:mm:ss')
          formData.book_today_endtime = moment(formData.book_today_endtime || '23:59:59', 'HH:mm:ss')
          formData.refund_today_endtime = moment(formData.refund_today_endtime || '23:59:59', 'HH:mm:ss')

          if (!formData.refund_strategy) {
            formData.refund_strategy = { type: 'FIXED' }
          }

          this.form = formData
          if (this.form.refund_strategy && formData.refund_strategy.type === 'TIME_RATE') {
            this.timeRateList = formData.refund_strategy.contents.map(item => {
              const timeEffect = item.seconds > 0 ? '+' : '-'
              const obj = this.formatTime(Math.abs(item.seconds))
              return {
                timeEffect: timeEffect,
                timeNum: obj.timeNum,
                timeType: obj.timeType,
                rate: item.rate
              }
            }).reverse()
          }
        })
        this.changeSeatTypeList = false
      }).finally(() => {
        this.loading = false
      })
    },
    show (data, id) {
      this.changeSeatTypeList = true
      this.data = data
      this.visible = true
      this.ticket_type_id = id
      this.getSalesInfo(data, id)
    },
    formatData (values) {
      return {
        price: values.price,
        status: this.form.status,
        is_change: values.is_change ? 1 : 0,
        is_book_today: values.is_book_today ? 1 : 0,
        book_future_days: values.book_future_days,
        sales_limit: values.sales_limit,
        total_sales_limit: values.total_sales_limit,
        book_today_endtime: values.book_today_endtime ? values.book_today_endtime.format('HH:mm:ss') : null,
        change_today_endtime: values.change_today_endtime ? values.change_today_endtime.format('HH:mm:ss') : null,
        is_refund: values.is_refund ? 1 : 0,
        refund_strategy: values.refund_strategy,
        refund_advance_days: values.refund_advance_days,
        refund_today_endtime: values.refund_today_endtime ? values.refund_today_endtime.format('HH:mm:ss') : null,
        seat_type_id: values.seat_type_id
      }
    },
    handleSubmit () {
      this.$refs.form.validate(validate => {
        if (validate) {
          this.confirmLoading = true
          const data = this.formatData(this.form)

          // if (data.is_refund) {
          //   data.refund_advance_days = data.refund_advance_days < 0 ? 0 : data.refund_advance_days
          // }

          const batch_type_id = this.data.id
          const price = data.price
          const ticket_type_id = this.ticket_type_id
          const period_price = []
          const weekday_price = {}
          const batch = {
            price,
            batch_type_id,
            ticket_type_id,
            period_price,
            weekday_price,
            ...data
          }
          setSalesInfo({ items: [batch] }).then(res => {
            this.$message.success('修改成功。')
            this.visible = false
            this.$emit('updateBatch')
          }).finally(() => {
            this.confirmLoading = false
            this.$refs.form.resetFields()
          })
          this.visible = false
        }
      })
    },
    calculateTime (e) {
      switch (e) {
        case 'minute':
          return 60
        case 'hour':
          return 60 * 60
        case 'day':
          return 60 * 60 * 24
        case 'week':
          return 60 * 60 * 24 * 7
        case 'month':
          return 60 * 60 * 24 * 30
        default:
          return 0
      }
    },
    formatTime (e) {
      switch (true) {
        case (e === 0):
          return {
            timeNum: e,
            timeType: 'minute'
          }
        case (e % (60 * 60 * 24 * 30) === 0):
          return {
            timeNum: e / (60 * 60 * 24 * 30),
            timeType: 'month'
          }
        case (e % (60 * 60 * 24 * 7) === 0):
          return {
            timeNum: e / (60 * 60 * 24 * 7),
            timeType: 'week'
          }
        case (e % (60 * 60 * 24) === 0):
          return {
            timeNum: e / (60 * 60 * 24),
            timeType: 'day'
          }
        case (e % (60 * 60) === 0):
          return {
            timeNum: e / (60 * 60),
            timeType: 'hour'
          }
        case (e % 60 === 0):
          return {
            timeNum: e / 60,
            timeType: 'minute'
          }
        default:
          return 0
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.form-wrap {
  ::v-deep .ant-form-item {
    display: inline-block;  width: 50%;
  }
}

</style>
