<template>
	<view class="signpage-container">
		<view class="warp-bg"></view>
		<view class="main-box">
			<!-- 提示信息 -->
			<view class="tips-box">
				<view class="tips-title">活动须知</view>
				<view class="tips-text">
					<scroll-view scroll-y class="content" @scroll="onScroll">
						<view v-for="item in rulesList" :key="item">{{ item }}</view>
					</scroll-view>
					<!-- <view class="scrollbar">
						<view class="thumb" :style="{ top: thumbPosition }"></view>
					</view> -->
				</view>
			</view>

			<!-- 表单信息 -->
			<view class="form-box">
				<form @submit="onSubmit">
					<block v-for="(item, index) in formData" :key="index" class="bot-warp">
						<FormTree v-bind="{ item, index, visible, areaVisible, formData, isView: query.isView }"
							@addSubForm="(subIndex) => addSubForm(index, subIndex)"
							@delSubForm="(subIndex) => delSubForm(index, subIndex)"
							@textInput="({ subIndex, fieldIndex, e, type }) => textInput(index, subIndex, fieldIndex, e, type)"
							@mobileInput="({ subIndex, fieldIndex, e }) => mobileInput(index, subIndex, fieldIndex, e)"
							@updateMobile="({ subIndex, fieldIndex }) => updateMobile(index, subIndex, fieldIndex)"
							@cardInput="({ subIndex, fieldIndex, e }) => cardInput(index, subIndex, fieldIndex, e)"
							@onRadioChange="({ subIndex, fieldIndex, e }) => onRadioChange(index, subIndex, fieldIndex, e)"
							@onCheckChange="({ subIndex, fieldIndex, e }) => onCheckChange(index, subIndex, fieldIndex, e)"
							@onUpload="({ subIndex, fieldIndex }) => onUpload(index, subIndex, fieldIndex)"
							@onPreviewImage="({ subIndex, fieldIndex, idx }) => onPreviewImage(index, subIndex, fieldIndex, idx)"
							@onImageDel="({ subIndex, fieldIndex, idx }) => onImageDel(index, subIndex, fieldIndex, idx)"
							@openAddressPicker="({ subIndex, fieldIndex }) => openAddressPicker(index, subIndex, fieldIndex)"
							@openDatePicker="({ subIndex, fieldIndex }) => openDatePicker(index, subIndex, fieldIndex)" />
					</block>
					<view class="form-bottom">
						<view class="agree-content" @click="onChange">
							<image v-if="query.agreement" :src="$baseUrl + 'sign-up/selected.png'" mode="aspectFit" />
							<image v-else :src="$baseUrl + 'sign-up/circle.png'" mode="aspectFit" />
							<view class="read-text">
								本人知晓并同意<text @click="openNoticeDialog"
									class="agree-text">《星妈会活动协议》</text>以及“活动须知”的全部条款内容，并保证报名信息填写的真实性
							</view>
						</view>
						<button v-if="!query.isView" form-type="submit" class="form-btn">
							提交报名
						</button>
						<button v-else @click="handleGoBack" class="form-btn">
							返回
						</button>
					</view>

				</form>
			</view>
		</view>
		<AreaPicker ref="areaPickerRef" v-model:visible="areaVisible"
			v-bind="{ currentIndex, currentSubIndex, currentFieldIndex, formData }"
			@confirm="({ currentIndex, currentSubIndex, currentFieldIndex, selected }) => handleAreaConfirm(currentIndex, currentSubIndex, currentFieldIndex, selected)" />
		<DatePicker v-model:visible="visible" v-bind="{ currentIndex, currentSubIndex, currentFieldIndex, formData }"
			@confirm="({ currentIndex, currentSubIndex, currentFieldIndex, formattedDate }) => handleDateConfirm(currentIndex, currentSubIndex, currentFieldIndex, formattedDate)" />
		<!-- 活动须知 -->
		<NoticeDialog :agreement="query.agreement" :isView="query.isView" ref="noticeDialogRef"
			@go-to-sign="(agreement) => goToSign(agreement)" />
		<!-- 活动已结束，报名失败 -->
		<RegisterDialog ref="registerDialogRef" v-bind="{ textValue, btnValue, titleValue }" @go-to-more="goToMore" />
	</view>
</template>

<script setup>
import { ref, watch, computed } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { signupFormApi, formCommitApi, uploadFileApi } from '@/api/momclub/index.js';
import NoticeDialog from './component/noticeDialog.vue'
import DatePicker from './component/datePicker.vue'
import AreaPicker from './component/areaPicker.vue'
import FormTree from './component/formTree.vue'
import RegisterDialog from './component/registerDialog.vue'
const thumbPosition = ref('0%')

