<template>
	<view class="page-container">
		<!-- 基本信息区域 -->
		<view class="section">
			<view class="section-title">基本信息</view>
			<view class="form-card">
				<!-- 变更理由 -->
				<view class="form-item">
					<view class="item-label">变更理由<text class="required">*</text></view>
					<picker :range="dictData.changeReason" :range-key="'label'"
						:value="getDictIndex('changeReason', editForm.changeReason)"
						@change="handleDictChange('changeReason', $event)">
						<view class="item-picker">
							{{ getDictLabel('changeReason', editForm.changeReason) || '请选择' }}
							<text class="picker-arrow">▼</text>
						</view>
					</picker>
				</view>

				<!-- 成员姓名 -->
				<view class="form-item">
					<view class="item-label">成员姓名<text class="required">*</text></view>
					<input class="item-input" v-model="editForm.cyxm" placeholder="请输入"
						placeholder-class="input-placeholder" />
				</view>

				<!-- 证件类型 -->
				<view class="form-item">
					<view class="item-label">证件类型<text class="required">*</text></view>
					<picker :range="dictData.cyzjlx" :range-key="'label'"
						:value="getDictIndex('cyzjlx', editForm.cyzjlx)" @change="handleDictChange('cyzjlx', $event)">
						<view class="item-picker">
							{{ getDictLabel('cyzjlx', editForm.cyzjlx) || '请选择' }}
							<text class="picker-arrow">▼</text>
						</view>
					</picker>
				</view>

				<!-- 证件号码 -->
				<view class="form-item">
					<view class="item-label">证件号码<text class="required">*</text></view>
					<input class="item-input" v-model="editForm.cyzjhm" placeholder="请输入"
						placeholder-class="input-placeholder" maxlength="18" />
				</view>

				<!-- 成员性别 -->
				<view class="form-item">
					<view class="item-label">成员性别<text class="required">*</text></view>
					<picker :range="dictData.cyxb" :range-key="'label'" :value="getDictIndex('cyxb', editForm.cyxb)"
						@change="handleDictChange('cyxb', $event)">
						<view class="item-picker">
							{{ getDictLabel('cyxb', editForm.cyxb) || '请选择' }}
							<text class="picker-arrow">▼</text>
						</view>
					</picker>
				</view>

				<!-- 与户主关系 -->
				<view class="form-item">
					<view class="item-label">与户主关系<text class="required">*</text></view>
					<picker :range="dictData.yhzgx" :range-key="'label'" :value="getDictIndex('yhzgx', editForm.yhzgx)"
						@change="handleDictChange('yhzgx', $event)">
						<view class="item-picker">
							{{ getDictLabel('yhzgx', editForm.yhzgx) || '请选择' }}
							<text class="picker-arrow">▼</text>
						</view>
					</picker>
				</view>

				<!-- 成员备注 -->
				<view class="form-item">
					<view class="item-label">成员备注</view>
					<picker :range="dictData.cybz" :range-key="'label'" :value="getDictIndex('cybz', editForm.cybz)"
						@change="handleDictChange('cybz', $event)">
						<view class="item-picker">
							{{ getDictLabel('cybz', editForm.cybz) || '请选择' }}
							<text class="picker-arrow">▼</text>
						</view>
					</picker>
				</view>

				<!-- 是否共有人 -->
				<view class="form-item">
					<view class="item-label">是否共有人</view>
					<picker :range="dictData.sf" :range-key="'label'" :value="getDictIndex('sf', editForm.sfgyr)"
						@change="handleDictChange('sf', $event)">
						<view class="item-picker">
							{{ getDictLabel('sf', editForm.sfgyr) || '请选择' }}
							<text class="picker-arrow">▼</text>
						</view>
					</picker>
				</view>

				<!-- 成员备注说明 -->
				<view class="form-item form-item-textarea">
					<view class="item-label">成员备注说明</view>
					<textarea class="item-textarea" v-model="editForm.cybzsm" placeholder="请输入"
						placeholder-class="input-placeholder" />
				</view>
			</view>
		</view>

		<!-- 图片信息区域 -->
		<view class="section">
			<view class="section-title">图片信息</view>
			<view class="form-card">
				<!-- 身份证人像面 -->
				<view class="upload-item">
					<view class="upload-title">身份证人像面（可用于识别姓名和身份证号码，错误请自行修改）</view>
					<view class="upload-wrap">
						<view class="upload-box" v-for="(img, idx) in imageList.idFront.img" :key="idx">
							<image :src="img" class="upload-img" mode="aspectFill" />
							<view class="del-btn" @click.stop="delImg('idFront', idx)">×</view>
						</view>
						<view class="upload-box add-box" @click="handleUploadImage('idFront')">
							<view class="upload-plus">+</view>
						</view>
					</view>
				</view>

				<!-- 身份证国徽面 -->
				<view class="upload-item">
					<view class="upload-title">身份证国徽面</view>
					<view class="upload-wrap">
						<view class="upload-box" v-for="(img, idx) in imageList.idBack.img" :key="idx">
							<image :src="img" class="upload-img" mode="aspectFill" />
							<view class="del-btn" @click.stop="delImg('idBack', idx)">×</view>
						</view>
						<view class="upload-box add-box" @click="handleUploadImage('idBack')">
							<view class="upload-plus">+</view>
						</view>
					</view>
				</view>

				<!-- 证明材料 -->
				<view class="upload-item">
					<view class="upload-title required">*证明材料(修改请上传户口本对应页,删除请上传证明材料)</view>
					<view class="upload-wrap">
						<view class="upload-box" v-for="(img, idx) in imageList.certificate.img" :key="idx">
							<image :src="img" class="upload-img" mode="aspectFill" />
							<view class="del-btn" @click.stop="delImg('certificate', idx)">×</view>
						</view>
						<view class="upload-box add-box" @click="handleUploadImage('certificate')">
							<view class="upload-plus">+</view>
						</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 底部添加按钮 -->
		<view class="submit-btn" @click="handleSubmit">添加</view>
	</view>
