<template>
	<el-form size="large" class="login-content-form" :rules="state.rules">
		<el-form-item class="login-animation-one">
			<el-input type="text" placeholder="输入手机号或用户名" v-model="state.ruleForm.username" clearable autocomplete="off"
				:readonly="state.loading">
			</el-input>
		</el-form-item>
		<el-form-item class="login-animation-three">
			<el-button :loading="state.loading" type="primary" :disabled="state.loading" class="login-content-submit"
				@click="handleNopassLogin">
				<span>免密登录</span>
			</el-button>
		</el-form-item>
	</el-form>
</template>

<script setup lang="ts">
import { reactive, computed, getCurrentInstance } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { signInByCode } from '@/api/login';
import { ElMessage } from 'element-plus';
import { initBackEndControlRoutes } from '@/router/index';
import Cookies from 'js-cookie';
import { formatAxis } from '@/utils/formatTime';
import { useI18n } from 'vue-i18n';

const { t } = useI18n();
const { proxy } = getCurrentInstance() as any;
const BASE_URL = import.meta.env.VITE_API_URL;
const route = useRoute();
const router = useRouter();
const state = reactive({
	ruleForm: {
		username: '',
	},
	rules: {
		username: [{ required: true, message: '请输入', trigger: 'blur' }],
	},
	STATUS_ID: null as any,
	loading: false as boolean,
});
// 时间获取
const currentTime = computed(() => {
	return formatAxis(new Date());
});
// 登录成功后的跳转
const signInSuccess = () => {
	// 初始化登录成功时间问候语
	let currentTimeInfo = currentTime.value;
		// 登录成功，跳到转首页
		// 添加完动态路由，再进行 router 跳转，否则可能报错 No match found for location with path "/"
		// 如果是复制粘贴的路径，非首页/登录页，那么登录成功后重定向到对应的路径中
		if (route.query.redirect) {
			router.push({
				path: route.query?.redirect,
				query: Object.keys(route.query?.params).length > 0 ? JSON.parse(route.query?.params) : '',
			});
		} else {
			router.push('/');
		}
	//登录成功提示
	setTimeout(() => {
		const signInText = t('message.signInText');
		ElMessage.success(`${currentTimeInfo}，${signInText}`);
		// 修复防止退出登录再进入界面时，需要刷新样式才生效的问题，初始化布局样式等(登录的时候触发，目前方案)
		proxy.mittBus.emit('onSignInClick');
	}, 300);
};

const handleNopassLogin = () => {
	if(!state.ruleForm.username) return

	state.loading = true;
	signInByCode(state.ruleForm.username).then((res) => {
		if (res.status == 0) {
			if (res.data.type == 'ding') {
				ElMessage.success('请在云上开投进行确认登录');
			} else {
				ElMessage.success('请在手机短信进行确认登录');
			}
			const eventSource = new EventSource(`/subscribe?token=${res.data.code}`);
			// 处理自定义事件
			eventSource.addEventListener('login', async (event) => {
				const customData = JSON.parse(event.data);
				if (customData) {
					localStorage.setItem('expire', customData.expire);
					Cookies.set('username', customData.username);
					await fetch(`/api/user/oauth/secret/${customData.secret}`)
					await initBackEndControlRoutes();
					signInSuccess();
					state.loading = false;
				}
			});
		} else {
			state.loading = false;
			ElMessage.error(res.msg);
		}
	}).catch((err) => {
		state.loading = false;
	})
};
</script>

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

	.login-animation-one,
	.login-animation-two,
	.login-animation-three,
	.login-animation-four {
		opacity: 0;
		animation-name: error-num;
		animation-duration: 0.5s;
		animation-fill-mode: forwards;
	}

	.login-animation-one {
		animation-delay: 0.1s;
	}

	.login-animation-two {
		animation-delay: 0.2s;
	}

	.login-animation-three {
		animation-delay: 0.3s;
		margin-bottom: 5px;
	}

	.login-animation-four {
		animation-delay: 0.4s;
	}

	.login-content-code {
		padding: 0 20px !important;
		width: max-content;
		padding: 0;
	}

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