<template>
	<view>
		<view class="containers po-r">
			<image src="" mode="" class="mainBg"></image>
			<view class="po-a content">

				<stepProgress :step="3"></stepProgress>

				<view class="step mt24">
					<view class="li flex-rowl">
						<view class="num flex-rowc">
							1
						</view>
						<view class="item">
							<view class="flex-between mb10">
								<view class="flex-rowl">
									<image class="img" src="@/static/images/ydd/end12.png" mode=""></image>
									<text class="size-30 color-000 fw700">实名认证</text>
								</view>
								<view class="size-22 color-ffb">
									已完成
								</view>
							</view>
							<view class="info">
								<!-- todo: 实名认证 -->
								<view class="size-22 color-777">
									{{ `真实姓名：${form.name}` }}
								</view>
								<view class="size-22 color-777">
									{{ `身份证号码：${form.idCard}` }}
								</view>
							</view>
						</view>
					</view>

					<view class="li flex-rowl po-r">
						<view class="line po-a">
						</view>
						<view class="num flex-rowc">
							2
						</view>
						<view class="item">
							<view class="flex-between mb10">
								<view class="flex-rowl">
									<image class="img" src="@/static/images/ydd/end13.png" mode="widthFix"></image>
									<text class="size-30 color-000 fw700">履约保证金缴纳</text>
								</view>
								<view class="size-22 color-999 jiao-disabled">
									暂未开放
								</view>
								<!-- todo -->
								<!-- <view class="size-22 highlight">
									已完成
								</view> -->
							</view>
							<view class="info color-777 size-22">
								请缴纳履约保证金，保证金注销时可申请退还
							</view>
						</view>
					</view>

					<view class="li flex-rowl po-r">
						<view class="line po-a" style="height: 150rpx;">
						</view>
						<view class="num flex-rowc">
							3
						</view>
						<view class="item">
							<view class="flex-between mb10">
								<view class="flex-rowl">
									<image class="img" src="@/static/images/ydd/end1(4).png" mode="widthFix"></image>
									<text class="size-30 color-000 fw700">添加客服微信</text>
								</view>
								<view class="size-22 highlight">
									请自行添加
								</view>
							</view>
							<view class="info color-777 size-22 flex-rowl">
								<text class="size-22 color-777">微信二维码</text>
								<image :src="configList.wx_image.paramValueImage" 
								@click="previewQRCode"
								mode="widthFix"
									style="width: 150rpx;height: 150rpx;cursor: pointer;"></image>
							</view>
						</view>
					</view>

					<view class="li flex-rowl po-r">
						<view class="line po-a" style="height: 150rpx;">
						</view>
						<view class="num flex-rowc">
							4
						</view>
						<view class="item">
							<view class="flex-between mb10">
								<view class="flex-rowl">
									<image class="img" src="@/static/images/ydd/end13.png" mode="widthFix"></image>
									<text class="size-30 color-000 fw700">服务工具准备</text>
								</view>
								<view class="size-22 flex-rowr" @click="openToolsInfoModal">
									<text>查看工具包</text>
									<up-icon name="arrow-down" color="#7F7F7F" size="17rpx"
										style="margin-left: 5rpx;"></up-icon>
								</view>
							</view>
							<!-- <view class="info color-777 size-22">
								<view class="flex-between">
									<text class="size-22">所在地区:</text>
									<view plain class="flex-rowr" @click="selectAddr">
										<text>{{ form.area ? form.area : '请选择' }}</text>
										<up-icon style="margin-left: 22rpx;" name="arrow-down" color="#7F7F7F"
											size="21rpx"></up-icon>
									</view>
								</view>
							</view> -->
							<view class="info color-777 size-22 mt20">
								<view class="flex-between">
									<text class="size-22">姓名:</text>
									<input v-model="form.name" 
										type="text" 
										placeholder="请输入姓名" 
										:class="{ 'input-error': formErrors.name }"
										@input="clearFieldError('name')" />
								</view>
							</view>
							<view class="info color-777 size-22 mt20">
								<view class="flex-between">
									<text class="size-22">电话:</text>
									<input v-model="form.phone" 
										type="text" 
										placeholder="请输入手机号码" 
										:class="{ 'input-error': formErrors.phone }"
										@input="clearFieldError('phone')" />
								</view>
							</view>
							<view class="info color-777 size-22 mt20">
								<view class="flex-between">
									<text class="size-22">地址:</text>
									<input v-model="form.address" 
										type="text" 
										placeholder="请输入收货地址" 
										:class="{ 'input-error': formErrors.address }"
										@input="clearFieldError('address')" />
								</view>
							</view>
						</view>


					</view>
				</view>

				<view class="footer-btn" @click="onSave">
					<view class="btn">
						提交审核
					</view>
				</view>
			</view>

			<up-modal :show="showToolsInfoModal" :showConfirmButton="false" :showCancelButton="false"
				:closeOnClickOverlay="true" @close="closeToolsInfoModal">
				<up-parse class="size-28" :content="configList.pet_tools.paramValueArea"></up-parse>
			</up-modal>

		</view>
		<!-- 使用全局客服组件 -->
		<CustomerService />
	</view>
