<template>
  <el-dialog
    :title="title"
    :visible.sync="visible"
    width="640px"
    @close="handleClose">
    <el-form
      inline
      :model="form"
      ref="form"
      class="form-wrap"
      label-width="100px">
      <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
          label="开始时间"
          prop="startTime">
          <el-time-picker
            v-model="form.startTime"
            placeholder="开始时间">
          </el-time-picker>
        </el-form-item>

        <el-form-item
          verify
          label="持续时长"
          prop="duration">
          <el-time-picker
            v-model="form.duration"
            placeholder="时长">
          </el-time-picker>
        </el-form-item>

        <el-form-item
          verify
          label="作用类型"
          prop="duration">
          <el-select
            v-model="form.strategy"
            @change="form.strategy_content=[]">
            <el-option
              v-for="{label,value} in strategyMap"
              :key="value"
              :label="label"
              :value="value">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item
          :verify="verifyPeriod"
          label="作用内容"
          style="width:100%"
          v-if="form.strategy!=='BASIC'"
          prop="strategy_content">
          <template v-if="form.strategy==='WEEKDAY'">
            <el-checkbox-group v-model="form.strategy_content">
              <el-checkbox
                v-for="(i,index) in weekdayMap"
                :key="index"
                :label="index">
                {{ i }}
              </el-checkbox>
            </el-checkbox-group>
          </template>

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

              <el-tooltip
                content="删除"
                placement="top"
                effect="dark">
                <el-button
                  @click="form.strategy_content.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="status">
          <el-switch
            v-model="form.status"
            :active-value="1"
            :inactive-value="0"
            active-color="#13ce66"
            inactive-color="#ff4949"
            active-text="激活"
            inactive-text="禁用">
          </el-switch>
        </el-form-item>
        <!-- <el-form-item
          :verify="verifyTicket"
          label="绑定票种"
          prop="batchConfigTicketTypeMatrix"
          style="width:100%">
          <div
            style="margin-bottom:10px"
            v-for="(item,index) in form.batchConfigTicketTypeMatrix"
            :key="index">
            <el-select
              v-model="item.ticketTypeId"
              filterable
              placeholder="请选择"
              @change="handleTicketChange($event,item)">
              <el-option
                :disabled="handleDisable(ticketType)"
                v-for="ticketType in ticketTypeList"
                :key="ticketType.id"
                :label="ticketType.name"
                :value="ticketType.id">
              </el-option>
            </el-select>

            <span class="priceInput">
              票价：
              <el-input-number
                v-model.number="item.price"
                :precision="2"
                :controls="false"
              >
                <template slot="append">
                  元
                </template>
              </el-input-number>
            </span>

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

          <el-button
            type="primary"
            @click="handleAddTicketType">
            新增票种
          </el-button>
        </el-form-item> -->

        <el-form-item
          label="是否有座"
          prop="type">
          <el-switch
            v-model="form.type"
            active-value="SEAT"
            inactive-value="NOSEAT"
            active-color="#13ce66"
            inactive-color="#ff4949"
            active-text="有座"
            inactive-text="无座">
          </el-switch>
        </el-form-item>
        <el-form-item
          verify
          v-if="form.type ==='SEAT'"
          label="选择座位表"
          prop="seat_config_id">
          <el-select v-model="form.seat_config_id">
            <el-option
              v-for="item in seatlist"
              :key="item.id"
              :value="item.id"
              :label="item.name">
            </el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item
          verify
          v-if="form.type ==='SEAT'&&form.seat_config_id"
          label="选择区域"
          prop="seat_config_id">
          <el-select v-model="form.seat_config_id">
            <el-option
              v-for="item in areaList"
              :key="item.id"
              :value="item.id"
              :label="item.name">
            </el-option>
          </el-select>
        </el-form-item> -->

        <el-form-item
          v-if="form.type !=='SEAT'"
          verify
          label="数量"
          prop="number">
          <el-input-number
            :min="1"
            v-model="form.number"
            placeholder="数量"></el-input-number>
        </el-form-item>
        <el-form-item
          verify
          label="是否同步到线上"
          prop="auto_send_ota">
          <el-switch
            v-model="form.auto_send_ota"
            :active-value="1"
            :inactive-value="0"
            active-color="#13ce66"
            inactive-color="#ff4949"
          >
          </el-switch>
        </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, createBatchConfig } from '@/api/batch'
