<template>
  <el-form
    inline
    :model="form"
    ref="form"
    class="form-wrap"
    label-width="120px">
    <div class="dialog-info">
      <div class="block-title">
        基本属性
      </div>
      <el-form-item
        verify
        label="会员大类"
        prop="category">
        <el-select
          v-model="form.category"
          @change="changeCategory">
          <el-option
            label="游客"
            :value="1"
          ></el-option>
          <el-option
            label="多人卡"
            :value="2"
          ></el-option>
          <el-option
            label="居民"
            :value="3"
          ></el-option>
          <el-option
            label="管理员"
            :value="4"
          ></el-option>
          <el-option
            label="储值卡"
            :value="5"
          ></el-option>
        </el-select>
      </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="person_num">
        <el-input-number
          :min="1"
          :step="1"
          :precision="0"
          :disabled="form.category !== 2"
          v-model="form.person_num"></el-input-number>
      </el-form-item>
      <el-form-item
        verify
        label="价格"
        prop="capital">
        <el-input-number
          controls-position="right"
          v-model="form.capital"
          :min="0"
          :precision="2"
          :step="0.01"
        ></el-input-number>
      </el-form-item>
      <el-form-item
        verify
        label="是否同步到会员系统"
        prop="is_sync_member">
        <el-select v-model="form.is_sync_member">
          <el-option
            label="是"
            :value="1"
          ></el-option>
          <el-option
            label="否"
            :value="0"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        label="检票统计类型"
        prop="check_statistics_type">
        <el-select v-model="form.check_statistics_type">
          <el-option
            label="按人数"
            :value="0"
          ></el-option>
          <el-option
            label="按次数"
            :value="1"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        label="必选项"
        prop="requiredField">
        <el-select
          v-model="form.requiredField"
          multiple>
          <el-option
            label="姓名"
            value="name"
          ></el-option>
          <el-option
            label="证件类型"
            value="papers_type">
          </el-option>
          <el-option
            label="证件号码"
            value="papers_id">
          </el-option>
          <el-option
            label="手机"
            value="phone">
          </el-option>
        </el-select>
      </el-form-item>
      <div class="block-title">
        有效日期
      </div>
      <el-form-item
        verify
        label="可售日期"
        prop="saleDateStart">
        <el-date-picker
          :clearable="false"
          :editable="false"
          v-model="form.saleDateStart"
          type="date"
          placeholder="选择日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item
        verify
        label-width="100"
        label="至"
        prop="saleDateEnd">
        <el-date-picker
          :clearable="false"
          :editable="false"
          v-model="form.saleDateEnd"
          type="date"
          placeholder="选择日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item
        verify
        :label="form.category==5?'有效日期':'可玩日期'"
        prop="play_startdate">
        <el-date-picker
          :clearable="false"
          :editable="false"
          v-model="form.play_startdate"
          type="date"
          placeholder="选择日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item
        verify
        label-width="100"
        label="至"
        prop="play_enddate">
        <el-date-picker
          :clearable="false"
          :editable="false"
          v-model="form.play_enddate"
          type="date"
          placeholder="选择日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item
        verify
        label="可提前预订天数"
        prop="pre_order_days">
        <el-input-number
          v-model="form.pre_order_days"
          controls-position="right"
          :precision="0"
          :min="0"
          :max="365"></el-input-number>
      </el-form-item>
      <div class="block-title">
        通关方式
      </div>
      <el-form-item
        verify
        label="身份证通关"
        prop="idcard_check">
        <el-select v-model="form.idcard_check">
          <el-option
            label="是"
            :value="1"
          ></el-option>
          <el-option
            label="否"
            :value="0"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        verify
        v-if="form.category !== 5"
        label="人脸识别通关"
        prop="face_check">
        <el-select v-model="form.face_check">
          <el-option
            label="是"
            :value="1"
          ></el-option>
          <el-option
            label="否"
            :value="0"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        verify
        label="IC卡通关"
        prop="iccard_check">
        <el-select
          v-model="form.iccard_check"
          :disabled="form.category === 2">
          <el-option
            label="是"
            :value="1"
          ></el-option>
          <el-option
            label="否"
            :value="0"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        verify
        v-if="form.category !== 5"
        label="指纹通关"
        prop="fingerprint_check">
        <el-select v-model="form.fingerprint_check">
          <el-option
            label="是"
            :value="1"
          ></el-option>
          <el-option
            label="否"
            :value="0"
          ></el-option>
        </el-select>
      </el-form-item>

      <div
        class="block-title"
        v-if="form.category === 5">
        储值卡设置
      </div>
      <el-form-item
        verify
        v-if="form.category === 5"
        label="折扣"
        prop="discount">
        <el-input-number
          controls-position="right"
          v-model="form.discount "
          :min="0"
          :max="10"
          :precision="1"
          :step="0.1"
        ></el-input-number>
      </el-form-item>
      <el-form-item
        verify
        v-if="form.category === 5"
        label="初始金额"
        prop="initial_money">
        <el-input-number
          controls-position="right"
          v-model="form.initial_money"
          :min="0"
          :precision="2"
          :step="0.01"
        ></el-input-number>
      </el-form-item>

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

      <el-form-item
        label="发票销售方"
        prop="invoice_seller"
      >
        <el-select v-model="form.invoice_seller">
          <el-option
            label="不绑定"
            value=""></el-option>
          <el-option
            v-for="item in invoiceSeller"
            :key="item.id"
            :label="item.invoice_seller"
            :value="item.id+''"
          >
          </el-option>
        </el-select>
      </el-form-item>

      <div
        class="block-title"
      >
        检票规则
      </div>
      <el-form-item
        verify
        label="检票类型"
        prop="check_pattern">
        <el-select
          v-model="form.check_pattern"
          :disabled="form.category === 2"
          placeholder="请选择">
          <el-option
            label="按有效期"
            value="time">
          </el-option>
          <el-option
            label="单人按次"
            value="count">
          </el-option>
          <el-option
            label="有效期内按次"
            value="both">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        v-if="form.check_pattern === 'count'||form.check_pattern === 'both'"
        class="is-required"
        label="景点限制"
        prop="scenic_checkTimes_type">
        <el-select
          v-model="form.scenic_checkTimes_type"
          placeholder="请选择">
          <el-option
            label="单独限制"
            :value="1">
          </el-option>
          <el-option
            label="批量限制"
            :value="2">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        class="is-required"
        v-if="(form.check_pattern === 'count'||form.check_pattern === 'both')&& form.scenic_checkTimes_type === 2"
        label="检票次数"
        prop="checkLimitTimes">
        <el-input-number
          controls-position="right"
          v-model="form.checkLimitTimes"
          :min="1"
          :precision="0"
        ></el-input-number>
      </el-form-item>
      <el-form-item
        v-if="form.check_pattern === 'time'||form.check_pattern === 'both'"
        class="is-required"
        label="日期限制"
        prop="date_limit_type">
        <el-select
          v-model="form.date_limit_type"
          placeholder="请选择">
          <el-option
            label="票种有效期"
            :value="1">
          </el-option>
          <el-option
            label="有效天数"
            :value="2">
          </el-option>
          <el-option
            label="购买时填入"
            :value="3">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        class="is-required"
        v-if="(form.check_pattern === 'time'||form.check_pattern === 'both')&& form.date_limit_type === 2"
        prop="valid_days"
        label="有效天数">
        <el-input-number
          controls-position="right"
          v-model="form.valid_days"
          :min="1"
          :precision="0"
        ></el-input-number>
      </el-form-item>
      <el-form-item
        class="is-required"
        v-if="(form.check_pattern === 'count'||form.check_pattern === 'both')"
        prop="checkTimes_add_type"
        label="计次类型">
        <el-select
          v-model="form.checkTimes_add_type"
          placeholder="请选择">
          <el-option
            label="一天一次"
            value="DAY">
          </el-option>
          <el-option
            label="一天多次"
            value="TIMES">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        prop="valid_days"
        label="添加适用售票点">
        <el-select
          v-model="spotList"
          multiple
          placeholder="请选择"
          @change="changeSpot">
          <el-option
            v-for="item in ticketSpotList"
            :key="item.id"
            :value="item.id"
            :label="item.name">
          </el-option>
        </el-select>
      </el-form-item>
    </div>

    <div class="btn-wrap-left">
      <el-button
        plain
        class="add-btn"
        type="primary"
        @click="handleAdd">
        添加适用景点
      </el-button>
    </div>

    <div class="table-box">
      <el-table
        border
        stripe
        style="margin: 10px 0"
        :data="form.memberTypeScenic">
        <el-table-column
          label="适用景点">
          <template slot-scope="scope">
            <el-select
              v-model="scope.row.scenic_id">
              <el-option
                v-for="item in scenicList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
                :disabled="isScenicDisabled(item.id)">
              </el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column
          v-if="(form.check_pattern === 'count'||form.check_pattern === 'both')&& form.scenic_checkTimes_type === 1"
          label="检票次数"
          min-width="90">
          <template slot-scope="scope">
            <el-input-number
              controls-position="right"
              :min="1"
              :precision="0"
              v-model="scope.row.checkLimitTimes"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column
          class-name="align-item"
          label="操作">
          <template slot-scope="scope">
            <span
              class="el-button el-button--primary el-button--small"
              @click="delScenic(scope.$index)">
              <i class="el-icon-delete"></i>
              删除
            </span>
          </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 { apiMember } from '@/api/member'