const onScroll = (e) => {
	// 简单线性映射，不需要精确计算
	console.log(e, 'eeeee')
	const progress = e.detail.scrollTop / 460
	thumbPosition.value = (progress * 100) + '%'
}
//存储活动信息等
const signupForm = ref()
//路由参数
const query = ref({
	agreement: false,
	activityId: '',
	isView: 0
})
const formData = ref();
// 报名失败弹窗ref
const registerDialogRef = ref(null)
const textValue = ref('')
const btnValue = ref('')
const titleValue = ref('')
// 返回上一页
const handleGoBack = () => {
	// 检查是否有上一页
	const pages = getCurrentPages()
	if (pages.length > 1) {
		// 返回前设置标记 有上一页，直接返回上一页（收藏状态已在更新时同步）
		uni.navigateBack({
			delta: 1
		})
		// uni.setStorageSync('needRefresh', true);
	} else {
		// 没有上一页，跳转到星妈实验室页面，并传递index参数
		uni.redirectTo({
			url: `/subPackages/momclub/index?activityId=${query.value.activityId}`
		})
	}
}
//活动须知
const rulesList = computed(() => {
	if (signupForm.value?.signupTip) {
		return signupForm.value.signupTip?.split('\n')
	} else {
		return []
	}
})
const noticeDialogRef = ref(null)
// 打开报名须知弹窗
const openNoticeDialog = () => {
	noticeDialogRef.value.open()
}
//打开报名信息页面
const goToSign = (agreement) => {
	query.value.agreement = agreement
}
//同意协议change
const onChange = () => {
	if (query.value.isView) return
	query.value.agreement = !query.value.agreement
}
// 验证单个表单组件的函数
const validateFormComponent = ({ required, fieldValue, placeholder, componentType, limitInfo }, index, subIndex, fieldIndex) => {
	if (required) {
		let isEmpty = false;
		if (componentType === 'ADDRESS') {
			isEmpty = !fieldValue || !Object.keys(fieldValue).length;
		} else if (componentType === 'MULTI_SELECT' || componentType === 'IMG') {
			isEmpty = !fieldValue?.length;
		}else if (componentType === 'MOBILE') {
			isEmpty = !fieldValue || (fieldValue && fieldValue.length != 11);
		} else if (componentType === 'ID_CARD') {
			isEmpty = !fieldValue || (fieldValue && fieldValue.length != 18);
		} else {
			isEmpty = !fieldValue;
		}
		if (isEmpty) {
			// uni.showToast({ title: placeholder,icon: "none"});
			getFormComponent(index, subIndex, fieldIndex).error = true
			return false;
		} else {
			getFormComponent(index, subIndex, fieldIndex).error = false
		}
		if ((componentType === 'TEXT' || componentType === 'LONG_TEXT') && limitInfo.limitType === 1 && fieldValue) {
			if (!(/^[1-9]\d*$/.test(fieldValue))) {
				getFormComponent(index, subIndex, fieldIndex).noInt = true
				return false;
			} else {
				getFormComponent(index, subIndex, fieldIndex).noInt = false
			}
		}
	}
	if(!required){
		let isFormatError = false;
		if (componentType === 'MOBILE') {
			isFormatError = fieldValue && fieldValue.length != 11;
		} else if (componentType === 'ID_CARD') {
			isFormatError = fieldValue && fieldValue.length != 18;
		}
		if (isFormatError) {
			getFormComponent(index, subIndex, fieldIndex).error = true
			return false;
		} else {
			getFormComponent(index, subIndex, fieldIndex).error = false
		}
	}
	return true;
};
//处理入参
const extractFormComponents = (formArray) => {
	return formArray.reduce((acc, form) => {
		// 添加主表单组件
		if (form.formComponentList) {
			form.formComponentList.forEach(component => {
				acc.push({
					componentId: component.componentId,
					fieldValue: component.fieldValue
				});
			});
		}

		// 添加 isShow 为 true 的子表单组件
		if (form.subFormList && form.subFormList.length > 0) {
			form.subFormList.forEach(subForm => {
				if (subForm.isShow === true && subForm.formComponentList) {
					subForm.formComponentList.forEach(component => {
						acc.push({
							componentId: component.componentId,
							fieldValue: component.fieldValue
						});
					});
				}
			});
		}
		return acc;
	}, []);
}
//提交表单
const onSubmit = async () => {
	if (!query.value.agreement) {
		return uni.showToast({
			title: "请阅读并勾选须知信息",
			icon: "none",
		});
	}
	console.log('原数组formData', formData.value)
	// 验证主表单
	let isValid = true;
	for (let index = 0; index < formData.value.length; index++) {
		const item = formData.value[index];

		// 验证主表单组件
		for (let i = 0; i < item.formComponentList.length; i++) {
			const component = item.formComponentList[i];
			if (!validateFormComponent(component, index, '', i)) {
				isValid = false;
			}
		}

		// 验证子表单
		if (item.subFormList) {
			for (let j = 0; j < item.subFormList.length; j++) {
				const subItem = item.subFormList[j];
				if (subItem.isShow) {
					for (let k = 0; k < subItem.formComponentList.length; k++) {
						const subComponent = subItem.formComponentList[k];
						if (!validateFormComponent(subComponent, index, j, k)) {
							isValid = false;
						}
					}
				}
			}
		}
	}

	// 如果有任何验证失败，则中断提交
	if (!isValid) {
		return
		// return uni.showToast({
		// 	title: "请完善必填信息",
		// 	icon: "none",
		// });
	}
	// 所有验证通过，可以继续提交逻辑
	let newFormData = JSON.parse(JSON.stringify(formData.value))
	const submitData = extractFormComponents(newFormData)
	console.log(submitData, '提交submitData')
	try {
		const res = await formCommitApi({
			activityId: query.value.activityId,
			agreement: true,
			formComponentList: submitData,
		})
		if (res.success) {
			uni.navigateBack({
				delta: 1
			})
			uni.setStorageSync('needRefresh', true);
		} else {
			if (['30002006','30002008','30002010','30002011','30002012', '30002014',].includes(res.code)) {
				setTimeout(() => {
					console.log(registerDialogRef.value, '已失败----')
					titleValue.value = '报名失败'
					textValue.value = res.message || '报名失败'
					btnValue.value = "已知晓"
					registerDialogRef.value?.open()
				}, 50)
			} else if (res.code === "30002003") {
				//非会员 未登录，跳转到登录注册页面
				uni.navigateTo({
					url: `/pages/activity/register`
				})
			} else if (res.code === "30002002") {
				//活动不存在，请查看其它活动
				setTimeout(() => {
					textValue.value = "活动不存在"
					btnValue.value = "查看更多其他活动"
					registerDialogRef.value?.open()
				}, 50)
			} else if (res.code === "30003001") {
				//异常情况，未获取到活动资源
				uni.redirectTo({
					url: `/subPackages/momclub/error`
				})
			} else {
				return uni.showToast({
					title: res.message || '报名失败',
					icon: "none",
				});
			}
		}
	} catch (error) {
		console.log(error, 'error')
	}
}
//已知晓
const goToMore = () => {
	console.log('关闭')
}
// 获取表单组件的辅助函数
const getFormComponent = (index, subIndex, fieldIndex) => {
	console.log(index, subIndex, fieldIndex, formData.value, 'index, subIndex, fieldIndex')
	if (subIndex !== '') {
		return formData.value[index].subFormList[subIndex]?.formComponentList[fieldIndex];
	} else {
		return formData.value[index]?.formComponentList[fieldIndex];
	}
}

