<template>
	<el-form size="large" class="login-content-form" ref="ruleFormRef" :model="state.ruleForm" @submit.native.prevent>
		<el-form-item class="login-animation1 mb30" prop="userName" :rules="[{ required: true, message: '请输入账号', trigger: 'blur' }]">
			<el-input
				type="text"
				class="inputDeep"
				placeholder="请输入账号"
				v-model="state.ruleForm.userName"
				clearable
				@keyup.enter="onSignIn(ruleFormRef)"
				autocomplete="off"
			>
				<template #prefix>
					<SvgIcon name="ele-User" class="el-input__icon" />
				</template>
			</el-input>
		</el-form-item>
		<el-form-item class="login-animation2 mb30" prop="password" :rules="[{ required: true, message: '请输入密码', trigger: 'blur' }]">
			<el-input
				class="inputDeep"
				clearable
				show-password
				placeholder="请输入密码"
				v-model="state.ruleForm.password"
				@keyup.enter="onSignIn(ruleFormRef)"
				autocomplete="off"
			>
				<template #prefix>
					<SvgIcon name="ele-Unlock" class="el-input__icon" />
				</template>
			</el-input>
		</el-form-item>
		<!--		 <el-form-item class="login-animation3">
			<el-col :span="15">
				<el-input type="text" maxlength="4" class="inputDeep" placeholder="请输入验证码" v-model="state.ruleForm.code" @keyup.enter="onSignIn(ruleFormRef)" clearable autocomplete="off">
					<template #prefix>
						<SvgIcon  name="ele-Position" class="el-input__icon"/>
					</template>
				</el-input>
			</el-col>
			<el-col :span="8" :offset=1>
				<el-button class="login-content-code">1234</el-button>
			</el-col>
		</el-form-item>-->
		<el-form-item class="login-animation4">
			<el-button type="primary" class="login-content-submit" round @click="onSignIn(ruleFormRef)" v-waves="'light'" :loading="state.loading"
				>登录</el-button
			>
		</el-form-item>
		<!-- <div class="font12 mt30 login-animation4 login-msg">
			* 温馨提示：建议使用谷歌、Microsoft Edge，版本 79.0.1072.62 及以上浏览器，360浏览器请使用极速模式
		</div> -->
		<div class="login-msg login-animation4">
			<div>联系管理员<b>重置密码</b></div>
			<!-- <el-button link type="primary" class="font16" @click="forgetPwd">忘记密码</el-button> -->
		</div>
	</el-form>
</template>