</template>

<script setup>
	import {
		ref,
		reactive,
		computed
	} from "vue";
	import {
		onShow
	} from '@dcloudio/uni-app'
	import {
		useStore
	} from 'vuex'
	import {
		udpateUser,
		getUserOne
	} from '@/api/userTeacher'
import { appletUsersTeacher } from '@/api/examination'

	import stepProgress from '../components/stepProgress.vue';

	const store = useStore()

	const configList = computed(() => {
		return store.getters.configList
	})

	const userId = computed(() => {
		return store.state.user.userInfo.userId
	})

	const id = ref()

	const form = reactive({
		name: null,
		idCard: null,
		area: null,
		latitude: null,
		longitude: null,
		address: null,
		phone: null,
	})

	// 添加错误状态管理
	const formErrors = reactive({
		name: false,
		phone: false,
		address: false
	})

	// 清除单个字段错误状态
	const clearFieldError = (field) => {
		formErrors[field] = false
	}

	const initData = async () => {
		console.log('--initData')
		try {

			const data = await getUserOne(userId.value)

			const {
				id: _id,
				name,
				idCard,
			} = data

			id.value = _id

			form.name = name
			form.idCard = idCard

		} catch (err) {
			console.log('--err', err)
		}
	}

	onShow(() => {
		initData()
	})

	// jumpToBond函数已移除，因为去缴费按钮已改为暂未开放状态

	const showToolsInfoModal = ref(false)
	const openToolsInfoModal = () => {
		showToolsInfoModal.value = true
	}
	const closeToolsInfoModal = () => {
		showToolsInfoModal.value = false
	}

	// 预览客服二维码
	const previewQRCode = () => {
		if (configList.value.wx_image && configList.value.wx_image.paramValueImage) {
			uni.previewImage({
				urls: [configList.value.wx_image.paramValueImage],
				current: 0,
				longPressActions: {
					itemList: ['保存图片'],
					success: function(data) {
						if (data.tapIndex === 0) {
							// 保存图片到相册
							uni.saveImageToPhotosAlbum({
								filePath: configList.value.wx_image.paramValueImage,
								success: function() {
									uni.showToast({
										title: '保存成功',
										icon: 'success'
									})
								},
								fail: function() {
									uni.showToast({
										title: '保存失败',
										icon: 'none'
									})
								}
							})
						}
					}
				}
			})
		} else {
			uni.showToast({
				title: '二维码图片加载失败',
				icon: 'none'
			})
		}
	}

	const setAddress = (res) => {
		//经纬度信息
		form.latitude = res.latitude
		form.longitude = res.longitude

		if (!res.address && res.name) { //用户直接选择城市的逻辑
			return form.area = res.name
		}
		if (res.address || res.name) {
			return form.area = res.address + res.name
		}
		form.area = '' //用户啥都没选就点击勾选
	}

	const selectAddr = () => {
		uni.chooseLocation({
			success: function(res) {
				setAddress(res)
			}
		})
	}

	const validateForm = () => {
		const { name, phone, address } = form
		let hasError = false
		
		// 重置错误状态
		Object.keys(formErrors).forEach(key => {
			formErrors[key] = false
		})
		
		// 必填字段验证
		if (!name || name.trim() === '') {
			formErrors.name = true
			hasError = true
			uni.showToast({
				title: '请输入姓名',
				icon: 'none'
			})
			return false
		}
		
		if (!phone || phone.trim() === '') {
			formErrors.phone = true
			hasError = true
			uni.showToast({
				title: '请输入电话号码',
				icon: 'none'
			})
			return false
		}
		
		if (!address || address.trim() === '') {
			formErrors.address = true
			hasError = true
			uni.showToast({
				title: '请输入收货地址',
				icon: 'none'
			})
			return false
		}
		
		// 姓名长度验证
		if (name.trim().length < 2 || name.trim().length > 10) {
			formErrors.name = true
			hasError = true
			uni.showToast({
				title: '姓名长度应在2-10个字符之间',
				icon: 'none'
			})
			return false
		}
		
		// 电话号码格式验证
		const phoneRegex = /^1[3-9]\d{9}$/
		if (!phoneRegex.test(phone.trim())) {
			formErrors.phone = true
			hasError = true
			uni.showToast({
				title: '请输入正确的手机号码',
				icon: 'none'
			})
			return false
		}
		
		// 地址长度验证
		if (address.trim().length < 5 || address.trim().length > 100) {
			formErrors.address = true
			hasError = true
			uni.showToast({
				title: '地址长度应在5-100个字符之间',
				icon: 'none'
			})
			return false
		}
		
		// 姓名格式验证（只允许中文、英文字母）
		const nameRegex = /^[\u4e00-\u9fa5a-zA-Z\s]+$/
		if (!nameRegex.test(name.trim())) {
			formErrors.name = true
			hasError = true
			uni.showToast({
				title: '姓名只能包含中文和英文字母',
				icon: 'none'
			})
			return false
		}
		
		return true
	}

	const onSave = async () => {
		try {
			// 先进行表单验证
			if (!validateForm()) {
				return
			}

			const {
				area,
				latitude,
				longitude,
				address,
				name,
				phone,
			} = form

			const data = {
				id: id.value,
				area,
				latitude,
				longitude,
				address: address.trim(),
				name: name.trim(),
				phone: phone.trim(),
			}

			await udpateUser(data)

            //成为伴宠师
			await appletUsersTeacher({
                userId : userId.value
            })

            store.dispatch('getUserInfo')

			uni.showToast({
				title: '提交成功!',
				icon: "none"
			})

			setTimeout(() => {
				uni.reLaunch({
					url: "/pages/workbenchManage/index"
				})
			}, 1000)

		} catch (err) {
			uni.showToast({
				title: '提交失败，请重试',
				icon: 'none'
			})
			console.error('提交失败:', err)
		}

	}
