<template>
	<view class="bind-tel-page">
		<!-- 返回 -->
		<view class="icon-title-navBar-box">
			<view @click="handleBack" class="nav-bar-icon"></view>
			<view class="nav-bar-title">绑定手机号</view>
		</view>
		<view class="ezy-page-body bind-tel-body">
			<!-- 手机号 -->
			<view class="tel-input">
				<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="tel-input">
					<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-btn" @click="startCountdown"
					:class="{ 'cxfs-btn-disabled': loginData.isDisabled}">{{loginData.buttonText}}</text>
			</view>
			<ezyActiveVue class="ezy-btn-active login-btn bd-btn" @aclick="bangdingFun" :class="loginData.yzmStatus">
				确认绑定
			</ezyActiveVue>
		</view>
		<!-- 图形验证码 -->
		<captchaVue ref="captcha" :config="config" @captchaSuccess="captchaSuccess" @captchaError="captchaError"
			@captchaFail="captchaFail" @captchaReady="captchaReady" @captchaClose="captchaClose"></captchaVue>
	</view>
</template>

<script setup>
	import {
		ref,
		reactive
	} from "vue"
	import {
		toast
	} from "@/utils/common";
	import {
		onLoad,
		onShow
	} from '@dcloudio/uni-app';
	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 from = ref('');
	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 props = defineProps({
		skipBtnFlag: {
			type: Boolean,
			default: true
		},
		openFangshi: {
			type: String,
			default: 'bottom'
		},
	})
	const sliderData = reactive({})

	function showDl() {
		dlRef.value.open(props.openFangshi);
	}

	onLoad((options) => {
		console.log('options', options);
		from.value = options.from
	})

	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;
		if (from.value = 'my') {


			uni.switchTab({
				url: "/pages/chanpinMy/my"
			})
		} else if (from.value = 'order') {
			uni.navigateTo({
				url: '/pages/chanpinMy/order'
			})
		} else {
			uni.switchTab({
				url: "/pages/chanpinMy/my"
			})
		}

	}

	// 返回
	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() {
		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)
				// 返回重新支付
				//绑定成功后更新缓存
				cacheManager.updateObject('auth', {
					userName: loginData.phoneNumber
				})
				handleBack();
				toast("绑定成功")
			}
		})
	}




	// 图形验证码
	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() {}
</script>

<style>
</style>