<template>
  <div style="width: 70%;margin:0 auto">
    <div class="fx-row jc-between ai-center pd10 pt10 mb20">
      <el-image class="pointer" @click="$router.push('/login')" :src="`${$imgBase}index/login/mxjc_img_logo.png`"
                fit="contain"
                style="width: 152px;"></el-image>
      <div>
        <img class="icon16" src="../../assets/images/icon_tel2.png"/>
        <span class="pl8">服务热线：400-0313-985</span>
      </div>
    </div>
    <el-form ref="form" class="border pd20" :model="form" :rules="rules" label-width="100px" label-position="right">
      <p class="f24 pb20 f-primary bold text-left">铭学锦程学生卡</p>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-image :src="require('../../assets/images/pay_banner.png')"/>
        </el-col>
        <el-col :span="12">
          <el-form-item label="价格:"><span v-if="cardActive.price" class="bold f-red f18">
            ￥{{ cardActive.price / 100 }}</span>
          </el-form-item>
          <el-form-item label="有效期:">{{ cardActive.outTime }}</el-form-item>
          <el-form-item label="入学年份:">
            <el-button @click="cardActive = card" :type="card == cardActive ? 'primary' : ''" v-for="card in cardList">
              {{ card.year }}
            </el-button>
          </el-form-item>
          <template v-if="!renew">
            <el-form-item label="手机号:" prop="phoneNumber">
              <el-input v-model="form.phoneNumber"></el-input>
            </el-form-item>
            <el-form-item label="验证码:" prop="captcha">
              <div class="fx-row">
                <el-input class="mr30" v-model="form.captcha"></el-input>
                <el-button type="plain" @click="getCode" :disabled="disabled">{{ captchaBtnText }}</el-button>
              </div>
            </el-form-item>
          </template>
          <template v-else>
            <el-form-item label="原卡号:" required>
              {{ renew.cardNo }}
            </el-form-item>
            <el-form-item label="绑定手机:" required>
              {{ renew.mobile }}
            </el-form-item>
          </template>
          <el-form-item>
            <el-button type="primary" @click="validate">{{ announcement.button }}</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="tips ">
      <p class="f20  bold f-red">{{announcement.title}}</p>
      <p v-for="(r,idx) in announcement.rules" :key="idx">{{idx+1}}、{{r}}</p>
    </div>
    <el-dialog :visible.sync="dialogVisible" :close-on-click-modal="false" custom-class="rd8" width="340px">
      <template #title>
        <div class="fx-column fx-cen-cen">
          <div class="f16">使用微信扫码支付</div>
          <div class="f-red f18">￥{{ cardActive.price / 100 }}</div>
        </div>
      </template>
      <el-image :src="payQR" style="width: 300px; height: 300px">
        <template v-if="isPaySuccess" #error>
          <div class="fx-column fx-cen-cen" style="padding-top: 50px">
            <el-icon class="f-success" name="success" style="font-size: 96px"/>
            <div class="mt20 f-red">{{ announcement.paySucceed }}</div>
            <div class="mt8">
              <el-link href="/login">点击此处，去登陆</el-link>
            </div>
          </div>
        </template>
        <template v-else-if="isPayFailed" #error>
          <div class="fx-column fx-cen-cen" style="padding-top: 50px">
            <el-icon class="f-danger" name="error" style="font-size: 96px"/>
            <div class="mt20 f-red">{{ announcement.payFailed }}</div>
            <el-button type="text" class="mt8 f-666" @click="form.captcha='',dialogVisible=false">关闭</el-button>
          </div>
        </template>
      </el-image>
      <template #footer>
        <div class="fx-column fx-cen-cen">
          <div>铭学锦程学习平台（{{ cardActive.year }}学年）</div>
          <div>有效期至 <span class="bold">{{ cardActive.outTime }}</span></div>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { getEcardPrices, getOrderPayStatus, prepayCard, sendSmsNoValidation } from '@/api/webApi/pay'

