<template>
	<uni-popup ref="dlRef" :animation="false" :is-mask-click="false" type="top" mask-background-color="rgba(255, 255, 255, 0.6);">
		<view class="ezy-login-page go-login-page">
			<view @click="handleBack" class="ezy-nav-bar-icon yzm-nav-bar-icon"></view>
			<icon class="login-img"></icon>
			<view class="login-body-box">
				<!-- 用户名 -->
				<view class="phone-input-box">
					<view class="phone-prefix">+86</view>
					<input class="phone-input" type="text" v-model="loginData.phoneNumber" placeholder="请输入手机号" maxlength="11"
						@input="clearTelInput" />
					<view class="close-btn" v-if="loginData.clearTelIcon" @click="clearTel"></view>
				</view>

				<!-- 验证码 -->
				<view class="yzm-row">
					<view class="phone-input-box">
						<input class="phone-input" type="text" v-model="loginData.yzmNumber" placeholder="请输入验证码" maxlength="4"
							@input="clearYzmInput" />
						<view class="close-btn" v-if="loginData.clearYzmIcon" @click="clearYzm"></view>
					</view>

					<text class="yzm-text-btn" @click="startCountdown">{{loginData.buttonText}}</text>
					<!-- <text class="cxfs-btn" @click="startCountdown"
						:class="{ 'cxfs-btn-disabled': loginData.isDisabled}">{{loginData.buttonText}}</text> -->
				</view>

				<!-- 隐私协议 -->
				<view class="agreement-checkbox-box">
					<checkbox-group @change="handleUpdateAgree">
						<checkbox class="agreement-checkbox-input" color="#FFFFFF" value="agree" :checked="isAgreed" />
					</checkbox-group>
					<view class="agreement-text-box">
						我已阅读并同意
						<view class="agreement-text" @click="agreeBtn('yhxy')">《用户协议》</view>
						和
						<view @click="agreeBtn('ystk')" class="agreement-text">《隐私政策》</view>
					</view>
				</view>
				<!-- 登录按钮 -->
				<ezyActiveVue class="ezy-btn-active login-btn yzm-btn" @aclick="handleLogin" :class="loginData.yzmStatus">登录
				</ezyActiveVue>
			</view>

		</view>
		</uni-popup>
		<!-- 政策协议 -->
		<agree-content-dialog ref="agreeContentDialogRef" :agreeType="agreeType"></agree-content-dialog>
		<!-- 图形验证码 -->
		<captchaVue ref="captcha" :config="config" @captchaSuccess="captchaSuccess" @captchaError="captchaError"
			@captchaFail="captchaFail" @captchaReady="captchaReady" @captchaClose="captchaClose"></captchaVue>
		<!-- 确认协议 -->
		<agree-dialog ref="agreeDialogRef" @confirm-btn="confirmBtn"></agree-dialog>

</template>

