<template>
  <!-- 暂时无用 -->
  <div class="pay-box"></div>
</template>
<script>
import Pay from '../action'
export default {
  name: 'PayWeChart',
  props: {
    requestParam: {
      type: Object,
      required: false,
      default () {
        return {
          product_id: '', // 提前设定
          open_id: '', // 通过微信授权获取
          prepay_id: '', // 通过调用接口获取
          app_id: '', // 提前设定
          app_secret: '', // 提前设定
          // 新增字段 接口返回
          timeStamp: '',
          nonceStr: '',
          signType: '',
          paySign: ''
        }
      }
    }
  },
  beforeDestroy() {
  },
  mounted () {
    this.onReady()
  },
  methods: {
    onReady () {
      this.VueEvent.$off('pay-wx-chart').$on('pay-wx-chart', (obj) => {
        this.goToPay()
      })
    },
    goToPay () {
      const obj = { code: 0, msg: '', data: {} }
      if (!this.requestParam.product_id) {
        obj.code = 3001
        obj.msg = '没有商品ID'
        this.VueEvent.$emit('pay-wx-chart-callback', obj)
        return false
      }
      if (!this.requestParam.open_id) {
        obj.code = 3002
        obj.msg = '没有小程序用户openid'
        this.VueEvent.$emit('pay-wx-chart-callback', obj)
        return false
      }
      Pay.getOrderId(this.requestParam).then(res => {
        if (res.code) {
          // this.requestParam.product_id
          // this.requestParam.open_id
          this.requestParam.prepay_id = res.data.prepay_id
          this.requestParam.app_id = res.data.options.appId
          // this.requestParam.app_secret

          this.requestParam.timeStamp = res.data.options.timeStamp
          this.requestParam.nonceStr = res.data.options.nonceStr
          this.requestParam.signType = res.data.options.signType
          this.requestParam.paySign = res.data.options.paySign
          this.wxWakeUpToPay(obj)
        } else {
          obj.code = 3003
          obj.msg = '获取订单ID失败'
          this.VueEvent.$emit('pay-wx-chart-callback', obj)
        }
      }).catch(e => {
        obj.code = 5001
        obj.msg = e.message
        this.VueEvent.$emit('pay-wx-chart-callback', obj)
        return obj
      })
    },
    wxWakeUpToPay (obj) {
      obj.code = 200
      obj.data = this.requestParam
      this.VueEvent.$emit('pay-wx-chart-callback', obj)
    }
  }
}
</script>

<style lang="scss">

</style>
