<template>
  <el-dialog
    title="会员升级"
    :visible.sync="visible"
    width="840px"
    :before-close="handleClose">
    <el-form
      inline
      :model="form"
      v-loading="loading"
      ref="form"
      class="form-wrap"
      label-width="160px">
      <div
        class="dialog-info"
      >
        <el-form-item
          label="当前会员类型"
        >
          {{ currentMemberOrder.tickets && currentMemberOrder.tickets[0].tname }}
        </el-form-item>
        <el-form-item
          class="is-required"
          verify
          label="可升级会员类型"
          prop="upgrade_id">
          <el-select
            v-model="form.upgrade_id"
            filterable
            @change="changeMemberType"
            placeholder="请选择">
            <el-option
              v-for="item in upgradeList"
              :key="item.upgrade_id"
              :label="item.upgradeName + '【'+item.upgrade_price+'元】'"
              :value="item.upgrade_id">
            </el-option>
          </el-select>
        </el-form-item>
      </div>
      <div class="footer block-wrap">
        <el-form-item
          label="应付金额"
          prop="memberTrade.total_money">
          <div class="input-space warning">
            <b class="strong">
              {{ form.memberTrade.total_money }}
            </b> 元
          </div>
        </el-form-item>
        <el-form-item
          verify
          label="付款方式"
          prop="memberTrade.payChannel">
          <el-select
            v-model="form.memberTrade.payChannel"
            class="warning">
            <el-option
              v-for="item in payChannelOptions"
              :key="item"
              :value="item"
              :label="item"
            ></el-option>
          </el-select>
        </el-form-item>
        <div
          class="btn-wrap">
          <el-button
            size="medium"
            @click="reset">
            重置
          </el-button>
          <el-button
            type="primary"
            size="medium"
            class="warn-btn"
            :disabled="submitDisable"
            @click="submit()">
            {{ 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-form>
  </el-dialog>
</template>

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

export default {
  mixins: [ posMixin ],
  components: {
    QueryPos
  },
  props: {

  },

  data () {
    return {
      title: '',
      visible: false,
      loading: false,
      currentMemberOrder: {},
      upgradeList: [],
      form: {
        order_id: '', // 订单ID
        payChannel: '现金',
        old_memberTypeId: '', // 旧会员类型的ID
        upgrade_id: '', // 升级的会员类型的ID
        memberTrade: {
          payChannel: '现金',
          total_money: 0,
          pay_money: 0,
          trade_type: 9
        }
      },
      orderTempInfo: {}, // 临时订单信息，防止重复创建订单
      createOrderStatus: 0, // 创建订单状态
      payStatus: 0, // 支付状态
      submitDisable: false,
      ticketId: null
    }
  },
  watch: {

  },
  computed: {
    payBack () {
      return (this.form.memberTrade.pay_money * 1000 - this.form.memberTrade.total_money * 1000) / 1000
    },
    payChannelOptions () {
      return this.$store.state.app.payChannelOptions.filter(i => i.indexOf('旅行社') < 0)
    },
    payType () {
      return getPayType(this.form.memberTrade.payChannel)
    }
  },
  methods: {
    show (data) {
      this.visible = true
      this.$nextTick(() => {
        this.reset()
        this.form = Object.assign({}, this.form)
        this.form.order_id = data.id
        this.form.old_memberTypeId = data.tickets[0].memberTypeId
        this.currentMemberOrder = data
        this.getMemberUpgradeList(data)
        console.log('data', data)
        this.submitDisable = false
        this.payStatus = 0
        this.createOrderStatus = 0
        this.ticketId = data.ticketId
        if (this.payChannelOptions[0]) {
          this.form.memberTrade.payChannel = this.payChannelOptions[0]
        }
      })
    },
    changeMemberType (val) {
      this.form.memberTrade.total_money = this.upgradeList.find(i => i.upgrade_id === val).upgrade_price
      this.form.memberTrade.pay_money = this.form.memberTrade.total_money
    },
    reset () {
      this.$refs.form.resetFields()
    },
    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()
    },

    // 获取升级会员类型列表
    getMemberUpgradeList (data) {
      this.loading = true
      apiMember('getMemberUpgradeList', { keyWords1: data.tickets[0].memberTypeId }).then(res => {
        console.log('res', res)
        this.upgradeList = res
        this.loading = false
      }).finally(() => {
        this.loading = false
      })
    },
    submit: debounce(1000, true, function (qrcode, cardInfo) {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.form.payChannel = this.form.memberTrade.payChannel
          this.form.total_money = this.form.memberTrade.total_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('memberUpgrade', 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.memberTrade.total_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.member = true
          this.form.ticket_id = this.ticketId
          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('memberUpgrade', 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('getUpgrade', this.form.upgrade_id, this.currentMemberOrder)
      this.$message.success('支付成功')
      // 关闭弹窗
      this.handleClose()
      this.createSuccessCallback && this.createSuccessCallback()
    },
    // 使用现有pos消费信息进行出票
    handleQueryPos (posInfo) {
      this.form.price = this.form.memberTrade.total_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)
    }

  }
}
</script>

<style lang="scss" scoped>

</style>
