<template>
	<uni-popup ref="dlRef" :animation="true" :is-mask-click="false" mask-background-color="rgba(255, 255, 255, 0.6);">
		<!-- 返回 -->
		<view class="icon-title-navBar-box333">
			<view @click="handleBack" class="nav-bar-icon"></view>
			<text @click="handleBack" class="nav-bar-title">绑定手机号</text>
		</view>
		<!-- 用户名 -->
		<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="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>

			<text class="cxfs-btn" @click="startCountdown"
				:class="{ 'cxfs-btn-disabled': loginData.isDisabled}">{{loginData.buttonText}}</text>
		</view>
		<!-- 登录按钮 -->
		<ezyActiveVue class="ezy-btn-active login-btn yzm-btn" @aclick="skipFun" :class="loginData.yzmStatus">跳过
		</ezyActiveVue>
		<ezyActiveVue class="ezy-btn-active login-btn yzm-btn" @aclick="bangdingFun" :class="loginData.yzmStatus">绑定
		</ezyActiveVue>


	</uni-popup>
	<!-- 图形验证码 -->
	<captchaVue ref="captcha" :config="config" @captchaSuccess="captchaSuccess" @captchaError="captchaError"
		@captchaFail="captchaFail" @captchaReady="captchaReady" @captchaClose="captchaClose"></captchaVue>
</template>

<script setup>
	import {
		ref,
		reactive
	} 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,
		clearTelIcon: false,
		yzmStatus: 'login-btn-disabled',
		timeLeft: 60, // 初始倒计时时间（秒）
		intervalId: null, // 定时器ID
		isDisabled: false, // 按钮是否禁用
		buttonText: '获取验证码', // 按钮文本
	})

	const sliderData = reactive({})

	function showDl() {
		dlRef.value.open('bottom');
	}

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

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

	function skipFun() {
		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() {
		loginData.yzmNumber = '';
		loginData.yzmStatus = 'login-btn-disabled';
		loginData.clearYzmIcon = false;
	}


	// 登录
	function bangdingFun() {
		// 用户名
		if (!loginData.phoneNumber) {
			toast('请输入手机号')
			return;
		}
		// 正确手机号
		if (!validatePhone(loginData.phoneNumber)) {
			toast('请输入正确手机号')
			return;
		}
		// 验证码
		if (!loginData.yzmNumber) {
			toast('请输入验证码')
			return;
		}

		let req = {
			tel: loginData.phoneNumber,
			code: loginData.yzmNumber,
		}
		console.log('req', req);
		telBind(req).then(res => {
			if (res.code == 0) {
				// 更新用户信息
				//	cacheManager.set('auth', res.data)
				// 返回重新支付
				handleBack();
				emits('success', res.data)
			}
		})
	}




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

	function startCountdown() {
		console.log('config', config.value);
		if (!loginData.phoneNumber) {
			toast('请输入手机号')
			return;
		}

		if (loginData.buttonText === '重新发送' || loginData.buttonText === '获取验证码') {
			showCaptcha();
			return;
		}
		runCountdown()

	}

	function runCountdown() {
		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 => {})
	}

	function captchaSuccess(result) {
		Object.assign(sliderData, result)
		getYzmBtn();
		runCountdown()
	}

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

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

	function captchaReady() {}

	function captchaClose() {}

	defineExpose({
		showDl
	})
</script>

<style>
</style>