<template>

  <el-container class="login-box">
    <div style="width: 50%"></div>
    <div class="login-container">
      <div class="login-header">
        <!-- <h1>知识图谱自动化构建平台</h1><br> -->
        <h1>欢迎{{ isSignedIn ? '注册' : '登录' }}知识图谱自动化构建平台</h1>
      </div>

      <div v-if="isSignedIn == false">
        <el-form v-model="loginForm">
          <el-form-item label="用户名" :label-width="loginForm.formLabelWidth" size="large" required>
            <el-input v-model="loginForm.username" autocomplete="username" name="username" placeholder="请输入用户名"
              required></el-input>
          </el-form-item>
          <el-form-item label="密码" :label-width="loginForm.formLabelWidth" size="large" required>
            <el-input v-model="loginForm.password" autocomplete="current-password" name="password" type="password"
              required placeholder="请输入密码"></el-input>
          </el-form-item>
          <el-form-item label="" :label-width="loginForm.formLabelWidth">
            <el-button type="primary" @click="handleLoginSubmit">登录</el-button>
            <el-button type="success" @click="handleSignIn">注册</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div v-if="isSignedIn == true">
        <!-- <div>
        <h1>注册</h1>
      </div> -->

        <el-form :model="loginForm" :rules="signinRules" ref="signinForm">
          <el-form-item label="用户名" :label-width="loginForm.formLabelWidth" prop="username" size="large">
            <el-input v-model="loginForm.username" name="username" placeholder="请输入用户名"></el-input>
          </el-form-item>
          <el-form-item label="显示姓名" :label-width="loginForm.formLabelWidth" prop="full_name" size="large">
            <el-input v-model="loginForm.full_name" name="full_name" placeholder="请输入姓名"></el-input>
          </el-form-item>
          <el-form-item label="密码" :label-width="loginForm.formLabelWidth" prop="password" size="large">
            <el-input v-model="loginForm.password" name="password" type="password" placeholder="请输入密码"></el-input>
          </el-form-item>
          <el-form-item lable="密码确认" :label-width="loginForm.formLabelWidth" prop="password2" size="large">
            <el-input v-model="loginForm.password2" name="password2" type="password" placeholder="请再次输入密码"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" :label-width="loginForm.formLabelWidth" prop="email" size="large">
            <el-input v-model="loginForm.email" name="email" placeholder="请输入邮箱"></el-input>
          </el-form-item>
          <el-form-item label="" :label-width="loginForm.formLabelWidth">
            <el-button type="primary" @click="handleSignInSubmit">注册</el-button>
            <el-button type="success" @click="handleSignIn">登录</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>

  </el-container>
</template>

<script setup lang="ts">
import { onMounted, ref, watch, watchEffect } from "vue";
import { useRouter, useRoute } from "vue-router";
import { userLogin, userSignin } from "@/api/AgentApi";
import { knowledgeGraphAddr } from "@/utils/config"
import {
  deleteSessionVar,
  getSessionVar,
  saveSessionVar,
} from "@/utils/session";
import { ElNotification, ElMessageBox, ElMessage } from "element-plus";
import { useMenuStore } from "@/stores/menu.js";
const { updateRouteList } = useMenuStore();
const router = useRouter();
const route = useRoute();
// console.log('router', router.getRoutes(), route)
const isSignedIn = ref(false);
const loginForm = ref({
  username: "",
  password: "",
  full_name: "",
  password2: "",
  email: "",
  formLabelWidth: 100,
});
const signinForm = ref();

function goToKMPlatform() {
  router.push({ name: "kmplatform" });
}

const validatePassword = (rule: any, value: any, callback: Function) => {
  if (value === "") {
    callback(new Error("请输入密码"));
  } else {
    if (loginForm.value.password2 !== "") {
      signinForm.value.validateField("password2");
    }
    callback();
  }
};
const validatePassword2 = (rule: Object, value: string, callback: Function) => {
  if (value === "") {
    callback(new Error("请再次输入密码"));
  } else if (value !== loginForm.value.password) {
    callback(new Error("两次输入密码不一致"));
  } else {
    callback();
  }
};

const signinRules = ref({
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    { min: 3, max: 20, message: "长度在 3 到 10 个字符", trigger: "blur" },
  ],
  full_name: [
    { required: true, message: "请输入姓名", trigger: "blur" },
    { min: 2, max: 50, message: "姓名长度为2到50个字符", trigger: "blur" },
  ],
  password: [
    { required: true, validator: validatePassword, trigger: "blur" },
    { min: 6, max: 32, message: "密码长度为6到32个字符", trigger: "blur" },
  ],
  password2: [
    { required: true, validator: validatePassword2, trigger: "blur" },
  ],
  email: [
    { required: true, message: "请输入邮箱", trigger: "blur" },
    {
      type: "email",
      message: "请输入有效的邮箱地址",
      trigger: ["blur", "change"],
    },
  ],
});
const isLoggedIn = ref(false);
const user = ref({
  id: "0",
  full_name: "John Doe",
  username: "johndoe",
});
//校验注册信息
const onSelectQueue = (idData: any) => {
  // console.log(router.getRoutes());
  // 跳转到队列详情页并且传递队列ID作为查询参数
  // 假设队列详情页的路由路径是 '/workspace/queue'
  // 可以使用 router.push 方法来实现路由跳转

  router.push({ path: `/workspace/queue/${idData.id}` });
};
const onSelectMenu = (menuData: any) => {
  if (menuData.name == "graph") {
    router.push({ path: `/workspace/graph` });
  }
};
const handleSignIn = () => {
  loginForm.value.username = "";
  loginForm.value.password = "";
  isSignedIn.value = !isSignedIn.value;
};

