<template>
  <a-modal
    width="800px"
    :visible="visible"
    @ok="handleSubmit"
    @cancel="visible=false"
    title="批量新增票种"
  >

    <a-form-model :model="form" class="form-wrap" ref="form">
      <div class="block-title">
        选择要绑定的票种
      </div>

      <a-form-model-item
        label="票种列表"
        style="width:100%"
        v-bind="formItemLayout2"
      >
        <a-select
          mode="multiple"
          v-model="form.selectTickets"
          :rules="[{ required: true, message: '请选择' }]"
        >
          <a-select-option
            v-for="(item) in ticketList"
            :key="item.id"
            :value="item.id"
          >{{ item.name }}</a-select-option>
        </a-select>
      </a-form-model-item>

      <div class="block-title">
        买票设置
      </div>

      <a-form-model-item
        label="价格"
        v-bind="formItemLayout"
        prop="price"
        :rules="[{ required: true, message: '请选择' }]"
      >
        <a-input-number
          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>

      <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>

      <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="formItemLayout"
        prop="is_change"
      >
        <a-switch
          checked-children="是"
          un-checked-children="否"
          v-model="form.is_change"
        />
      </a-form-model-item>

      <a-form-model-item
        v-if="form.is_change"
        label="当日改签截止时间"
        v-bind="formItemLayout"
        prop="change_today_endtime"
        :rules="[{ required: true, message: '请选择截止时间' }]"
      >
        <a-time-picker v-model="form.change_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
          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.type"
          :rules="[{ required: true, message: '请输入' }]"
        >
          <a-select v-model="form.refund_strategy.type">
            <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
            style="width:128px"
            :precision="2"
            :min="0"
            :max="1"
            :step="0.01"
            v-model="form.refund_strategy.rate"
          />（0 表示全额退款）
        </a-form-model-item>

        <a-form-model-item
          label="退票价格"
          v-if="form.refund_strategy.type==='FIXED'"
          v-bind="formItemLayout"
          :rules="[{ required: true, message: '请输入' }]"
          prop="refund_strategy.price"
        >
          <a-input-number
            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.refund_strategy.price"
          />
        </a-form-model-item>
        <br>
        <a-form-model-item
          label="阶梯费率"
          v-if="form.refund_strategy.type==='TIME_RATE'"
          v-bind="formItemLayout"
        >
          <a-button
            class="addBtn"
            type="primary"
            icon="plus"
            @click="handleAdd"
            size="small"
          >新增</a-button>
          <br>
          <ul class="priceList">
            <li
              v-for="(item,index) in timeRateList"
              :key="index"
            >

              <template>
                <div style="display:flex;margin-bottom:10px;width:400px">
                  <span style="white-space:nowrap">时间：</span>
                  <a-select v-model="item.timeEffect" slot="prepend" placeholder="请选择">
                    <a-select-option value="+">开场前</a-select-option>
                    <a-select-option value="-">开场后</a-select-option>
                  </a-select>
                  <a-input-number
                    style="width:100%"
                    v-model="item.timeNum"
                    controls-position="right"
                    :min="0"
                    :max="999"></a-input-number>
                  <a-select v-model="item.timeType" slot="prepend" placeholder="请选择">
                    <a-select-option value="minute">分钟</a-select-option>
                    <a-select-option value="hour">小时</a-select-option>
                    <a-select-option value="day">天</a-select-option>
                    <a-select-option value="week">周</a-select-option>
                    <a-select-option value="month">月</a-select-option>
                  </a-select>
                  <span style="white-space:nowrap" v-if="item.timeEffect">{{ item.timeEffect ==='-'?'之后':'以内' }}</span>
                  <span style="white-space:nowrap;margin-left:20px">费率：</span>
                  <a-input-number
                    style="width:100%;"
                    :precision="2"
                    :min="0"
                    :max="1"
                    :step="0.01"
                    v-model="item.rate"
                  />
                  <a-tooltip placement="top">
                    <template slot="title">
                      <span>删除</span>
                    </template>

                    <a-popconfirm
                      title="确定删除吗？"
                      @confirm="handleDelete(index)"
                      ok-text="是"
                      cancel-text="否"
                    >
                      <a-button
                        type="danger"
                        icon="close"
                        size="small"
                        style="width:100px"
                      ></a-button>
                    </a-popconfirm>
                  </a-tooltip>
                </div>
              </template>
            </li>
          </ul>
        </a-form-model-item>
      </template>
    </a-form-model>

    <PriceCalendar
      :weekDayPrice="weekDayPrice"
      :periodPrice="periodPrice"
      ref="priceCalendar"
    ></PriceCalendar>
  </a-modal>
</template>

<script>
import PriceCalendar from './PriceCalendar'
import moment from 'moment'

export default {
  components: {
    PriceCalendar
  },
  props: {
    ticketList: {
      type: Array,
      default: () => []
    }
  },
  data () {
    return {
      visible: false,
      timeRateList: [
        { timeEffect: '+',
          timeNum: '30',
          timeType: 'minute',
          rate: 0
        }
      ],
      form: {
        price: '',
        status: 'active',
        selectTickets: [],
        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: {
          'type': 'RATE',
          'price': 0,
          'rate': 0,
          'contents': []
        },
        refund_advance_days: 0,
        refund_today_endtime: moment().endOf('day')
      },
      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
      })
    },
    handleDelete (index) {
      this.timeRateList.splice(index, 1)
    },
    show (e) {
      this.visible = true

      const week = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']

      this.weekDayPrice = week.map((val, index) => {
        return {
          label: val,
          value: null
        }
      })

      this.periodPrice = []
      this.form.selectTickets = []

      this.$nextTick(() => {
        this.$refs.form.resetFields()
      })
    },
    formatData (values) {
      return {
        price: values.price,
        status: this.form.status,
        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,
        is_change: values.is_change ? 1 : 0,
        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
      }
    },
    handleSubmit () {
      this.$refs.form.validate(validate => {
        if (validate) {
          if (this.form.refund_strategy && this.form.refund_strategy.type === 'TIME_RATE') {
            this.form.refund_strategy.contents = this.timeRateList.map(item => {
              const seconds = item.timeEffect + item.timeNum * this.calculateTime(item.timeType)
              const rate = item.rate
              return {
                seconds,
                rate
              }
            })
          }
          const data = this.formatData(this.form)
          const ticketList = this.form.selectTickets.map(id => {
            const { name } = this.ticketList.find(i => i.id === id)
            return { id, name, ...data }
          })

          this.$emit('addTickets', ticketList)

          // eslint-disable-next-line prefer-const
          let { priceList, weekDayPriceList } = this.$refs.priceCalendar

          let weekPrice = weekDayPriceList.map(i => i.value)
          weekPrice = Object.assign({}, weekPrice)

          priceList = priceList.map(item => {
            const start = moment(item.start).format('YYYY-MM-DD')
            const end = moment(item.end).format('YYYY-MM-DD')
            const price = item.price
            return {
              start,
              end,
              price
            }
          })

          const ticketPrice = this.form.selectTickets.map(id => {
            return {
              ticket_type_id: id,
              price: data.price,
              period_price: priceList,
              weekday_price: weekPrice
            }
          })
          this.$emit('addTicketPrice', ticketPrice)

          this.visible = false
          this.$refs.form.resetFields()
        }
      })
    },
    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
      }
    }
  }
}
</script>

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

</style>
