<template>
	<view class="bind-container">
		<!-- 页面头部 -->
		<view class="bind-header">
			<view class="back-btn" @click="handleBack">
				<text class="back-icon">‹</text>
				<text class="back-text">返回</text>
			</view>
			<text class="bind-title">绑定账号</text>
			<view class="placeholder"></view>
		</view>

		<!-- 绑定说明 -->
		<view class="bind-tips">
			<view class="tips-icon">💡</view>
			<text class="tips-text">首次使用微信登录，请绑定已有账号或注册新账号</text>
		</view>

		<!-- 绑定表单 -->
		<view class="bind-form">
			<!-- 账号输入 -->
			<view class="form-item">
				<text class="label">账号</text>
				<input 
					v-model="bindForm.username" 
					class="input" 
					placeholder="请输入用户名/手机号/邮箱"
					placeholder-class="placeholder"
					:focus="true"
				/>
			</view>

			<!-- 密码输入 -->
			<view class="form-item">
				<text class="label">密码</text>
				<input 
					v-model="bindForm.password" 
					class="input" 
					password 
					placeholder="请输入密码"
					placeholder-class="placeholder"
					@confirm="handleBind"
				/>
			</view>

			<!-- 验证码 -->
			<view class="form-item" v-if="showCaptcha">
				<text class="label">验证码</text>
				<view class="captcha-input">
					<input 
						v-model="bindForm.code" 
						class="input" 
						placeholder="请输入验证码"
						placeholder-class="placeholder"
					/>
					<image 
						:src="bindForm.captchaImg" 
						class="captcha-img" 
						@click="getCaptcha" 
						mode="aspectFit"
					></image>
				</view>
			</view>

			<!-- 绑定按钮 -->
			<button class="bind-btn" @click="handleBind" :disabled="binding">
				{{ binding ? '绑定中...' : '立即绑定' }}
			</button>

			<!-- 注册链接 -->
			<view class="register-section">
				<text class="register-text">还没有账号?</text>
				<text class="register-link" @click="goRegister">立即注册</text>
			</view>
		</view>

		<!-- 绑定成功弹窗 -->
		<view class="success-modal" v-if="showSuccessModal">
			<view class="modal-mask" @click="hideSuccessModal"></view>
			<view class="modal-content">
				<view class="success-icon">✓</view>
				<text class="success-title">绑定成功</text>
				<text class="success-desc">微信账号已成功绑定</text>
				<button class="confirm-btn" @click="handleConfirmSuccess">确定</button>
			</view>
		</view>
	</view>
</template>

<script setup>
	import { ref, reactive, onMounted } from 'vue'
	import { onLoad } from '@dcloudio/uni-app'
	import modal from '@/plugins/modal'
	import { getCodeImg } from '@/api/login'
	import { bindWechatAccount } from '@/api/oauth'
	import useUserStore from '@/store/modules/user'
	import { setToken } from '@/utils/auth'

	const userStore = useUserStore()

	// 路由参数
	const routeParams = ref({})

	// 响应式数据
	const binding = ref(false)
	const showCaptcha = ref(false)
	const showSuccessModal = ref(false)

	// 绑定表单
	const bindForm = reactive({
		username: '',
		password: '',
		code: '',
		captchaImg: '',
		uuid: ''
	})

	// 页面加载
	onLoad((options) => {
		console.log('绑定页面参数:', options)
		routeParams.value = options || {}
		
		// 如果有微信登录信息，可以在这里处理
		if (options.source || options.code) {
			console.log('微信登录信息:', {
				source: options.source,
				code: options.code
			})
		}
	})

	// 返回上一页
	const handleBack = () => {
		uni.navigateBack()
	}

	// 获取验证码
	const getCaptcha = async () => {
		try {
			const res = await getCodeImg()
			bindForm.captchaImg = 'data:image/gif;base64,' + res.img
			bindForm.uuid = res.uuid
			showCaptcha.value = true
		} catch (error) {
			modal.alert('验证码获取失败')
		}
	}

	// 处理绑定
	const handleBind = async () => {
		// 表单验证
		if (!bindForm.username.trim()) {
			modal.alert('请输入账号')
			return
		}

		if (!bindForm.password.trim()) {
			modal.alert('请输入密码')
			return
		}

		if (showCaptcha.value && !bindForm.code.trim()) {
			modal.alert('请输入验证码')
			return
		}

		binding.value = true

		try {
			// 准备绑定参数
			const bindParams = {
				username: bindForm.username,
				password: bindForm.password,
				source: routeParams.value.source || 'miniapp', // 默认小程序
				code: routeParams.value.code || '' // 微信授权code
			}

			// 如果需要验证码
			if (showCaptcha.value) {
				bindParams.code = bindForm.code
				bindParams.uuid = bindForm.uuid
			}

			console.log('绑定参数:', bindParams)

			// 调用绑定接口
			const res = await wxRegister(bindParams)

			if (res.token) {
				// 绑定成功，保存token并获取用户信息
				setToken(res.token)
				await userStore.getInfo()
				
				// 显示成功提示
				showSuccessModal.value = true
			} else {
				modal.alert(res.message || '绑定失败')
			}
		} catch (error) {
			console.error('绑定失败:', error)
			
			// 处理不同的错误情况
			if (error.code === 401 || error.message?.includes('验证码')) {
				// 需要验证码
				getCaptcha()
				modal.alert('请输入验证码')
			} else if (error.code === 400) {
				// 账号密码错误
				modal.alert('账号或密码错误')
			} else if (error.code === 409) {
				// 微信账号已绑定其他账号
				modal.alert('该微信账号已绑定其他账号')
			} else {
				modal.alert(error.message || '绑定失败，请重试')
			}
		} finally {
			binding.value = false
		}
	}

	// 跳转注册页面
	const goRegister = () => {
		uni.navigateTo({
			url: '/pages_system/pages/register/index'
		})
	}

	// 隐藏成功弹窗
	const hideSuccessModal = () => {
		showSuccessModal.value = false
	}

	// 确认绑定成功
	const handleConfirmSuccess = () => {
		showSuccessModal.value = false
		
		// 跳转到首页
		uni.switchTab({
			url: '/pages/index'
		})
	}

	// 生命周期
	onMounted(() => {
		// 可以在这里初始化一些数据
	})
