<template>
  <el-dialog
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :visible="visible"
    :before-close="handleClose"
    title="出票确认"
    width="80%">
    <el-form
      class="info-wrap"
      label-width="100px"
      :inline="true">
      <div style="margin-bottom: 20px;">
        付款方式：
        <el-radio-group
          size="medium"
          fill="#ff6934"
          v-model="currentPayChannel">
          <el-radio-button
            v-for="val in payChannelOptions"
            :key="val"
            :label="val"></el-radio-button>
        </el-radio-group>
      </div>

      <el-table
        border
        :data="orderInfo"
        style="margin-bottom:30px">
        <el-table-column
          prop="ticketName"
          label="票种名称">
        </el-table-column>
        <el-table-column
          label="游玩日期">
          <template slot-scope="scope">
            {{ scope.row.payDateBegin | formatDate }}
          </template>
        </el-table-column>
        <el-table-column
          prop="count"
          label="数量">
        </el-table-column>
        <el-table-column
          prop="total"
          label="小计">
        </el-table-column>
      </el-table>

      <el-form-item
        label="检票方式"
        class="warning">
        <span class="strong">
          {{ getCheckWayName(formData?formData.checkWay:'') }}
        </span>
      </el-form-item>

      <el-form-item
        label="总数"
        class="warning">
        <span class="strong">
          {{ totalCount }}
        </span>
      </el-form-item>

      <el-form-item
        label="总金额"
        class="warning">
        <span class="strong">
          {{ orderPrice }}
        </span> 元
      </el-form-item>

      <el-form-item
        label="付款方式"
        class="warning">
        <span class="strong">
          {{ currentPayChannel }}
        </span>
      </el-form-item>

      <br>
      <el-form-item
        label="备注">
        {{ remark }}
      </el-form-item>
    </el-form>
    <div
      class="table-box"
      style="padding-top:0">
      <Collapse title="游客详情信息">
        <el-table
          stripe
          :data="tickets">
          <el-table-column
            type="index"
            width="50"
          >
          </el-table-column>

          <el-table-column
            prop="guestName"
            label="游客姓名"
          >
          </el-table-column>

          <el-table-column
            prop="guestPhone"
            label="游客电话"
          >
          </el-table-column>

          <el-table-column
            prop="guestIdentify"
            label="身份证"
            min-width="130"
          >
          </el-table-column>
        </el-table>
      </Collapse>
    </div>

    <div class="dialog-btn-wrap">
      <el-button @click="handleClose">
        取消
      </el-button>
      <el-button
        type="danger"
        v-if="scenicName==='狼山景区'||scenicName==='军山景区'"
        @click="$refs.queryPos.show()">
        查询POS机交易
      </el-button>
      <el-button
        type="primary"
        :disabled="submitDisable"
        @click="submit"
      >
        {{ submitDisable?'正在处理':'确认出票' }}
      </el-button>
    </div>

    <ReadValueCard
      ref="readValueCard"
      @getInfo="handleValueCardPay"
      @close="submitDisable=false"></ReadValueCard>

    <QueryPos
      ref="queryPos"
      @confirm="handleQueryPos"></QueryPos>
  </el-dialog>
</template>

<script>
import { checkWayList } from '@/assets/staticData'
import { createOrder, getSingleOrder } from '@/api/order'
import { createValueCardOrder } from '@/api/valueCard'
import ReadValueCard from '../common/ReadValueCard'
import Collapse from '@/components/Collapse'
import QueryPos from '../common/QueryPos'

import mixin from './mixin'
import posMixin from '@/pages/common/posMixin'

import handlePay from '../common/handlePay'

