<template>
  <el-form
    inline
    :model="form"
    ref="form"
    class="form-wrap"
    label-width="150px"
  >

    <div class="dialog-info">
      <el-alert
        type="warning"
        title="字段说明"
        show-icon
        :closable="false">
        <p>线下票种ID：请仔细核对线下票种ID后填写。并确保属性和线下属性一致； <br>是否需要预订日期：决定票种销售时，是否需要指定游玩日期。</p>
      </el-alert>

      <div class="block-title">
        基本属性
      </div>
      <el-form-item
        verify
        label="线下票种ID"
        prop="id">
        <el-input v-model="form.id"></el-input>
      </el-form-item>
      <el-form-item
        verify
        label="票种名称"
        prop="name"
      >
        <el-input v-model="form.name"></el-input>
      </el-form-item>
      <el-form-item
        verify
        label="助记符"
        prop="shorthand"
      >
        <el-input v-model="form.shorthand"></el-input>
      </el-form-item>
      <el-form-item
        verify
        label="销售价格"
        prop="price"
      >
        <el-input-number
          controls-position="right"
          v-model="form.price"
          :min="0"
          :precision="2"
        ></el-input-number>
      </el-form-item>
      <el-form-item
        label="打印提示"
        prop="print_notes"
      >
        <el-input
          type="textarea"
          :rows="2"
          :max-length="100"
          v-model="form.print_notes"
        ></el-input>
      </el-form-item>
      <div class="block-title">
        销售时间及使用时间
      </div>
      <el-form-item
        verify
        label="可售日期"
        prop="sellStartDate"
      >
        <el-date-picker
          :editable="false"
          :clearable="false"
          :picker-options="pickerOptions"
          v-model="form.sellStartDate"
          type="date"
          placeholder="开始日期"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item
        verify
        label-width="40px"
        label="至"
        prop="sellEndDate"
      >
        <el-date-picker
          :editable="false"
          :clearable="false"
          :picker-options="pickerOptions"
          v-model="form.sellEndDate"
          type="date"
          placeholder="结束日期"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item
        verify
        label="游玩日期"
        prop="useStartDate"
      >
        <el-date-picker
          :editable="false"
          :clearable="false"
          :picker-options="pickerOptions"
          v-model="form.useStartDate"
          type="date"
          placeholder="开始日期"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item
        verify
        label-width="40px"
        label="至"
        prop="useEndDate"
      >
        <el-date-picker
          :editable="false"
          :clearable="false"
          :picker-options="pickerOptions"
          v-model="form.useEndDate"
          type="date"
          placeholder="结束日期"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item
        verify
        label="当日游玩时段"
        prop="useTimeStart"
      >
        <el-time-picker
          :editable="false"
          :clearable="false"
          v-model="form.useTimeStart"
          value-format="HH:mm:ss"
          placeholder="选择开始时间"
        >
        </el-time-picker>
      </el-form-item>
      <el-form-item
        verify
        label-width="40px"
        label="至"
        prop="useTimeEnd"
      >
        <el-time-picker
          :editable="false"
          :clearable="false"
          v-model="form.useTimeEnd"
          value-format="HH:mm:ss"
          placeholder="选择结束时间"
        >
        </el-time-picker>
      </el-form-item>

      <el-form-item
        verify
        label="需要预定日期"
        prop="is_need_playtime"
      >
        <el-select v-model="form.is_need_playtime">
          <el-option
            label="是"
            :value="1"
          ></el-option>
          <el-option
            label="否"
            :value="0"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        verify
        label="游玩天数"
        prop="useValidDays"
      >
        <el-input-number
          controls-position="right"
          v-model="form.useValidDays"
          :min="1"
          :precision="0"
        ></el-input-number>
      </el-form-item>

      <div class="block-title">
        二次入园设置
      </div>
      <el-form-item
        verify
        label="是否二次入园"
        prop="check_second">
        <el-select v-model="form.check_second">
          <el-option
            label="是"
            :value="1"
          ></el-option>
          <el-option
            label="否"
            :value="0"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        class="is-required"
        v-if="form.check_second"
        label="人脸二次入园"
        prop="second_type_face">
        <el-select
          v-model="form.second_type_face"
          placeholder="请选择">
          <el-option
            label="是"
            :value="1"
          ></el-option>
          <el-option
            label="否"
            :value="0"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        class="is-required"
        v-if="form.check_second"
        label="指纹二次入园"
        prop="second_type_finger">
        <el-select
          v-model="form.second_type_finger"
          placeholder="请选择">
          <el-option
            label="是"
            :value="1"
          ></el-option>
          <el-option
            label="否"
            :value="0"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        class="is-required"
        v-if="form.check_second"
        label="二次入园有效期"
        prop="second_time">
        <el-input-number
          :min="1"
          :precision="0"
          controls-position="right"
          v-model="form.second_time_value">
        </el-input-number>
        &nbsp;天
      </el-form-item>
      <div class="block-title">
        限购设置
      </div>
      <el-form-item
        verify
        label="每个身份证每天限购张数"
        prop="idcard_sell_limit_perday"
      >
        <el-input-number
          controls-position="right"
          v-model="form.idcard_sell_limit_perday"
          :min="0"
          :precision="0"
        ></el-input-number>
      </el-form-item>
      <span>（0表示不限制）</span>
      <el-form-item
        verify
        label="是否实名制"
        prop="real_name_limit"
      >
        <el-select
          v-model="form.real_name_limit"
          placeholder="请选择">
          <el-option
            label="是"
            value="1"
          ></el-option>
          <el-option
            label="否"
            value="0"
          ></el-option>
        </el-select>
      </el-form-item>
      <span>（如果实名制 需要每张票都有身份信息）</span>
      <el-form-item
        label="白名单地区列表"
        prop="area_white_list"
        style="width:100%"
      >
        <el-tag
          :key="tag"
          v-for="tag in form.area_white_list"
          closable
          size="medium"
          :disable-transitions="false"
          @close="handleCloseTag(tag,form.area_white_list)">
          {{ tag }}
        </el-tag>
        <el-input-number
          :controls="false"
          class="input-new-tag"
          v-if="inputVisible1"
          v-model="inputValue1"
          ref="saveTagInput1"
          size="small"
          @keyup.enter.native="handleInputConfirm(1,form.area_white_list)"
          @blur="handleInputConfirm(1,form.area_white_list)"
        >
        </el-input-number>
        <el-button
          v-else
          class="button-new-tag"
          size="small"
          @click="showInput(1)">新增</el-button>
      </el-form-item>
      <span style="margin-bottom:10px">（身份证以此类项开头的 可以购票）</span>
      <el-form-item
        label="黑名单地区列表"
        prop="area_black_list"
        style="width:100%"
      >
        <el-tag
          :key="tag"
          v-for="tag in form.area_black_list"
          closable
          size="medium"
          :disable-transitions="false"
          @close="handleCloseTag(tag,form.area_black_list)">
          {{ tag }}
        </el-tag>
        <el-input-number
          :controls="false"
          class="input-new-tag"
          v-if="inputVisible2"
          v-model="inputValue2"
          ref="saveTagInput2"
          size="small"
          @keyup.enter.native="handleInputConfirm(2,form.area_black_list)"
          @blur="handleInputConfirm(2,form.area_black_list)"
        >
        </el-input-number>
        <el-button
          v-else
          class="button-new-tag"
          size="small"
          @click="showInput(2)">新增</el-button>
      </el-form-item>
      <span style="margin-bottom:10px">（身份证以此类项开头的 不可购票）</span>
      <div class="block-title">
        取票设置
      </div>
      <el-form-item
        verify
        label="是否允许自助机取票"
        prop="can_self_use">
        <el-select v-model="form.can_self_use">
          <el-option
            label="是"
            :value="1"
          ></el-option>
          <el-option
            label="否"
            :value="0"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        verify
        label="最多可提前几天取票"
        prop="advance_pick_day"
      >
        <el-input-number
          controls-position="right"
          v-model="form.advance_pick_day"
          :min="-1"
          :precision="0"
        ></el-input-number>
        <div>（-1 表示不限制）</div>
      </el-form-item>
      <el-form-item
        label="购买后延迟取票时间"
        prop="pick_delay_after_buy">
        <el-time-picker
          :editable="false"
          :clearable="false"
          v-model="form.pick_delay_after_buy"
          value-format="HH:mm:ss"
          placeholder="选择开始时间"
        >
        </el-time-picker>
      </el-form-item>
    </div>
    <div class="btn-wrap-left">
      <el-button
        plain
        class="add-btn"
        type="primary"
        @click="handleAdd">
        添加适用景点
      </el-button>
    </div>
    <div
      class="tableBox"
      style="padding: 0 20px;">
      <el-table
        stripe
        :data="form.ticketTypeScenic">
        <el-table-column
          label="适用景点">
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.scenic_name">
            </el-input>
          </template>
        </el-table-column>
        <el-table-column
          label="检票次数"
          min-width="90">
          <template slot-scope="scope">
            <el-input-number
              controls-position="right"
              :min="1"
              :precision="0"
              v-model="scope.row.check_limit_times"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column
          class-name="align-item"
          label="操作">
          <template slot-scope="scope">
            <el-button
              type="primary"
              @click="delScenic(scope.$index)">
              <i class="el-icon-delete"></i>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="dialog-info">
      <div class="block-title">
        年龄设置
      </div>
    </div>
    <div class="btn-wrap-left">
      <el-button
        plain
        class="add-btn"
        type="primary"
        @click="addAge">
        添加年龄限制
      </el-button>
      <el-tooltip
        content="年龄区间请从小到大排序,且年龄区间不能交叉"
        placement="top-start">
        <i class="el-icon-info"> </i>
      </el-tooltip>
    </div>
    <div
      class="tableBox"
      style="padding: 0 20px;">
      <el-table
        stripe
        :data="form.age_limit">
        <el-table-column
          label="起始年龄">
          <template slot-scope="scope">
            <el-input-number
              controls-position="right"
              :min="0"
              :precision="0"
              v-model="scope.row.age_start"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column
          label="截至年龄"
          min-width="90">
          <template slot-scope="scope">
            <el-input-number
              controls-position="right"
              :min="0"
              :precision="0"
              v-model="scope.row.age_end"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column
          class-name="align-item"
          label="操作">
          <template slot-scope="scope">
            <el-button
              type="primary"
              @click="delAge(scope.$index)">
              <i class="el-icon-delete"></i>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="dialog-btn-wrap">
      <el-button
        @click="reset"
        v-if="dialogType==='add'">
        重置
      </el-button>
      <el-button
        @click="handleClose"
        v-if="dialogType==='edit'">
        关闭
      </el-button>
      <el-button
        @click="submit"
        type="primary">
        保存
      </el-button>
    </div>
  </el-form>
