<template>
  <div style="height: 100%;">
    <el-form
      style="height: 100%;"
      ref="form"
      :model="form"
      :inline="true"
      label-width="100px"
    >
      <ElCard id="guest-list-card">
        <div
          class="block-title"
          v-if="currentTicket"
        >
          {{ currentTicket.name }}（请刷身份证）
        </div>
        <ElTable
          width="100%"
          :max-height="tableHeight"
          :data="guestList"
        >
          <ElTableColumn
            label="#"
            type="index"
          >
          </ElTableColumn>
          <ElTableColumn
            prop="guestName"
            label="游客姓名"
          >
            <template slot-scope="scope">
              {{ scope.row.guestName || '（空）' }}
            </template>
          </ElTableColumn>

          <ElTableColumn
            label="身份证"
          >
            <template slot-scope="scope">
              {{ scope.row.guestIdentify || '（空）' }}
            </template>
          </ElTableColumn>

          <ElTableColumn label="操作">
            <template slot-scope="scope">
              <span
                class="el-button el-button--primary el-button--mini"
                @click="delTicket(scope.row.idKey)"
              >
                <i class="el-icon-delete"></i>
                删除
              </span>
            </template>
          </ElTableColumn>
        </ElTable>
      </ElCard>

      <el-card>
        <div class="block-title">
          交易信息
        </div>

        <el-form-item label="订单总金额">
          <div class="input-space">
            <b class="strong">
              {{ totalPrice }}
            </b> 元
          </div>
        </el-form-item>
        <el-form-item
          class="is-required"
          label="付款方式"
          prop="payChannel"
        >
          <el-select v-model="form.payChannel">
            <el-option
              v-for="item in payChannelOptions"
              :key="item.id"
              :value="item.id"
              :label="item.name"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="实付金额">
          <el-input-number
            :min="0"
            :precision="2"
            :controls="false"
            v-model.number="form.actualMoney"
          ></el-input-number>
        </el-form-item>
        <el-form-item
          :label="payBack>0?'找零':'还需支付'"
          v-if="payBack!==0"
        >
          <div class="input-space">
            <b class="strong">
              {{ Math.abs(payBack) }}
            </b> 元
          </div>
        </el-form-item>
        <div class="btn-wrap">
          <div class="right">
            <el-checkbox
              v-model="autoPrint"
              style="margin-right:30px"
            >
              自动打印
            </el-checkbox>
            <el-button
              type="default"
              @click="reset"
            >
              重置
            </el-button>
            <el-button
              type="primary"
              @click="submit"
            >
              出票
            </el-button>
          </div>
        </div>
      </el-card>
    </el-form>

    <div
      class="print-wrap"
      v-if="currentPrint"
    >
      <div id="printMe">
        <table>
          <tr>
            <td>订单号:</td>
            <td>{{ orderInfo.orderNo }}</td>
          </tr>
          <tr>
            <td>下单时间:</td>
            <td>{{ orderInfo.createTime }}</td>
          </tr>
          <tr>
            <td>票号:</td>
            <td>{{ currentPrint.qrcode }}</td>
          </tr>
        </table>
        <h3>{{ currentPrint.ticketTypeName }}</h3>
        <qriously
          :value="currentPrint.qrcode"
          id="qrcode"
          style="display:none"
          :size="120"
        />
        <div class="img">
          <img :src="qrImg">
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { createOrder, getSingleOrder } from '@/api/order'
import { getIdInfo } from '@/api/ZTKReaderApi'
import moment from 'moment'
export default {
  props: {
    guestData: {
      type: Array,
      default: () => []
    },
    value: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  computed: {
    model () {
      return {
        guestData: this.guestData
      }
    },
    totalPrice () {
      if (!this.currentTicket) {
        return 0
      }
      console.log('票价', this.currentTicket.price)
      console.log('数量', this.form.count)
      return this.currentTicket.price * this.form.count
    },
    payBack () {
      if (this.form.actualMoney === undefined) {
        return (-this.totalPrice * 1000) / 1000
      } else {
        return (this.form.actualMoney * 1000 - this.totalPrice * 1000) / 1000
      }
    }
  },
  data () {
    return {
      autoPrint: false,
      finished: false,
      visible: false,
      currentTicket: null,
      idKey: 0,
      guestList: [],
      currentPrint: null,
      orderInfo: null,
      form: {
        payChannel: 1,
        actualMoney: 0,
        count: 0,
        buyerIdentify: '',
        buyerName: '',
        buyerIdentifyType: 1,
        buyerPhone: '',
        groupIndividual: 1,
        payDateBegin: new Date(),
        playDateEnd: '',
        price: 0
      },
      payChannelOptions: [{
        id: 1,
        name: '现金'
      },
      {
        id: 2,
        name: '微信'
      },
      {
        id: 3,
        name: '支付宝'
      }, {
        id: 4,
        name: '挂账'
      }],
      tableHeight: 300
    }
  },
  methods: {
    formatDateTime (input) {
      return moment(input).format('YYYY-MM-DD HH:mm:ss')
    },
    formatDate (input) {
      return moment(input).format('YYYY-MM-DD')
    },
    setEndDate () {
      if (!this.form.payDateBegin) return
      let endDate = moment(this.form.payDateBegin).add(this.currentTicket.useDays - 1, 'days')
      let endTime = endDate.format('YYYY-MM-DD') + ' 23:59:59'
      this.form.playDateEnd = new Date(endTime)
    },
    async getIdInfo () {
      if (this.finished) return
      this.timer && clearTimeout(this.timer)
      let idInfo = await getIdInfo()
      idInfo && this.addTicket(idInfo)
      this.timer = setTimeout(() => {
        this.getIdInfo()
      }, 300)
    },
    handleClose () {
      this.$parent.handleClose()
      this.finished = true
    },
    handleAdd () {
      this.$emit('addTicket')
    },
    addTicket (data) {
      let existInfo = this.guestList.find(item => {
        return data.IDNumber === item.guestIdentify
      })

      if (existInfo) return
      let guestInfo = {
        idKey: this.idKey++,
        guestName: data.Name,
        guestPhone: '',
        guestIdentify: data.IDNumber
      }
      this.guestList.unshift(guestInfo)
      this.form.count++
    },
    delTicket (id) {
      let index = this.guestList.findIndex(item => {
        return item.idKey === id
      })
      this.guestList.splice(index, 1)
      this.form.count--
    },
    reset () {
      this.$refs.form.resetFields()
      this.form.count = 0
      this.guestList = []
    },
    submit () {
      if (this.guestList.length === 0) {
        this.$message.error('请刷身份证，录入信息')
        return
      }
      let tickets = this.guestList.map(item => {
        return {
          ticketTypeId: this.currentTicket.id,
          checkNum: this.currentTicket.check_count,
          price: this.currentTicket.price,
          guestName: item.guestName,
          guestPhone: item.guestPhone,
          guestIdentify: item.guestIdentify,
          payDateBegin: this.form.payDateBegin,
          playDateEnd: this.form.playDateEnd
        }
      })
      let params = Object.assign({}, this.form)
      params.price = this.totalPrice
      params.sellDevice = this.sellerDevice && this.sellerDevice.ip4
      params.tickets = tickets
      createOrder(params).then(res => {
        this.$message.success('出票成功')
        this.reset()
        this.guestList = []

        // 获取订单详情
        this.autoPrint && getSingleOrder(res?.data).then(res => {
          // console.log(res)
          this.orderInfo = res
          this.orderInfo.createTime = moment(this.orderInfo.createTime).format('YYYY-MM-DD HH:mm:ss')
          res.tickets.forEach((item, index) => {
            setTimeout(() => {
              this.currentPrint = item
              // console.log('拿到数据')
              this.$nextTick(() => {
                let qr = document.getElementById('qrcode').childNodes[0]
                this.qrImg = qr.toDataURL('image/png')
                // console.log('生成数据')
                setTimeout(() => {
                  this.printPage('#printMe')
                  // console.log('打印数据')
                }, 100)
              })
            }, 500 * index)
          })
        })
      })
    }
  },
  mounted () {
    let elem = document.getElementById('guest-list-card')
    this.tableHeight = elem.offsetHeight - 82
    this.getIdInfo()
  },
  watch: {
    value (val) {
      this.currentTicket = val
      this.setEndDate()
    },
    totalPrice (val) {
      this.form.actualMoney = val
    }
  },
  beforeDestroy () {
    this.timer && clearTimeout(this.timer)
    this.finished = true
  }
}
</script>

<style lang="scss" scoped>
#guest-list-card {
  height: calc(100% - 330px);
}
</style>
