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

			<view class="bg-fff mt22 form ">
				<view class="title fw700 size-30 flex-rowl">
					基本信息
				</view>
				<dForm ref="formRef" :list="state.list" labelWidth="220rpx" :isFooter="false" @input="onFormInput"></dForm>
			</view>
			
			<view class="license__view" v-if="form.isHave">
				<view class="license">
					<up-checkbox-group 
						v-model="licenseData.selected" 
						shape="circle"
						activeColor="#FFBF60"
						labelColor="#000000"
						labelSize="26rpx"
					>
						<view class="license-options">
							<up-checkbox
								v-for="item in licenseOptions"
								:key="`license-${item.id}`"
								:label="item.title"
								:name="item.id"
							>
							</up-checkbox>
						</view>
					</up-checkbox-group>
					<view class="tips">
						{{ configList.pet_news.paramValueText }}
					</view>
					<up-upload
						:fileList="licenseData.fileList"
						@afterRead="afterRead"
						@delete="deletePic"
						multiple
					>
						<image src="../static/list/icon-upload.png" style="width: 144rpx;height: 144rpx;"></image>
					</up-upload>
				</view>							
			</view>

			<view class="bg-fff mt22 form bt120">
				<view class="title fw700 size-30 flex-rowl">
					个人宠物类型
				</view>
				<view class="flex-between wrap mt32">

					<view class="type" v-for="item in petTypeOptions" :key="`petType-${item.id}`" @click="onSelectPetType(item.id)">
						<image :src="item.imageNo" mode="widthFix"></image>
						<template v-if="petType.includes(item.id)">
							<image class="active" :src="item.image" mode="widthFix"></image>
							<view class="active-icon">
								<up-icon name="checkmark-circle" color="#FFBF60" size="32rpx"></up-icon>
							</view>
						</template>
					</view>
				</view>
			</view>

			<view class="footer-btn" @click="toNext">
				<view class="btn">
					下一步
				</view>
			</view>
		</view>

		<configPopup ref="configPopupRef" />

		<!-- 客服组件 -->
		<CustomerService />
	</view>
</template>

