<template>
  <el-form
    class="sell-form"
    ref="form"
    :model="form"
    :inline="true"
    label-width="100px"
  >
    <div class="sell-form-inner">
      <div class="top-block">
        <div class="side-content">
          <TickList
            type-id="1"
            @update="handleTicketUpdate"
            slot="left"
          ></TickList>
        </div>
        <div class="main-content">
          <div
            class="content-inner custom-scroll block-wrap"
            id="guest-list-card">
            <div
              class="block-title"
              v-if="currentTicket"
            >
              当前票种：<b>{{ currentTicket.name }}</b>（请刷身份证）
            </div>
            <el-table
              border
              stripe
              width="100%"
              :max-height="tableHeight"
              :data="guestList"
            >
              <el-table-column
                label="#"
                type="index"
              >
              </el-table-column>
              <el-table-column
                prop="guestName"
                label="游客姓名"
              >
                <template slot-scope="scope">
                  {{ scope.row.guestName || '（空）' }}
                </template>
              </el-table-column>
              <el-table-column
                label="身份证"
              >
                <template slot-scope="scope">
                  {{ scope.row.guestIdentify || '（空）' }}
                </template>
              </el-table-column>
              <el-table-column 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>
              </el-table-column>
            </el-table>
          </div>
          <div class="footer block-wrap">
            <el-form-item label="订单总金额">
              <div class="input-space warning">
                <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"
                  :value="item"
                  :label="item"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="实付金额">
              <el-input-number
                :min="0"
                :step="0.01"
                :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"
                  @change="handleAutoPrintChange"
                >
                  自动打印
                </el-checkbox>
                <el-button
                  type="default"
                  size="medium"
                  @click="reset"
                >
                  重置
                </el-button>
                <el-button
                  type="primary"
                  class="warnBtn"
                  size="medium"
                  :disabled="submitDisable"
                  @click="confirm"
                >
                  {{ submitDisable?'正在处理':'确认出票' }}
                </el-button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <ElDialog
      title="确认出票"
      v-model="confirmDialogVisible">
      <ConfirmDialog
        @submit="submit"
        :current-ticket="currentTicket"
        :guest-list="guestList"
        :total-price="totalPrice"
      />
    </ElDialog>

    <ReadValueCard
      ref="readValueCard"
      @getInfo="handleValueCardPay"
      @close="submitDisable=false"></ReadValueCard>
  </el-form>
</template>

<script>
import TickList from './common/TicketList'
import { createOrder, getSingleOrder } from '@/api/order'
import { createValueCardOrder } from '@/api/valueCard'
import { getIdInfo } from '@/api/ZTKReaderApi'
import { getPayChannel } from '@/api/systemConfig'
import { getTicketTypeInfo } from '@/api/ticketType'

import ReadValueCard from './common/ReadValueCard'
import moment from 'moment'
import ElDialog from '@/components/Dialog'
import ConfirmDialog from './quickSell/ConfirmDialog'
import posMixin from '@/pages/common/posMixin'

import handlePay from './common/handlePay'

export default {
  mixins: [posMixin],
  components: {
    TickList,
    ElDialog,
    ConfirmDialog,
    ReadValueCard
  },
  computed: {
    model () {
      return {
        guestData: this.guestData
      }
    },
    totalPrice () {
      if (!this.currentTicket) {
        return 0
      }
      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 {
      submitDisable: false,
      currentTicket: null,
      currentPrice: 0,
      autoPrint: this.$localStore.get('autoPrint'),
      finished: false,
      visible: false,
      idKey: 0,
      guestList: [],
      currentPrint: null,
      orderInfo: null,
      qrImg: '',
      form: {
        payChannel: '现金',
        actualMoney: 0,
        count: 0,
        buyerIdentify: '',
        buyerName: '',
        buyerIdentifyType: 1,
        buyerPhone: '',
        groupIndividual: 1,
        payDateBegin: new Date(),
        playDateEnd: '',
        price: 0
      },
      payChannelOptions: [],
      tableHeight: 300,
      confirmDialogVisible: false
    }
  },
  methods: {
    handleTicketUpdate (ticket) {
      this.currentTicket = ticket
    },
    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.Certificate && this.addTicket(idInfo.Certificate)
      this.timer = setTimeout(() => {
        this.getIdInfo()
      }, 300)
    },
    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 = []
    },
    confirm () {
      if (this.guestList.length === 0) {
        this.$message.error('请刷身份证，录入信息')
        return
      }
      this.confirmDialogVisible = true
    },
    submit () {
      if (this.submitDisable) return
      this.submitDisable = true

      let tickets = this.guestList.map(item => {
        return {
          ticketTypeId: this.currentTicket.id,
          checkNum: this.currentTicket.check_count,
          price: this.currentPrice,
          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.tickets = tickets

      this.params = params

      handlePay(params, this, () => {
        this.createOrder(params)
      })
    },
    handleValueCardPay (cardInfo) {
      console.log('储值卡信息', cardInfo)
      // console.log(createValueCardOrder)
      createValueCardOrder({
        cardNo: cardInfo.cardCode,
        cardVendor: 'CHANGYI',
        order: this.params
      }).then(res => {
        this.$message.success('出票成功。')
        this.handleCreateSuccess(res)
      })
    },
    createOrder (params) {
      createOrder(params).then(res => {
        this.handleCreateSuccess(res)
      }).finally(() => {
        this.submitDisable = false
      })
    },
    handleCreateSuccess (res) {
      this.$message.success('出票成功')
      this.reset()
      this.guestList = []
      // 获取订单详情
      this.autoPrint && getSingleOrder(res?.data).then(order => {
        this.$print(order)
      })
    },
    handleAutoPrintChange (val) {
      this.$localStore.set('autoPrint', val)
    },
    setPrice () {
      this.loading = true
      getTicketTypeInfo({
        id: this.currentTicket.id,
        start: moment(this.form.payDateBegin).format('YYYY-MM-DD'),
        end: moment(this.form.payDateBegin).format('YYYY-MM-DD')
      }).then(res => {
        this.currentPrice = res?.data.prices[0] ? res?.data.prices[0].price : 0
      }).finally(() => {
        this.loading = false
      })
    }
  },
  mounted () {
    let elem = document.getElementById('guest-list-card')
    this.tableHeight = elem.offsetHeight - 82
    this.getIdInfo()
    getPayChannel().then(res => {
      this.payChannelOptions = res
      this.form.payChannel = this.payChannelOptions[0]
    })
  },
  watch: {
    currentTicket (val) {
      if (!val) return
      // 设置初始日期
      if (moment(val.useDateStart).isAfter(new Date())) {
        this.form.payDateBegin = val.useDateStart
      } else {
        this.form.payDateBegin = new Date(moment().startOf('day').valueOf())
      }

      this.setPrice()
    },
    'form.payDateBegin' (val) {
      if (val) {
        this.setEndDate()

        this.setPrice()
      }
    },
    totalPrice (val) {
      this.form.actualMoney = val
    }
  },
  beforeDestroy () {
    this.timer && clearTimeout(this.timer)
    this.finished = true
    this.killAllPosProcess()
  }
}
</script>

<style scoped>
</style>
