<template>
	<el-form ref="loginFormRef" class="form" :model="loginForm" :rules="loginRules" size="large">
		<el-form-item prop="account">
			<el-input v-model="loginForm.account" placeholder="请输入账号">
				<template #prefix>
					<img src="@/assets/images/login/accountIcon.png" alt="" class="configureIcon" />
				</template>
			</el-input>
		</el-form-item>
		<el-form-item prop="showPassword">
			<el-input
				type="password"
				v-model="loginForm.showPassword"
				placeholder="请输入密码"
				show-password
				autocomplete="new-password"
			>
				<template #prefix>
					<!-- <el-icon class="el-input__icon"><lock /></el-icon> -->
					<img src="@/assets/images/login/lockIcon.png" alt="" class="configureIcon" />
				</template>
			</el-input>
		</el-form-item>
	</el-form>
	<!-- <div class="login-btn"> -->
	<div class="login-btn">
		<!-- <el-button :icon="CircleClose" round @click="resetForm(loginFormRef)" size="large">重置</el-button>
		<el-button :icon="UserFilled" round @click="login(loginFormRef)" size="large" type="primary" :loading="loading">
			登录
		</el-button> -->
		<el-button @click="login(loginFormRef)" size="large" :loading="loading"> 登录 </el-button>
	</div>
	<div class="logon">
		<el-button type="info" style="color: #2246b4" @click="companyLogon" link>企业注册</el-button>
		<el-button style="margin: 0 40px; color: #2246b4" type="info" link @click="projectLogon">项目注册</el-button>
	</div>
</template>

<script setup lang="ts" name="logonPage">
import { ref, reactive, onMounted, onBeforeUnmount } from "vue";
import { useRouter } from "vue-router";
import { Login } from "@/api/interface";
import { ElMessage, ElNotification } from "element-plus";
import { loginApi } from "@/api/modules/login";
import { GlobalStore } from "@/stores";
import { TabsStore } from "@/stores/modules/tabs";
import { KeepAliveStore } from "@/stores/modules/keepAlive";
import { getTimeState } from "@/utils/util";
import { HOME_URL } from "@/enums/Home";
import { initDynamicRouter } from "@/routers/modules/dynamicRouter";
import { CircleClose, UserFilled } from "@element-plus/icons-vue";
import type { ElForm } from "element-plus";
import DynamicRouter from "@/assets/json/dynamicRouter.json";
// import md5 from "js-md5";

const router = useRouter();
const tabsStore = TabsStore();
const keepAlive = KeepAliveStore();
const globalStore = GlobalStore();

// 定义 formRef（校验规则）
type FormInstance = InstanceType<typeof ElForm>;
const loginFormRef = ref<FormInstance>();
const loginRules = reactive({
	account: [{ required: true, message: "请输入用户名", trigger: "blur" }],
	showPassword: [{ required: true, message: "请输入密码", trigger: "blur" }]
});

const loading = ref(false);
const loginForm = reactive<Login.ReqLoginForm>({ account: "", showPassword: "" });
const login = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.validate(async (valid, params) => {
		if (!valid) return;
		loading.value = true;
		try {
			// 1.执行登录接口
			const { result } = await loginApi({ ...loginForm, showPassword: loginForm.showPassword });
			const arr = ["/government", "/home", "/home", "/home"];

			globalStore.setToken(result.token);
			globalStore.setAccount(result.account);
			globalStore.setAccountType(result.accountType);
			globalStore.setProjectDateAuth(result.projectDateAuth);
			if (result.accountType === 1) {
				await initDynamicRouter();
			} else {
				router.push(arr[result.accountType - 1]);
			}

			// 2.添加动态路由
			// await initDynamicRouter();
			router.push(arr[result.accountType - 1]);
			// 3.清空 tabs、keepAlive 保留的数据
			tabsStore.closeMultipleTab();
			keepAlive.setKeepAliveName();

			// 4.跳转到首页

			// ElNotification({
			// 	title: getTimeState(),
			// 	message: "欢迎登录",
			// 	type: "success",
			// 	duration: 3000
			// });
			return router.push(arr[result.accountType - 1]);
		} finally {
			loading.value = false;
		}
	});
};

// resetForm
const resetForm = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.resetFields();
};

const projectLogon = () => {
	router.push("/projectlogon");
};

const companyLogon = () => {
	router.push("/compLogon");
};
onMounted(() => {
	// console.log(import.meta.env.VITE_API_URL);

	// 监听enter事件（调用登录）
	document.onkeydown = (e: any) => {
		e = window.event || e;
		if (e.code === "Enter" || e.code === "enter" || e.code === "NumpadEnter") {
			if (loading.value) return;
			login(loginFormRef.value);
		}
	};
});
// login页面销毁时，需要去掉enter监听
onBeforeUnmount(() => {
	document.onkeydown = null;
});
</script>

<style scoped lang="scss">
@import "../index.scss";
</style>
