<template>
  <div class="pay">
    <!-- 微信 -->
    <div class="qr-pay" v-if="payment === '2'">
      <qrcode-vue :value="qrcodeValue" size="200"></qrcode-vue>
      <p class="tips">微信扫一扫支付</p>
    </div>
    <!-- 支付宝 -->
    <div class="qr-pay" v-else-if="payment === '1'">
      <qrcode-vue :value="qrcodeValue" size="200"></qrcode-vue>
      <p class="tips">支付宝扫一扫支付</p>
    </div>
    <!-- 银行转账 -->
    <div class="bank-pay" v-else>
      <p>银行账户名称：清控紫荆（北京）教育科技股份有限公司</p>
      <p>银行帐号：694485289</p>
      <p>开户行：中国民生银行股份有限公司北京魏公村支行</p>
      <div class="is-center">
        <el-button type="primary" @click="$emit('success')">我已支付成功，已告知教务老师</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import * as api from '../api'
import QrcodeVue from 'qrcode.vue'

export default {
  props: {
    payment: { type: String }, // 支付方式
    productId: { type: String, required: true }, // 商品ID
    num: { type: [Number, String], default: 1 } // 购买数量
  },
  components: { QrcodeVue },
  data() {
    return {
      order: {}, // 创建订单返回的数据
      rawOrder: {}, // 获取订单返回的数据
      timer: null
    }
  },
  computed: {
    qrcodeValue() {
      return this.order.url
    }
  },
  methods: {
    // 创建微信订单
    createWxPayOrder(productId, num = 1) {
      return api.createWxpayOrder('ezijing', productId, { num }).then(response => {
        this.order = response
        return response
      })
    },
    // 创建支付宝订单
    createAliPayOrder(productId, num = 1) {
      return api.createAlipayOrder(productId, { type: 2, num }).then(response => {
        this.order = response
        return response
      })
    },
    getOrder() {
      return api.getOrder(this.order.order_no).then(response => {
        const { order } = response
        this.rawOrder = order
        return order
      })
    },
    setTimer() {
      this.timer = setInterval(() => {
        this.getOrder().then(response => {
          // 支付成功
          if (response.status === 1) {
            this.$emit('success')
            this.clearTimer()
          }
        })
      }, 5000)
    },
    clearTimer() {
      this.timer && clearInterval(this.timer)
    }
  },
  mounted() {
    if (this.payment === '2') {
      // 微信支付
      this.createWxPayOrder(this.productId, this.num).then(this.setTimer)
    } else if (this.payment === '1') {
      // 支付宝支付
      this.createAliPayOrder(this.productId, this.num).then(this.setTimer)
    }
  },
  destroyed() {
    this.clearTimer()
  }
}
</script>

<style lang="scss" scoped>
.qr-pay {
  text-align: center;
}
.tips {
  color: #999;
}
.bank-pay {
  line-height: 30px;
  p {
    margin: 0;
  }
  .el-button {
    margin-top: 20px;
  }
}
.is-center {
  text-align: center;
}
</style>
