<template>
  <div class="login-container">
    <div class="qrcode-login">
      <div class="qrcode-image">
        <el-image
          :src="qrCodeImg"
          fit="cover"
        />
      </div>
      <div class="qrcode-desc">
        打开 华新驾驶舱 扫一扫登录
      </div>

      <div v-show="isOvertime" class="qrcode-overtime">
        <div class="qrcode-overtime-desc">该二维码已失效</div>
        <el-button type="primary" size="small" @click="initQrCode">请点击刷新</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import { getQrCode, checkIsLogined } from '@/api/login'
export default {
  name: 'QrCodeLogin',
  data() {
    return {
      qrCodeImg: '',
      qrcodeId: '',
      qrcodeLoginCheck: null, // 定时器
      tryLoginCount: -1, // 尝试次数，=-1时未初始化二维码，不做任何动作
      isOvertime: false // 是否超时
    }
  },
  mounted() {
    // 开始计时器进行轮询是否已经扫码登录，2秒钟查询一次
    this.qrcodeLoginCheck = setInterval(this.checkIsLogined, 2 * 1000)
  },
  methods: {
    initQrCode() {
      this.isOvertime = false

      getQrCode().then(response => {
        console.log(response)
        if (response.code === 200) {
          this.qrCodeImg = this.baseConfig.baseUrl + '/static/' + response.data.qrcodeImgUrl
          this.qrcodeId = response.data.qrcodeId

          this.tryLoginCount = 0
        } else {
          // 获取二维码失败，返回用户名密码登录
          this.tryLoginCount = -1
          this.$emit('qrcodeError')
        }
      })
    },
    checkIsLogined() {
      if (this.tryLoginCount >= 90) {
        this.isOvertime = true
      } else if (this.tryLoginCount >= 0) {
        // 尝试次数不为负数时表示已经初始化过，已经获取了二维码和id
        checkIsLogined(this.qrcodeId).then(response => {
          console.log(response)
          if (response.code === 200) {
            // 登录成功
            this.tryLoginCount = -1
            this.$emit('qrcodeLogin', response.data.token)
          } else if (response.code === 501) {
            // 未登录，继续执行
            this.tryLoginCount++
          }
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
  .login-container {
    width: 400px;
    height:300px !important;

    .qrcode-login {
      padding-top: 50px;

      .qrcode-image {
        text-align: center;
      }

      .qrcode-desc {
        margin-top: 20px;
        text-align: center;
        font-size: 14px;
        color: #9c9c9c;
      }

      .qrcode-overtime {
        position: absolute;
        top: 50px;
        left: 130px;
        width: 140px;
        text-align: center;
        background-color: rgba(232, 232, 232, 0.75);
        height: 140px;

        .qrcode-overtime-desc {
          margin-top: 30px;
          margin-bottom: 15px;
          font-size: 14px;
          font-weight: bold;
          color: #000000;
        }
      }
    }
  }
</style>
