<!-- 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
	} from 'vue'
	import {
		bindApplet,
		SendCode
	} from "@/api/login.js"
	import {
		toast
	} from '@/utils/common'
	import {
		onLoad
	} from '@dcloudio/uni-app';

	// 数据
	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(async (options) => {
		// 先动态加载 uni.webview SDK
		await loadUniSDK()

		const queryCode = options.code
		if (queryCode) {
			wxCode.value = queryCode
			showCaptcha.value = true
			initCaptcha()
		} else {
			toast('参数错误，请重新登录')
		}
	})

	// 加载 uni.webview SDK
	function loadUniSDK() {
		return new Promise((resolve) => {
			// 如果已经存在，直接返回
			if (window.uni && window.uni.postMessage) {
				console.log('uni SDK 已存在')
				resolve()
				return
			}

			// 动态创建 script 标签加载
			const script = document.createElement('script')
			script.src = 'https://www.chengxiangjiaoyu.com/uni.webview.1.5.6.js'
			script.onload = () => {
				console.log('uni.webview SDK 加载成功')
				console.log('window.uni:', window.uni)
				resolve()
			}
			script.onerror = () => {
				console.error('uni.webview SDK 加载失败')
				resolve()
			}
			document.head.appendChild(script)
		})
	}

	// 初始化验证码
	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 (!isValidate.value) {
			toast('请先完成滑块验证！')
			return false
		}

		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('发送失败，请重试')
		}
	}

	// 倒计时
	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
			}

			const response = await bindApplet(params)

			if (response.code == 0) {
				uni.postMessage({
					data: {
						status: 'success',
						phone: userTel.value,
						captchaResult: sliderData.value.param,
						bindResult: response.data
					}
				})
				setTimeout(() => {
					uni.navigateBack({
						delta: 1
					});
				}, 1000)
				toast('绑定成功1')·
				toast('uni.navigateBack()失败')
			} else {
				toast(response.msg || '绑定失败')
			}
		} catch (error) {
			console.error('绑定失败:', error)
			toast('绑定失败，请重试', error)
		}
	}
</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;
	}

	.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>