// 短文本组件/长文本组件
const textInput = (index, subIndex, fieldIndex, e, type) => {
	console.log(index, subIndex, fieldIndex, e.detail.value, type, '文本')
	//0为字符 1为正整数
	const inputVal = e.detail.value
	const testVal = inputVal.replace(/[^0-9]/g, '').replace(/[\,]+/g, ',')
	getFormComponent(index, subIndex, fieldIndex).fieldValue = type ? testVal : inputVal
}

//手机号组件  只能输入正整数
const mobileInput = (index, subIndex, fieldIndex, e) => {
	console.log(index, subIndex, fieldIndex, e, '手机号')
	const inputVal = e.detail.value
	getFormComponent(index, subIndex, fieldIndex).fieldValue = inputVal.replace(/[^0-9]/g, '').replace(/[\,]+/g, ',')
}
//更新手机号
const updateMobile = (index, subIndex, fieldIndex) => {
	console.log(index, subIndex, fieldIndex, '更新手机号')
	if (query.value.isView) return
	getFormComponent(index, subIndex, fieldIndex).fieldValue = ""
}
//身份证号组件  只能输入数字和字母
const cardInput = (index, subIndex, fieldIndex, e) => {
	console.log(index, subIndex, fieldIndex, e.detail.value, '身份证号')
	const inputVal = e.detail.value
	getFormComponent(index, subIndex, fieldIndex).fieldValue = inputVal.replace(/[^X0-9]/g, '')
}
//单选组件
const onRadioChange = (index, subIndex, fieldIndex, e) => {
	console.log(index, subIndex, fieldIndex, e.detail.value, '单选')
	if (query.value.isView) return
	getFormComponent(index, subIndex, fieldIndex).fieldValue = e.detail.value
}
//多选组件
const onCheckChange = (index, subIndex, fieldIndex, e) => {
	console.log(index, subIndex, fieldIndex, e.detail.value, '多选')
	if (query.value.isView) return
	const inputVal = e.detail.value
	getFormComponent(index, subIndex, fieldIndex).fieldValue = inputVal
}
// 图片预览
const onPreviewImage = (index, subIndex, fieldIndex, idx) => {
	console.log(index, subIndex, fieldIndex, idx, '预览图片')
	const url = getFormComponent(index, subIndex, fieldIndex).fieldValue[idx];
	uni.previewImage({
		current: '1',
		urls: [url]
	})
}