</template>

<script setup lang="ts">
	import { ref, computed } from 'vue';
	import { onLoad } from '@dcloudio/uni-app';
	import { uploadFile } from '@/utils/upload.js'
	import { getDictData, addfamilyMembersList } from '@/api/farmerApi.js';

	// ==================== 类型定义 ====================
	interface DictItem {
		value: string;
		label: string;
	}
	interface DictData {
		changeReason: DictItem[];
		cyzjlx: DictItem[];
		cyxb: DictItem[];
		yhzgx: DictItem[];
		cybz: DictItem[];
		sf: DictItem[];
	}
	interface EditForm {
		auditOpinion: string;
		bizStatus: string;
		changeReason: string;
		sfgyr: string;
		cyxm: string;
		cyzjlx: string;
		cyzjhm: string;
		cyxb: string;
		yhzgx: string;
		cybz: string;
		cybzsm: string;
		cbfbm?: any;
	}
	
	// ✅ 类型同步修改
	interface ImageItem {
		img: string[];
		number: string[];
	}
	interface ImageList {
		idFront: ImageItem;
		idBack: ImageItem;
		certificate: ImageItem;
	}
	type DictType = keyof DictData;

	// ==================== 响应式数据 ====================
	const member = ref<any>(null);
	const dictData = ref<DictData>({
		changeReason: [],
		cyzjlx: [],
		cyxb: [],
		yhzgx: [],
		cybz: [],
		sf: []
	});
	const editForm = ref<EditForm>({
		auditOpinion: '',
		bizStatus: '',
		changeReason: '',
		sfgyr: '',
		cyxm: '',
		cyzjlx: '',
		cyzjhm: '',
		cyxb: '',
		yhzgx: '',
		cybz: '',
		cybzsm: ''
	});

	// ✅ 统一结构：img 显示 / number 存后端ID
	const imageList = ref<ImageList>({
		idFront: { img: [], number: [] },
		idBack: { img: [], number: [] },
		certificate: { img: [], number: [] }
	});

	// ==================== 字典工具函数 ====================
	const transformDictFormat = (originalDict: Record<string | number, string>): DictItem[] => {
		if (!originalDict || typeof originalDict !== 'object') return [];
		return Object.entries(originalDict).map(([key, value]) => ({
			value: String(key),
			label: value as string
		}));
	};
	const getDictLabel = (dictType: DictType, value: string | number | undefined): string => {
		if (!value || !dictData.value[dictType]?.length) return '';
		const item = dictData.value[dictType].find(item => String(item.value) === String(value));
		return item?.label || '';
	};
	const getDictIndex = computed(() => {
		return (dictType: DictType, value: string) => {
			if (!value || !dictData.value[dictType].length) return 0;
			return dictData.value[dictType].findIndex(item => String(item.value) === String(value));
		};
	});
	const handleDictChange = (dictType: DictType, e: any) => {
		const list = dictData.value[dictType];
		if (!list.length) return;
		if (dictType === 'sf') {
			editForm.value.sfgyr = list[e.detail.value]?.value || '';
		} else if (dictType === 'changeReason') {
			editForm.value.changeReason = list[e.detail.value]?.value || '';
		} else {
			editForm.value[dictType] = list[e.detail.value]?.value || '';
		}
	};

	// ==================== 字典加载 ====================
	const loadDictData = async () => {
		try {
			const [resChangeReason, rescyzjlx, rescyxb, resyhzgx, resRemark, ressf] = await Promise.all([
				getDictData('dic_bgly'),
				getDictData('dic_zjlx'),
				getDictData('dic_xb'),
				getDictData('dic_yhzgx'),
				getDictData('dic_cybz'),
				getDictData('dic_sf')
			]);
			dictData.value.changeReason = resChangeReason?.code === 200 ? transformDictFormat(resChangeReason.data) : [];
			dictData.value.cyzjlx = rescyzjlx?.code === 200 ? transformDictFormat(rescyzjlx.data) : [];
			dictData.value.cyxb = rescyxb?.code === 200 ? transformDictFormat(rescyxb.data) : [];
			dictData.value.yhzgx = resyhzgx?.code === 200 ? transformDictFormat(resyhzgx.data) : [];
			dictData.value.cybz = resRemark?.code === 200 ? transformDictFormat(resRemark.data) : [];
			dictData.value.sf = ressf?.code === 200 ? transformDictFormat(ressf.data) : [];
		} catch (err) {
			uni.showToast({ title: '字典加载失败', icon: 'none' });
		}
	};

	// ==================== ✅ 上传：分开存储 显示路径 + 提交ID ====================
	const handleUploadImage = async (type: keyof ImageList) => {
		try {
			const chooseRes = await uni.chooseImage({ count: 1, sizeType: ['compressed'] });
			const filePath = chooseRes.tempFilePaths[0];
			uni.showLoading({ title: '上传中...' });

			const result = await uploadFile(filePath);

			if (result.code === 200 && result.data.id) {
				// 🔥 本地路径 → 用于显示
				imageList.value[type].img.push(filePath);
				// 🔥 后端返回ID → 用于提交
				imageList.value[type].number.push(result.data.id);
				uni.showToast({ title: '上传成功', icon: 'success' });
			} else {
				uni.showToast({ title: '上传失败', icon: 'none' });
			}
		} catch (err) {
			console.error(err);
			uni.showToast({ title: '取消上传', icon: 'none' });
		} finally {
			uni.hideLoading();
		}
	};

	// ==================== ✅ 删除：同时删除 img 和 number，保持对应 ====================
	const delImg = (type: keyof ImageList, index: number) => {
		imageList.value[type].img.splice(index, 1);
		imageList.value[type].number.splice(index, 1);
	};

	// ==================== 表单校验 ====================
	const validateForm = (): boolean => {
		const { changeReason, cyxm, cyzjlx, cyzjhm, cyxb, yhzgx } = editForm.value;
		if (!changeReason) { uni.showToast({ title: '请选择变更理由', icon: 'none' }); return false; }
		if (!cyxm?.trim()) { uni.showToast({ title: '请输入成员姓名', icon: 'none' }); return false; }
		if (!cyzjlx) { uni.showToast({ title: '请选择证件类型', icon: 'none' }); return false; }
		if (!cyzjhm?.trim()) { uni.showToast({ title: '请输入证件号码', icon: 'none' }); return false; }
		if (!cyxb) { uni.showToast({ title: '请选择成员性别', icon: 'none' }); return false; }
		if (!yhzgx) { uni.showToast({ title: '请选择与户主关系', icon: 'none' }); return false; }
		if (imageList.value.certificate.number.length === 0) { uni.showToast({ title: '请上传证明材料', icon: 'none' }); return false; }
		return true;
	};

	// ==================== 提交接口 ====================
	const addFMList = async (addList: any) => {
		try {
			const res = await addfamilyMembersList(addList);
			if (res?.code === 200) return true;
			uni.showToast({ title: res?.msg || '提交失败', icon: 'none' });
			return false;
		} catch (err) {
			uni.showToast({ title: '网络异常', icon: 'none' });
			return false;
		}
	};

	// ==================== ✅ 提交：只拼接 ID 给后端 ====================
	const handleSubmit = async () => {
		if (!validateForm()) return;

		const submitData = {
			...editForm.value,
			cbfbm: member.value.cbfbm,
			attachmentsfzfmFileIds: imageList.value.idFront.number,
			attachmentsfzzmFileIds: imageList.value.idBack.number,
			attachmentszmclFileIds: imageList.value.certificate.number
		};

		uni.showLoading({ title: '提交中...' });
		const ok = await addFMList(submitData);
		if (ok) {
			uni.hideLoading();
			uni.showToast({ title: '添加成功', icon: 'success' });
			resetForm();
			setTimeout(() => {
				uni.navigateBack({
					success: () => {
						const pages = getCurrentPages();
						const prevPage = pages[pages.length - 1];
						if (prevPage && typeof prevPage.onLoad === 'function') {
							prevPage.onLoad(prevPage.options);
						}
					}
				});
			}, 1500);
		}
	};

	// ==================== 重置 ====================
	const resetForm = () => {
		editForm.value = {
			auditOpinion: '', bizStatus: '', changeReason: '', sfgyr: '',
			cyxm: '', cyzjlx: '', cyzjhm: '', cyxb: '', yhzgx: '', cybz: '', cybzsm: ''
		};
		imageList.value = {
			idFront: { img: [], number: [] },
			idBack: { img: [], number: [] },
			certificate: { img: [], number: [] }
		};
	};

	// ==================== 初始化 ====================
	onLoad(async (options: any) => {
		await loadDictData();
		if (options.memberInfo) {
			member.value = JSON.parse(decodeURIComponent(options.memberInfo));
			console.log(111,member.value)
			const info = member.value;
			editForm.value = { ...editForm.value, ...info };
		}
	});
