<template>
  <div class="scan-login">
     <el-form ref="qwForm" :model="qwForm" :rules="qwRules" label-width="70px">
      <el-row v-loading="loading" align="middle" justify="center">
        <el-col :span="24">
          <el-card class="scan-card" shadow="hover">
            <div class="scan-card-content">
              <h1 class="title">扫码登录</h1>
               <el-form-item label="账号" prop="account" style="width:100%" v-if="!showVerifyCode">
                  <el-input  v-model="qwForm.account" placeholder="请输入账号" style="margin-bottom: 20px"></el-input>
               </el-form-item>
                <el-form-item label="验证码" prop="verifyCode" style="width:100%" v-if="showVerifyCode">
                  <el-input  v-model="qwForm.verifyCode" placeholder="请输入验证码" style="margin-bottom: 20px"></el-input>
               </el-form-item>
              <el-button type="primary" @click.native.prevent="handleLogin" style="width:200px">{{loginTips}}</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>
     </el-form>

  </div>
</template>

<script>
import store from "@/store";
import { getQrCode,verify } from '@/api/qw/login';
import { getDeviceId} from '@/api/qw/account';
import { Notification } from 'element-ui'
export default {
  data() {
    return {
      loading: false,// 遮罩层
      account: '', // 用户输入的账号
      qrcode: null, // 二维码实例
      loading: false, // 刷新按钮加载状态
      deviceId: '', // 账号关联的 deviceId
      showQRCode: false, // 是否显示二维码
      errorMessage: '', // 错误信息
      qrCode:'',
      companyUser:store.getters.user,
      showVerifyCode:false,
      loginTips:"获取二维码",
      qwForm: {
          account:"",
          verifyCode:null
      },
       // 表单校验
      qwRules: {
        account: [
          { required: true, message: "请输入账号", trigger: "blur" }
        ],
         verifyCode: [
          { required: true, message: "请输入验证码", trigger: "blur" }
        ]
      }
    };
  },
  created() {
      
  },
  mounted () {
      // if (process.env.NODE_ENV === 'development') {
      //       this.qwForm.account = "1261818888";
      //  }
  },
  methods: {
    handleLogin() {
      this.$refs.qwForm.validate(valid => {
          if (valid) {
                if(!this.showVerifyCode){
                    this.loginAction();
                }else{
                     this.verify();
                }
          }
      });
    },
    getQrCode(){
            // 获取二维码
           getQrCode(this.deviceId).then(response => {
                this.loading=false;  
                if(response.code==200){
                        this.qrCode = response.data.qrcode; 
                        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{
                         this.showQRCode=false;
                         Notification.error({title: response.msg });
                  }
              });
    },
    loginAction(){
              const account = this.qwForm.account;
              this.loading=true;
              if (this.showQRCode) {
                  this.getQrCode();
              }else{
                    getDeviceId(account).then(response => {
                          this.deviceId = response.deviceId;
                          this.showQRCode = !!this.deviceId; // 根据 deviceId 控制是否显示二维码
                          this.initSocket(this.deviceId);
                          if (this.showQRCode) {
                               this.getQrCode();
                          }else{
                              // deviceId 为空时显示错误提示
                              this.errorMessage = '请检查账号是否正确或是否审核通过';
                              this.loading=false;
                          }
                  });
              }
    },
    verify(){
              // 验证码验证
              this.loading=true;
              const verifyCode=this.qwForm.verifyCode;
              let data={"verifyCode":verifyCode,"deviceId":this.deviceId};
              verify(data).then(response => {
                  this.loading=false;  
              });
    },
     initSocket(userId) {
          let that=this;
          if(!!this.qwIm.socket){
              this.qwIm.initSocket(userId,true);
                // 监听socket连接
              this.qwIm.socket.onopen = function() {
                    console.log("socket 连接成功");
              };
              // 监听socket错误信息
              this.qwIm.socket.onerror = function() {
                  console.log("连接错误")
              };
              // 监听socket消息
              this.qwIm.socket.onmessage = function(res) {
                    var data=JSON.parse(res.data);
                    console.log("收到服务端内容", JSON.stringify(data));
                    if(data.cmd=="heartbeat"){ //收到心跳数据不处理
                        console.log("收到心跳数据 heartbeat");
                    }
                    if(data.cmd=="loginSucc"){
                        var qwUserInfo=JSON.parse(data.msg);
                        Notification.success({title: "登录成功!" });
                        that.$store.dispatch("qwUser", qwUserInfo);
                        that.showQRCode=false;
                        setTimeout(() => {
                            that.$router.push({path:'/qw/qwChat',query:{"isFromLogin":1}});
                        }, 2000);
                    }
                    if(data.cmd=="verifyCode"){
                        that.loginTips="登录";
                        that.showQRCode=false;
                        that.showVerifyCode=true;
                    }
                    // if(data.cmd=="offline"){
                    //     that.loginTips="获取验证码";
                    //     that.showQRCode=true;
                    //     that.showVerifyCode=false;
                    //     that.$store.dispatch('qwLoginOut').then(() => {
                    //     });
                    // }
              };
              // 监听socket重连
              this.qwIm.socket.onreconnect = function(res) {
                  console.log("socket 断线重连...")
              };
          }
      },
      open() {
            console.log("socket连接成功");

      },
      error() {
            console.log("连接错误")
      },
      getMessage(msg) {
            console.log(msg.data)
       },
      // 发送消息给被连接的服务端
      send(params) {
            // this.qwIm.socket.send(params)
      },
      close() {
           
      },
      destroyed () {
        // 销毁监听
        //this.qwIm.socket.onclose = this.close
    }

  },
};
</script>

<style lang="scss" scoped>
.scan-login {
  height: 80vh;
  display: flex;
  flex: 1;
  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: 30px;
  margin-top: 0px;
}
.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>