<template>
  <div class="h5pay">
    <el-button type="primary" @click="dialogFormVisible = true">去支付</el-button>
    <el-dialog title="输入邀请码" :visible.sync="dialogFormVisible">
        <el-input v-model="discountCode" autocomplete="off" placeholder="请输入邀请码"></el-input>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handlePay('code')">立即支付</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as api from '@/api/my'
export default {
  data() {
    return {
      openId: window.localStorage.getItem('open_id'),
      dialogFormVisible: false,
      discountCode: ''
    }
  },
  computed: {
    pageUrl() {
      return window.location.origin + this.$route.path
    }
  },
  methods: {
    // 获取订单
    getOrder(callback, type) {
      const params = { wx_open_id: this.openId, payment_method: 'WX_PAY' }
      type === 'code' && (params.discount_code = this.discountCode)
      api.getPayment(params).then(response => {
        const { data, error, message } = response
        if (error.toString() === '0') {
          this.order = data
          this.$emit('update', this.order)
          callback && callback(this.order)
          // 邀请码
          this.discountCode = ''
          this.dialogFormVisible = false
        } 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(type) {
      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)}`
      }, type)
    }
  },
  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>