export default {
  props: {
    tickets: {
      type: Array,
      default: () => []
    },
    orderItems: {
      type: Array,
      default: () => []
    },
    remark: {
      type: String,
      default: ''
    },
    orderPrice: {
      type: Number,
      default: 0
    },
    formData: {
      type: Object,
      default: () => {}
    },
    payChannel: {
      type: String,
      default: ''
    },
    totalCount: {
      type: Number,
      default: 0
    }
  },
  mixins: [mixin, posMixin],
  components: {
    Collapse,
    ReadValueCard,
    QueryPos
  },
  computed: {
    scenicName () {
      return this.$localStore.get('scenicName') || this.$store.state.user.scenicName
    },
    maxNum () {
      return this.$store.state.app.systemConfig.find(i => i.configKey === 'ticket_checkNum_limit').configValue
    }
  },
  data () {
    return {
      submitDisable: false,
      visible: false,
      active: '',
      orderInfo: [],
      printArray: [],
      currentPrint: null,
      currentPayChannel: '',
      payStatus: 0, // 支付状态
      createOrderStatus: 0 // 创建订单状态
    }
  },
  methods: {
    show () {
      this.visible = true
      this.submitDisable = false
      this.payStatus = 0
      this.createOrderStatus = 0
      this.orderInfo = JSON.parse(JSON.stringify(this.orderItems))
      this.currentPayChannel = this.payChannel
    },
    changePayChannel (n) {
      let i = this.payChannelOptions.findIndex(channel => channel === this.currentPayChannel)
      let l = this.payChannelOptions.length
      let j = (i - n + l) % l
      this.currentPayChannel = this.payChannelOptions[j]
    },
    arrowUp () {
      this.changePayChannel(1)
    },
    arrowDown () {
      this.changePayChannel(-1)
    },
    getCheckWayName (val) {
      let a = checkWayList.find(i => i.val === val)
      return a && a.name
    },
    handleClose () {
      if (this.submitDisable) {
        this.$confirm('支付尚未完成，是否强制关闭？', '提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$log.info('支付进程被强制关闭')
          this.visible = false

          // 结束支付进程
          this.killAllPosProcess()
        }).catch(() => {})
        return
      }

      if (this.payStatus === 1 && this.createOrderStatus !== 1) {
        this.$confirm('支付成功但下单失败，是否重试？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.createOrder(this.params)
        }).catch(() => {
        })

        return
      }

      this.visible = false

      // 结束支付进程
      this.killAllPosProcess()
    },
    // 使用现有pos消费信息进行出票
    handleQueryPos (posInfo) {
      this.setParams()
      this.params.bocTradeNo = JSON.stringify(posInfo)

      if (this.$NP.divide(posInfo.amount, 100) !== this.params.price) {
        this.$message.error('消费金额与当前出票信息不符。')
        return
      }
      this.createOrder(this.params)
    },
    setParams () {
      let tickets = this.tickets
      let params = Object.assign({}, this.formData)

      // 一码多人,根据单张门票最大限额进行拆分
      if (params.checkWay - 0 === 2) {
        let allTickets = []

        this.orderInfo.forEach((item, index) => {
          let count = item.count
          let ticketOrderTravellers = item.tickets.map(i => {
            return {
              name: i.guestName,
              idType: i.guestIdentifyType,
              idNum: i.guestIdentify,
              mobile: i.guestPhone
            }
          })
          let obj = JSON.parse(JSON.stringify(item.tickets[0]))
          obj.ticketOrderTravellers = ticketOrderTravellers
          let originItem = JSON.stringify(obj)

          if (!this.maxNum) {
            let item = JSON.parse(originItem)
            item.checkNum = count
            item.price = this.$NP.times(item.checkNum, item.price)
            allTickets.push(item)
            return
          }

          if (count > this.maxNum) {
            let num = Math.ceil(count / this.maxNum)

            for (let i = 0; i < num - 1; i++) {
              let newItem = JSON.parse(originItem)
              newItem.checkNum = this.maxNum
              newItem.price = this.$NP.times(this.maxNum, item.price)
              allTickets.push(newItem)
            }
            let lastItem = JSON.parse(originItem)
            if (count % this.maxNum === 0) {
              lastItem.checkNum = this.maxNum
            } else {
              lastItem.checkNum = count % this.maxNum
            }
            lastItem.price = this.$NP.times(lastItem.checkNum, item.price)

            allTickets.push(lastItem)
          } else {
            let item = JSON.parse(originItem)
            item.checkNum = count
            item.price = this.$NP.times(item.checkNum, item.price)
            allTickets.push(item)
          }
        })

        params.tickets = allTickets
      } else {
        params.tickets = tickets
      }
      // params.count = this.totalCount
      params.payChannel = this.currentPayChannel
      params.price = this.orderPrice
      params.sellDevice = this.sellerDevice && this.sellerDevice.ip4

      this.params = params
    },
    submit () {
      // 防止重复提交
      if (this.submitDisable) return
      this.submitDisable = true

      // 支付已成功只提交订单
      if (this.payStatus === 1) {
        this.createOrder(this.params)
        return
      }

      // 设置参数
      this.setParams()

      this.$log.warn('散客支付下单')

      // 支付处理
      handlePay(this.params, null, this, () => {
        this.createOrder(this.params)
      })
    },
    handleValueCardPay (cardInfo) {
      console.log('储值卡信息', cardInfo)
      // console.log(createValueCardOrder)
      createValueCardOrder({
        cardNo: cardInfo.cardCode,
        cardVendor: 'CHANGYI',
        order: this.params
      }).then(res => {
        this.handleCreateSuccess(this.params, res)
      })
    },
    createOrder (params) {
      this.submitDisable = true
      this.createOrderStatus = 0

      createOrder(params).then(res => {
        this.$log.warn('散客下单成功')
        this.createOrderStatus = 1
        this.submitDisable = false
        this.handleCreateSuccess(params, res)
      }).catch(err => {
        this.$log.error(err)
        this.$confirm('下单失败，是否重试？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.createOrder(this.params)
        }).catch(() => {
        })
      }).finally(() => {
        this.submitDisable = false
      })
    },
    handleCreateSuccess (params, res) {
      this.$message.success('出票成功')
      // 身份证检票不打印
      let autoPrint = params.checkWay === 3 ? false : (this.$localStore.get('autoPrint') || false)

      // 获取订单详情
      // 自动打印
      autoPrint && getSingleOrder(res?.data).then(order => {
        this.$print(order)
      })

      // 关闭弹窗
      this.handleClose()

      this.$emit('complete')
    }
  },
  beforeDestroy () {
    this.killAllPosProcess()
  }
}
</script>

<style lang="scss" scoped>
.btn-wrap {
  padding-top: 20px; text-align: center;
}
.info-wrap {
  padding: 20px 20px;
  ::v-deep .el-form-item__label{
    font-size: 16px;
  }
  ::v-deep .el-form-item{
    display: inline-block;
  }
  .strong {
    font-size: 1.8em; font-weight: bold;
  }
}
</style>

<style lang="scss">

</style>
