<template>
  <el-dialog
    :title="title"
    :visible.sync="visible"
    width="840px"
    @close="handleClose">
    <el-form
      inline
      :model="form"
      ref="form"
      class="form-wrap"
      label-width="160px">
      <div class="dialog-info">
        <el-form-item
          style="width:100%"
          verify
          label="场次名称"
          prop="name">
          <el-input v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item
          verify
          style="width:100%"
          label="循环策略"
          prop="strategy">
          <el-select
            v-model="form.strategy"
            @change="form.strategyContent=[]">
            <el-option label="日常" value="basic"></el-option>
            <el-option label="周期性" value="week"></el-option>
            <el-option label="日期段" value="date"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          :verify="verifyPeriod"
          label="策略内容"
          style="width:100%"
          v-if="form.strategy !== 'basic'"
          prop="strategyContent">
          <template v-if="form.strategy==='week'">
            <el-checkbox-group v-model="form.strategyContent">
              <el-checkbox
                v-for="(i,index) in weekdayMap"
                :key="index + 1"
                :label="index + 1">
                {{ i }}
              </el-checkbox>
            </el-checkbox-group>
          </template>

          <template v-else>
            <div
              v-for="(item,index) in form.strategyContent"
              :key="index"
              class="periodItem"
            >
              <el-date-picker
                style="width:414px; margin-right:10px"
                v-model="form.strategyContent[index]"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期">
              </el-date-picker>

              <el-tooltip
                content="删除"
                placement="top"
                effect="dark">
                <el-button
                  @click="form.strategyContent.splice(index, 1)"
                  type="danger"
                  icon="el-icon-minus"
                  size="mini"
                  circle
                ></el-button>
              </el-tooltip>
            </div>

            <el-button
              type="primary"
              @click="handleAddPeriod">
              新增时间段
            </el-button>
          </template>
        </el-form-item>
        <el-form-item
          verify
          label="开始时间"
          prop="startTime">
          <el-time-picker
            v-model="form.startTime"
            placeholder="开始时间">
          </el-time-picker>
        </el-form-item>

        <el-form-item
          verify
          label="结束时间"
          prop="endTime">
          <el-time-picker
            v-model="form.endTime"
            placeholder="结束时间">
          </el-time-picker>
        </el-form-item>

        <el-form-item
          verify
          label="开场后停售(分钟)"
          prop="saleStopMinutes">
          <el-input-number
            v-model="form.saleStopMinutes"
            :min="-1"
            placeholder="-1为不限制">
          </el-input-number>
        </el-form-item>

        <el-form-item
          verify
          label="开场前停止退票(分钟)"
          prop="cancelStopBeforeStartMinutes">
          <el-input-number
            v-model="form.cancelStopBeforeStartMinutes"
            :min="-1"
            placeholder="-1为不限制">
          </el-input-number>
        </el-form-item>

        <el-form-item
          verify
          label="开场后停止退票(分钟)"
          prop="cancelStopAfterStartMinutes">
          <el-input-number
            v-model="form.cancelStopAfterStartMinutes"
            :min="-1"
            placeholder="-1为不限制">
          </el-input-number>
        </el-form-item>

        <el-form-item
          verify
          label="开场前允许检票(分钟)"
          prop="preCheckMinutes">
          <el-input-number
            v-model="form.preCheckMinutes"
            :min="-1"
            placeholder="-1为不限制">
          </el-input-number>
        </el-form-item>

        <el-form-item
          verify
          label="开场后停止检票(分钟)"
          prop="stopCheckMinutes">
          <el-input-number
            v-model="form.stopCheckMinutes"
            :min="-1"
            placeholder="-1为不限制">
          </el-input-number>
        </el-form-item>

        <el-form-item
          verify
          label="最大销售数量"
          prop="maxSaleNums"
          style="width:100%">
          <el-input-number
            v-model="form.maxSaleNums"
            :min="-1"
            placeholder="-1为不限制">
          </el-input-number>
        </el-form-item>

        <el-form-item
          :verify="verifyTicket"
          label="绑定票种"
          prop="ticketTypeIds"
          style="width:100%">
          <el-select
            v-model="form.ticketTypeIds"
            filterable
            multiple
            placeholder="请选择">
            <el-option
              v-for="ticketType in ticketTypeList"
              :key="ticketType.id"
              :label="ticketType.name"
              :value="ticketType.id">
            </el-option>
          </el-select>
        </el-form-item>
      </div>
    </el-form>

    <div slot="footer">
      <el-button @click="handleClose">
        取 消
      </el-button>
      <el-button
        type="primary"
        :loading="loading"
        @click="handleSubmit">
        确 定
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
import { updateBatchConfig, saveBatchConfig } from '@/api/batch'
import { strategyMap, weekdayMap } from '@/assets/staticData'
import moment from 'moment'