import { getTicketSpotList } from '@/api/ticketSpot'

import moment from 'moment'
export default {
  props: {
    dialogType: {
      type: String,
      default: 'edit'
    },
    scenicList: {
      type: Array,
      default: () => []
    },
    currentItem: {
      type: Object,
      default: () => {}
    },
    invoiceSeller: {
      type: Array,
      default: () => []
    }
  },
  data () {
    return {
      visible: false,
      ticketSpotList: [],
      spotList: [],
      form: {
        category: 1, // 1 游客 2 多人卡 3 居民 4 管理员
        name: '', // 类型名称
        deposit: 0, // 押金
        card_fee: 0, // 工本费
        capital: 0, // 本金金额
        play_startdate: moment().format('YYYY-MM-DD'),
        play_enddate: moment().add(10, 'years').format('YYYY-MM-DD'),
        saleDateStart: moment().format('YYYY-MM-DD'),
        saleDateEnd: moment().add(10, 'years').format('YYYY-MM-DD'),
        pre_order_days: 30, // 可提前预订天数
        papers_type: '',
        idcard_check: 1, // 可否身份证通关
        is_sync_member: 0, // 是否同步到会员系统
        check_statistics_type: 0, //  检票统计类型 0 按人数 / 1 按次数
        face_check: 1, // 可否人脸通关
        iccard_check: 1, // 可否IC卡通关
        fingerprint_check: 1,
        check_pattern: 'time', // 检票类型
        discount: 10, // 储值卡折扣
        initial_money: 0, // 储值卡储值金额
        scenic_checkTimes_type: 1, // 景点限制：单独限制、批量限制
        checkLimitTimes: 1, // 批量限制的次数
        /* 有效期限制类型：1截止到门票有效期、2按有效天数,接口没有此字段，
          初始化时，date_limit_type = valid_days === -1 ? 1 : 2
          提交时valid_days = date_limit_type === 1 ? -1 : valid_days */
        date_limit_type: 1,
        valid_days: 365, // 有效天数
        memberTypeScenic: [],
        memberTypeSpot: [],
        person_num: 1,
        checkTimes_add_type: 'DAY',
        invoice_seller: '' // 票种绑定发票销售方
      }
    }
  },
  watch: {
    visible (val) {
      // 初始化表单
      if (val) {
        this.reset()
        this.getTicketSpotList()
        if (this.dialogType === 'edit' && this.currentItem) {
          this.form = Object.assign({}, this.form, JSON.parse(JSON.stringify(this.currentItem)))
          // this.form.date_limit_type = this.form.valid_days === -1 ? 1 : 2
          if (this.form.valid_days === -1) {
            this.form.date_limit_type = 1
          } else if (this.form.valid_days === -2) {
            this.form.date_limit_type = 3
          } else {
            this.form.date_limit_type = 2
          }
          this.spotList = this.form.memberTypeSpot.map(i => { return i.spot_id })
          if (typeof this.form.requiredField === 'string') {
            this.form.requiredField = JSON.parse(this.form.requiredField)
          } else {
            this.form.requiredField = []
          }
        }
      }
    }
  },
  methods: {
    changeSpot (e) {
      console.log('e', e)
    },
    handleClose () {
      this.$parent.handleClose()
    },
    reset () {
      this.$refs.form.resetFields()
      this.spotList = []
    },
    getTicketSpotList () {
      this.loading = true
      return getTicketSpotList({
        pageNum: 1,
        pageSize: 10000
      }).then(res => {
        this.ticketSpotList = res.list
      })
    },
    changeCategory (id) {
      if (id !== 2) {
        this.form.person_num = 1
      } else {
        // this.form.idcard_check = 0
        this.form.iccard_check = 0
        this.form.check_pattern = 'time'
      }
    },
    isScenicDisabled (id) {
      return this.form.memberTypeScenic.some(s => s.scenic_id === id)
    },
    // 增加 适用景点-检票次数
    handleAdd () {
      this.form.memberTypeScenic.push({
        scenic_id: '',
        checkLimitTimes: 1
      })
    },
    // 删除 适用景点-检票次数
    delScenic (index) {
      this.form.memberTypeScenic.splice(index, 1)
    },
    isScenicValid () {
      if (this.form.memberTypeScenic.length === 0) {
        this.$message.error('请添加适用景点')
        return false
      } else if (this.form.memberTypeScenic.some(item => !item.scenic_id)) {
        this.$message.error('适用景点信息错误')
        return false
      } else {
        return true
      }
    },
    submit () {
      this.$refs.form.validate((valid) => {
        if (valid && this.isScenicValid()) {
          // if (!this.form.idcard_check && !this.form.iccard_check && !this.form.face_check && !this.form.fingerprint_check) {
          //   this.$message.error('至少选择一种检票方式!')
          //   return
          // }
          if (moment(this.form.saleDateStart).isAfter(this.form.saleDateEnd)) {
            this.$message.error('起售时间不可晚于停售时间!')
            return
          }
          if (moment(this.form.play_startdate).isAfter(this.form.play_enddate)) {
            this.$message.error('游玩开始时间不可晚于游玩截止时间!')
            return
          }
          if (moment(this.form.saleDateStart).isAfter(this.form.play_startdate)) {
            this.$message('起售时间不可晚于游玩开始时间!')
            return
          }
          if (moment(this.form.saleDateEnd).isAfter(this.form.play_enddate)) {
            this.$message('停售时间不可晚于游玩截止时间!')
            return
          }
          this.form.saleDateStart = this.formatStartTime(this.form.saleDateStart)
          this.form.saleDateEnd = this.formatEndTime(this.form.saleDateEnd)
          this.form.play_startdate = this.formatStartTime(this.form.play_startdate)
          this.form.play_enddate = this.formatEndTime(this.form.play_enddate)
          this.form.memberTypeSpot = this.spotList.map(i => {
            return {
              spot_id: i
            }
          })
          // 如何是储值卡，默认关闭人脸和指纹
          if (this.form.category === 5) {
            this.form.face_check = 0
            this.form.fingerprint_check = 0
          }
          if (this.form.date_limit_type === 1) {
            this.form.valid_days = -1
          }
          if (this.form.date_limit_type === 3) {
            this.form.valid_days = -2
          }
          this.form.requiredField = JSON.stringify(this.form.requiredField)
          let url = this.dialogType === 'edit' ? 'updateMemberType' : 'createMemberType'
          apiMember(url, this.form).then(res => {
            this.$message.success('保存成功')
            this.reset()
            this.handleClose()
            this.$emit('updateList')
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    formatStartTime (time) {
      return moment(time).hour(0).minute(0).second(0).toDate()
    },
    formatEndTime (time) {
      return moment(time).hour(23).minute(59).second(59).toDate()
    }
  }
}
</script>
<style lang="scss" scoped>
.dialog-info {
  padding-bottom: 0;
}
.table-box {
  padding: 0 20px;
}
</style>
