<template>
	<view class="my-tel-dialog">
		<view class="my-tel-content">
			<view class="tel-close" @click="telClose(AWSC)"></view>
			<view class="tel-row">
				<view class="my-tel-title">修改手机号</view>
				<view class="my-input-box">
					<input class="my-input" type="text" v-model="bindObj.telNumber" placeholder="请输入手机号" maxlength="11"
						@input="changeTelInput" />
					<view class="close-btn" v-if="bindObj.clearTelIcon" @click="clearTel"></view>
				</view>


				<captcha ref="captcha" :config="config" @captchaSuccess="captchaSuccess" @captchaError="captchaError"
					@captchaFail="captchaFail" @captchaReady="captchaReady" @captchaClose="captchaClose"></captcha>
				<view class="get-yzm-btn" @click="getYzmBtn" :class="{ 'get-yzm-disabled': bindObj.isDisabled}">
					{{bindObj.buttonText}}
				</view>


			</view>
			<view class="yzm-row">
				<view class="yzm-tip" v-if="bindObj.getYzmFlag">验证码已发送至：{{bindObj.telNumber}}</view>
				<view class="my-input-box">
					<input class="my-input" type="text" v-model="bindObj.yzmNumber" placeholder="请输入验证码" maxlength="6"
						@input="changeYzmInput" />
					<view class="close-btn" v-if="bindObj.clearYzmIcon" @click="clearYzm"></view>
				</view>
				<ezyActiveVue @aclick="bindBtn" class="ezy-btn-active my-bind-btn">绑定</ezyActiveVue>
			</view>

		</view>
	</view>
</template>
<script>
	import cacheManager from '@/utils/cacheManager.js';
	import captcha from "@/components/captcha4/index.vue";
	import ezyActiveVue from "@/components/ezyActive/ezyActive.vue";
	import {
		telBind,
		sendCode
	} from "@/api/login.js"
	import {
		toast
	} from "@/utils/common";
	export default {
		data() {
			return {
				myflag: 0,
				sliderObj: {
					sessionId: '',
					sig: '',
					token: '',
				},
				bindObj: {
					telNumber: '',
					clearTelIcon: false,
					yzmNumber: '',
					clearYzmIcon: false,
					/*** 验证码 ***/
					yzmStatus: 'login-btn-disabled',
					timeLeft: 60, // 初始倒计时时间（秒）
					intervalId: null, // 定时器ID
					isDisabled: true, // 按钮是否禁用
					buttonText: '获取验证码', // 按钮文本
					getYzmFlag: false, // 是否发送验证码
				},
				config: {
					captchaId: "9d5837b0807b8de44da0de310a0b2813",
				},
			}
		},
		components: {
			captcha,ezyActiveVue
		},
		methods: {
			telClose() {
				this.$emit('telClose')
			},

			// 清空手机号
			clearTel() {
				this.bindObj.telNumber = '';
				this.bindObj.isDisabled = true;
				this.bindObj.clearTelIcon = false;
				this.bindObj.getYzmFlag = false;
			},

			// 判断是否输入手机号
			changeTelInput(event) {
				if (event.detail.value.length > 0) {
					this.bindObj.clearTelIcon = true;
					this.validatePhoneNumber(event.detail.value);
				} else {
					this.bindObj.clearTelIcon = false;
				}
			},

			// 手机号校验规则
			validatePhoneNumber(value) {
				const phoneRegex = /^1[3-9]\d{9}$/;
				if (phoneRegex.test(value)) {
					// 通过
					this.bindObj.isDisabled = false;
				} else {
					// 不通过
					this.bindObj.isDisabled = true;
				}
			},
			// 获取验证码按钮
			getYzmBtn() {
				// 判断手机号校验是否通过
				if (this.bindObj.timeLeft != 60) {
					toast('请在' + this.bindObj.timeLeft + '后重新获取验证码！')
					return
				} else if (this.bindObj.isDisabled === true) {
					toast("请输入正确的手机号！")
					return
				} else {
				this.$refs.captcha.showCaptcha();
				}
			},

	captchaSuccess(result) { // app端的回调
				console.log(result)
				this.startCountdown();
				this.sliderData = result;
				this.getMessage();

			},
			captchaError(e) {
				// app端的回调
				toast(JSON.stringify(e))
			},
			captchaReady() {
				// app端的回调
			},
			captchaFail() {
				// app端的回调
				toast('验证失败！')
			},
			captchaClose() {
				// uni.redirectTo({
				// 	url: `/pages/login/index`
				// })
			},


			getMessage() {
				let req = {
				phone: this.bindObj.telNumber,
				captchaOutput: this.sliderData.captcha_output,
				genTime: this.sliderData.gen_time,
				lotNumber: this.sliderData.lot_number,
				passToken: this.sliderData.pass_token,
				}
				sendCode(req).then(res => {
					this.bindObj.getYzmFlag = true;
				}).catch(err => {
					this.bindObj.getYzmFlag = false;
					toast('验证码获取失败：' + err)
				})
			},

			// 清空验证码
			clearYzm() {
				this.bindObj.yzmNumber = '';
				this.bindObj.isDisabled = true;
				this.bindObj.clearYzmIcon = false;
			},

			// 判断是否输入验证码
			changeYzmInput(event) {
				if (event.detail.value.length > 0) {
					this.bindObj.clearYzmIcon = true;
				} else {
					this.bindObj.clearYzmIcon = false;
				}
			},

			// 开始计时
			startCountdown() {

				if (this.bindObj.buttonText === '重新发送') {
					this.sliderFlag = true;
				}
				this.bindObj.isDisabled = true;
				this.bindObj.buttonText = `重新发送（${this.bindObj.timeLeft}S）`;

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

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

			// 绑定按钮
			bindBtn() {
				if (this.bindObj.telNumber === '') {
					toast('手机号不能为空')
					return;
				}
				if (this.bindObj.yzmNumber === '') {
					toast('验证码不能为空')
					return;
				}

        if (this.bindObj.isDisabled) {
          toast('请输入正确的手机号！')
          return;
        }

				let req = {
					tel: this.bindObj.telNumber,
					code: this.bindObj.yzmNumber,
				}

				telBind(req).then(res => {
					if (res.code == 0) {
						toast('手机号绑定成功')
						this.updataTel(this.bindObj.telNumber);
						this.$emit('bindBtn')
					}
				})
			},

			// 在缓存中修改手机号
			updataTel(data) {
				cacheManager.updateObject('auth', {
					userName: data
				})
			}
		}
	}
</script>