const defaultForm = {
  name: '',
  strategy: 'basic',
  strategyContent: [],
  startTime: new Date(2020, 1, 1, 0, 0, 0),
  endTime: new Date(2020, 1, 1, 0, 0, 0),
  saleStopMinutes: -1,
  cancelStopBeforeStartMinutes: -1,
  cancelStopAfterStartMinutes: -1,
  preCheckMinutes: -1,
  stopCheckMinutes: -1,
  maxSaleNums: -1,
  ticketTypeIds: []
}

export default {
  computed: {
    ticketTypeList () {
      return this.$store.state.app.ticketTypeList
    }
  },
  data () {
    return {
      title: '',
      visible: false,
      strategyMap,
      weekdayMap,
      loading: false,
      form: {
        ...defaultForm
      }
    }
  },
  methods: {
    show (data, type) {
      // 获取所有票种列表
      this.$store.dispatch('getTicketTypeList')

      this.type = type
      this.title = type === 'edit' ? '编辑场次' : '新增场次'
      this.visible = true

      this.$nextTick(() => {
        this.reset()

        if (type === 'edit' && data) {
          this.form = Object.assign({}, this.form, JSON.parse(JSON.stringify(data)))

          this.form.startTime = new Date('2020-1-1 ' + data.startTime)

          this.form.endTime = new Date('2020-1-1 ' + data.endTime)

          this.form.ticketTypeIds = data.ticketTypes?.map(ticket => ticket.id) || []

          if (this.form.strategy === 'date') {
            this.form.strategyContent = this.formatPeriodToArray(data.strategyContent)
          }

          if (this.form.strategy === 'week') {
            this.form.strategyContent = JSON.parse(data.strategyContent)
          }
        } else {
          this.form = JSON.parse(JSON.stringify(defaultForm))
        }
      })
    },
    reset () {
      this.$refs.form.resetFields()
    },
    handleClose () {
      this.visible = false
    },
    handleAddPeriod () {
      this.form.strategyContent.push([new Date(), new Date()])
    },
    formatPeriodToArray (arr) {
      try {
        const periods = JSON.parse(arr)
        return periods.map(i => {
          return [i.start, i.end]
        })
      } catch (e) {
        return []
      }
    },
    formatPeriodToObject (arr) {
      return arr.map(i => {
        return {
          start: moment(i[0]).format('YYYY-MM-DD'),
          end: moment(i[1]).format('YYYY-MM-DD')
        }
      })
    },
    verifyPeriod (rule, val, callback) {
      if (this.form.strategy === 'date') {
        if (val.length > 0) {
          if (val.some(i => i === null)) {
            callback(Error('内容不能为空'))
          } else {
            callback()
          }
        } else {
          callback(Error('请添加时间段'))
        }
      }

      if (this.form.strategy === 'week') {
        if (val.length > 0) {
          callback()
        } else {
          callback(Error('请选择星期'))
        }
      }
    },
    verifyTicket (rule, val, callback) {
      if (val.length > 0) {
        if (val.some(i => i.ticketTypeId === '')) {
          callback(Error('请选择票种'))
        } else {
          callback()
        }
      } else {
        callback(Error('请添加票种'))
      }
    },
    handleSubmit () {
      console.log(this.form)
      this.$refs.form.validate(valid => {
        if (valid) {
          let params = JSON.parse(JSON.stringify(this.form))

          params.startTime = moment(params.startTime).format('HH:mm:ss')
          params.endTime = moment(params.endTime).format('HH:mm:ss')

          if (params.strategy === 'date') {
            params.strategyContent = this.formatPeriodToObject(params.strategyContent)
          }

          // 按星期排序
          if (params.strategy === 'week') {
            params.strategyContent.sort()
          }

          if (params.strategy === 'basic') {
            params.strategyContent = ''
          } else {
            params.strategyContent = JSON.stringify(params.strategyContent)
          }

          this.loading = true
          if (this.type === 'edit') {
            updateBatchConfig(params).then(res => {
              this.$message.success('更新成功')
              this.$emit('update-list')
              this.handleClose()
            }).finally(() => {
              this.loading = false
            })
          } else {
            saveBatchConfig(params).then(res => {
              this.$message.success('添加成功')
              this.$emit('update-list')
              this.handleClose()
            }).finally(() => {
              this.loading = false
            })
          }
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.periodItem {
  display: flex;  margin: 0 10px 10px 0; align-items: center;
}
.form-wrap {
  .priceInput {
     margin: 0 10px;
    .el-input-number{
        width: 160px;
    }
    ::v-deep .el-input {
      width: 100%;
    }
  }
}

</style>
