<template>
  <el-dialog
    :title="title"
    :visible.sync="visible"
    width="1000px"
    @close="handleClose">
    <div style="width: 100%; text-align: center; margin-bottom: 10px">
      <el-tag type="warning">经登记入库的预制门票，可以在此激活，激活后可直接扫码检票入园。散客购买激活请至售票窗口端操作激活</el-tag>
    </div>
    <el-form
      inline
      label-width="140px"
      :model="form"
      class="form-wrap"
      ref="form">
      <div class="dialog-info">
        <el-form-item
          label="票种名称"
          v-if="currentLog.ticketTypeName">
          {{ currentLog.ticketTypeName }}
        </el-form-item>
        <el-form-item
          label="创建时间"
          v-if="currentLog.playDate">
          {{ currentLog.playDate | formatTime }}
        </el-form-item>

        <el-form-item
          style="width:100%"
          verify
          label="创建方式"
          prop="type">
          <el-radio-group
            v-model="form.type">
            <el-radio label="INPUT_TICKET_NO">
              手动输入票号
            </el-radio>
            <el-radio label="PREFIX_AND_SEQ">
              标识顺序码
            </el-radio>
            <!-- <el-radio label="BATCH_TICKET_NO">
              批量导入
            </el-radio> -->
          </el-radio-group>
        </el-form-item>

        <el-form-item
          verify
          v-if="type === 'active'"
          label="游玩日期"
          prop="playDate">
          <el-date-picker
            v-model="form.playDateBegin"
            type="date"
            placeholder="选择日期时间"
          >
          </el-date-picker>
          <!-- <el-date-picker
            style="width:340px"
            v-model="form.playDate"
            type="datetimerange"
            range-separator="至"
            format="yyyy-MM-dd"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker> -->
        </el-form-item>

        <template v-if="form.type==='INPUT_TICKET_NO'">
          <el-form-item
            key="ticketNos"
            style="width:100%"
            verify
            label="票号"
            prop="ticketNos">
            <div style="display:flex">
              <QRReader v-model="qrCode"></QRReader>
              <el-button
                style="margin-left:10px"
                type="primary"
                @click="handleCodeAdd">
                新增
              </el-button>
              <el-tag type="info" style="margin: 5px">连续票号可以用'-'分隔输入 比如HH001-HH005 单次不超过500张</el-tag>
            </div>

            <div style="margin-top:5px">
              <el-tag
                style="margin-right:5px"
                :key="index"
                v-for="(item,index) in form.ticketNos"
                closable
                @close="form.ticketNos.splice(index,1)">
                {{ item }}
              </el-tag>
            </div>
          </el-form-item>
        </template>

        <template v-if="form.type==='PREFIX_AND_SEQ'">
          <el-form-item
            verify
            key="ticketNoPrefix"
            label="标识码"
            prop="ticketNoPrefix">
            <el-input v-model="form.ticketNoPrefix">
            </el-input>
          </el-form-item>

          <el-form-item
            verify
            key="ticketNoStartIndex"
            label="顺序码首位"
            prop="ticketNoStartIndex">
            <el-input-number
              v-model="form.ticketNoStartIndex"
              :precision="0"
              :min="0">
            </el-input-number>
          </el-form-item>
          <el-form-item
            verify
            key="ticketNoEndIndex"
            label="顺序码末位"
            prop="ticketNoEndIndex">
            <el-input-number
              v-model="form.ticketNoEndIndex"
              :precision="0"
              :min="0">
            </el-input-number>
          </el-form-item>
          <el-form-item
            label="总数">
            {{ Math.abs(form.ticketNoEndIndex-form.ticketNoStartIndex+1) }}
          </el-form-item>
        </template>

        <template v-if="form.type==='BATCH_TICKET_NO'">
          <el-form-item label="批量导入起始票号">
            <QRReader
              v-model="ticketRange.keyWords1"
              ref="firstCode"></QRReader>
          </el-form-item>
          <el-form-item label="批量导入截止票号">
            <QRReader
              @keyup.enter.native="handleEnter"
              v-model="ticketRange.keyWords2"
              ref="nextCode"></QRReader>
          </el-form-item>
          <el-form-item
            label=" "
            style="width:100%">
            <el-button @click="getTicketRange">
              批量导入
            </el-button>
          </el-form-item>
          <el-form-item
            label=" "
            style="width:100%">
            共{{ tableData.length }}条
            <el-table
              stripe
              border
              :data="tableData"
            >
              <el-table-column
                v-for="(col,idx) in columns"
                :key="idx"
                :prop="col.key"
                :label="col.title"
              >
                <template slot-scope="scope">
                  <span v-if="col.key==='isActive'">{{ scope.row.isActive?'已激活':'未激活' }}</span>
                  <span v-else-if="col.key==='activeTime'">{{ scope.row.activeTime | formatTime }}</span>
                  <span v-else-if="col.key==='status'">
                    <OrderStatusTag
                      :value="scope.row.status"
                      v-if="scope.row.status"></OrderStatusTag>
                  </span>
                  <span v-else>{{ scope.row[col.key] }}</span>
                </template>
              </el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button @click="delItem(scope.row)">
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </template>
      </div>
      <div class="dialog-btn-wrap">
        <el-button
          type="primary"
          @click="submit">
          确定
        </el-button>
      </div>
    </el-form>
  </el-dialog>
