<template>
  <el-row class="loginPage">
    <!-- element-plus login form -->
    <el-form
      ref="form"
      size="large"
      autocomplete="false"
      :model="loginData"
      :rules="rules"
      v-if="isLogin === true"
    >
      <el-form-item>
        <h1>登录</h1>
      </el-form-item>
      <el-form-item prop="username">
        <el-input
          placeholder="请输入用户名或邮箱"
          v-model="loginData.username"
        ></el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          placeholder="请输入密码"
          type="password"
          v-model="loginData.password"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button
          class="button"
          type="primary"
          auto-insert-space
          @click="login"
          >登录</el-button
        >
      </el-form-item>
      <el-form-item class="flex">
        <el-link @click="isLogin = false"> 注册 </el-link>
      </el-form-item>
    </el-form>

    <!-- element-plus register form -->
    <el-form
      ref="form"
      size="large"
      autocomplete="false"
      :model="registerData"
      :rules="rules"
      v-if="isLogin === false"
    >
      <el-form-item>
        <h1>注册</h1>
      </el-form-item>
      <el-form-item prop="username">
        <el-input
          placeholder="请输入用户名"
          v-model="registerData.username"
        ></el-input>
      </el-form-item>
      <el-form-item prop="email">
        <el-input
          placeholder="请输入邮箱"
          v-model="registerData.email"
        ></el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          placeholder="请输入密码"
          type="password"
          v-model="registerData.password"
        ></el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          placeholder="请再次输入密码"
          type="password"
          v-model="registerData.repassword"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" auto-insert-space>注册</el-button>
      </el-form-item>
      <el-form-item class="flex">
        <el-link @click="isLogin = true"> 返回 </el-link>
      </el-form-item>
    </el-form>
  </el-row>
  <div>
    <div class="qrcode" ref="qrCodeUrl"></div>
    <vue-qr :logoSrc="imageUrl" text="https://blog.csdn.net/weixin_42601136" :size="200"></vue-qr>
  </div>
</template>

<script setup>
import { ref, inject } from "vue";
import axios from "axios";
import { getQRService, getUUIDService, loginService, registerService } from "@/api/user.js";
import router from "@/router/index.js";
import VueQr from 'vue-qr'
const isLogin = ref(true);
if (localStorage.getItem("token") !== null) {
  router.push("/videoList");
}


const globalData = inject("globalData");

var uuid = "";
//表单数据
var loginData = ref({
  username: "",
  email: "lijun.lj@foxmail.com",
  password: "",
  ip:"",
});
const registerData = ref({
  username: "",
  email: "",
  password: "",
  repassword: "",
});

//表单校验规则
const rules = {
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    {
      min: 6,
      max: 20,
      message: "密码长度在 6 到 20 个字符",
      trigger: "blur",
    },
  ],
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    {
      min: 5,
      max: 20,
      message: "用户名长度在 6 到 20 个字符",
      trigger: "blur",
    },
  ],
  email: [{}],
};

const creatQrCode =async () =>{
      var qrcode = new qrcode(this.$refs.qrCodeUrl, {
        text: uuid, // 需要转换为二维码的内容
        width: 100,
        height: 100,
        colorDark: "#000000",
        colorLight: "#ffffff",
        correctLevel: QRCode.CorrectLevel.H,
      });
    };

//登录接口调用
const login = async () => {
  //   let req = axios.create({
  //     baseURL: "/api",
  //     timeout: 5000,
  //   });
  //   await req
  //     .post("/user/login", {
  //       email: loginData.value.username,
  //       password: loginData.value.password,
  //     })
  //     .then((response) => {
  //       alert(response.data.message);
  //       resp = response.data;
  //       jwt = resp.data;
  //       console.log(jwt);
  //     })
  //     .catch((error) => {
  //       console.error(error);
  //     });
  let result = await loginService(loginData);
  globalData.token = result.data;
  localStorage.setItem("token", result.data.token);
  localStorage.setItem("userId", result.data.id);
  localStorage.setItem("username", result.data.username);
  let now=new Date();
  localStorage.setItem("end_time", now.setDate(now.getHours() + 12));//过期时间
  //token.value= result.data;
  router.push("/videoList");
};

const getUUID= async() => {
      try {
        const response = await getUUIDService({"device":"windows"});
        uuid =response.data.toString();
        let uid =uuid.toString();
        console.log("uuid=",uuid);
        await creatQrCode(uid);
      } catch (error) {
        console.error(error);
      }
    };

const getQRStatus = async () => {
  let result = await getQRService({"uuid":uuid});
  if (result.code === 0) {
    if(result.data==="0"){
    }else if(result.data==="1"){
      alert("等待确认");
    }else{
      globalData.token = result.data;
      localStorage.setItem("token", result.data.token);
      localStorage.setItem("userId", result.data.id);
      localStorage.setItem("username", result.data.username);
      let now=new Date();
      localStorage.setItem("end_time", now.setDate(now.getHours() + 12));//过期时间
      //token.value= result.data;
      router.push("/videoList");
    }

  } else {
    alert(result.message);
  }
}

const  getIpClient= async() => {
      try {
        const response = await axios.get("https://ipinfo.io/json");
        loginData.value.ip =response.data.ip;
        localStorage.setItem("ip", response.data.ip);
        localStorage.setItem("city", response.data.city);
        // console.log("ip:",response.data.ip);
        // console.log("login ip:",loginData.ip);
        // console.log(response.data);
        // console.log(loginData);
      } catch (error) {
        console.error(error);
      }
    };

getIpClient();
await getUUID();
getQRStatus();
setInterval("getQRStatus()","1000");//showLogin()函数名一定要带括号
const register = async () => {
  let result = registerService(registerData.value);
  if (result.code === 0) {
    alert(result.message);
  } else {
    alert(result.message);
  }
};
</script>
