import QueryPos from './QueryPos'
import ReadValueCard from './ReadValueCard'
import Collapse from '@/components/Collapse'

import { payRefresh } from '@/api/pay'
import handlePay, { getPayType } from '../common/handlePay'
import { debounce } from 'throttle-debounce'
import { checkWayList } from '@/assets/staticData'
import { createValueCardOrder } from '@/api/valueCard'
import { createOrder, getSingleOrder } from '@/api/order'
import { EventBus } from '@/utils/eventBus'

export default {
  props: {
    tickets: {
      type: Array,
      default: () => []
    },
    orderItems: {
      type: Array,
      default: () => []
    },
    createOrderRemark: {
      type: String,
      default: ''
    },
    orderPrice: {
      type: Number,
      default: 0
    },
    formData: {
      type: Object,
      default: () => { }
    },
    payChannel: {
      type: String,
      default: ''
    },
    totalCount: {
      type: Number,
      default: 0
    },
    currentTicket: {
      type: Object,
      default: () => null
    }
  },
  components: {
    Collapse,
    ReadValueCard,
    QueryPos
  },
  computed: {
    payType () {
      return getPayType(this.currentPayChannel)
    },
    showRefresh () {
      return this.payType === 'B_SCAN_C_PAY' && 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
    },
    playDate () {
      return this.currentTicket ? this.currentTicket.playDate : ''
    }
  },
  data () {
    return {
      isPrint: false,
      isPrintSmallTicket: false,
      submitDisable: false,
      visible: false,
      active: '',
      orderInfo: [],
      printArray: [],
      isRefresh: false,
      countNum: 5,
      orderTempInfo: {}, // 临时订单信息，防止重复创建订单
      timer: null, // 检查订单是否支付成功计时器
      currentPrint: null,
      currentPayChannel: '',
      payStatus: 0, // 支付状态
      createOrderStatus: 0, // 创建订单状态
      payCode: '',
      payCodeDialogVisible: false
    }
  },
  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 })
    },
    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)
    },
    submit: debounce(1000, true, function (qrcode, cardInfo) {
      console.log(this.payType)
      // 西宁景区储值卡支付预留
      if (this.payType === 'VALUECARD' && this.scenicName === '西宁景区') {
        this.setParams()
        this.$refs.readValueCard.show(this.params)
        return
      }

      // POS支付是否使用外部扫码
      if (this.payType === 'POS' && this.currentPayChannel === '聚合扫码' && !qrcode && this.showPosQrcode) {
        this.$refs.posQrCodeReader.show()
        return
      }

      const scanArr = ['瑞通储值卡']
      // 是否使用外部扫码
      if ((scanArr.indexOf(this.currentPayChannel) > -1 || this.payType === 'B_SCAN_C_PAY') && !qrcode) {
        if (this.submitDisable) return
        this.setParams()
        this.submitDisable = true
        createOrder(this.params).then(res => {
          this.$log.warn(this.pageName + '下单成功')
          this.createOrderStatus = 1
          this.orderTempInfo = res.data.order || {}
          this.payCodeDialogVisible = true
          // this.$refs.XSCQrCodeReader.show(this.tickets, this.currentPayChannel)
          this.submitDisable = false
        })
          .catch(e => {
            this.submitDisable = false
          })

        return
      }

      // 储值卡支付
      if (this.currentPayChannel === '储值卡支付' && !cardInfo) {
        this.$refs.ValueCardInput.show(this.tickets, this.currentPayChannel)
        return
      }

      // 防止重复提交
      if (this.submitDisable) return
      this.submitDisable = true

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

      // 设置参数
      this.setParams()
      if (typeof this.params.guestId === 'string') {
        this.params.guideName = this.params.guestId
        this.params.guestId = null
      }
      this.params.qrCode = qrcode
      this.params.discount = cardInfo ? cardInfo.discount : ''
      this.params.password = cardInfo ? cardInfo.password : ''
      this.params.memberSystemId = cardInfo ? cardInfo.memberSystemId : ''

      this.$log.warn(this.pageName + '支付下单')
      this.createOrder(this.params)
    }),
    handleValueCardPay (cardInfo) {
      console.log('储值卡信息', cardInfo)
      this.$log.info('储值卡信息', JSON.stringify(cardInfo))
      createValueCardOrder({
        cardNo: cardInfo.cardCode,
        cardVendor: 'CHANGYI',
        order: this.params
      }).then(res => {
        this.handleCreateSuccess(this.params, res)
      })
    },
    submitOnlinePay () {
      if (!this.payCode) {
        this.$message.error('请输入支付码')
        return
      }
      this.payCodeDialogVisible = false
      this.submit(this.payCode)
      // this.createOrder(this.params, true)
    },
    cancelOnlinePay () {
      this.payCodeDialogVisible = false
      this.payCode = ''
    },
    createOrder (params, isOnlinePay = false) {
      // if (this.payType === 'B_SCAN_C_PAY' && !isOnlinePay) {
      //   this.payCodeDialogVisible = true
      //   return
      // }

      this.submitDisable = true
      params.tickets.forEach(ticket => {
        if (params.checkWay !== 5) {
          ticket.ticketNo = ''
          ticket.isStorage = 0
        } else {
          ticket.isStorage = 1 // 预印票
        }

        ticket.face = {
          faceImg: ticket.face
        }

        ticket.batchConfigId = params.batchConfigId || ticket.batchConfigId || ''
      })

      params.discountDescription = params.tickets.map((item) => item.discountDescription).filter(i => i).join('，')
      params.createOrderRemark = this.createOrderRemark
      this.tickets = params.tickets
      // debugger;

      if (this.createOrderStatus === 1) {
        handlePay(this.params, this.orderTempInfo, this, () => { })
        if (this.payStatus !== 1) {
          this.getSingleOrder(this.orderTempInfo, params)
        }
      } else {
        createOrder(params).then(res => {
          const order = res.data.order
          this.$log.warn(`下单成功,订单号ID：${order.id}`)
          this.createOrderStatus = 1
          this.orderTempInfo = order
          handlePay(this.params, order, this, () => { })
          if (this.payStatus !== 1) {
            this.getSingleOrder(order, params)
          }
          EventBus.$emit('orderCreated', order)
        }).catch(e => {
          this.submitDisable = false
          EventBus.$emit('orderCreated')
        })
      }
    },
    getSingleOrder (order, params) {
      const orderId = order?.id
      if (!orderId) return
      this.timer && clearTimeout(this.timer)
      getSingleOrder(orderId).then(res => {
        if (res.data?.payStatus === 'PAYED') {
          this.$log.warn(`支付成功,订单号：${res.data.orderNo}`)
          this.submitDisable = false
          this.handleCreateSuccess(params, res.data)
        } else if (res.data?.payStatus === 'CLOSED') {
          this.$message.error('交易失败，订单关闭，请重新创建订单')
          this.submitDisable = false
          this.visible = false
        } else {
          this.timer = setTimeout(() => {
            this.getSingleOrder(order, params)
          }, 2000)
        }
      })
    },
    handleCreateSuccess (params, order) {
      this.$message.success('出票成功')
      this.submitDisable = false
      this.payCode = ''
      // 获取订单详情
      // 自动打印
      getSingleOrder(order?.id).then(async res => {
        this.isPrintSmallTicket && this.$printSmallTicket(order)

        const order2 = JSON.parse(JSON.stringify(res.data))
        this.isPrint && this.$print(order2)
      })

      // 关闭弹窗
      this.handleClose()

      this.$emit('complete')
      this.createSuccessCallback && this.createSuccessCallback()
    },
    beforeDestroy () {
      this.killAllPosProcess()
      this.payCode = ''
    },
    handlePayCodeInput (e) {
      this.timer && clearTimeout(this.timer)
      this.timer = setTimeout(() => {
        if (this.payCode.length > 10) {
          this.submitOnlinePay()
        }
      }, 200)
    }
  },
  watch: {
    payCode (val) {
      if (val) {
        this.handlePayCodeInput()
      }
    },
    payCodeDialogVisible (val) {
      if (val) {
        this.$nextTick(() => {
          if (this.$refs.payCodeInputRef) {
            this.payCode = ''
            this.$refs.payCodeInputRef.focus()
          }
        })
      }
    }
  }
}
