<template>
  <div class="cert-container">
    <h5>证书查询</h5>
    <el-form :model="form" :rules="rules" ref="ruleForm" label-width="80px" class="rule-form">
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="form.phone" size="small" placeholder="请输入手机号"></el-input>
      </el-form-item>
      <el-form-item label="验证码" required>
        <el-col :span="16">
          <el-form-item prop="code">
            <el-input v-model="form.code" size="small" placeholder="请输入手机验证码"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="7" style="float:right">
          <el-button type="primary" @click="sendCode" size="small" style="width:100%;" id="checkedCode" :disabled="isBtnDisabled">
            获取验证码
          </el-button>
        </el-col>
      </el-form-item>
      <el-form-item label="">
        <el-button type="primary" @click="handleSubmit" size="mini">查询证书</el-button>
        <el-button v-if="certUrl" type="primary" @click="handleDownload" size="mini" plain style="margin-left:50px;">下载证书</el-button>
      </el-form-item>
    </el-form>
    <div class="cert" v-if="certUrl">
      <img :src="certUrl">
    </div>
  </div>
</template>
<script>
import { certSendCode, certSearch } from '@/api/my'
const MOBILE_REG = /^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/
const checkMobile = (rule, value, callback) => {
  if (value) {
    if (!MOBILE_REG.test(value)) {
      callback(new Error('手机号格式错误'));
    } else {
      callback()
    }
  }
}
export default {
  data() {
    return {
      form: {
        phone: '',
        code: ''
      },
      rules: {
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ],
        code: { required: true, message: '请输入验证码', trigger: 'blur' }
      },
      isBtnDisabled: false,
      certUrl: '' // https://webapp-pub.oss-cn-beijing.aliyuncs.com/certificate/13034769668.jpg
    }
  },
  methods: {
    handleSubmit() {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          this.fetchCertSearch()
        } else {
          return false
        }
      })
    },
    handleDownload() {
      this.fileDownload(this.certUrl, this.certUrl)
    },
    async fileDownload(fileUrl, fileName) {
      fileUrl = await this.getBase64(fileUrl) // 将图片转成base64，以防下载直接打开图片
      const elink = document.createElement('a')// 创建一个a标签
      elink.download = fileName;// 设置a标签的下载属性
      elink.style.display = 'none';// 将a标签设置为隐藏
      elink.href = fileUrl;// 把之前处理好的地址赋给a标签的href
      document.body.appendChild(elink);// 将a标签添加到body中
      elink.click();// 执行a标签的点击方法
      // URL.revokeObjectURL(elink.href) // 下载完成释放URL 对象
      document.body.removeChild(elink)// 移除a标签
    },
    getBase64(url) {
      return new Promise((resolve, reject) => {
        var Img = new window.Image()
        var dataURL = ''
        Img.setAttribute('crossOrigin', 'Anonymous')
        Img.src = url + '?v=' + Math.random()
        Img.onload = function() {
          // 要先确保图片完整获取到，这是个异步事件
          var canvas = document.createElement('canvas') // 创建canvas元素
          var width = Img.width // 确保canvas的尺寸和图片一样
          var height = Img.height
          canvas.width = width
          canvas.height = height
          canvas.getContext('2d').drawImage(Img, 0, 0, width, height) // 将图片绘制到canvas中
          dataURL = canvas.toDataURL('image/jpeg', 1) // 转换图片为dataURL
          resolve(dataURL)
        }
      })
    },
    sendCode() {
      if (!this.form.phone) {
        this.$message('请填写手机号')
      } else if (!MOBILE_REG.test(this.form.phone)) {
        this.$message('手机号格式错误')
      } else {
        this.fetchSendCode()
        this.isBtnDisabled = true
        this.btnDisabledTimer()
      }
    },
    // 发送验证码按钮计时器
    btnDisabledTimer() {
      let count = 60
      const btnEl = document.querySelector('#checkedCode')
      btnEl.innerHTML = count + '秒后重发'
      const timer = setInterval(() => {
        count--
        if (count < 1) {
          clearInterval(timer)
          this.isBtnDisabled = false
          btnEl.innerHTML = '获取验证码'
        } else {
          btnEl.innerHTML = count + '秒后重发'
        }
      }, 1000)
    },
    fetchSendCode() {
      const params = {
        phone: this.form.phone
      }
      certSendCode(params).then(res => {
        if (res.code === 0) {
          this.$message.success('验证码发送成功')
        } else {
          this.$message.error(res.msg || '发送验证码失败')
        }
      })
    },
    fetchCertSearch() {
      certSearch(this.form).then(res => {
        if (res.code === 0 && res.name === 'Bad Request') {
          this.$message.error(res.message || '获取证书失败')
        } else {
          this.certUrl = res.url
        }
      }).catch(err => {
        console.log(err)
      })
    }
  }
}
</script>
<style scoped>
.cert-container{
}
h5{
  font-size:20px;
  line-height:80px;
  text-align:center;
}
.rule-form{
  width: 400px;
  margin:0 auto;
}
.cert{
  width:1200px;
  margin:0 auto;
  padding: 10px 0 30px;
}
.cert img{
  width:100%;
}
</style>