</template>

<script>
import { addTicketType, updateTicketType } from '@/api/ticketType'
import moment from 'moment'
export default {
  props: {
    ticketItem: {
      type: Object,
      default: () => {}
    },
    dialogType: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      visible: false,
      pickerOptions: {
        disabledDate: (theTime) => {
          let startTime = moment().format('YYYY-MM-DD') + ' 00:00:00'
          return moment(theTime).isBefore(startTime)
        }
      },
      form: {
        // is_book_today: 1,
        // book_today_endtime: '23:59:59',
        unique_id: '',
        id: '',
        category: 1, // 大类
        name: '', // 名称
        shorthand: '', // 助记符
        print_notes: '', // 打印提示
        is_idcard_check: 1, // 身份证检票
        price: 0, // 价格
        useValidDays: 1, // 有效天数
        idcard_sell_limit_perday: 0, // 每个身份证每天限购张数
        real_name_limit: '0', // 是否实名制
        can_self_use: 1, // 是否允许自助机取票传
        advance_pick_day: -1,
        useStartDate: moment().format('YYYY-MM-DD'),
        useEndDate: moment().add(10, 'years').format('YYYY-MM-DD'),
        useTimeStart: '00:00:00',
        useTimeEnd: '23:59:59',
        sellStartDate: moment().format('YYYY-MM-DD'),
        sellEndDate: moment().add(10, 'years').format('YYYY-MM-DD'),
        check_second: 0, // 二次入园
        second_type_face: 1,
        second_type_finger: 1,
        second_time_type: 'days',
        second_time_value: 1,
        ticketTypeScenic: [], // 景点-检票次数
        creator: '', // 创建人
        is_need_playtime: 1, // 是否需要预定游玩日期
        check_type: 1, // 检票类型
        scenic_check_times_type: 1, // 景点限制：单独限制、批量限制
        batch_check_times: 1, // 批量限制的次数
        date_limit_type: 1, // 有效期限制：截止到门票有效期、有效天数
        valid_days_from_buy_date: 1, // 有效天数,
        age_limit: [],
        area_white_list: [],
        area_black_list: [],
        pick_delay_after_buy: '00:00:00'
      },
      inputVisible1: false,
      inputValue1: '',
      inputVisible2: false,
      inputValue2: ''
    }
  },
  watch: {
    visible (val) {
      this.reset()
      this.form.ticketTypeScenic = []
      this.form.age_limit = []
      if (val) {
        if (this.dialogType === 'edit' && this.ticketItem) {
          this.form = Object.assign({}, this.form, JSON.parse(JSON.stringify(this.ticketItem)))
        }
        if (this.dialogType === 'edit' && (this.ticketItem.area_white_list === '' || this.ticketItem.area_white_list === null)) {
          this.form.area_white_list = []
        } else {
          this.form.area_white_list = JSON.parse(`[${this.ticketItem.area_white_list}]`)
        }
        if (this.dialogType === 'edit' && (this.ticketItem.area_black_list === '' || this.ticketItem.area_black_list === null)) {
          this.form.area_black_list = []
        } else {
          this.form.area_black_list = JSON.parse(`[${this.ticketItem.area_black_list}]`)
        }
      }
    }
  },
  methods: {
    handleClose () {
      this.$parent.handleClose()
    },
    reset () {
      this.$refs.form.resetFields()
      this.form.ticketTypeScenic = []
      this.form.age_limit = []
    },
    // 增加 适用景点-检票次数
    handleAdd () {
      this.form.ticketTypeScenic.push({
        scenic_name: '',
        check_limit_times: 1
      })
    },
    // 删除 适用景点-检票次数
    delScenic (index) {
      this.form.ticketTypeScenic.splice(index, 1)
    },
    // 增加 适用景点-检票次数
    addAge () {
      this.form.age_limit.push({
        age_start: 0,
        age_end: 0
      })
    },
    // 删除 适用景点-检票次数
    delAge (index) {
      this.form.age_limit.splice(index, 1)
    },
    isScenicValid () {
      if (this.form.ticketTypeScenic.some(item => !item.scenic_name)) {
        this.$message.error('景点名不能为空')
        return false
      } else {
        return true
      }
    },
    submit () {
      this.$refs.form.validate(valid => {
        if (valid && this.isScenicValid()) {
          if (moment(this.form.sellStartDate).isAfter(this.form.sellEndDate)) {
            this.$message.error('起售日期不可晚于停售日期')
            return
          }
          if (moment(this.form.useStartDate).isAfter(this.form.useEndDate)) {
            this.$message.error('游玩开始日期不可晚于游玩截止日期')
            return
          }
          if (moment(this.form.sellEndDate).isAfter(this.form.useEndDate)) {
            this.$message.error('停售日期不可晚于游玩截止日期')
            return
          }
          if (moment(this.form.sellStartDate).isAfter(this.form.useStartDate)) {
            this.$message.error('起售日期不可晚于游玩开始日期')
            return
          }
          if (moment('2019-01-21 ' + this.form.useTimeStart).isAfter('2019-01-21 ' + this.form.useTimeEnd)) {
            this.$message.error('当日游玩开始时间不可晚于结束时间')
            return
          }

          // 年龄校验
          if (this.form.age_limit.length) {
            let length = this.form.age_limit.length
            let count = 0
            let sort = 0
            this.form.age_limit.forEach(v => {
              if ((v.age_start !== undefined) && (v.age_end !== undefined)) count++
              if (v.age_start < v.age_end) sort++
            })
            if (count < length) return this.$message.error('请补充年龄')
            if (sort < length) return this.$message.error('年龄区间顺序有误')

            if (length > 1) {
              for (let i = 1; i < this.form.age_limit.length; i++) {
                if (this.form.age_limit[i].age_start < this.form.age_limit[i - 1].age_end) return this.$message.error('年龄区间有交叉')
              }
            }
          }

          if (this.form.check_type === 1 && this.form.scenic_check_times_type === 2) {
            this.form.ticketTypeScenic.forEach(item => {
              item.check_limit_times = this.form.batch_check_times
            })
          } else if (this.form.check_type === 2 && this.form.date_limit_type === 1) {
            this.form.valid_days_from_buy_date = 0
          }
          this.form.sellStartDate = this.formatStartTime(this.form.sellStartDate)
          this.form.sellEndDate = this.formatEndTime(this.form.sellEndDate)
          this.form.useStartDate = this.formatStartTime(this.form.useStartDate)
          this.form.useEndDate = this.formatEndTime(this.form.useEndDate)

          if (this.form.area_white_list.filter(v => v).length) {
            this.form.area_white_list = this.form.area_white_list.filter(v => v).join(',')
          } else {
            this.form.area_white_list = ''
          }
          if (this.form.area_black_list.filter(v => v).length) {
            this.form.area_black_list = this.form.area_black_list.filter(v => v).join(',')
          } else {
            this.form.area_black_list = ''
          }
          switch (this.dialogType) {
            case 'add':
              this.addTicket()
              break
            case 'edit':
              this.updateTicket()
              break
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    addTicket () {
      this.form.creator = this.$store.state.user.name
      addTicketType(this.form).then(res => {
        this.$message.success('添加成功')
        this.reset()
        this.handleClose()
        this.$emit('updateList')
      })
    },
    updateTicket () {
      updateTicketType(this.form).then(res => {
        this.$message.success('保存成功')
        this.reset()
        this.handleClose()
        this.$emit('updateList')
      })
    },
    formatStartTime (time) {
      return moment(time).hour(0).minute(0).second(0).toDate()
    },
    formatEndTime (time) {
      return moment(time).hour(23).minute(59).second(59).toDate()
    },
    handleCloseTag (tag, list) {
      list.splice(list.indexOf(tag), 1)
    },

    showInput (num) {
      if (num === 1) {
        this.inputVisible1 = true
        this.$nextTick(_ => {
          this.$refs.saveTagInput1.$refs.input.focus()
        })
      } else if (num === 2) {
        this.inputVisible2 = true
        this.$nextTick(_ => {
          this.$refs.saveTagInput2.$refs.input.focus()
        })
      }
    },

    handleInputConfirm (num, list) {
      if (num === 1) {
        let inputValue = this.inputValue1
        if (inputValue) {
          list.push(inputValue)
        }
        this.inputVisible1 = false
        this.inputValue1 = ''
      } else if (num === 2) {
        let inputValue = this.inputValue2
        if (inputValue) {
          list.push(inputValue)
        }
        this.inputVisible2 = false
        this.inputValue2 = ''
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.el-alert{
   margin-bottom: 20px;
   p{
      margin: 0;margin: 0;
   }
}

  .el-tag + .el-tag {
    margin-left: 10px;
  }
  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }
  .input-new-tag {
     ::v-deep .el-input{
      width: 90px;
      margin-left: 10px;
      vertical-align: bottom;
    }
  }
</style>