</template>
<script>
import { ticketInStockActivate, ticketBackToStock, getTicketInStockBySeq } from '@/api/ticketType'
import columns from './recordOfStorage/columns'
import moment from 'moment'
import { debounce } from 'throttle-debounce'

export default {
  props: {
    currentLog: {
      type: Object,
      default: () => {}
    }
  },
  computed: {
    title () {
      return this.type === 'active' ? '门票激活' : '退 库'
    }
  },
  data () {
    return {
      visible: false,
      type: 'active',
      qrCode: '',
      ticketRange: {
        keyWords1: '',
        keyWords2: ''
      },
      tableData: [],
      columns,
      form: {
        type: 'INPUT_TICKET_NO',
        ticketTypeName: '',
        playDate: [new Date(moment().format('YYYY-MM-DD')), new Date(moment().add(7, 'day').format('YYYY-MM-DD'))],
        playDateBegin: new Date(moment().format('YYYY-MM-DD')),
        playDateEnd: new Date(moment().format('YYYY-MM-DD')),
        ticketNoPrefix: '',
        ticketNoStartIndex: 0,
        ticketNoEndIndex: 0,
        ticketNoLength: 0,
        ticketNos: []
      }
    }
  },
  methods: {
    show (type) {
      this.type = type
      this.visible = true

      this.$nextTick(() => {
        const record = this.currentLog

        if (record && record.ticketNoPrefix) {
          this.form.type = 'PREFIX_AND_SEQ'
          this.form.ticketNoPrefix = record.ticketNoPrefix
          this.form.ticketNoStartIndex = record.ticketNoStartIndex
          this.form.ticketNoEndIndex = record.ticketNoEndIndex
          this.form.ticketNoLength = record.ticketNoLength
        }
      })
    },
    reset () {
      this.form.type = 'INPUT_TICKET_NO'
      this.$refs.form.resetFields()
    },
    handleClose () {
      this.reset()
    },
    handleCodeAdd () {
      if (this.qrCode && this.form.ticketNos.findIndex(v => v === this.qrCode) < 0) {
        this.form.ticketNos.push(this.qrCode)
        this.qrCode = ''
      }
    },
    handleEnter () {
      if (!this.tableData.length) {
        this.getTicketRange()
      } else {
        this.submit()
      }
    },
    openNextCode: debounce(1000, false, function (arg) {
      if (this.ticketRange.keyWords2) return
      this.$refs.nextCode.$refs.QRReader.focus()
    }),
    async getTicketRange () {
      if (!(this.ticketRange.keyWords1 && this.ticketRange.keyWords2)) return this.$message.error('请补充查询条件')
      const { extraInfo } = await getTicketInStockBySeq(this.ticketRange)
      if (!extraInfo.length) return this.$message.error('未查询到符合的门票')
      this.tableData = extraInfo
    },
    delItem (item) {
      this.tableData = this.tableData.filter(v => v.ticketNo !== item.ticketNo)
    },
    submit () {
      const { ticketNoPrefix, ticketNoStartIndex, ticketNoEndIndex, playDate, playDateBegin, type, ticketNoLength } = this.form
      const fillLength = (num) => {
        return num.toString().padStart(ticketNoLength, '0')
      }
      if (playDate) {
        const [s, e] = playDate
        this.form.playDateBegin = s ? moment(s).format('YYYY-MM-DD') : ''
        this.form.playDateEnd = e ? moment(e).format('YYYY-MM-DD') : ''
      }

      if (playDateBegin) {
        this.form.playDateBegin = moment(playDateBegin).format('YYYY-MM-DD')
        this.form.playDateEnd = playDateBegin
      }

      this.$refs.form.validate((valid) => {
        if (valid) {
          if (type === 'INPUT_TICKET_NO') {
          } else {
            this.form.ticketPrepareNo = `${ticketNoPrefix}${fillLength(ticketNoStartIndex)}-${ticketNoPrefix}${fillLength(ticketNoEndIndex)}`
          }

          if (!this.form.ticketPrepareNo) {
            return this.$message.error('请补充票号')
          }

          const action = this.type === 'active' ? ticketInStockActivate : ticketBackToStock

          action(this.form).then(res => {
            if (res.code !== '200') {
              return this.$message.error(res.msg)
            }
            this.$message.success('操作成功')
            this.handleClose()
            this.$emit('update')
            this.$nextTick(() => {
              this.form.ticketNos = []
            })
          })
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-tag + .el-tag{
  margin:0
}
</style>
