<template>
	<el-form ref="loginForm" size="large" class="login-content-form" :model="ruleForm">
		<el-form-item class="login-animation1">
			<el-input type="text" :placeholder="$t('message.email.placeholder1')" v-model="ruleForm.userName" clearable autocomplete="off">
				<template #prefix>
					<el-icon class="el-input__icon">
						<ele-Message />
					</el-icon>
				</template>
			</el-input>
		</el-form-item>
		<el-form-item class="login-animation2">
			<el-col :span="15">
				<el-input type="text" maxlength="6" :placeholder="$t('message.email.placeholder2')" v-model="ruleForm.code" 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-code" @click="smsCode" :disabled="disabled">
					<div v-if="disabled">{{ countDown }}秒后重新获取</div>
					<div v-else>{{ $t('message.email.codeText') }}</div>
				</el-button>
			</el-col>
		</el-form-item>
		<el-form-item class="login-animation3">
			<el-button round type="primary" class="login-content-submit" @click="sendSms">
				<span>{{ $t('message.email.btnText') }}</span>
			</el-button>
		</el-form-item>
		<!--		<div class="font12 mt30 login-animation4 login-msg">{{ $t('message.email.msgText') }}</div>-->
	</el-form>
</template>

<script lang="ts">
import { toRefs, reactive, defineComponent, getCurrentInstance, computed, onMounted } from 'vue';
import { emailCode, loginEmail } from '/@/api/login';
import { Session } from '/@/utils/storage';
import { initFrontEndControlRoutes } from '/@/router/frontEnd';
import { initBackEndControlRoutes } from '/@/router/backEnd';
import { useI18n } from 'vue-i18n';
import { useStore } from '/@/store';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { formatAxis } from '/@/utils/formatTime';

export default defineComponent({
	name: 'loginEmail',
	setup() {
		const { t } = useI18n();
		const store = useStore();
		const route = useRoute();
		const router = useRouter();
		const { proxy } = <any>getCurrentInstance();
		const state = reactive({
			disabled: false,
			countDown: 60,
			ruleForm: {
				userName: '',
				code: '',
			},
			loading: {
				signIn: false,
			},
		});
		// 时间获取
		const currentTime = computed(() => {
			return formatAxis(new Date());
		});
		const sendSms = () => {
			proxy.$refs.loginForm
				.validate((valid: boolean) => {
					if (valid) {
						loginEmail(state.ruleForm)
							.then(async (res) => {
								console.log(res);
								const userInfos = res.data.userInfo;
								userInfos.avatar = proxy.getUpFileUrl(userInfos.avatar);
								// 存储 token 到浏览器缓存
								Session.set('token', res.data.token);
								// 存储用户信息到浏览器缓存
								Session.set('userInfo', userInfos);
								// 设置用户菜单
								Session.set('userMenu', res.data.menuList);
								// 设置按钮权限
								Session.set('permissions', res.data.permissions);
								// 1、请注意执行顺序(存储用户信息到vuex)
								await store.dispatch('userInfos/setUserInfos', userInfos);
								await store.dispatch('userInfos/setPermissions', res.data.permissions);
								if (!store.state.themeConfig.themeConfig.isRequestRoutes) {
									// 前端控制路由，2、请注意执行顺序
									await initFrontEndControlRoutes();
									signInSuccess();
								} else {
									// 模拟后端控制路由，isRequestRoutes 为 true，则开启后端控制路由
									// 添加完动态路由，再进行 router 跳转，否则可能报错 No match found for location with path "/"
									await initBackEndControlRoutes();
									// 执行完 initBackEndControlRoutes，再执行 signInSuccess
									signInSuccess();
								}
							})
							.catch(() => {
								state.loading.signIn = false;
							});
					}
				})
				.catch(() => {});
		};
		// 登录成功后的跳转
		const signInSuccess = () => {
			// 初始化登录成功时间问候语
			let currentTimeInfo = currentTime.value;
			// 登录成功，跳到转首页
			// 添加完动态路由，再进行 router 跳转，否则可能报错 No match found for location with path "/"
			// 如果是复制粘贴的路径，非首页/登录页，那么登录成功后重定向到对应的路径中
			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('/');
			}
			// 登录成功提示
			// 关闭 loading
			state.loading.signIn = false;
			const signInText = t('message.signInText');
			ElMessage.success(`${currentTimeInfo}，${signInText}`);
		};
		const smsCode = () => {
			// console.log(state.ruleForm);
			state.disabled = true;
			let timer = setInterval(function () {
				if (state.countDown > 0) {
					state.countDown--;
				} else {
					clearInterval(timer);
					state.disabled = false;
					state.countDown = 60;
				}
			}, 1000);
			emailCode(state.ruleForm).then((res) => {
				console.log(res);
			}).catch(()=>{
        clearInterval(timer);
        state.disabled = false;
        state.countDown = 60;
      });
		};
		return {
			sendSms,
			smsCode,
			...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-code {
		width: 100%;
		padding: 0;
	}

	.login-content-submit {
		width: 100%;
		letter-spacing: 2px;
		font-weight: 300;
		margin-top: 15px;
	}

	.login-msg {
		color: var(--el-text-color-placeholder);
	}
}
</style>
