<template>
  <div class="pay">
    <h5-pay @update="handleUpdateOrder" v-if="isWechat"></h5-pay>
    <qrcode-pay @update="handleUpdateOrder" v-else></qrcode-pay>
    <div class="pay-ft">
      <p class="t2">注释：缴费成功后，即可进入首页中的课程学习开始私人财富风险管理顾问证书项目的相关学习。</p>
    </div>
    <el-dialog
      title="报名成功"
      :visible.sync="dialogVisible"
      :center="true"
      :close-on-click-modal="false"
      @close="$router.replace('/')"
      width="348px"
    >
      <div class="dialog-pay">
        <p>请点击课程学习进入到学习系统，或者点击右上角的x，返回首页。</p>
        <div class="icon"><img src="../../../assets/images/icon_success.png" /></div>
      </div>
      <template #footer>
        <a href="https://prp-learning.ezijing.com/" target="_blank">
        <el-button type="primary">课程学习</el-button>
        </a>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import * as api from '@/api/my'
import qrcodePay from './components/qrcodePay'
import h5Pay from './components/h5Pay'
export default {
  name: 'AppPay',
  components: { qrcodePay, h5Pay },
  data() {
    const UA = window.navigator.userAgent
    const isMobile = /android|iphone|ipad|ipod/i.test(UA)
    return {
      isWechat: isMobile && /micromessenger/i.test(UA),
      dialogVisible: false,
      timer: null,
      paymentRecords: [] // 所有订单
    }
  },
  computed: {
    // 支付成功
    paySuccess() {
      return !!this.paymentRecords.find(item => {
        return item.bill_type === 'TUITION' && item.payment_status === 'SUCCESS'
      })
    }
  },
  methods: {
    // 检查支付状态
    checkPay(order) {
      api.getPaymentList().then(response => {
        if (parseInt(response.error) === 0) {
          this.paymentRecords = response.data
        }
        if (this.paySuccess) {
          this.dialogVisible = true
        }
      })
    },
    // 检测支付状态定时器
    setCheckPayTimer() {
      this.checkPay()
      this.timer && clearInterval(this.timer)
      this.timer = setInterval(() => {
        if (this.paySuccess) {
          this.timer && clearInterval(this.timer)
        } else {
          this.checkPay()
        }
      }, 3000)
    },
    // 填写个人资料
    toApplication() {
      this.$router.push('/my/account')
    },
    handleUpdateOrder(order) {
      this.order = order
    }
  },
  mounted() {
    this.setCheckPayTimer()
  },
  destroyed() {
    this.timer && clearInterval(this.timer)
  }
}
</script>

<style lang="scss" scoped>
.pay {
  max-width: 562px;
  margin: 0 auto;
  padding: 40px 0;
}
.t1 {
  font-size: 14px;
  color: #303030;
  line-height: 20px;
  text-align: center;
  span {
    color: #ffa448;
  }
}
.t2 {
  font-size: 12px;
  color: #999;
  line-height: 20px;
}
.dialog-pay {
  text-align: center;
  p {
    color: #262626;
    line-height: 20px;
  }
  .icon {
    margin-top: 20px;
    text-align: center;
  }
}
</style>
