<template>
  <el-dialog
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :visible="visible"
    :before-close="handleClose"
    title="出票确认"
    width="80%">
    <el-form
      v-loading="submitDisable"
      element-loading-text="正在处理付款请求，请稍候"
      class="info-wrap"
      label-width="100px"
      :inline="true">
      <div style="margin-bottom: 20px;">
        付款方式：
        <el-radio-group
          :disabled="createOrderStatus===1"
          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">
          {{ 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">
          {{ discount }}
        </span> 折
      </el-form-item>

      <el-form-item
        label="折后总额"
        class="warning">
        <span class="strong">
          {{ finalPrice }}
        </span> 元
      </el-form-item>

      <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">
          {{ payChannel }}
        </span>
      </el-form-item>

      <el-form-item
        v-if="currentPayChannel==='旅行社余额' && currentAgency"
        label="预付余额"
        class="warning">
        <span class="strong">
          {{ currentAgency.prepayment_amount }}
        </span>
      </el-form-item>

      <el-form-item
        v-if="currentPayChannel==='旅行社余额' && currentAgency"
        label="信用限额"
        class="warning">
        <span class="strong">
          {{ currentAgency.prepayment_type?currentAgency.prepayment_limit:'无限制' }}
        </span>
      </el-form-item>

      <br>
      <el-form-item
        label="备注">
        {{ formData.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-switch
        style="margin:0 50px 0 10px"
        v-model="isPrintSmallTicket">
      </el-switch>

      自动打印
      <el-switch
        style="margin:0 50px 0 10px"
        v-model="isPrint">
      </el-switch>

      <el-button @click="handleClose">
        取消
      </el-button>

      <el-button
        type="warning"
        v-if="showRefresh"
        :disabled="isRefresh"
        @click="payRefresh">
        刷新支付状态<span v-if="isRefresh">({{ countNum }})</span>
      </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>

    <!-- GlobalComponents 全局组件 -->
    <PosQrCodeReader
      ref="posQrCodeReader"
      @getQrcode="submit"></PosQrCodeReader>
    <XSCQrCodeReader
      ref="XSCQrCodeReader"
      @getQrcode="submit"></XSCQrCodeReader>
  </el-dialog>
</template>

<script>
import { checkWayList } from '@/assets/staticData'
import { createAgencyPreorderTickets, getSingleOrder } from '@/api/order'
import { createValueCardOrder } from '@/api/valueCard'
import { getPosPayChannel } from '@/utils/choosePay'

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'
import { payRefresh } from '@/api/pay'
import { debounce } from 'throttle-debounce'

export default {
  props: {
    tickets: {
      type: Array,
      default: () => []
    },
    orderItems: {
      type: Array,
      default: () => []
    },
    remark: {
      type: String,
      default: ''
    },
    discount: {
      type: Number,
      default: 0
    },
    orderPrice: {
      type: Number,
      default: 0
    },
    finalPrice: {
      type: Number,
      default: 0
    },
    formData: {
      type: Object,
      default: () => {}
    },
    payChannel: {
      type: String,
      default: ''
    },
    totalCount: {
      type: Number,
      default: 0
    },
    preOrderInfo: {
      type: Object,
      default: () => null
    }
  },
  mixins: [mixin, posMixin],
  components: {
    Collapse,
    ReadValueCard,
    QueryPos
  },
  computed: {
    showRefresh () {
      const scanArr = ['中旅银行', '建行B扫C']
      return scanArr.indexOf(this.currentPayChannel) > -1 && this.submitDisable
    },
    showPosQrcode () {
      // 需要手动扫码的景区
      const list = ['东方绿舟', '天津之眼', '绿博园']

      if (this.scenicName === '绿博园' && (!this.$localStore.get('posName') || this.$localStore.get('posName') === 'jianhang')) {
        return false
      }

      return list.indexOf(this.scenicName) > -1
    },
    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
    },
    agencyList () {
      return this.$store.state.app.agencyList
    },
    currentAgency () {
      return this.agencyList.find(i => i.id === this.formData.travelAgencyId)
    }
  },
  data () {
    return {
      isPrint: false,
      isPrintSmallTicket: false,
      submitDisable: false,
      visible: false,
      active: '',
      currentPayChannel: '',
      orderInfo: [],
      printArray: [],
      isRefresh: false,
      countNum: 5,
      orderTempInfo: {}, // 临时订单信息，防止重复创建订单
      timer: null, // 检查订单是否支付成功计时器
      currentPrint: null,
      printPlayDateBegin: '',
      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

      this.$nextTick(() => {
        this.isPrint = this.formData.checkWay === 3 ? false : (this.$localStore.get('autoPrint') || false)

        this.isPrintSmallTicket = this.$localStore.get('autoPrintSmallTicket')
      })
    },
    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]
    },
    payRefresh () {
      // if (!this.orderTempInfo.extraInfo) return
      this.countTimer && clearTimeout(this.countTimer)

      this.isRefresh = true
      this.countNum = 5
      this.countdown()

      payRefresh({ type: 'TICKET', id: this.orderTempInfo.extraInfo })
    },
    countdown () {
      this.countTimer = setTimeout(() => {
        this.countNum--
        this.countdown()
        if (this.countNum === 0) {
          this.isRefresh = false
        }
      }, 1000)
    },
    arrowUp () {
      this.changePayChannel(1)
    },
    arrowDown () {
      this.changePayChannel(-1)
    },
    getCheckWayName (val) {
      let a = checkWayList.find(i => i.val === val)
      return a && a.name
    },
    handleClose () {
      this.timer && clearTimeout(this.timer)
      if (this.submitDisable) {
        this.$confirm('支付尚未完成，是否强制关闭？', '提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$log.info('支付进程被强制关闭')
          this.visible = false

          // 结束支付进程
          this.killAllPosProcess()
        }).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 = JSON.parse(JSON.stringify(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.discountPrice)
            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, newItem.discountPrice)
              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, lastItem.discountPrice)

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

        params.tickets = allTickets
      } else {
        params.tickets = tickets.map(item => {
          item.price = item.discountPrice
          return item
        })
      }
      params.payChannel = this.currentPayChannel
      params.price = this.finalPrice
      params.sellDevice = this.sellerDevice && this.sellerDevice.ip4

      this.params = params
    },
    submit: debounce(1000, true, function (qrcode, cardInfo) {
      // 西宁景区储值卡支付预留
      if (this.currentPayChannel.indexOf('储值卡') > -1 && this.scenicName === '西宁景区') {
        // ID卡
        this.$refs.readValueCard.show(this.params)
        return
      }

      // 是否使用外部扫码
      if (this.currentPayChannel === '聚合扫码' && !qrcode && this.showPosQrcode) {
        this.$refs.posQrCodeReader.show()
        return
      }
      const scanArr = ['中旅银行', '瑞通储值卡', '建行B扫C']
      // 是否使用外部扫码
      if (scanArr.indexOf(this.currentPayChannel) > -1 && !qrcode) {
        this.$refs.XSCQrCodeReader.show(this.tickets, this.currentPayChannel)
        return
      }
      // 防止重复提交
      if (this.submitDisable) return
      this.submitDisable = true

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

      this.setParams()

      this.params.qrCode = qrcode
      this.params.discount = cardInfo ? cardInfo.discount : ''
      this.params.password = cardInfo ? cardInfo.password : ''
      this.$log.warn('团体预订票支付下单')
      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) {
      if (params.bocTradeNo) {
        params.payChannel = getPosPayChannel(params.bocTradeNo)
      }
      this.submitDisable = true
      if (this.createOrderStatus === 1) {
        handlePay(this.params, this.orderTempInfo, this, () => {})
      } else {
        createAgencyPreorderTickets({
          order: params,
          travel_agency_order_id: this.preOrderInfo.id
        }).then(res => {
          this.$log.warn('团体预订票下单成功')
          this.createOrderStatus = 1
          this.orderTempInfo = res
          handlePay(this.params, res, this, () => {})
          if (this.payStatus !== 1) {
            this.getSingleOrder(res, params)
          }
        }).catch(e => {
          this.submitDisable = false
        })
      }
    },
    getSingleOrder (res, params) {
      this.timer && clearTimeout(this.timer)
      getSingleOrder(res?.data).then(order => {
        console.log('order', order)
        if (order.pay_status === 'PAYED') {
          this.handleCreateSuccess(params, res)
        } else if (order.pay_status === 'CLOSED') {
          this.$message.error('交易失败，订单关闭，请重新创建订单')
          this.submitDisable = false
          this.visible = false
        } else {
          this.timer = setTimeout(() => {
            this.getSingleOrder(res, params)
          }, 2000)
        }
      })
    },
    handleCreateSuccess (params, res) {
      this.$message.success('出票成功。')
      this.submitDisable = false

      getSingleOrder(res?.data).then(order => {
        this.isPrint && this.$print(order)
        this.isPrintSmallTicket && this.$printSmallTicket(order)
      })

      // 关闭弹窗
      this.handleClose()
      // 更新旅行社余额
      this.currentPayChannel === '旅行社余额' && (this.$store.dispatch('getAgencyList'))

      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>
