<template>
  <el-container v-if="isLoggedIn == false" 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">
          <el-input v-model="loginForm.username" name="username" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="密码" :label-width="loginForm.formLabelWidth" size="large">
          <el-input v-model="loginForm.password" name="password" type="password" 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>
  <el-container class="main-container" v-if="isLoggedIn">
    <el-header class="site_header">
      <el-row>

        <el-col :span="18">
          <div style="margin-top:8px;font-size:large;font-weight: bold;">
            <span style="vertical-align: middle;">知识图谱自动化构建平台</span>
            <span class="knowledge-base-icon" @click="goToKMPlatform"></span>
          </div>
        </el-col>
        <el-col :span="6" style="justify-content:flex-end;display: flex; flex-direction: row;margin-top:8px;">
          <el-dropdown style="margin-top:10px">
            <div style="font-size:medium;font-weight: bold; color:#000">{{ user.full_name }}</div>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item>用户资料</el-dropdown-item>
                <el-dropdown-item>修改密码</el-dropdown-item>
                <el-dropdown-item @click="handleLogout">登出</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>

        </el-col>
      </el-row>
    </el-header>
    <el-container>
      <el-aside class="main-aside">
        <SideMenu @selectQueue="onSelectQueue" @selectMenu="onSelectMenu"></SideMenu>
      </el-aside>
      <el-main class="content-area">
        <!-- 主要内容区域 -->
        <router-view v-slot="{ Component }">
          <component :is="Component" />
        </router-view>
      </el-main>
    </el-container>
  </el-container>
</template>
<script setup lang="ts">
import { onMounted, ref,watch, watchEffect } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { RouterView } from 'vue-router'
import SideMenu from '@/components/SideMenu.vue'
import { userLogin, userSignin } from '@/api/AgentApi'
import { deleteSessionVar, getSessionVar, saveSessionVar } from '@/utils/session'
import { ElNotification, ElMessageBox } from 'element-plus'
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, value, callback) => {
  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_id)
    saveSessionVar("user_id", res.records[0].user_id)
    saveSessionVar("username", res.records[0].username)
    saveSessionVar("full_name", res.records[0].full_name)

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

    isLoggedIn.value = true;
    goToKMPlatform()
  })
}

function handleLogout() {
  deleteSessionVar("session_id")
  deleteSessionVar("user_id")
  deleteSessionVar("username")
  deleteSessionVar("full_name")
  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>
