<template>
	<div>
		<!-- 导航栏 -->
		<van-nav-bar>
			<!-- 左侧关闭按钮 -->
			<template #left>
				<van-icon name="cross" />
			</template>
		</van-nav-bar>

		<!-- 页面主体 -->
		<div class="page_container !bg-white relative">
			<!-- Logo -->
			<img class="logo" src="@assets/images/logo.png" alt="">

			<!-- 欢迎信息 -->
			<div class="welcom">嗨聊<span>HI.CHAT</span></div>

			<!-- 登录表单 -->
			<van-form @submit="onSubmit">
				<!-- 国家/地区选择（手机登录） -->
				<div class="list" @click="showAreaCode = true" v-if="!isByEmail">
					<div class="label">国家/地区</div>
					<div class="info">
						{{ formData.areaCode }}<van-icon name="arrow-down" />
					</div>
				</div>

				<!-- 手机号码输入框（手机登录） -->
				<div class="list" v-if="!isByEmail">
					<div class="label">{{ $t('cellphone') }}</div>
					<div class="info">
						<van-field class="!py-1 " clearable v-model="formData.phoneNumber" name="phoneNumber"
							type="number" :placeholder="$t('placeholder.inputPhoneNumber')" />
					</div>
				</div>

				<!-- 邮箱输入框（邮箱登录） -->
				<div class="list" v-if="isByEmail">
					<div class="label">{{ $t('email') }}</div>
					<div class="info">
						<van-field class="!py-1" clearable v-model="formData.email" name="email"
							:placeholder="$t('placeholder.inputEmail')" />
					</div>
				</div>

				<!-- 密码输入框（密码登录） -->
				<div class="list" v-if="isByPassword">
					<div class="label">{{ $t('password') }}</div>
					<div class="info">
						<van-field class="!py-1 " clearable v-model="formData.password" name="password" type="password"
							:placeholder="$t('placeholder.inputPassword')" />
					</div>
				</div>

				<!-- 验证码输入框（验证码登录） -->
				<div class="list" v-else>
					<div class="label">{{ $t('reAcquireDesc') }}</div>
					<div class="info">
						<van-field class="!py-1" clearable v-model="formData.verificationCode" name="verificationCode"
							type="text" :placeholder="$t('placeholder.inputVerificationCode')" />
						<!-- 重新发送验证码 -->
						<div class="yzm" @click="reSend" v-if="count <= 0">{{ $t('buttons.verificationCode') }}</div>
						<div class="yzm ed" v-else>{{ count }}S</div>
					</div>
				</div>

				<!-- 登录切换链接 -->
				<div class="links">
					<!-- 切换密码/验证码登录 -->
					<div @click="handisByPassword" class="link">
						{{ isByPassword ? $t('buttons.verificationCodeLogin') : $t('buttons.passwordLogin') }}
					</div>
					<!-- 切换手机/邮箱登录 -->
					<div @click="isByEmail = !isByEmail" class="link">
						{{ isByEmail ? $t('buttons.phoneNumberLogin') : $t('buttons.emailLogin') }}
					</div>
				</div>

				<!-- 提交按钮 -->
				<van-button :loading="loading" :disabled="
				  !(
				    (formData.phoneNumber || formData.email) &&
				    (formData.password || formData.verificationCode)
				  )
				" block type="primary" native-type="submit">
					{{ $t('buttons.login') }}
				</van-button>

			</van-form>

			<!-- 注册链接 -->
			<div class="tips">
				<span>{{ $t('notHaveAccount') }}</span>
				<div class="link" @click="getRegiste">{{ $t('nowRegister') }}</div>
			</div>

			<!-- 国家/地区选择弹出层 -->
			<van-popup v-model:show="showAreaCode" round position="bottom">
				<van-picker :columns="countryCode" @cancel="showAreaCode = false" @confirm="onConfirmAreaCode"
					:columns-field-names="{ text: 'phone_code', value: 'phone_code', children: 'children' }" />
			</van-popup>
			<van-action-sheet v-model:show="showActions" :actions="actions" @select="onSelect" />
		</div>
	</div>
</template>