<script setup lang="ts" name="loginAccount">
import { reactive, computed, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import {ElMessage, ElNotification} from 'element-plus';
import { storeToRefs } from 'pinia';
import { useThemeConfig } from '/@/stores/themeConfig';
import { initFrontEndControlRoutes } from '/@/router/frontEnd';
import { initBackEndControlRoutes } from '/@/router/backEnd';
import { Session, Local, Cookie } from '/@/utils/storage';
import { formatAxis } from '/@/utils/formatTime';
import { NextLoading } from '/@/utils/loading';
import Watermark from '/@/utils/watermark';
import type { FormInstance } from 'element-plus';
import { signIn } from '/@/api/login';
import { JSEncrypt } from 'jsencrypt'; // rsa加密
// 定义变量内容
const storesThemeConfig = useThemeConfig(); // 主题配置
const { themeConfig } = storeToRefs(storesThemeConfig); // 主题配置
const route = useRoute(); // 路由
const router = useRouter(); // 路由
const state = reactive<any>({
	ruleForm: {
		userName: '', // 账号
		password: '', // 密码
	},
	loading: false, // 加载
});
const ruleFormRef = ref<FormInstance>();  // 表单ref
// 时间获取
const currentTime = computed(() => {
	return formatAxis(new Date());
});
// 登录
const onSignIn = async (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	await formEl.validate((valid: boolean) => {
		if (!valid) return;
		state.loading = true;
		// 新建一个JSEncrypt对象
		const encryptor = new JSEncrypt({ default_key_size: '2048' });
		// 设置公钥
		const publicKey =
			'-----BEGIN PUBLIC KEY-----MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAgw+/x6IQPkH0A4eoF63jkLThsOXWyNBdcL9LATGy/G1yTHOr1RyKJB//iNug+V8DIoIHuFTlhgLHDbSqxvRWMONxIIF289riS6bDI4Ox/pFmOfmElFRk0lKGihaTE2Aefd6g/N+RfLLaHWztY+/voVeDTiOIw9y3tokIxjKwuJ/mQ66MkKh78AqQjjSD/3jcBP8ZhMyCJOK9XQcqvhD6WBFWkxlAqKOWggDU7YohfrbNkg3bd0oGE6zCE2EHhkcQbzGCh3lu1zf4TfKMXD+PPrr5JWDNYQTXFQklqgae+Puge7xxZGYRoi5YpIUnkQGm6zpPxhIOdxlz+Yb5geSJUQIDAQAB-----END PUBLIC KEY-----';
		encryptor.setPublicKey(publicKey); // publicKey为公钥
		// 加密数据
		const submitObj = {
			userName: encryptor.encrypt(state.ruleForm.userName),
			password: encryptor.encrypt(state.ruleForm.password),
		};
		signIn(submitObj)
			.then(async (res: any) => {
				//登录
				// 存储 token 到浏览器缓存
				Cookie.set('token', res.result);
				if (!themeConfig.value.isRequestRoutes) {
					// 前端控制路由，2、请注意执行顺序
					const isNoPower = await initFrontEndControlRoutes();
					signInSuccess(isNoPower);
				} else {
					// 模拟后端控制路由，isRequestRoutes 为 true，则开启后端控制路由
					// 添加完动态路由，再进行 router 跳转，否则可能报错 No match found for location with path "/"
					const isNoPower = await initBackEndControlRoutes();
					// 执行完 initBackEndControlRoutes，再执行 signInSuccess
					signInSuccess(isNoPower);
				}
			})
			.catch(() => {
				state.loading = false;
			});
	});
};
// 登录成功后的跳转
const signInSuccess = (isNoPower: boolean | undefined) => {
	if (isNoPower) {
		state.loading = false;
		ElNotification({
			title: '提示',
			message: '抱歉，您没有登录权限，请联系管理员',
			type: 'warning',
		});
		Session.clear();
		Cookie.clear();
		Local.clear();
	} else {
		// 初始化登录成功时间问候语
		let currentTimeInfo = currentTime.value;
		// 登录成功，跳到转首页
		// 如果是复制粘贴的路径，非首页/登录页，那么登录成功后重定向到对应的路径中
		if (route.query?.redirect) {
			router.push({
				path: <string>route.query?.redirect,
				query: Object.keys(<string>route.query?.params).length > 0 ? JSON.parse(<string>route.query?.params) : '',
			});
		} else {
			router.push('/');
		}
		// 设置水印
		themeConfig.value.isWatermark = true;
		themeConfig.value.watermarkText = state.ruleForm.userName;
		Watermark.set(state.ruleForm.userName);
		Cookie.set('userName', state.ruleForm.userName);
		// 登录成功提示
		// 关闭 loading
		state.loading = true;
		const signInText = '欢迎回来！';
    ElMessage.success(`${currentTimeInfo}，${signInText}`);
		NextLoading.start();
	}
};
</script>

<style scoped lang="scss">
.inputDeep {
	:deep(.el-input__wrapper) {
		box-shadow: 0 0 0 0 var(--el-input-border-color, var(--el-border-color)) inset;
		border-radius: 0;
		border-bottom: 1px solid var(--el-input-border-color, var(--el-border-color));
	}
}

.login-content-form {
	margin-top: 20px;
	font-size: 16px;

	:deep(.el-input--large) {
		font-size: 16px;
	}

	:deep(.el-form-item__error) {
		font-size: 14px;
	}

	@for $i from 1 through 4 {
		.login-animation#{$i} {
			opacity: 0;
			animation-name: error-num;
			animation-duration: 0.5s;
			animation-fill-mode: forwards;
			animation-delay: calc($i/10) + s;
		}
	}

	.login-content-password {
		display: inline-block;
		width: 20px;
		cursor: pointer;

		&:hover {
			color: #909399;
		}
	}

	.login-content-code {
		width: 100%;
		padding: 0;
		font-weight: bold;
		letter-spacing: 5px;
	}

	.login-content-submit {
		width: 100%;
		font-weight: 300;
		margin-top: 85px;
		height: 50px;
		border-radius: 30px;
		font-size: 16px;
		letter-spacing: 5px;
	}

	.login-msg {
		margin-top: 39px;
		display: flex;
		justify-content: space-between;
		align-items: center;
		color: var(--el-color-primary);
		b {
			color: #999;
			padding-left: 4px;
		}
	}
}
</style>