<script setup>
	import {
		ref,
		reactive,
		nextTick
	} from "vue"
	import {
		toast
	} from "@/utils/common";
	import {
		login,
    telBind,
		sendCode
	} from "@/api/login";
	import cacheManager from "@/utils/cacheManager";
	import agreeContentDialog from '@/pages/login/agreeContentDialog.vue';
	import agreeDialog from '@/pages/login/agreeDialog.vue'
	import captchaVue from "@/components/captcha4/index.vue";
	import ezyActiveVue from "@/components/ezyActive/ezyActive.vue"

	const emits = defineEmits(['success'])

	const dlRef = ref(null)
	const captcha = ref(null);
	const agreeType = ref(null);
	const agreeDialogRef = ref(null);
	const agreeContentDialogRef = ref(null);

	const isAgreed = ref(false);
	const config = ref({
		captchaId: "9d5837b0807b8de44da0de310a0b2813",
	});

	const loginData = reactive({
		phoneNumber: null,
		yzmNumber: null,
		clearYzmIcon: false,
		yzmStatus: 'login-btn-disabled',
		timeLeft: 60, // 初始倒计时时间（秒）
		intervalId: null, // 定时器ID
		isDisabled: false, // 按钮是否禁用
		buttonText: '获取验证码', // 按钮文本
	})

	const sliderData = reactive({})

	function showDl() {
		dlRef.value.open();
		loginData.buttonText = '获取验证码';
		clearInterval(loginData.intervalId);
		loginData.intervalId = null;
	}

	function closeDl() {
		clearInterval(loginData.intervalId);
		loginData.intervalId = null;
		loginData.phoneNumber = null;
		loginData.yzmNumber = null;
		loginData.clearYzmIcon = false;
		loginData.yzmStatus = 'login-btn-disabled';
		loginData.timeLeft = 60;
		loginData.intervalId = null;
		loginData.isDisabled = false;
		loginData.buttonText = '获取验证码';
		config.value = null;
		isAgreed.value = false;
		dlRef.value.close();
	}

	// 返回
	function handleBack() {
		closeDl();
	}

	// 手机号校验规则
	const validatePhoneNumber = (value) => {
		const phoneRegex = /^1[3-9]\d{9}$/;
		if (phoneRegex.test(value)) {
			loginData.telStatus = 'login-btn-normal';
		} else {
			loginData.telStatus = 'login-btn-disabled';
		}
	}

	const validatePhone = (value) => {
		const phoneRegex = /^1[3-9]\d{9}$/;
		return phoneRegex.test(value)
	}

	function clearTelInput(event) {
		if (event.detail.value.length > 0) {
			loginData.clearTelIcon = true;
			validatePhoneNumber(event.detail.value);
		} else {
			loginData.clearTelIcon = false;
		}
	}

	function clearTel() {
		loginData.phoneNumber = '';
		loginData.telStatus = 'login-btn-disabled';
		loginData.clearTelIcon = false;
	}

	function clearYzmInput(event) {
		if (event.detail.value.length > 0) {
			loginData.clearYzmIcon = true;
			loginData.yzmStatus = 'login-btn-normal';
		} else {
			loginData.clearYzmIcon = false;
			loginData.yzmStatus = 'login-btn-disabled';
		}
	}

	function clearYzm() {
		this.loginData.yzmNumber = '';
		this.loginData.yzmStatus = 'login-btn-disabled';
		this.loginData.clearYzmIcon = false;
	}


	// 登录
	function handleLogin() {
		// 用户名
		if (!loginData.phoneNumber) {
			toast('请输入手机号')
			return;
		}
		// 正确手机号
		if (!validatePhone(loginData.phoneNumber)) {
			toast('请输入正确手机号')
			return;
		}
		// 验证码
		if (!loginData.yzmNumber) {
			toast('请输入验证码')
			return;
		}
		// 协议
		if (!isAgreed.value) {
			agreeDialogRef.value.handleShow()
			return;
		}
		let req = {
			tel: loginData.phoneNumber,
			code: loginData.yzmNumber,
		}
    login(req).then(res => {
			if (res.code == 0 && res.data) {
				cacheManager.clearAll();
				nextTick(() => {
					cacheManager.set('auth', res.data)
					// 返回重新支付
					handleBack();
					emits('success',  res.data)
				})
			}
		})
	}

	// 更新协议
	function handleUpdateAgree() {
		isAgreed.value = !isAgreed.value
	}

	// 协议跳转
	function agreeBtn(data) {
		agreeType.value = data;
		agreeContentDialogRef.value.handleShow();
	}

	function confirmBtn() {
		isAgreed.value = true;
		handleLogin();
	}

	// 图形验证码
	function showCaptcha() {
		captcha.value.showCaptcha();
	}

	function startCountdown() {

		if (!loginData.phoneNumber) {
			toast('请输入手机号')
			return;
		}

		if (loginData.buttonText === '重新发送' ||loginData.buttonText ===  '获取验证码') {
			showCaptcha();
			return;
		}
		loginData.isDisabled = true;
		loginData.buttonText = `（${loginData.timeLeft}S）`;

		// 清除之前的定时器（如果有）
		if (loginData.intervalId) {
			clearInterval(loginData.intervalId);
			loginData.intervalId = null;
		}

		// 设置新的定时器
		loginData.intervalId = setInterval(() => {
			loginData.timeLeft--;
			if (loginData.timeLeft <= 0) {
				clearInterval(loginData.intervalId);
				loginData.intervalId = null;
				loginData.timeLeft = 60; // 重置倒计时
				loginData.isDisabled = false;
				loginData.buttonText = '重新发送';
			} else {
				loginData.buttonText = `（${loginData.timeLeft}S）`;
			}
		}, 1000);
	}

	function getYzmBtn() {
		let req = {
			phone: loginData.phoneNumber,
			captchaOutput: sliderData.captcha_output,
			genTime: sliderData.gen_time,
			lotNumber: sliderData.lot_number,
			passToken: sliderData.pass_token,
		}
		sendCode(req).then(res => {}).catch(err => {
			loginData.buttonText = '重新发送';
			loginData.timeLeft = 60;
			clearInterval(loginData.intervalId);
			loginData.intervalId = null;
		})
	}

	function captchaSuccess(result) {
		loginData.buttonText = `（${loginData.timeLeft}S）`;
		startCountdown();
		Object.assign(sliderData, result)

		getYzmBtn();
	}

	function captchaError(e) {
		toast(JSON.stringify(e))
	}

	function captchaFail() {
		toast('验证失败！')
	}

	function captchaReady() {}

	function captchaClose() {}

	defineExpose({
		showDl
	})
</script>

<style>
</style>