import { getSeatArea } from '@/api/seat'
import { strategyMap, weekdayMap } from '@/assets/staticData'
import moment from 'moment'

const defaultForm = {
  name: '',
  strategy: 'BASIC',
  status: 1,
  auto_send_ota: 1,
  number: 0,
  startTime: new Date(2020, 1, 1, 0, 0, 0),
  duration: new Date(2020, 1, 1, 0, 0, 0),
  strategy_content: [],
  batchConfigTicketTypeMatrix: [],
  type: 'SEAT',
  seat_config_id: ''

}

export default {
  computed: {
    ticketTypeList () {
      return this.$store.state.app.ticketTypeList
    }
  },
  data () {
    return {
      title: '',
      visible: false,
      strategyMap,
      weekdayMap,
      loading: false,
      seatlist: [], // 座位表
      areaList: [], // 区域表
      form: {
        ...defaultForm
      }
    }
  },
  watch: {
    seat_config_id (newName, oldName) {
      let params = { keyWords1: newName }
      this.getSeatArea(params)
    }
  },
  methods: {
    // 获取区域
    getSeatArea (params) {
      getSeatArea(params).then(res => {
        this.areaList = res.list
        console.log('areaList', this.areaList)
      })
    },
    handleDisable (ticketType) {
      let selectTicket = this.form.batchConfigTicketTypeMatrix.map(i => i.ticketTypeId)
      return selectTicket.some(i => i === ticketType.id)
    },
    show (data, type, seatlist) {
      console.log(data)
      this.type = type
      this.title = type === 'edit' ? '编辑场次' : '新增场次'
      this.seatlist = seatlist
      this.visible = true

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

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

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

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

          if (this.form.strategy === 'PERIOD') {
            this.form.strategy_content = this.formatPeriodToArray(data.strategy_content)
          }
        } else {
          this.form = JSON.parse(JSON.stringify(defaultForm))
        }
      })
    },
    reset () {
      this.$refs.form.resetFields()
    },
    handleClose () {
      this.visible = false
    },
    handleAddPeriod () {
      this.form.strategy_content.push([new Date(), new Date()])
    },
    formatPeriodToArray (arr) {
      return arr.map(i => {
        return [i.start, i.end]
      })
    },
    formatPeriodToObject (arr) {
      return arr.map(i => {
        return {
          start: moment(i[0]).format('YYYY-MM-DD'),
          end: moment(i[1]).format('YYYY-MM-DD')
        }
      })
    },
    handleAddTicketType () {
      this.form.batchConfigTicketTypeMatrix.push({ batch_config_id: this.form.id || '', ticketTypeId: '', price: 0 })
    },
    handleTicketChange (e, item) {
      let t = this.ticketTypeList.find(i => i.id === e)
      item.price = t.price
    },
    verifyPeriod (rule, val, callback) {
      if (this.form.strategy === 'PERIOD') {
        if (val.length > 0) {
          if (val.some(i => i === null)) {
            callback(Error('内容不能为空'))
          } else {
            callback()
          }
        } else {
          callback(Error('请添加时间段'))
        }
      }

      if (this.form.strategy === 'WEEKDAY') {
        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 () {
      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.duration = moment(params.duration).format('HH:mm:ss')

          if (params.strategy === 'PERIOD') {
            params.strategy_content = this.formatPeriodToObject(params.strategy_content)
          }

          // 按星期排序
          if (params.strategy === 'WEEKDAY') {
            params.strategy_content.sort()
          }
          this.loading = true
          if (this.type === 'edit') {
            updateBatchConfig(params).then(res => {
              this.$message.success('更新成功')
              this.$emit('update')
              this.handleClose()
            }).finally(() => {
              this.loading = false
            })
          } else {
            createBatchConfig(params).then(res => {
              this.$message.success('添加成功')
              this.$emit('update')
              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>
