<template>
	<div>
		<!-- 导航栏，左侧返回按钮 -->
		<van-nav-bar>
			<template #left>
				<router-link :to="{ path:'/login' }"><van-icon name="cross" /></router-link>
			</template>
		</van-nav-bar>

		<!-- 页面主体容器，设置背景为白色 -->
		<div class="page_container !bg-white relative">
			<img class="logo" src="@assets/images/logo.png" alt="Logo">
			<div class="welcom">嗨聊 <span>HI.CHAT</span></div>

			<!-- 表单提交 -->
			<van-form @submit="onSubmit">
				<!-- 昵称输入框 -->
				<div class="list">
					<div class="label">{{ $t('name') }}</div>
					<div class="info">
						<van-field class="!py-1" clearable v-model="baseInfo.nickname" name="nickname" type="text"
							:placeholder="$t('placeholder.inputNickname')" />
					</div>
				</div>

				<!-- 国家/地区选择 -->
				<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">
					<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">
					<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">
					<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="list">
					<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="tips">
					<van-checkbox v-model="checked"></van-checkbox> 我已阅读并同意 <a
						href="https://changliaoadmin.app12345.cn/contnent">《软件许可及服务协议》</a> 本页收集的信息仅用于注册账号
				</div>

				<!-- 提交按钮，只有勾选了服务协议才可以提交 -->
				<van-button :loading="loading" :disabled="!checked || !validateForm()" block type="success"
					native-type="submit">
					同意并继续
				</van-button>
			</van-form>

			<!-- 国家/地区选择弹窗 -->
			<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>
		</div>
	</div>
</template>

