<template>
  <div class="scan-login">
    <el-row align="middle" justify="center">
      <el-col :span="8">
        <el-card class="scan-card" shadow="hover">
          <div class="scan-card-content">
            <h1 class="title">扫码登录</h1>
            <el-input v-model="userName" placeholder="请输入账号" style="margin-bottom: 20px;"></el-input>
            <el-button type="primary" @click="login" >登录</el-button>
            <div class="qrcode-container" v-show="showQRCode">
              <div>
                <img ref="imageElement" alt="Base64 Image" style="width:250px,height:auto ;">
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { getQrCode } from '@/api/qw/login';
import { getDeviceId} from '@/api/qw/account';

export default {
  data() {
    return {
      userName: '', // 用户输入的账号
      qrcode: null, // 二维码实例
      loading: false, // 刷新按钮加载状态
      deviceId: '', // 账号关联的 deviceId
      showQRCode: false, // 是否显示二维码
      errorMessage: '', // 错误信息
      qrCode:'',
    };
  },
  methods: {
    login() {
      const userName = this.userName;
      getDeviceId(userName).then(response => {
        this.deviceId = response.deviceId;
      });
      this.showQRCode = !!this.deviceId; // 根据 deviceId 控制是否显示二维码
      if (this.showQRCode) {
          // 获取二维码
          getQrCode(this.deviceId).then(response => {
            this.qrCode = response.data; 
            const base64Data = this.qrCode; // Base64 编码
            const image = new Image();
            image.onload = () => {
              this.$refs.imageElement.src = image.src;
            };
            image.src = `data:image/jpeg;base64,${base64Data}`;     
          });
        } else {
          // deviceId 为空时显示错误提示
          this.errorMessage = '请检查账号是否正确或是否审核通过';
        }
    },
    // convertBase64ToImage(qrCode) {

    //   const base64Data = qrCode; // Base64 编码

    //   console.log(base64Data)
    //   const image = new Image();
    //   image.onload = () => {
    //     this.$refs.imageElement.src = image.src;
    //   };
    //   image.src = `data:image/jpeg;base64,${base64Data}`;
    // },
    
  },
};
</script>

<style scoped>
.scan-login {
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
}

.scan-card {
  width: 400px;
}

.scan-card-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
}

.title {
  font-size: 24px;
  margin-bottom: 20px;
}

.qrcode-container {
  position: relative;
  text-align: center;
}

.qrcode {
  display: inline-block;
  margin-bottom: 10px;
}

.qrcode-refresh {
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  display: flex;
  align-items: center;
  cursor: pointer;
  color: #1890ff;
}

.qrcode-refresh i {
  margin-right: 5px;
}

.qrcode-refresh:hover {
  color: #40a9ff;
}
</style>