<template>
	<el-form ref="formRef" size="large" class="login-content-form" :model="state.ruleForm" :rules="rules" @keyup.enter="loginClick">
		<!-- <el-form-item class="login-animation1" prop="merchant_code">
				<el-input type="text" :placeholder="'请输入商户号'" v-model="ruleForm.merchant_code" clearable autocomplete="off">
					<template #prefix>
						<el-icon class="el-input__icon"><ele-Shop /></el-icon>
					</template>
				</el-input>
		</el-form-item> -->
		<el-form-item class="login-animation1" prop="username">
			<el-input type="text" :placeholder="$t('message.account.accountPlaceholder1')" v-model="ruleForm.username" clearable autocomplete="off">
				<template #prefix>
					<el-icon class="el-input__icon"><ele-User /></el-icon>
				</template>
			</el-input>
		</el-form-item>
		<el-form-item class="login-animation2" prop="password">
			<el-input :type="isShowPassword ? 'text' : 'password'" :placeholder="$t('message.account.accountPlaceholder2')" v-model="ruleForm.password">
				<template #prefix>
					<el-icon class="el-input__icon"><ele-Unlock /></el-icon>
				</template>
				<template #suffix>
					<i
						class="iconfont el-input__icon login-content-password"
						:class="isShowPassword ? 'icon-yincangmima' : 'icon-xianshimima'"
						@click="isShowPassword = !isShowPassword"
					>
					</i>
				</template>
			</el-input>
		</el-form-item>
		<el-form-item class="login-animation3" v-if="isShowCaptcha" prop="captcha">
			<el-col :span="15">
				<el-input
					type="text"
					maxlength="4"
					:placeholder="$t('message.account.accountPlaceholder3')"
					v-model="ruleForm.captcha"
					clearable
					autocomplete="off"
				>
					<template #prefix>
						<el-icon class="el-input__icon"><ele-Position /></el-icon>
					</template>
				</el-input>
			</el-col>
			<el-col :span="1"></el-col>
			<el-col :span="8">
				<el-button class="login-content-captcha">
					<el-image :src="ruleForm.captchaImgBase" @click="refreshCaptcha" />
				</el-button>
			</el-col>
		</el-form-item>
		<el-form-item>
			<!-- <el-row :gutter="20">
				<el-col :span="24"> -->
					<el-checkbox v-model="state.rememberPassword">
						记住密码
					</el-checkbox>
				<!-- </el-col>
			</el-row> -->
			<!-- <el-row style="margin-top: 10px;">
				<el-col :span="24">
					<el-checkbox v-model="state.agreePolicy">
						已阅读并同意
						<a href="/user-agreement" target="_blank" class="login-link">《用户服务协议》</a>
						与
						<a href="/privacy-policy" target="_blank" class="login-link">《隐私协议》</a>
					</el-checkbox>
				</el-col>
			</el-row> -->
		</el-form-item>
		<el-form-item class="login-animation4">
			<el-button type="primary" class="login-content-submit" round @click="loginClick" :loading="loading.signIn" :disabled="!state.agreePolicy">
				<span>{{ $t('message.account.accountBtnText') }}</span>
			</el-button>
		</el-form-item>
	</el-form>
	<!--   	<div>沪ICP备2024071246号-3</div>   申请试用-->
	<div style="text-align: center" v-if="showApply()">
		<el-button class="login-content-apply" link type="primary" plain round @click="applyBtnClick">
			<span>申请试用</span>
		</el-button>
	</div>
</template>

<script lang="ts">
import { toRefs, reactive, defineComponent, computed, onMounted, onUnmounted, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, FormInstance, FormRules } from 'element-plus';
import { useI18n } from 'vue-i18n';
import Cookies from 'js-cookie';
import { storeToRefs } from 'pinia';
import { useThemeConfig } from '/@/stores/themeConfig';
import { initFrontEndControlRoutes } from '/@/router/frontEnd';
import { initBackEndControlRoutes } from '/@/router/backEnd';
import { Session } from '/@/utils/storage';
import { formatAxis } from '/@/utils/formatTime';
import { NextLoading } from '/@/utils/loading';
import * as loginApi from '/@/views/system/login/api';
import { useUserInfo } from '/@/stores/userInfo';
import { DictionaryStore } from '/@/stores/dictionary';
import { SystemConfigStore } from '/@/stores/systemConfig';
import { BtnPermissionStore } from '/@/plugin/permission/store.permission';
import { Md5 } from 'ts-md5';
import { errorMessage } from '/@/utils/message';
import { getBaseURL } from '/@/utils/baseUrl';