<script setup lang='ts'>
	// 导入需要的库和函数
	import md5 from 'md5';
	import type {
		PickerConfirmEventParams
	} from 'vant';
	import {
		register,
		sendSms
	} from '@/api/login';
	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 props = defineProps < {
		isByEmail: boolean
	} > ()
	const isByEmail = props.isByEmail; // 是否使用邮箱注册
	const checked = ref(false); // 是否勾选服务协议
	const loading = ref(false); // 是否显示加载动画
	const showAreaCode = ref(false); // 是否显示国家/地区选择弹窗
	const count = ref(0); // 倒计时
	let timer: NodeJS.Timer; // 定时器

	// 定义表单数据
	const formData = reactive({
		nickname: '',
		email: '',
		phoneNumber: '',
		areaCode: '+86',
		password: '',
		verificationCode: '123456',
		accept: true
	});
	const baseInfo = reactive({
		faceURL: '',
		nickname: '',
		password: '',
		confirmPassword: '',
		gender: 0,
		birth: 0,
	});

	// 表单提交时的处理逻辑
	const onSubmit = async () => {
		loading.value = true;

		// 验证密码的长度和复杂性
		const passwordPattern = /^(?=.*[a-zA-Z])(?=.*\d)[a-zA-Z\d]{6,20}$/;
		if (!passwordPattern.test(formData.password)) {
			feedbackToast({
				message: "请输入6-20位密码，至少包含数字加字母",
			});
			loading.value = false;
			return;
		}

		localStorage.setItem("IMAccount", formData.phoneNumber); // 将手机号存入本地存储

		// 提交注册请求
		try {
			const {
				data: {
					userID
				}
			} = await register({
				verifyCode: formData.verificationCode,
				deviceID: '',
				user: {
					...baseInfo,
					phoneNumber: formData.phoneNumber,
					email: formData.email,
					password: md5(formData.password),
					areaCode: formData.areaCode
				},
			});
			setIMProfile({
				userID
			}); // 设置用户IM资料
			feedbackToast({
				message: t("注册成功"),
				onClose: () => router.push('login'),
			});
			router.push('login'); // 注册成功后跳转至登录页面
		} catch (error) {

			const errorMessages: Record < number, string > = {
				1001: '昵称为空、平台无效或用户信息不完整，请检查输入',
				1002: '仅管理员可以设置用户ID',
				20003: '手机号已注册，请更换手机号或直接登录',
				20004: '账号已注册，请更换账号或直接登录',
				20014: '邮箱已注册，请更换邮箱或直接登录',
				500: '验证码功能未启用，请联系管理员',
				20005: '验证码发送频率过高，请稍后再试',
				20006: '验证码不匹配，请重新输入',
				20007: '验证码错误或已过期',
				20008: '验证码发送已达最大次数',
				20009: '验证码已使用，请重新获取',
				20012: '当前访问被禁止，请稍后再试',
			};

			const additionalMessages: Record < string, string > = {
				"Nickname is nil": "昵称不能为空",
				"platform is invalid": "无效的平台信息",
				"user is nil": "用户信息缺失",
				"user is empty": "用户信息为空",
				"PhoneNumber and Email is empty": "手机号和邮箱不能为空",
				"PhoneNumber and Email is not empty": "手机号和邮箱不能同时填写",
				"Email is invalid": "邮箱地址格式无效",
				"AreaCode is empty": "区号不能为空",
				"invalid AreaCode": "区号无效",
				"phoneNumber is empty": "手机号不能为空",
				"phoneNumber is invalid": "手机号格式无效",
				"area code must be number": "区号必须是数字",
				"area code or phone number is empty": "区号或手机号不能为空",
				"phone number must be number": "手机号必须是数字",
				"area code or phone number error, no email provide": "区号或手机号有误，且未提供邮箱",
				"phone already register": "手机号已被注册",
				"email must be right": "请输入正确的邮箱地址",
				"email already register": "邮箱已被注册",
				"verify code is empty": "验证码不能为空",
				"appoint user id already register": "指定的用户ID已注册",
				"email verification code is not enabled": "邮箱验证码功能未启用",
				"mobile phone verification code is not enabled": "手机验证码功能未启用",
				"Forbidden": "当前访问被禁止，请稍后再试",
				"used unknown": "未知错误，请稍后重试",
			};

			// 解析错误信息
			const err = error as {
				errCode ? : number;
				errMsg ? : string;
				errDlt ? : string;
			};

			let message = '请求失败，请稍后再试'; // 默认提示

			// 提取 `errCode` 并匹配错误提示
			if (err.errCode !== undefined) {
				message = errorMessages[err.errCode] || message;
			}

			// 提取 `errMsg` 并匹配附加说明
			if (err.errMsg) {
				const matchedKey = Object.keys(additionalMessages).find((key) =>
					err.errMsg && err.errMsg.includes(key)
				);
				if (matchedKey) {
					message += `，${additionalMessages[matchedKey]}`;
				}
			}

			// 如果 `errDlt` 提供了额外信息，也可以解析
			if (err.errDlt) {
				const parts = err.errDlt.split(':');
				const errCode = parseInt(parts[0], 10);
				if (!isNaN(errCode) && errorMessages[errCode]) {
					message = errorMessages[errCode];
				}
				const errDetailMsg = parts[1]?.trim();
				if (errDetailMsg && additionalMessages[errDetailMsg]) {
					message += `，${additionalMessages[errDetailMsg]}`;
				}
			}

			// 显示提示信息
			feedbackToast({
				message,
				error: err,
			});
		}

		loading.value = false;
	};


	// 验证表单内容是否完整
	const validateForm = () => {
		// 检查手机号、验证码、密码是否为空
		if (formData.phoneNumber) {
			return baseInfo.nickname && formData.phoneNumber && formData.verificationCode && formData.password;
		} else {
			return baseInfo.nickname && formData.email && formData.verificationCode && formData.password;
		}

	};

	// 选择国家/地区代码后的处理逻辑
	const onConfirmAreaCode = ({
		selectedValues
	}: PickerConfirmEventParams) => {
		formData.areaCode = String(selectedValues[0]);
		showAreaCode.value = false;
	};

	// 发送验证码
	const reSend = () => {
		if (count.value > 0) return; // 倒计时未结束前不允许再次发送
		sendSms({
				phoneNumber: formData.phoneNumber,
				email: formData.email,
				areaCode: formData.areaCode,
				usedFor: UsedFor.Register
			})
			.then(startTimer)
			.catch(error => feedbackToast({
				message: t('messageTip.sendCodeFailed'),
				error
			}));
	};

	// 启动验证码倒计时
	const startTimer = () => {
		if (timer) {
			clearInterval(timer);
		}
		count.value = 60; // 初始化倒计时为60秒
		timer = setInterval(() => {
			if (count.value > 0) {
				count.value -= 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: 22.42rem;
		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: 22.42rem;
		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: 1.78rem;
		font-size: 1.17rem;
	}

	.tips {
		display: flex;
		align-items: center;
		justify-content: center;
		flex-wrap: wrap;
		width: 16rem;
		margin: 0 auto;
		font-size: 0.78rem;
		color: #B6B6B6;
		text-align: center;
		margin-top: 7rem;

		a {
			color: #576B95;
		}

		.van-checkbox {
			margin-right: 0.2rem;
		}
	}
</style>