<script setup>
	import { ref, reactive, computed } from "vue";
	import { useStore } from 'vuex'
	import { onLoad } from '@dcloudio/uni-app'
	import { ossUpload } from '@/utils/oss-upload/oss/index.js'
	import { getLicenseList } from '@/api/examination'
	import { insertUser, udpateUser, getUserOne } from '@/api/userTeacher'

	import dForm from "@/components/dForm/index.vue"
	import stepProgress from '../components/stepProgress.vue';
	import configPopup from '@/components/configPopup.vue'
	
	const configPopupRef = ref(null)
	
	
	const store = useStore()

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

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

	const id = ref(null)

	const state = reactive({
		list: [{
				type: "input",
				label: "姓名",
				key: "name",
				placeholder: "请输入您的真实姓名",
			},
			{
				type: "input",
				label: "身份证号",
				key: "idCard",
				placeholder: "请输入您的真实身份证号",
			},
			{
				type: "radio",
				label: "性别",
				key: "sex",
				options: [{
						name: "男",
						value: 0,
					},
					{
						name: "女",
						value: 1,
					}
				]
			},
			{
				type: "input",
				label: "年龄",
				key: "age",
				placeholder: "请输入您的年龄",
			},
			{
				type: "input",
				label: "手机号",
				key: "phone",
				placeholder: "请输入您的手机号",
			},
			{
				type: "input",
				label: "养宠经验",
				key: "experience",
				placeholder: "请输入您的养宠年限",
				unit: "年"
			},
			{
				type: "radio",
				label: "是否有专业执照",
				key: "isHave",
				placeholder: "请选择",
				options: [{
					name: "是",
					value: 1,
				}, {
					name: "没有",
					value: 0,
				}]
			},
		]
	})

	const formRef = ref()
	const form = ref({})
	const onFormInput = (e) => {
		form.value = e
	}

	const fetchUserInfo = async () => {
		try {
			const { userTelephone } = store.state.user.userInfo
			
			if(!userId.value) {
				return
			}
			
			const data = await getUserOne(userId.value)

			if (data) {
				const {
					id: _id,
					status,
					name,
					idCard,
					sex,
					age,
					phone,
					experience,
					isHave,
					license,
					images,
					petType: _petType,
				} = data

				if ([1,2].includes(status)) { // status: 0-审核中 1-通过 2-不通过
					uni.navigateTo({
						url: `/otherPages/authentication/examination/trainCompleted/index?status=${status}`
					})
					return
				}
				

				id.value = _id

				formRef.value.setData({
					name,
					idCard,
					sex,
					age,
					phone: phone || userTelephone,
					experience,
					isHave,
				})

				licenseData.selected = license?.split?.(';').map(str => parseInt(str)) || []
				licenseData.fileList = images?.split?.(';').map(url => ({ url })) || []

				petType.value = _petType.split(',').map(n => parseInt(n))
			} else {
				formRef.value.setData({
					phone: userTelephone,
				})
			}

			
			store.dispatch('fetchPetTypeOptions')
			fetchLicenseOptions()
			
		} catch (err) {
			console.log('--err', err)
		}
	}

	const licenseData = reactive({
		selected: [],
		fileList: []
	})
	const licenseOptions = ref([])
	const fetchLicenseOptions = async () => {
		try {
			licenseOptions.value = await getLicenseList()
		} catch (err) {

		}
	}
	const afterRead = (event) => {
		event.file.forEach(n => {
			ossUpload(n.url)
				.then(url => {
					licenseData.fileList.push({
						url
					})
				})
		})
	};
	const deletePic = (event) => {
		licenseData.fileList.splice(event.index, 1);
	};

	const petType = ref([])
	const petTypeOptions = computed(() => {
		return store.getters.petTypeOptions
	})
	const onSelectPetType = (type) => {
		petType.value = petType.value.includes(type) ? petType.value.filter(n => n !== type) : [...petType.value, type]
	}

	const toNext = async () => {
		try {
			const {
				name,
				idCard,
				sex,
				age,
				phone,
				experience,
				isHave,
			} = form.value

			const data = {
				userId: userId.value,
				name,
				idCard,
				sex,
				age,
				phone,
				experience,
				isHave,
				petType: petType.value.join(','),
			}

			if (isHave) {
				const { selected, fileList } = licenseData

				data.license = selected.join(';')
				data.images = fileList.map(item => item.url).join(';')
			}

			// 效验字段必填
			const requiredFields = {
				name: '姓名',
				idCard: '身份证号',
				age: '年龄',
				phone: '手机号',
				experience: '养宠经验'
			}
			
			for (const [field, label] of Object.entries(requiredFields)) {
				if (!data[field]) {
					uni.showToast({
						title: `请填写${label}`,
						icon: 'none'
					})
					return
				}
			}
			
			// 性别需要单独判断，因为0是有效值（男性）
			if (data.sex != 0 && data.sex != 1) {
				uni.showToast({
					title: '请选择性别',
					icon: 'none'
				})
				return
			}
			
			// 验证手机号格式
			if (!/^1[3-9]\d{9}$/.test(data.phone)) {
				uni.showToast({
					title: '请输入正确的手机号',
					icon: 'none'
				})
				return
			}
			
			// 验证身份证号格式
			if (!/^\d{17}[\dXx]$/.test(data.idCard)) {
				uni.showToast({
					title: '请输入正确的身份证号',
					icon: 'none'
				})
				return
			}
			
			// 验证年龄范围
			if (isNaN(data.age) || data.age < 18 || data.age > 70) {
				uni.showToast({
					title: '请输入有效的年龄（18-70岁）',
					icon: 'none'
				})
				return
			}
			
			if (petType.value.length === 0) {
				uni.showToast({
					title: '请选择宠物类型',
					icon: 'none'
				})
				return
			}
			
			if (data.isHave === 1) {
				if (licenseData.selected.length === 0) {
					uni.showToast({
						title: '请选择专业执照类型',
						icon: 'none'
					})
					return
				}
				
				if (licenseData.fileList.length === 0) {
					uni.showToast({
						title: '请上传执照图片',
						icon: 'none'
					})
					return
				}
			}

			if (id.value) {
				data.id = id.value
				await udpateUser(data)
			} else {
				let r = await insertUser(data)
				if(r.code != 200){
					return
				}
			}

			uni.navigateTo({
				url: `/otherPages/authentication/examination/start?petType=${petType.value.join(',')}`
			})
		} catch (err) {
			
		}
	}


	onLoad(() => {
		fetchUserInfo()
        store.dispatch('fetchPetTypeOptions')
	})
</script>

<style lang="scss" scoped>
	.bt120 {
		margin-bottom: 120rpx;
		width: 716rpx;
		box-sizing: border-box;
	}

	.footer-btn {
		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;
		position: relative;

		image {
			width: 100%;
		}

		.active {
			position: absolute;
			top: 0;
			left: 0;
			
      &-icon {
  			position: absolute;
        top: 14rpx;
        right: 18rpx;
      }
		}
	}

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

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

		.content {
			top: 0;
			left: 0;
			padding: 16rpx;

		}
	}

	.license__view {
		width: 716rpx;
		padding-bottom: 40rpx;
		box-sizing: border-box;
		background-color: #FFFFFF;

		.license {
			width: 100%;
			padding: 13rpx 16rpx;
			box-sizing: border-box;
			background-color: #FFFCF1;

			&-options {
				display: grid;
				grid-template-columns: repeat(2, 1fr);
			}
		}

		.tips {
			margin: 22rpx 0 24rpx 0;
			color: #FFBF60;
			font-size: 22rpx;
			width: 100%;
			word-break: break-all;
		}
	}
</style>