<template>
  <div class="h5pay">
    <el-button type="primary" @click="handlePay">去支付</el-button>
  </div>
</template>

<script>
import * as api from '@/api/my'
export default {
  data() {
    return {
      openId: window.localStorage.getItem('open_id')
    }
  },
  computed: {
    pageUrl() {
      return window.location.origin + this.$route.path
    }
  },
  methods: {
    // 获取订单
    getOrder(callback) {
      api.getOrder({ wx_open_id: this.openId, payment_method: 'WX_PAY' }).then(response => {
        const { data, error, message } = response
        if (error.toString() === '0') {
          this.order = data
          this.$emit('update', this.order)
          callback && callback(this.order)
        } else {
          this.$message.error(message)
        }
      })
    },
    // 获取微信code
    getCode() {
      const redirectURI = `https://pages.ezijing.com/given/auth.html?redirect_uri=${encodeURIComponent(this.pageUrl)}`
      window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx451c01d40d090d7a&redirect_uri=${redirectURI}&response_type=code&scope=snsapi_base#wechat_redirect`
    },
    // 获取微信openid
    getOpenId(code) {
      api.getOpenId({ code, identity: 'ezijing' }).then(response => {
        if (response.code === 0) {
          this.openId = response.openid
          window.localStorage.setItem('open_id', this.openId)
          this.getOrder()
        } else {
          this.getCode()
        }
      })
    },
    // 去支付
    handlePay() {
      this.getOrder(() => {
        window.location.href = `https://web-pay.ezijing.com/wxpay/h5?prepay_id=${this.order.wx_prepay_id}&open_id=${
          this.openId
        }&redirect_uri=${encodeURIComponent(this.pageUrl)}`
      })
    }
  },
  beforeMount() {
    if (!this.openId) {
      const { code } = this.$route.query
      code ? this.getOpenId(code) : this.getCode()
    }
  }
}
</script>

<style scoped>
.h5pay {
  padding: 40px;
  text-align: center;
}
</style>
