<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 v-if="data.type==='SEAT'">
        <div class="block-title">
          选择座位类型
        </div>
        <a-form-model-item
          label="
          选择座位类型"
          v-bind="formItemLayout"
          prop="seat_type_id"
          :rules="[{ required: true, message: '请选择' }]"
        >

          <a-select v-model="form.seat_type_id" style="width:200px">
            <a-select-option
              v-for="(i,index) in seatTypeList"
              :value="i.id"
              :key="index"
            >
              {{ i.name }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-button
          class="addBtn"
          type="primary"
          size="small"
          @click="$refs.singleAddArea.show(ticket_type_id,seatTypeList)"
        >新增区域</a-button>
        <a-popconfirm
          title="确定删除当前座位类型？"
          @confirm="handleDelete(form.seat_type_id)"
        >
          <a-icon
            slot="icon"
            type="question-circle-o"
            style="color: red"
          />
          <a-button
            size="small"
            type="danger"
          >
            删除
          </a-button>
        </a-popconfirm>
      </div>
      <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>
      <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 v-if="data.type!=='SEAT'">
        <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>

      <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"
          :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="handleDeleteStrategy(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
      v-if="!['demo', 'YINXIANGMAZU'].includes(this.project)"
      :weekDayPrice="weekDayPrice"
      :periodPrice="periodPrice"
      ref="priceCalendar"
    ></PriceCalendar >

    <SingleAddArea ref="singleAddArea" :allSeatTypeList="allSeatTypeList" :data="data" @updateArea="getNewArea">
    </SingleAddArea>
  </a-modal>
</template>

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

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

export default {
  components: {
    PriceCalendar,
    SingleAddArea
  },
  props: {
    currentBatch: {
      type: Object,
      default: () => {}
    },
    currentBatchPrice: {
      type: Object,
      default: () => {}
    },
    ticketList: {
      type: Array,
      default: () => []
    },
    allSeatTypeList: {
      type: Array,
      default: () => []
    },
    fatherSelectedRowKeys: {
      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 {
      deleteParams: {},
      visible: false,
      selectTickes: [],
      seatTypeList: [],
      changeSeatTypeList: false, // 是否变动座位类型列表
      ticket_type_id: '',
      confirmLoading: false,
      data: {},
      timeRateList: [
        { timeEffect: '+',
          timeNum: '30',
          timeType: 'minute',
          rate: 0
        }
      ],
      form: {
        price: '',
        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] && this.seatTypeList[0].id) || null
      }
    },
    handleDeleteStrategy (index) {
      this.timeRateList.splice(index, 1)
    },
    // 删除座位类型
    handleDelete (seat_type_id) {
      this.fatherSelectedRowKeys.map((item, index) => {
        const params = {}
        params.ticket_type_id = this.ticket_type_id
        params.batch_type_id = item
        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
        console.log('%c [ this.seatTypeList ]-503', 'font-size:13px; background:pink; color:#bf2c9f;', this.seatTypeList)

        this.seatTypeList = this.changeSeatTypeList ? (res.extraInfo.seat_types || []) : this.seatTypeList
        console.log('%c [ this.seatTypeList ]-504', 'font-size:13px; background:pink; color:#bf2c9f;', 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()
          }

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

          this.weekDayPrice = week.map((val, index) => {
            return {
              label: val,
              value: formData.weekday_price[index]
            }
          })

          this.periodPrice = formData.period_price.map(item => {
            item.tempValue = item.price
            item.dateRange = [moment(item.start, 'YYYY-MM-DD'), moment(item.end, 'YYYY-MM-DD')]

            return item
          })
        })
        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
          // eslint-disable-next-line prefer-const
          let { priceList, weekDayPriceList } = ['demo', 'YINXIANGMAZU'].includes(this.project) ? {} : this.$refs.priceCalendar
          priceList = []
          weekDayPriceList = [{
            'label': '周一',
            'value': null
          }, {
            'label': '周二',
            'value': null
          },
          {
            'label': '周三',
            'value': null
          },
          {
            'label': '周四',
            'value': null
          },
          {
            'label': '周五',
            'value': null
          },
          {
            'label': '周六',
            'value': null
          },
          {
            'label': '周日',
            'value': null
          }
          ]

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

          // 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 = priceList
          const weekday_price = weekPrice

          const myItems = this.fatherSelectedRowKeys.map(item => {
            const t = {
              price,
              batch_type_id,
              ticket_type_id,
              period_price,
              weekday_price,
              ...data
            }
            t.batch_type_id = item
            return t
          })
          // console.log(this.fatherSelectedRowKeys)
          // console.log(myItems.length, myItems)
          setSalesInfo({ items: myItems }).then(res => {
            this.$message.success('修改成功。')
            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>