</script>

<style lang="scss" scoped>
	// 原客服按钮样式已移动到全局组件中

	.line {
		width: 3rpx;
		height: 100rpx;
		background-color: #BDBDBD;
		left: 25rpx;
		top: -50rpx;
	}

	.jiao {
		padding: 5px 20rpx;
		border-radius: 30rpx;
		background-color: #FFBF60;
		color: #fff;
	}

	.jiao-disabled {
		padding: 5px 20rpx;
		border-radius: 30rpx;
		background-color: #CCCCCC;
		color: #999999;
		cursor: not-allowed;
	}

	.li {
		width: 710rpx;

		.num {
			width: 50rpx;
			height: 50rpx;
			border-radius: 50%;
			background-color: #FFBF60;
			color: #fff;
			font-weight: 700;
			font-size: 26rpx;
			margin-right: 20rpx;
		}
	}

	.item {
		padding: 26rpx 36rpx;
		border-radius: 24rpx;
		background-color: #fff;
		margin-bottom: 24rpx;
		width: 590rpx;

		.info {
			padding: 16rpx;
			background-color: #f3f3f3;
			border-radius: 16rpx;
		}
	}

	.img {
		width: 40rpx;
		height: 40rpx;
		margin-right: 8rpx;
	}

	.bt120 {
		margin-bottom: 120rpx;
		width: 716rpx;
		box-sizing: border-box;
	}

	.footer-btn {
		z-index: 9999;
		width: 100vw;
		height: 144rpx;
		background-color: #fff;
		display: flex;
		justify-content: center;
		position: fixed;
		bottom: 0;
		left: 0;
		align-items: center;

		.btn {
			font-size: 30rpx;
			color: #fff;
			display: flex;
			justify-content: center;
			align-items: center;
			width: 574rpx;
			height: 94rpx;
			border-radius: 94rpx;
			background-color: #FFBF60;
		}
	}

	.type {
		width: 190rpx;
		margin-bottom: 74rpx;
	}

	.form {
		padding: 40rpx 32rpx;
		box-sizing: border-box;
		width: 716rpx;
	}

	.title {
		&::before {
			content: "";
			display: block;
			width: 9rpx;
			height: 33rpx;
			background-color: #FFBF60;
			margin-right: 7rpx;
		}
	}

	.mb6 {
		margin-bottom: 6rpx;
	}

	.containers {
		.neir {
			padding: 47rpx 27rpx 36rpx 27rpx;
			border-radius: 16rpx;
			box-sizing: border-box;
			width: 716rpx;

			.steps {
				.line {
					width: 163rpx;
					height: 3rpx;
					background-color: #BDBDBD;
					margin-bottom: 30rpx;
				}

				.num {
					width: 50rpx;
					height: 50rpx;
					background-color: #FFBF60;
					border-radius: 50%;
				}

			}
		}


		.mainBg {
			width: 100vw;
			height: 442rpx;
			background-image: linear-gradient(to bottom, #FFBF60, #f5f5f5);
		}

		.content {
			top: 0;
			left: 0;
			padding: 16rpx;
			padding-bottom: 200rpx;

			.logo {
				width: 194rpx;
				height: 70rpx;
			}

			.renz {

				image {
					width: 26rpx;
					height: 26rpx;
				}
			}
		}
	}

	.highlight {
		color: #FFBF60;
	}

	// 添加输入框错误状态样式
	.input-error {
		border: 1px solid #ff4757 !important;
		background-color: #fff5f5 !important;
		color: #ff4757 !important;
	}

	.input-error::placeholder {
		color: #ff9999 !important;
	}
</style>