<!-- my/index.vue -->
<template>
	<view class="my-page">
		<!-- 你的页面内容 -->
		<div class="captcha-container" v-if="showCaptcha">
			<view class="input-item">
				<text class="label">手机号：</text>
				<input v-model="userTel" type="number" placeholder="请输入手机号" class="input" maxlength="11" />
			</view>

			<view id="your-dom-id" class="nc-container"></view>

			<view class="code-input">
				<input v-model="verification" type="number" placeholder="请输入验证码" class="code-input-field" />
				<button @click="checkVerification" class="code-btn">
					{{btnText}}
				</button>
			</view>

			<button @click="save()" class="verify-phone-btn">绑定手机号</button>
		</div>
	</view>
</template>

<script setup>
	import {
		ref,
		onMounted,
		onUnmounted
	} from 'vue'

	import {
		bindApplet,
		SendCode
	} from "@/api/login.js"
	import {
		toast
	} from '@/utils/common'
	import {
		onLoad,
		onShow
	} from '@dcloudio/uni-app';
	// 从URL参数中获取code
	const wxCode = ref('')
	const showCaptcha = ref(false)
	const userTel = ref('')
	const verification = ref('')
	const btnTextDisabled = ref(false)
	const btnText = ref('获取验证码')
	const countdown = ref(60)
	const isValidate = ref(false)
	const sliderData = ref({})
	const timer = ref(null)
	// 生命周期
	onLoad((options) => {
		// 获取URL中的code参数
		const queryCode = options.code
		console.log('接收到code参数:', queryCode)

		if (queryCode) {
			wxCode.value = queryCode
			showCaptcha.value = true
			// 页面加载完成后初始化验证码
			initCaptcha()
		} else {
			toast('参数错误，请重新登录')
		}
	})

	onUnmounted(() => {
		clearTimer()
	})




	// 初始化验证码
	function initCaptcha() {
		try {
			window.initAliyunCaptcha({
				SceneId: "1xp14eyl",
				mode: "embed",
				element: "#your-dom-id",
				success: function(captchaVerifyParam) {
					console.log('验证成功:', captchaVerifyParam);
					sliderData.value.param = captchaVerifyParam
					isValidate.value = true;
				},
				fail: function(result) {
					console.error('验证失败:', result);
					isValidate.value = false;
				},
				slideStyle: {
					width: 350,
					height: 40,
				},
				language: 'cn',
			});
		} catch (error) {
			console.error('初始化验证码失败:', error)
			toast('验证码初始化失败')
		}
	}

	// 获取验证码
	async function checkVerification() {
		if (!userTel.value) {
			toast('请输入手机号!')
			return false
		}

		// if (!/^1[3-9]\d{9}$/.test(userTel.value)) {
		// 	toast('请输入正确的手机号!')
		// 	return false
		// }

		if (isValidate.value) {
			try {
				const res = await SendCode({
					'param': sliderData.value.param,
					'phone': userTel.value,
					'sceneId': '1xp14eyl',
				})

				if (res.code === 0 && res.data) {
					setTime()
				} else {
					toast(res.msg || '发送失败')
				}
			} catch (error) {
				console.error('发送验证码失败:', error)
				isValidate.value = false
				initCaptcha()
				toast('发送失败，请重试')
			}
		} else {
			toast('请先完成滑块验证！')
			return false
		}
	}

	// 倒计时
	function setTime() {
		if (countdown.value === 0) {
			btnTextDisabled.value = false
			btnText.value = '获取验证码'
			countdown.value = 60
			isValidate.value = false
			initCaptcha()
		} else {
			btnTextDisabled.value = true
			btnText.value = countdown.value + 's'
			countdown.value--
			timer.value = setTimeout(() => {
				setTime()
			}, 1000)
		}
	}

	function clearTimer() {
		if (timer.value) {
			clearTimeout(timer.value)
			timer.value = null
		}
	}

	// 绑定手机号
	async function save() {
		if (!verification.value) {
			toast('请输入验证码')
			return
		}

		try {
			const params = {
				tel: userTel.value,
				code: verification.value,
				openId: wxCode.value // 传递微信的code
			}

			// 使用tijiao接口绑定手机号
			const response = await bindApplet(params)

			if (response.code === 0) {
				toast('绑定成功')

				uni.postMessage({
					data: {
						status: 'success',
						phone: userTel.value,
						captchaResult: sliderData.value.param,
						bindResult: response.data
					}
				})

				// 延迟返回
				setTimeout(() => {
					uni.navigateBack()
				}, 1000)
			} else {
				toast(response.msg || '绑定失败')
			}
		} catch (error) {
			console.error('绑定失败:', error)
			toast('绑定失败，请重试')
		}
	}
</script>

<style scoped>
	.my-page {
		padding: 30rpx;
	}

	.captcha-container {
		background: white;
		padding: 40rpx 30rpx;
		border-radius: 16rpx;
		box-shadow: 0 4rpx 24rpx rgba(0, 0, 0, 0.08);
	}

	.input-item {
		display: flex;
		align-items: center;
		margin-bottom: 30rpx;
	}

	.label {
		width: 150rpx;
		font-size: 28rpx;
		color: #333;
	}

	.input {
		flex: 1;
		height: 80rpx;
		padding: 0 20rpx;
		border: 1px solid #e5e5e5;
		border-radius: 8rpx;
		font-size: 28rpx;
	}

	.nc-container {
		margin: 30rpx 0;
		display: block !important;
	}

	.code-input {
		display: flex;
		align-items: center;
		height: 80rpx;
		margin-bottom: 30rpx;
		border: 1px solid #e5e5e5;
		border-radius: 8rpx;
		overflow: hidden;
	}

	.icon {
		width: 40rpx;
		height: 40rpx;
		margin: 0 20rpx;
	}

	.code-input-field {
		flex: 1;
		height: 100%;
		padding: 0 20rpx;
		font-size: 28rpx;
	}

	.code-btn {
		width: 200rpx;
		height: 100%;
		line-height: 80rpx;
		background-color: #17c05b;
		color: #fff;
		font-size: 26rpx;
		border: none;
		border-radius: 0;
	}

	.code-btn:disabled {
		background-color: #ccc;
	}

	.verify-phone-btn {
		width: 100%;
		height: 90rpx;
		line-height: 90rpx;
		background-color: #17c05b;
		color: #fff;
		font-size: 32rpx;
		border: none;
		border-radius: 45rpx;
	}
</style>