export default defineComponent({
	name: 'loginAccount',
	setup() {
		const { t } = useI18n();
		const storesThemeConfig = useThemeConfig();
		const { themeConfig } = storeToRefs(storesThemeConfig);
		const { userInfos } = storeToRefs(useUserInfo());
		const route = useRoute();
		const router = useRouter();
		const state = reactive({
			isShowPassword: false,
			ruleForm: {
				username: '',
				password: '',
				captcha: '',
				captchaKey: '',
				captchaImgBase: '',
				//merchant_code: localStorage.getItem('merchant_code') || 'ML01',
				/* tenant_id: 8, */
			},
			loading: {
				signIn: false,
			},
			agreePolicy: true,
			rememberPassword: false,
		});
		const rules = reactive<FormRules>({
			//merchant_code: [{ required: true, message: '请填写商户号', trigger: 'blur' }],
			username: [{ required: true, message: '请填写账号', trigger: 'blur' }],
			password: [
				{
					required: true,
					message: '请填写密码',
					trigger: 'blur',
				},
			],
			captcha: [
				{
					required: true,
					message: '请填写验证码',
					trigger: 'blur',
				},
			],
		});
		const formRef = ref();
		// 时间获取
		const currentTime = computed(() => {
			return formatAxis(new Date());
		});
		// 是否关闭验证码
		const isShowCaptcha = computed(() => {
			return SystemConfigStore().systemConfig['base.captcha_state'];
		});

		const getCaptcha = async () => {
			loginApi.getCaptcha().then((ret: any) => {
				state.ruleForm.captchaImgBase = ret.data.image_base;
				state.ruleForm.captchaKey = ret.data.key;
			});
		};
		const applyBtnClick = async () => {
			window.open(getBaseURL('/api/system/apply_for_trial/'));
		};
		const refreshCaptcha = async () => {
			state.ruleForm.captcha = '';
			loginApi.getCaptcha().then((ret: any) => {
				state.ruleForm.captchaImgBase = ret.data.image_base;
				state.ruleForm.captchaKey = ret.data.key;
			});
		};
		
		// 简单的加密函数（使用异或加密 + Base64编码）
		const simpleEncrypt = (text: string, key: string): string => {
			let encrypted = '';
			for (let i = 0; i < text.length; i++) {
				const textChar = text.charCodeAt(i);
				const keyChar = key.charCodeAt(i % key.length);
				encrypted += String.fromCharCode(textChar ^ keyChar);
			}
			// 使用Base64进一步编码
			return btoa(encrypted);
		};

		// 简单的解密函数（Base64解码 + 异或解密）
		const simpleDecrypt = (encryptedText: string, key: string): string => {
			try {
				// 先进行Base64解码
				const decoded = atob(encryptedText);
				let decrypted = '';
				for (let i = 0; i < decoded.length; i++) {
					const encryptedChar = decoded.charCodeAt(i);
					const keyChar = key.charCodeAt(i % key.length);
					decrypted += String.fromCharCode(encryptedChar ^ keyChar);
				}
				return decrypted;
			} catch (error) {
				console.warn('解密失败，可能是数据损坏');
				return '';
			}
		};

		// 生成加密密钥（基于用户名和固定字符串）
		const generateEncryptionKey = (username: string): string => {
			const fixedKey = 'DVA_ADMIN_2024';
			return fixedKey + username;
		};

		// 处理记住密码功能
		const handleRememberPassword = () => {
			if (state.rememberPassword) {
				// 记住用户名和加密后的密码
				const encryptionKey = generateEncryptionKey(state.ruleForm.username);
				const encryptedPassword = simpleEncrypt(state.ruleForm.password, encryptionKey);
				
				localStorage.setItem('rememberedUsername', state.ruleForm.username);
				localStorage.setItem('rememberedPassword', encryptedPassword);
				localStorage.setItem('rememberPasswordChecked', 'true');
				
				console.log('密码已加密存储');
			} else {
				// 清除记住的用户名和密码
				localStorage.removeItem('rememberedUsername');
				localStorage.removeItem('rememberedPassword');
				localStorage.removeItem('rememberPasswordChecked');
			}
		};
		
		// 初始化记住密码数据
		const initRememberPassword = () => {
			const rememberedUsername = localStorage.getItem('rememberedUsername');
			const rememberedPassword = localStorage.getItem('rememberedPassword');
			const rememberPasswordChecked = localStorage.getItem('rememberPasswordChecked');
			
			if (rememberPasswordChecked === 'true' && rememberedUsername && rememberedPassword) {
				state.ruleForm.username = rememberedUsername;
				
				// 解密密码
				const encryptionKey = generateEncryptionKey(rememberedUsername);
				const decryptedPassword = simpleDecrypt(rememberedPassword, encryptionKey);
				
				if (decryptedPassword) {
					state.ruleForm.password = decryptedPassword;
					state.rememberPassword = true;
					console.log('已成功加载并解密记住的密码');
				} else {
					// 解密失败，清除存储的数据
					localStorage.removeItem('rememberedUsername');
					localStorage.removeItem('rememberedPassword');
					localStorage.removeItem('rememberPasswordChecked');
					console.warn('密码解密失败，已清除存储数据');
				}
			}
		};
		const loginClick = async () => {
			if (!formRef.value) return;
			await formRef.value.validate((valid: any) => {
				if (valid) {
					loginApi
						.login({ ...state.ruleForm, password: Md5.hashStr(state.ruleForm.password) })
						.then((res: any) => {
							if (res.code === 2000) {
								const { data } = res;
								Cookies.set('username', res.data.username);
								Session.set('token', res.data.access);
								Session.set('merchant_info', res.data.merchant_info);
								useUserInfo().setPwdChangeCount(data.pwd_change_count);
								
								// 处理记住密码逻辑
								handleRememberPassword();
								
								/* if (data.pwd_change_count == 0) {
									return router.push('/login');
								} */
								if (!themeConfig.value.isRequestRoutes) {
									// 前端控制路由，2、请注意执行顺序
									initFrontEndControlRoutes();
									loginSuccess();
								} else {
									// 模拟后端控制路由，isRequestRoutes 为 true，则开启后端控制路由
									// 添加完动态路由，再进行 router 跳转，否则可能报错 No match found for location with path "/"
									initBackEndControlRoutes();
									// 执行完 initBackEndControlRoutes，再执行 signInSuccess
									loginSuccess();
								}
							}
						})
						.catch((err: any) => {
							// 登录错误之后，刷新验证码
							refreshCaptcha();
						});
				} else {
					errorMessage('请填写登录信息');
				}
			});
		};

		// 登录成功后的跳转
		const loginSuccess = () => {
			//获取所有字典
			DictionaryStore().getSystemDictionarys();
			// 初始化登录成功时间问候语
			let currentTimeInfo = currentTime.value;
			// 登录成功，跳到转首页
			const pwd_change_count = userInfos.value.pwd_change_count;
			router.push('/');
			state.loading.signIn = true;
			const signInText = t('message.signInText');
			ElMessage.success(`${currentTimeInfo}，${signInText}`);
			/* if (pwd_change_count > 0) {
				// 如果是复制粘贴的路径，非首页/登录页，那么登录成功后重定向到对应的路径中
				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 {
					
				}
				// 登录成功提示
				// 关闭 loading
				
			} */
			// 添加 loading，防止第一次进入界面时出现短暂空白
			NextLoading.start();
		};
		onMounted(() => {
			getCaptcha();
			//获取系统配置
			SystemConfigStore().getSystemConfigs();
			// 初始化记住密码功能
			initRememberPassword();
		});
		// 是否显示申请试用按钮
		const showApply = () => {
			return window.location.href.indexOf('public') != -1;
		};

		return {
			refreshCaptcha,
			loginClick,
			loginSuccess,
			isShowCaptcha,
			state,
			formRef,
			rules,
			applyBtnClick,
			showApply,
			handleRememberPassword,
			initRememberPassword,
			...toRefs(state),
		};
	},
});
</script>

<style scoped lang="scss">
.login-content-form {
	margin-top: 20px;

	@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-captcha {
		width: 100%;
		padding: 0;
		font-weight: bold;
		letter-spacing: 5px;
	}

	.login-content-submit {
		width: 100%;
		letter-spacing: 2px;
		font-weight: 800;
		margin-top: 15px;
	}
	:deep(.el-checkbox__label) {
		color: #808080 !important;
	}
	:deep(.el-checkbox__input.is-checked + .el-checkbox__label) {
		color: #808080 !important;
	}
	.login-link {
		color: #0017ab;
		text-decoration: none;
		cursor: pointer;
		&:hover {
			color: #0017ab;
		}
	}
}
</style>