// 删除上传图片
const onImageDel = (index, subIndex, fieldIndex, idx) => {
	console.log(index, subIndex, fieldIndex, idx, '删除图片')
	if (query.value.isView) return
	getFormComponent(index, subIndex, fieldIndex).fieldValue.splice(idx, 1);
}

// 上传图片
const onUpload = (index, subIndex, fieldIndex) => {
	if (query.value.isView) return
	const currentCount = getFormComponent(index, subIndex, fieldIndex).fieldValue?.length || 0;
	// 计算还可以上传的图片数量
	const remainingCount = 3 - currentCount;

	// 唤起图片选择器
	uni.chooseImage({
		count: remainingCount, // 限制选择数量为剩余可上传数量
		sizeType: ["original", "compressed"],
		sourceType: ["album", "camera"],
		success: async (res) => {
			const tempFilePaths = res.tempFilePaths;
			// 逐个上传
			for (const filePath of tempFilePaths) {
				// 检查文件格式
				const fileExtension = filePath.split('.').pop().toLowerCase()
				if (!['jpg', 'png', 'jpeg'].includes(fileExtension)) {
					uni.showToast({
						title: '请选择jpg、png或jpeg格式的图片',
						icon: 'none',
						duration: 2000
					})
					continue;
				}

				console.log(filePath)
				const fs = uni.getFileSystemManager();
				const base64 = "data:image/jpeg;base64," + fs.readFileSync(filePath, "base64");
				const uploadRes = await uploadFileApi({
					fileName: filePath,
					content: base64,
				});
				if (uploadRes.success) {
					console.log(uploadRes)
					// 确保fieldValue是数组后再执行push操作
					const fieldComponent = getFormComponent(index, subIndex, fieldIndex);
					if (!Array.isArray(fieldComponent.fieldValue)) {
						fieldComponent.fieldValue = [];
					}
					fieldComponent.fieldValue.push(uploadRes.data)
				} else {
					uni.showToast({
						title: uploadRes.message,
						icon: "none",
					});
				}
			};
		}
	});
}

const currentIndex = ref()
const currentSubIndex = ref()
const currentFieldIndex = ref()

const visible = ref(false)
// 日期组件
const openDatePicker = (index, subIndex, fieldIndex) => {
	if (query.value.isView) return
	currentIndex.value = index
	currentSubIndex.value = subIndex
	currentFieldIndex.value = fieldIndex
	visible.value = true
}
// 选择日期回调确认
const handleDateConfirm = (index, subIndex, fieldIndex, val) => {
	console.log('选择的日期是：', val);
	getFormComponent(index, subIndex, fieldIndex).fieldValue = val
	visible.value = false
}
const areaPickerRef = ref(null)
const areaVisible = ref(false)
//地址组件
const openAddressPicker = (index, subIndex, fieldIndex) => {
	if (query.value.isView) return
	currentIndex.value = index
	currentSubIndex.value = subIndex
	currentFieldIndex.value = fieldIndex
	areaVisible.value = true
	setTimeout(() => {
		areaPickerRef.value?.open()
	}, 50);
}
// 选择地址回调确认
const handleAreaConfirm = (index, subIndex, fieldIndex, val) => {
	console.log('选择的地址是：', index, subIndex, fieldIndex, val);
	getFormComponent(index, subIndex, fieldIndex).fieldValue = val
	areaVisible.value = false
}
//添加内嵌表单
const addSubForm = (index, subIndex) => {
	console.log(index, subIndex, '添加内嵌')
	if (formData.value[index].subFormList[subIndex].isShow) return
	formData.value[index].subFormList[subIndex].isShow = true
}
//删除内嵌表单
const delSubForm = (index, subIndex) => {
	console.log(index, subIndex, '添加内嵌')
	formData.value[index].subFormList[subIndex].isShow = false
}
// 获取活动信息并赋值
const getInfo = () => {
	if (query.value.activityId) {
		signupFormApi({ activityId: query.value.activityId }).then(async (res) => {
			if (res.success) {
				signupForm.value = res.data
				formData.value = res.data.formList
				console.log(formData.value, "formData.value-------")
			} else {
				return uni.showToast({
					title: res.message || '数据异常',
					icon: "none",
				});
			}
		})
	} else {
		console.log('无配置')
	}
}