export default {
  name: 'PayIndex',
  data() {
    let checkPhone = (rule, value, callback) => {
      let reg = /^1[345789]\d{9}$/
      if (!reg.test(value)) {
        callback(new Error('手机号格式不正确！'))
      } else {
        callback()
      }
    }
    return {
      rules: {
        //  required: true   是否必填，如不设置，则会根据校验规则自动生成
        phoneNumber: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { type: 'number', validator: checkPhone, message: '请输入11位有效手机号号码', trigger: ['blur', 'change'] }
        ],
        captcha: { required: true, message: '短信验证码不能为空', trigger: 'change' }
      },
      form: {
        phoneNumber: '',
        captcha: ''
      },
      captchaBtnText: '免费获取',
      disabled: false,
      spaceTime: 60,
      cardActive: {},
      cardList: [],
      countdownTimer: null,
      // qr dialog
      dialogVisible: false,
      payQR: '',
      // pay/order status
      orderTimer: null,
      orderId: '',
      isPaySuccess: false,
      isPayFailed: false,
      isUnPaid: false,
      // announcements
      announcement: {
        title: '购卡须知',
        rules: [
          '您将购买的是电子卡,不同的入学年份有效期和价格不同。',
          '购买后系统会将账号与密码通过短信发送到手机，若忘记账号请联系客服。',
          '由于产品特性，本电子卡不适用“7天无理由退换货”。'
        ],
        paySucceed: '支付成功，账号已通过短信发送，请注意查收',
        payFailed: '支付失败，您可以重新发起支付',
        button: '购买'
      },
      // renew
      renew: null
    }
  },
  mounted() {
    this.getEcardPrices()
  },
  beforeDestroy() {
    this.stopOrderStatusTimer()
    this.stopCountdownTimer()
  },
  methods: {
    getCode() {
      this.$refs.form.clearValidate([])
      this.$refs.form.validateField('phoneNumber', (res) => {
        if (res == '') {
          // 通过
          sendSmsNoValidation({
            mobile: this.form.phoneNumber,
            smsType: 1
          }).then(res => {
            if (res.code == 200) {
              this.$message.success('发送成功,请在手机上查收')
              // 成功60秒不让点击
              this.disabled = true
              this.captchaBtnText = `(${this.spaceTime}秒)免费获取`
              this.countdownTimer = window.setInterval(() => {
                this.spaceTime--
                this.captchaBtnText = `(${this.spaceTime}秒)免费获取`
                if (this.spaceTime < 0) {
                  this.stopCountdownTimer()
                  this.captchaBtnText = '免费获取'
                  this.totalTime = 60
                  this.disabled = false
                }
              }, 1000)

            }
          })
        }
      })
    },
    getEcardPrices() {
      getEcardPrices(this.renew).then(res => {
        this.cardList = res.data
        this.cardActive = res?.data[0]
      })
    },
    validate() {
      this.$refs.form.validate(valid => {
        if (!valid) return
        prepayCard({
          mobile: this.form.phoneNumber,
          code: this.form.captcha,
          ecardPayId: this.cardActive.id,
          id: this.cardActive.id,
          amount: 1,
          ...this.renew
        }).then(res => {
          this.payQR = res.data.qrCode
          this.orderId = res.data.orderId
          this.dialogVisible = true
          this.stopOrderStatusTimer()
          this.startOrderStatusTimer()
        })
      })
    },
    startOrderStatusTimer() {
      if (this.orderTimer) return
      this.orderTimer = setInterval(() => {
        getOrderPayStatus({ orderId: this.orderId }).then(res => {
          const copyStatus = ['isPaySuccess', 'isPayFailed', 'isUnPaid']
          copyStatus.forEach(key => this[key] = res.data[key])
          const terminateStatus = ['isPaySuccess', 'isPayFailed']
          const terminate = terminateStatus.some(key => this[key])
          if (terminate) {
            this.stopOrderStatusTimer()
            this.payQR = ''
          }
        })
      }, 5000)
    },
    stopOrderStatusTimer() {
      if (this.orderTimer) {
        clearInterval(this.orderTimer)
        this.orderTimer = null
      }
    },
    stopCountdownTimer() {
      if (this.countdownTimer) {
        clearInterval(this.countdownTimer)
        this.countdownTimer = null
      }
    }
  }
}
</script>

<style scoped>
.border {
  border: 1px solid #e2e2e2;
}

>>> .el-form-item {
  margin-bottom: 20px;
}

.tips {
  padding: 20px 0;
}

.tips > p {
  margin-top: 10px;
}

/deep/ .el-dialog__body {
  padding-top: 0;
  padding-bottom: 0;
}
</style>