<script setup lang='ts'>
	// 引入必要模块和工具函数
	import md5 from 'md5'; // MD5加密
	import type {
		PickerConfirmEventParams
	} from 'vant'; // 类型定义
	import {
		login,
		sendSms
	} from '@/api/login'; // 登录及发送验证码API
	import countryCode from '@/utils/areaCode'; // 国家区号
	import {
		feedbackToast
	} from '@/utils/common'; // 提示反馈工具
	import {
		setIMProfile
	} from '@/utils/storage'; // 本地存储
	import {
		UsedFor
	} from '@/api/data'; // 枚举类型

	// 国际化方法和路由
	const {
		t
	} = useI18n(); // 语言翻译
	const router = useRouter(); // 路由管理

	// 响应式数据
	const formData = reactive({
		phoneNumber: localStorage.getItem("IMAccount") ?? '', // 手机号从本地存储获取
		email: '',
		areaCode: '+86', // 默认国家区号
		password: '', // 密码
		verificationCode: '', // 验证码
		accept: true // 是否接受协议
	});
	const showActions = ref(false)
	const actions = ref < {
		idx: number;name: string
	} [] > ([])
	const loading = ref(false); // 加载状态
	const showAreaCode = ref(false); // 国家区号选择器显示状态
	const count = ref(0); // 验证码倒计时
	let timer: NodeJS.Timer; // 定时器
	const isByPassword = ref(false); // 是否使用密码登录
	const isByEmail = ref(false); // 是否使用邮箱登录
	const getRegiste = () => {
		// actions.value = [{
		// 		idx: 0,
		// 		name: t('buttons.emailRegiste')
		// 	},
		// 	{
		// 		idx: 1,
		// 		name: t('buttons.phoneNumberRegiste')
		// 	},
		// ]

		// showActions.value = true
		router.push('/register')
	}
	const onSelect = (item: {
		idx: number;name: string
	}) => {
		router.push({
			path: 'register',
			query: {
				isByEmail: item.idx === 0 ? true + '' : false + '',
			},
		})
	}
	// 表单提交处理
	// 表单提交处理
	const onSubmit = async () => {
		loading.value = true; // 开始加载
		localStorage.setItem("IMAccount", formData.phoneNumber); // 保存手机号到本地存储
		try {
			const {
				data: {
					chatToken,
					imToken,
					userID
				}
			} = await login({
				email: formData.email,
				phoneNumber: formData.phoneNumber,
				verifyCode: formData.verificationCode,
				password: formData.password ? md5(formData.password) : '', // 密码MD5加密
				areaCode: formData.areaCode
			});

			setIMProfile({
				chatToken,
				imToken,
				userID
			}); // 保存登录信息
			router.push('/conversation'); // 跳转到会话页面
		} catch (error) {
			// 错误码与提示消息的映射表
			const errorMessages: Record < number, string > = {
				1001: '区号必须为数字或不能为空，且密码或验证码必须设置',
				20002: '账户未注册，请先完成注册',
				20012: '当前IP地址禁止访问',
				20005: '验证码发送频率过高，请稍后再试',
				20006: '验证码不匹配，请重新输入',
				20007: '验证码错误或已过期',
				20008: '验证码发送已达最大次数',
				20009: '验证码已使用，请重新获取',
				20001: '密码错误，请检查后重新输入',
				20003: '手机号已注册，请更换手机号或直接登录',
				20004: '账号已注册，请更换账号或直接登录',
				20014: '邮箱已注册，请更换邮箱或直接登录',
				1505: 'Token 类型未知',
				500: '生成用户ID失败，请稍后重试',
			};

			// 将错误转换为包含 errCode 的类型
			const err = error as {
				errCode: number
			};

			// 根据 errCode 获取对应的消息
			const message = errorMessages[err.errCode] || '登录失败，请稍后再试'; // 默认提示文字

			feedbackToast({
				message,
				error: err,
			});
		}
		loading.value = false; // 结束加载
	};

	// 选择国家区号
	const onConfirmAreaCode = ({
		selectedValues
	}: PickerConfirmEventParams) => {
		formData.areaCode = String(selectedValues[0]); // 更新区号
		showAreaCode.value = false; // 关闭选择器
	};

	// 发送验证码
	const reSend = () => {
		if (count.value > 0) return; // 倒计时未结束时不允许再次发送
		sendSms({
				email: formData.email,
				phoneNumber: formData.phoneNumber,
				areaCode: formData.areaCode,
				usedFor: UsedFor.Login // 用于登录的短信
			})
			.then(startTimer) // 成功发送后开始倒计时
			.catch(error => feedbackToast({
				message: t('messageTip.sendCodeFailed'), // 验证码发送失败提示
				error
			}));
	};
	// 切换登录方式
	const handisByPassword = () => {
		formData.password = ''
		formData.phoneNumber = ''
		formData.email = ''
		isByPassword.value = !isByPassword.value
	};

	// 开始倒计时
	const startTimer = () => {
		if (timer) clearInterval(timer); // 清除之前的定时器
		count.value = 60; // 设置倒计时为60秒
		timer = setInterval(() => {
			if (count.value > 0) {
				count.value -= 1; // 每秒减1
			} else {
				clearInterval(timer); // 倒计时结束，清除定时器
			}
		}, 1000); // 每秒执行一次
	};
</script>

<style lang='scss' scoped>
	.page_container {
		background: #fff;
	}

	.van-nav-bar {
		border-bottom: 0.03rem solid #EFEFEF;

		.van-icon {
			font-size: 1.2rem;
			color: #282828;
		}
	}

	.page_container {
		align-items: center;
	}

	.logo {
		width: 5.2rem;
		height: 5.2rem;
		margin-top: 0.39rem;
	}

	.welcom {
		font-weight: 800;
		font-size: 1.43rem;
		color: #000000;
		margin-bottom: 1.9rem;

		span {
			font-weight: 500;
		}
	}

	.list {
		width: 20rem;
		height: 3.9rem;
		display: flex;
		align-items: center;
		justify-content: space-between;
		border-bottom: 0.03rem solid #EFEFEF;

		.label {
			width: 6.63rem;
			font-size: 1.1rem;
			color: #282828;
			flex-shrink: 0;
		}

		.info {
			width: 100%;
			display: flex;
			align-items: center;
			justify-content: space-between;

			.van-cell {
				padding: 0;
			}

			.yzm {
				width: 6.37rem;
				height: 2.08rem;
				border-radius: 1.04rem;
				font-size: 0.91rem;
				background: #02C25F;
				color: #fff;
				display: flex;
				align-items: center;
				justify-content: center;
				flex-shrink: 0;
			}

			.ed {
				background: #E1E1E1;
				color: #9B9B9B;
			}
		}
	}

	.links {
		width: 20rem;
		display: flex;
		align-items: center;
		justify-content: space-between;
		margin-top: 0.97rem;
		font-size: 1.1rem;
		color: #576B95;
	}

	.van-button {
		width: 11.7rem;
		height: 3.12rem;
		margin: 0 auto;
		margin-top: 5.78rem;
		font-size: 1.17rem;
	}

	.tips {
		position: absolute;
		left: 0;
		bottom: 0rem;
		font-size: 0.91rem;
		width: 100%;
		display: flex;
		align-items: center;
		justify-content: center;
		color: #282828;

		div {
			color: #576B95;
		}
	}
</style>