</script>

<style lang="scss" scoped>
	.page-container {
		padding: 20rpx;
		padding-bottom: 40rpx;
		background-color: #f5faff;
	}

	.section {
		margin-bottom: 40rpx;
	}

	.section-title {
		font-size: 36rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 20rpx;
		padding-left: 10rpx;
	}

	.form-card {
		background-color: #fff;
		border-radius: 24rpx;
		padding: 30rpx;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
	}

	.form-item {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 30rpx 0;
		border-bottom: 1rpx solid #f0f0f0;

		&.form-item-textarea {
			align-items: flex-start;
			padding-bottom: 0;
			border-bottom: none;
			flex-direction: column;
		}
	}

	.item-label {
		font-size: 32rpx;
		color: #333;
		flex-shrink: 0;
	}

	.required {
		color: #f5222d;
		margin-left: 4rpx;
	}

	.item-input {
		flex: 1;
		text-align: right;
		font-size: 32rpx;
		color: #333;
		height: 40rpx;
		line-height: 40rpx;

		&::placeholder {
			color: #c9cdd4;
		}
	}

	.input-placeholder {
		color: #c9cdd4;
		font-size: 32rpx;
	}

	.item-picker {
		flex: 1;
		display: flex;
		align-items: center;
		justify-content: flex-end;
		font-size: 32rpx;
		color: #333;
		height: 40rpx;
		line-height: 40rpx;
	}

	.picker-arrow {
		margin-left: 10rpx;
		font-size: 28rpx;
		color: #333;
	}

	.item-textarea {
		width: 100%;
		min-height: 200rpx;
		font-size: 32rpx;
		color: #333;
		border: 1rpx solid #e5e6eb;
		border-radius: 12rpx;
		padding: 20rpx;
		box-sizing: border-box;
		margin-top: 20rpx;
	}

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

	.upload-title {
		font-size: 32rpx;
		color: #333;
		margin-bottom: 20rpx;
		line-height: 1.5;

		&.required::before {
			content: "*";
			color: #f5222d;
			margin-right: 4rpx;
		}
	}

	.upload-wrap {
		display: flex;
		flex-wrap: wrap;
		gap: 20rpx;
		align-items: center;
	}

	.upload-box {
		width: 280rpx;
		height: 280rpx;
		background-color: #f5f5f5;
		border-radius: 8rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		overflow: hidden;
		position: relative;
	}

	.upload-plus {
		font-size: 80rpx;
		color: #333;
		font-weight: 300;
	}

	.upload-img {
		width: 100%;
		height: 100%;
	}

	.add-box {
		border: 2rpx dashed #ccc;
	}

	.del-btn {
		position: absolute;
		top: 0;
		right: 0;
		width: 50rpx;
		height: 50rpx;
		background: rgba(255, 0, 0, 0.7);
		color: #fff;
		font-size: 30rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.submit-btn {
		width: 80%;
		height: 90rpx;
		background-color: #409eff;
		color: #fff;
		font-size: 36rpx;
		font-weight: 50;
		border-radius: 45rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		margin: 0 auto;
		box-shadow: 0 4rpx 12rpx rgba(64, 158, 255, 0.3);
	}
</style>