</script>

<style scoped>
	.bind-container {
		min-height: 100vh;
		background: #f5f5f5;
	}

	/* 头部样式 */
	.bind-header {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 40rpx 30rpx;
		background: #fff;
		border-bottom: 1rpx solid #e0e0e0;
	}

	.back-btn {
		display: flex;
		align-items: center;
		padding: 10rpx 0;
	}

	.back-icon {
		font-size: 48rpx;
		color: #333;
		margin-right: 10rpx;
	}

	.back-text {
		font-size: 28rpx;
		color: #333;
	}

	.bind-title {
		font-size: 36rpx;
		color: #333;
		font-weight: bold;
		flex: 1;
		text-align: center;
	}

	.placeholder {
		width: 120rpx;
	}

	/* 提示信息 */
	.bind-tips {
		display: flex;
		align-items: center;
		background: #e6f7ff;
		padding: 30rpx;
		margin: 20rpx;
		border-radius: 12rpx;
		border-left: 6rpx solid #1890ff;
	}

	.tips-icon {
		font-size: 36rpx;
		margin-right: 20rpx;
	}

	.tips-text {
		flex: 1;
		font-size: 26rpx;
		color: #1890ff;
		line-height: 1.5;
	}

	/* 表单样式 */
	.bind-form {
		background: #fff;
		margin: 20rpx;
		padding: 40rpx 30rpx;
		border-radius: 16rpx;
		box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);
	}

	.form-item {
		margin-bottom: 40rpx;
	}

	.label {
		display: block;
		font-size: 28rpx;
		color: #333;
		margin-bottom: 20rpx;
		font-weight: 500;
	}

	.input {
		width: 100%;
		height: 88rpx;
		border: 2rpx solid #e0e0e0;
		border-radius: 12rpx;
		padding: 0 24rpx;
		font-size: 28rpx;
		box-sizing: border-box;
		background: #fafafa;
		transition: border-color 0.3s;
	}

	.input:focus {
		border-color: #007aff;
		background: #fff;
	}

	.placeholder {
		color: #ccc;
		font-size: 28rpx;
	}

	/* 验证码输入 */
	.captcha-input {
		display: flex;
		align-items: center;
		gap: 20rpx;
	}

	.captcha-img {
		width: 200rpx;
		height: 80rpx;
		border-radius: 8rpx;
		border: 2rpx solid #e0e0e0;
		background: #f5f5f5;
	}

	/* 绑定按钮 */
	.bind-btn {
		width: 100%;
		height: 88rpx;
		background: linear-gradient(135deg, #007aff, #0056cc);
		color: #fff;
		border: none;
		border-radius: 44rpx;
		font-size: 32rpx;
		font-weight: 500;
		margin-top: 20rpx;
		margin-bottom: 40rpx;
		box-shadow: 0 8rpx 20rpx rgba(0, 122, 255, 0.3);
	}

	.bind-btn[disabled] {
		background: #ccc;
		box-shadow: none;
	}

	/* 注册部分 */
	.register-section {
		display: flex;
		justify-content: center;
		align-items: center;
		padding: 20rpx 0;
	}

	.register-text {
		font-size: 26rpx;
		color: #666;
		margin-right: 10rpx;
	}

	.register-link {
		font-size: 26rpx;
		color: #007aff;
		font-weight: 500;
	}

	/* 成功弹窗 */
	.success-modal {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		z-index: 9999;
	}

	.modal-mask {
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: rgba(0, 0, 0, 0.5);
	}

	.modal-content {
		position: absolute;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
		width: 560rpx;
		background: #fff;
		border-radius: 20rpx;
		padding: 60rpx 40rpx 40rpx;
		text-align: center;
		box-shadow: 0 20rpx 60rpx rgba(0, 0, 0, 0.2);
	}

	.success-icon {
		width: 120rpx;
		height: 120rpx;
		background: #52c41a;
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 60rpx;
		color: #fff;
		margin: 0 auto 30rpx;
	}

	.success-title {
		display: block;
		font-size: 36rpx;
		color: #333;
		font-weight: bold;
		margin-bottom: 20rpx;
	}

	.success-desc {
		display: block;
		font-size: 28rpx;
		color: #666;
		margin-bottom: 40rpx;
	}

	.confirm-btn {
		width: 100%;
		height: 80rpx;
		background: #007aff;
		color: #fff;
		border: none;
		border-radius: 40rpx;
		font-size: 30rpx;
	}
</style>