onLoad(async (options) => {
	console.log(options, 'options===sign')
	const { agreement } = options
	query.value = options
	query.value.agreement = agreement === 'true' ? true : false
	if (options.isView) { query.value.agreement = true }
	console.log(query.value, 'query.value')
	getInfo()
})
watch(() => formData.value, (newVal) => {
    if (newVal) {
        console.log(newVal,'fwatch')
        newVal.forEach(item => {
            if (item.subFormList && item.subFormList.length > 0) {
                let flag = false;
                item.subFormList.forEach(subItem => {
                    if (subItem.isShow || subItem.hasFilledOut) {
                        if (!flag) {
                            subItem.isFirstFound = true;
                            flag = true;
                        } else {
                            delete subItem.isFirstFound;
                        }
                    } else {
                        delete subItem.isFirstFound;
                    }
                });
            }
        })
    }
}, { 
    immediate: true,
    deep: true  // 添加深度监听
});

</script>

<style lang="less" scoped>
// @import "@/common.less";
.signpage-container {
	height: 100vh;
	width: 100%;
	overflow: hidden;
	position: relative;
	background-color: #F2F2F2;
	color: #1C1C1C;

	.top-box {
		width: 100%;
		height: 177rpx;
		position: fixed;
		z-index: 999;
		background-color: #FFFFFF;

		.nav-box {
			width: 100%;
			position: fixed;
			top: 100rpx;
			left: 30rpx;
			display: flex;
			align-items: center;

			// 返回按钮样式
			.btnback {
				width: 60rpx;
				height: 60rpx;
			}

			.page_title {
				width: calc(100% - 190rpx);
				font-size: 28rpx;
				text-align: center;
			}
		}
	}

	.warp-bg {
		position: absolute;
		background: linear-gradient(180deg, #ECC990 0%, rgba(211, 164, 88, 0) 100%);
		height: 240rpx;
		width: 100%;
	}

	.main-box {
		width: 100%;
		height: calc(100vh - 250rpx);
		overflow: scroll;
		position: absolute;
		padding-top: 20rpx;
		box-sizing: border-box;
	}

	.tips-box {
		margin: 0rpx 20rpx 20rpx;
		padding: 20rpx;
		max-height: 180rpx;
		box-sizing: border-box;
		background-color: #FFFFFF;
		border-radius: 16rpx;
		text-align: justify;

		.tips-title {
			color: #D3A458;
			font-weight: 500;
			font-size: 26rpx;
			margin-bottom: 10rpx;
		}

		.tips-text {
			display: flex;
			font-size: 24rpx;
			max-height: 99rpx;
			line-height: 33rpx;

			.content {
				flex: 1;
			}

			.scrollbar {
				width: 12rpx;
				height: 100%;
				background: #D9D9D9;
				border-radius: 6rpx;
				position: relative;
				margin-left: 10rpx;

				.thumb {
					width: 100%;
					height: 54rpx;
					background: #D3A358;
					border-radius: 20rpx;
					position: absolute;
					transition: top 0.1s;
				}
			}
		}
	}

	.form-box {
		width: calc(100% - 40rpx);
		margin: 20rpx;
		border-radius: 16rpx;
		font-size: 24rpx;
		box-shadow: 0rpx 0rpx 16rpx 0rpx #0000000A;

		.bot-warp {
			margin-bottom: 20rpx;
		}

		.form-bottom {
			position: fixed;
			bottom: 60rpx;
			left: 50%;
			transform: translateX(-50%);
			width: calc(100% - 85rpx);

			.agree-content {
				font-size: 20rpx;
				text-align: justify;
				display: flex;
				justify-content: space-between;
				margin-bottom: 15rpx;

				image {
					width: 18rpx;
					height: 18rpx;
					margin-top: 6rpx;
				}

				.read-text {
					width: calc(100% - 25rpx);

					.agree-text {
						color: #B27C1E;
						text-decoration: underline;
					}
				}
			}

			.form-btn {
				height: 90rpx;
				line-height: 90rpx;
				border-radius: 40rpx;
				background: #D3A458;
				color: #ffffff;
				font-size: 32rpx;
				z-index: 2;
			}
		}

	}
}
</style>