<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" @click="onRegister" 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>二维码状态: {{ qr_status }}</div>
    <canvas ref="qrCodeCanvas"></canvas>
  </div>
</template>

<script setup>
import { ref, onMounted, inject, onUnmounted } 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"; // 确保你已经注册了这个组件
import {ElMessage} from "element-plus";
import QRCode from "qrcode";

const isLogin = ref(true);
const qrCodeCanvas = ref(null);
const globalData = inject("globalData");

// 创建一个响应式引用来存储定时器ID
const intervalId = ref(null);
var uuid = "";

const qr_status = ref("未被扫描");
//表单数据
var loginData = ref({
  username: "",
  email: "",
  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: [{}],
};
onMounted(() => {
  init();
  startInterval();
  const token = localStorage.getItem("token");
  if (token !== null) {
    isLogin.value = true; // 更新登录状态
    router.push("/videoList"); // 跳转到视频列表页面
    // 你可以在这里获取 UID 并更新 uid.value
  }
});
onUnmounted(() => {
  stopInterval();
});

// 开启定时器
const startInterval = () => {
  if (intervalId.value) {
    // 如果定时器已经开启，则不执行任何操作
    return;
  }
  intervalId.value = setInterval(getQRStatus, 2000);
};

// 关闭定时器
const stopInterval = () => {
  if (intervalId.value) {
    clearInterval(intervalId.value);
    intervalId.value = null; // 清除引用中的定时器ID
  }
};

const creatQrCode = async () => {
  console.log("creatQrCode:", uuid);
  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 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 onRegister = async () => {
  //校验密码是否一致
  if (registerData.value.password !== registerData.value.repassword) {
    //alert("两次密码不一致");
    ElMessage.error("两次密码不一致");
    return;
  }
  //校验邮箱是否合法
  let email = registerData.value.email;
  let reg = /^(\w-*\.*)+@(\w-?)+(\.\w{2,})+$/;
  if (!reg.test(email)) {
    //alert("邮箱格式不正确");
    ElMessage.error("邮箱格式不正确");
    return;
  }

  let result = await registerService(registerData);
  if (result !== null) {
    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 generateQRCode = () => {
  // 假设我们有一个数据字符串要转换为二维码
  const data = uuid;
  // 确保 canvas 已经被渲染到 DOM 中
  if (qrCodeCanvas.value) {
    const canvas = qrCodeCanvas.value;
    const ctx = canvas.getContext("2d");

    // 设置 canvas 的大小
    canvas.width = 256;
    canvas.height = 256;

    // 使用 qrcode 库生成二维码
    QRCode.toCanvas(
      canvas,
      data,
      {
        width: 256,
        height: 256,
        color: {
          dark: "#000000",
          light: "#ffffff",
        },
      },
      function (error) {
        if (error) console.error(error);
        console.log("二维码已生成");
      }
    );
  }
};

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

const getQRStatus = async () => {
  let result = await getQRService({ uuid: uuid });
  if (result.code === 0) {
    if (result.data === "0") {
    } else if (result.data === "1") {
      qr_status.value = "等待确认";
    } 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);
    ElMessage.error(result.message);
  }
};

const getIpClient = async () => {
  try {
    const response = await axios.get("https://ip.zxinc.org/api.php?type=json");
    loginData.value.ip = response.data.data.myip;
    localStorage.setItem("ip", response.data.data.myip);
    localStorage.setItem("city", response.data.data.country);
    localStorage.setItem("address", response.data.data.location);
    // console.log("ip:",response.data.ip);
    // console.log("login ip:",loginData.ip);
    // console.log(response.data);
    // console.log(loginData);
  } catch (error) {
    console.error(error);
  }
};
const init = async () => {
  getIpClient();
  await getUUID();
};
const register = async () => {
  let result = registerService(registerData.value);
  if (result.code === 0) {
    //alert(result.message);
    ElMessage.success(result.message);
  } else {
    //alert(result.message);
    ElMessage.error(result.message);
  }
};
</script>
<style scoped>
canvas {
  border: 1px solid #000;
}
</style>