<template>
  <el-dialog
    :close-on-click-modal="false"
    :visible.sync="visible"
    :before-close="handleClose"
    title="余额充值"
    width="80%">
    <div>
      <el-form
        v-loading="submitDisable"
        :model="form"
        ref="form"
        class="dialog-info"
        inline
        label-width="120px">
        <el-form-item
          verify
          prop="recharge_money"
          label="充值金额"
          class="is-required">
          <el-input-number
            :min="0"
            :precision="2"
            controls-position="right"
            v-model="form.recharge_money">
            {{ form.recharge_money }}
          </el-input-number>
        </el-form-item>
        <el-form-item
          verify
          prop="payChannel"
          label="付款方式"
          class="is-required">
          <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>
      <div class="dialog-btn-wrap">
        <el-button
          :disabled="submitDisable"
          @click="submit()"
          type="primary">
          {{ submitDisable?'正在处理':'确认充值' }}
        </el-button>
      </div>
      <QueryPos
        ref="queryPos"
        @confirm="handleQueryPos"></QueryPos>

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

<script>
import { apiMember, getMemberTradeById } from '@/api/member'
import { debounce } from 'throttle-debounce'
import handlePay, { getPayType } from '../../sellManage/common/handlePay'
import QueryPos from '../../sellManage/common/QueryPos'
import posMixin from '@/pages/common/posMixin'

export default {
  mixins: [ posMixin ],
  components: {
    QueryPos
  },
  props: {
    currentItem: {
      type: Object,
      default: () => {}
    }
  },
  computed: {
    payChannelOptions () {
      return this.$store.state.app.payChannelList.filter(i => i.name.indexOf('旅行社') < 0 && i.name.indexOf('储值卡支付') < 0).map(i => i.name)
    },
    scenicName () {
      return this.$localStore.get('scenicName') || this.$store.state.user.scenicName
    },
    showPosQrcode () {
      // 需要手动扫码的景区
      const list = ['东方绿舟', '天津之眼', '绿博园']
      if (this.scenicName === '绿博园' && (!this.$localStore.get('posName') || this.$localStore.get('posName') === 'jianhang')) {
        return false
      }
      return list.indexOf(this.scenicName) > -1
    },
    payType () {
      return getPayType(this.form.payChannel)
    }
  },
  data () {
    return {
      visible: false,
      extra_balance: 0, // 赠送金额
      timer: null, // 检查订单是否支付成功计时器
      form: {
        member_id: '',
        total_money: 0,
        payChannel: '现金',
        recharge_money: 0 // 充值金额
      },
      orderTempInfo: {}, // 临时订单信息，防止重复创建订单
      createOrderStatus: 0, // 创建订单状态
      payStatus: 0, // 支付状态
      submitDisable: false
    }
  },

  methods: {
    show (data) {
      this.visible = true
      this.$nextTick(() => {
        this.reset()
        this.submitDisable = false
        this.extra_balance = data.extra_balance
        this.form.member_id = data.id
        this.payStatus = 0
        this.createOrderStatus = 0
      })
    },
    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.form.price = this.form.recharge_money
      this.form.bocTradeNo = JSON.stringify(posInfo)

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

    submit: debounce(1000, true, function (qrcode, cardInfo) {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.form.total_money = this.extra_balance + this.form.recharge_money

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

          const scanArr = ['瑞通储值卡']
          // 是否使用外部扫码
          if ((scanArr.indexOf(this.form.payChannel) > -1 || this.payType === 'B_SCAN_C_PAY') && !qrcode) {
            apiMember('rechargeMemberMoney', this.form).then(res => {
              this.$log.warn(this.pageName + '下单成功')
              this.createOrderStatus = 1
              this.orderTempInfo = res
              this.$refs.XSCQrCodeReader.show(null, this.form.payChannel, this.form.recharge_money)
            })
            return
          }

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

          // 支付已成功只提交订单
          if (this.payStatus === 1) {
            this.createOrder(this.form)
            return
          }
          this.form.price = this.form.recharge_money
          this.form.qrCode = qrcode
          this.form.discount = cardInfo ? cardInfo.discount : ''
          this.form.password = cardInfo ? cardInfo.password : ''
          this.form.memberSystemId = cardInfo ? cardInfo.memberSystemId : ''
          this.form.memberTrade = true
          this.form.member = true
          this.createOrder(this.form)
        } else {
          return false
        }
      })
    }),
    createOrder (params) {
      this.submitDisable = true
      if (this.createOrderStatus === 1) {
        handlePay(this.form, this.orderTempInfo, this, () => {})
        if (this.payStatus !== 1) {
          this.getSingleOrder(this.orderTempInfo, params)
        }
      } else {
        apiMember('rechargeMemberMoney', params).then(res => {
          this.$log.warn(`下单成功,订单号ID：${res?.data}`)
          this.createOrderStatus = 1
          this.orderTempInfo = res
          handlePay(this.form, res, this, () => {})
          if (this.payStatus !== 1) {
            this.getSingleOrder(res)
          }
        }).catch(e => {
          this.submitDisable = false
        })
      }
    },
    getSingleOrder (res) {
      this.timer && clearTimeout(this.timer)
      getMemberTradeById(res?.data).then(order => {
        if (order.extraInfo.pay_status === 'PAYED') {
          this.$log.warn(`支付成功,订单号：${order.extraInfo.orderNo}`)
          this.handleCreateSuccess()
        } else if (order.extraInfo.pay_status === 'CLOSED') {
          this.$message.error('交易失败，订单关闭，请重新发起充值')
          this.submitDisable = false
          this.handleClose()
        } else {
          this.timer = setTimeout(() => {
            this.getSingleOrder(res)
          }, 2000)
        }
      })
    },
    handleCreateSuccess () {
      this.submitDisable = false
      this.$emit('updateList')
      this.$message.success('充值成功')

      // 关闭弹窗
      this.handleClose()

      this.createSuccessCallback && this.createSuccessCallback()
    },
    reset () {
      this.$refs.form.resetFields()
    }
  }
}
</script>