const handleSignInSubmit = () => {
  // console.log('submit', loginForm.value)
  signinForm.value.validate((valid: boolean) => {
    if (valid) {
      userSignin({
        username: loginForm.value.username,
        password: loginForm.value.password,
        full_name: loginForm.value.full_name,
        email: loginForm.value.email,
      })
        .then((res: any) => {
          loginForm.value.password = "";
          loginForm.value.password2 = "";
          loginForm.value.email = "";
          loginForm.value.full_name = "";
          loginForm.value.username = "";
          ElNotification({
            title: "成功",
            message: res.message,
            type: "success",
            duration: 3000,
          });
          isSignedIn.value = !isSignedIn.value;
        })
        .catch((err: any) => {
          ElNotification({
            title: "错误",
            message: err.message,
            type: "error",
            duration: 3000,
          });
        });
    } else {
      console.log("表单校验失败");
    }
  });
};

const handleLoginSubmit = () => {
  // console.log('submit', loginForm.value)
  userLogin({
    username: loginForm.value.username,
    password: loginForm.value.password,
  }).then((res: any) => {
    // console.log(res.records[0])
    loginForm.value.password = "";
    saveSessionVar("session_id", res.records[0].session.session_id);
    saveSessionVar("user_id", res.records[0].session.user_id);
    saveSessionVar("username", res.records[0].session.username);
    saveSessionVar("full_name", res.records[0].session.full_name);
    let knowledageSystem = '';
    let routeList: any = [{
      path: '/kmplatform/home',
      name: 'kmplatform-home',
      title: "主页",
      children: []
    }]
    res.records[0].menu_permissions.sort((a: any, b: any) => {
      return a.id - b.id;
    });
    res.records[0].menu_permissions.forEach((item: any) => {
      if (item.menu_name == "知识更新管理") {
        knowledageSystem = 'true';
        routeList.push({
          path: knowledgeGraphAddr,
          name: '',
          title: item.name,
          children: item.children,
        });
      } else if (item.menu_route) {
        routeList.push({
          path: item.menu_route,
          name: item.menu_route.split("/")[2],
          title: item.name,
          children: item.children,
        });
      }
    });
    console.log("knowledageSystem", knowledageSystem);
    saveSessionVar("knowledageSystem", knowledageSystem);
    saveSessionVar('routeList', JSON.stringify(routeList))

    updateRouteList(routeList);

    user.value = {
      id: getSessionVar("user_id") || "0",
      full_name: getSessionVar("full_name") || "John Doe",
      username: getSessionVar("username") || "johndoe",
    };

    isLoggedIn.value = true;
    goToKMPlatform()
  }).catch((err: any) => {
    ElMessage({
      message: err.message,
      type: 'error'
    })
    console.log(err)
  })
}

function handleLogout() {
  deleteSessionVar("session_id");
  deleteSessionVar("user_id");
  deleteSessionVar("username");
  deleteSessionVar("full_name");
  updateRouteList([]);
  deleteSessionVar("knowledageSystem");
  isLoggedIn.value = false;
}

onMounted(() => {
  // 模拟从后端获取数据
  setTimeout(() => {
    user.value = {
      id: getSessionVar("user_id") || "0",
      full_name: getSessionVar("full_name") || "John Doe",
      username: getSessionVar("username") || "johndoe",
    };
    if (user.value.id != "0") {
      isLoggedIn.value = true;
    } else {
      isLoggedIn.value = false;
    }

    // router.push({ path: "/" });
  });
});
watchEffect(() => {
  // 监听路由变化
  console.log("route changed", route);
  if (route.query.logout) {
    handleLogout()
  }
})
</script>
<style scoped>
#app {
  width: 100vw;
  height: 100vh;
  overflow: auto;
}

.main-container {
  width: 100vw;
  height: 100vh;
  overflow: hidden;
}

.login-box {
  width: 100vw;
  height: 100vh;
  background-image: url("@/assets/images/loginBanar.png");
  background-repeat: no-repeat;
  background-size: cover;
}

.login-container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  margin: auto;
  width: 500px;
  /* width: 100vw; */
  /* height: 100vh; */
  padding: 50px;
  background-color: #eef6ff;
  border-radius: 12px 12px 12px 12px;
}

.login-header {
  font-size: 26px;
  font-weight: bold;
  margin-bottom: 20px;
}

.content-area {
  padding: 20px;
  width: calc(100vw - 300px);
  overflow: auto;
}

.main-aside {
  width: 300px;
  border-right: 0px solid #e4e7ed;
  padding: 1px;
}

.site_header {
  /* background-color: #c5c5c5; */
  background-color: #eef6ff;
  padding: 0 20px;
  height: 50px;
  /* border-bottom: 1px solid #e4e7ed; */
}

.knowledge-base-icon {
  cursor: pointer;
  vertical-align: middle;
  margin-left: 10px;
}
</style>
