<template>
	<view class="page-container">
		<view class="section">
			<view class="section-header">
				<view class="section-title">基本信息</view>
				<view class="header-right">
					<view class="info-icon">ⓘ</view>
					<view class="delete-btn-top" @click="handleTopDelete">删除</view>
				</view>
			</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')"
						@change="(e) => handleDictChange('changeReason', 'changeReason', e)">
						<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.memberName" placeholder="请输入"
						placeholder-class="input-placeholder" />
				</view>

				<!-- 证件类型 -->
				<view class="form-item">
					<view class="item-label">证件类型<text class="required">*</text></view>
					<picker :range="dictData.idType" range-key="label" :value="getDictIndex('idType')"
						@change="(e) => handleDictChange('idType', 'idType', e)">
						<view class="item-picker">
							{{ getDictLabel('idType', editForm.idType) || '请选择' }}
							<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.idNumber" placeholder="请输入"
						placeholder-class="input-placeholder" maxlength="18" />
				</view>

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

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

				<!-- 成员备注 -->
				<view class="form-item">
					<view class="item-label">成员备注</view>
					<picker :range="dictData.memberRemark" range-key="label" :value="getDictIndex('memberRemark')"
						@change="(e) => handleDictChange('memberRemark', 'memberRemark', e)">
						<view class="item-picker">
							{{ getDictLabel('memberRemark', editForm.memberRemark) || '请选择' }}
							<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')"
						@change="(e) => handleDictChange('sf', 'sfgyr', e)">
						<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.remarkDesc" 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.attachmentsfzzmFileIds.img" :key="idx">
							<image :src="img" class="upload-img" mode="aspectFill" />
							<!-- ✅ 修复：传递正确索引 -->
							<view class="del-btn" @click.stop="delImg('attachmentsfzzmFileIds', idx)">×</view>
						</view>
						<view class="upload-box add-box" @click="handleUploadImage('attachmentsfzzmFileIds')">
							<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.attachmentsfzfmFileIds.img" :key="idx">
							<image :src="img" class="upload-img" mode="aspectFill" />
							<!-- ✅ 修复：传递正确索引 -->
							<view class="del-btn" @click.stop="delImg('attachmentsfzfmFileIds', idx)">×</view>
						</view>
						<view class="upload-box add-box" @click="handleUploadImage('attachmentsfzfmFileIds')">
							<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.attachmentszmclFileIds.img" :key="idx">
							<image :src="img" class="upload-img" mode="aspectFill" />
							<!-- ✅ 修复：传递正确索引 -->
							<view class="del-btn" @click.stop="delImg('attachmentszmclFileIds', idx)">×</view>
						</view>
						<view class="upload-box add-box" @click="handleUploadImage('attachmentszmclFileIds')">
							<view class="upload-plus">+</view>
						</view>
					</view>
				</view>
			</view>
		</view>

		<view class="bottom-buttons">
			<view class="btn-delete" @click="handleDelete">删除</view>
			<view class="btn-modify" @click="handleModify">修改</view>
		</view>
	</view>
</template>

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

	// ==================== 类型定义 ====================
	interface DictItem {
		value: string;
		label: string;
	}
	interface DictData {
		changeReason: DictItem[];
		idType: DictItem[];
		gender: DictItem[];
		relation: DictItem[];
		memberRemark: DictItem[];
		sf: DictItem[];
	}
	interface EditForm {
		changeReason: string;
		memberName: string;
		idType: string;
		idNumber: string;
		gender: string;
		relation: string;
		memberRemark: string;
		sfgyr: string;
		remarkDesc: string;
	}
	interface ImageItem {
		img: string[];
		number: string[];
	}
	interface ImageList {
		attachmentsfzzmFileIds: ImageItem;
		attachmentsfzfmFileIds: ImageItem;
		attachmentszmclFileIds: ImageItem;
	}
	type ImageType = keyof ImageList;

	// ==================== 响应式数据 ====================
	const m = ref<any>(null);
	const dictData = ref<DictData>({
		changeReason: [], idType: [], gender: [], relation: [], memberRemark: [], sf: []
	});

	const editForm = ref<EditForm>({
		changeReason: '', memberName: '', idType: '', idNumber: '', gender: '', relation: '',
		memberRemark: '', sfgyr: '', remarkDesc: ''
	});

	const imageList = ref<ImageList>({
		attachmentsfzzmFileIds: { img: [], number: [] },
		attachmentsfzfmFileIds: { img: [], number: [] },
		attachmentszmclFileIds: { img: [], number: [] }
	});

	// ==================== 字典工具函数 ====================
	const transformDictFormat = (data: Record<string, any>): DictItem[] =>
		Object.entries(data || {}).map(([k, v]) => ({ value: k, label: v }));

	const getDictLabel = (type: string, val: any): string =>
		dictData.value[type as keyof DictData]?.find(i => i.value === val)?.label || '';

	const getDictIndex = (type: string): number => {
		const val = type === 'sf' ? editForm.value.sfgyr : editForm.value[type as keyof EditForm];
		return dictData.value[type as keyof DictData]?.findIndex(i => i.value === val) || 0;
	};

	const handleDictChange = (dictType: string, formField: string, e: any) => {
		if (!e || !e.detail) return;
		editForm.value[formField as keyof EditForm] = dictData.value[dictType as keyof DictData][e.detail.value]?.value || '';
	};

	// ==================== 加载字典 ====================
	const loadDictData = async () => {
		try {
			const keys = ['dic_bgly', 'dic_zjlx', 'dic_xb', 'dic_yhzgx', 'dic_cybz', 'dic_sf'];
			const [bgly, zjlx, xb, yhzgx, cybz, sf] = await Promise.all(keys.map(getDictData));
			dictData.value = {
				changeReason: bgly?.code === 200 ? transformDictFormat(bgly.data) : [],
				idType: zjlx?.code === 200 ? transformDictFormat(zjlx.data) : [],
				gender: xb?.code === 200 ? transformDictFormat(xb.data) : [],
				relation: yhzgx?.code === 200 ? transformDictFormat(yhzgx.data) : [],
				memberRemark: cybz?.code === 200 ? transformDictFormat(cybz.data) : [],
				sf: sf?.code === 200 ? transformDictFormat(sf.data) : []
			};
		} catch (e) {
			uni.showToast({ title: '字典加载失败', icon: 'none' });
		}
	};

	// ==================== 上传图片 ====================
	const handleUploadImage = async (type: ImageType) => {
		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);
				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();
		}
	};

	// ==================== ✅ 优化：删除图片 —— 获取被删除的图片ID ====================
	const delImg = async (type: ImageType, index: number) => {
		// 1. ✅ 获取要删除的图片ID（核心你要的功能）
		const deletedId = imageList.value[type].number[index];
		console.log("被删除的图片ID：", deletedId); // 你要的ID

		// 2. 可选：调用后端接口删除服务器文件（如果需要）
		if (deletedId) {
			try {
				await deletefMaterials(deletedId);
				console.log("调用删除接口，ID：", deletedId);
			} catch (e) {
				console.error("删除服务器文件失败", e);
			}
		}

		// 3. 同步删除界面显示和ID数组
		imageList.value[type].img.splice(index, 1);
		imageList.value[type].number.splice(index, 1);

		uni.showToast({
			title: "已删除",
			icon: "success"
		});
	};

	// ==================== 删除成员 ====================
	const handleTopDelete = async () => {
		if (!m.value?.id) {
			uni.showToast({ title: '未获取到数据ID，无法删除', icon: 'none' });
			return;
		}

		uni.showModal({
			content: '确定删除？',
			success: async (res) => {
				if (!res.confirm) return;

				uni.showLoading({ title: '删除中...' });
				try {
					const result = await DeletefamilyMembers(m.value.id);
					uni.hideLoading();

					if (result?.code === 200) {
						uni.showToast({ title: '删除成功' });
						setTimeout(() => {
							uni.navigateBack({
								success: () => {
									const pages = getCurrentPages();
									const prevPage = pages[pages.length - 1];
									if (prevPage && typeof prevPage.onLoad === 'function') {
										prevPage.onLoad(prevPage.options);
									}
								}
							});
						}, 1500);
					} else {
						uni.showToast({ title: result?.msg || '删除失败', icon: 'none' });
					}
				} catch (err) {
					uni.hideLoading();
					uni.showToast({ title: '删除接口异常', icon: 'none' });
				}
			}
		});
	};

	const handleDelete = handleTopDelete;

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

	// ==================== 修改提交 ====================
	const handleModify = async () => {
		const f = editForm.value;
		const checkList = [
			[f.changeReason, '请选择变更理由'],
			[f.memberName, '请输入姓名'],
			[f.idType, '请选择证件类型'],
			[f.idNumber, '请输入证件号'],
			[f.gender, '请选择性别'],
			[f.relation, '请选择与户主关系'],
			[imageList.value.attachmentszmclFileIds.number.length, '请上传证明材料']
		];
		for (const [val, msg] of checkList) {
			if (!val) {
				uni.showToast({ title: msg, icon: 'none' });
				return;
			}
		}

		const submitData = {
			auditOpinion: '', bizStatus: '', cbfbm: m.value?.cbfbm, changeReason: f.changeReason,
			cyxm: f.memberName, cyzjlx: f.idType, cyzjhm: f.idNumber, cyxb: f.gender,
			yhzgx: f.relation, cybz: f.memberRemark, sfgyr: f.sfgyr, cybzsm: f.remarkDesc,
			attachmentsfzzmFileIds: imageList.value.attachmentsfzzmFileIds.number,
			attachmentsfzfmFileIds: imageList.value.attachmentsfzfmFileIds.number,
			attachmentszmclFileIds: imageList.value.attachmentszmclFileIds.number
		};

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

	// ==================== 页面初始化 ====================
	onLoad(async (options: any) => {
		await loadDictData();
		if (options.memberInfo) {
			const info = JSON.parse(decodeURIComponent(options.memberInfo));
			m.value = info;
			
			editForm.value = {
				changeReason: info.changeReason || '', memberName: info.cyxm || '', idType: info.cyzjlx || '',
				idNumber: info.cyzjhm || '', gender: info.cyxb || '', relation: info.yhzgx || '',
				memberRemark: info.cybz || '', sfgyr: info.sfgyr || '', remarkDesc: info.cybzsm || ''
			};

			const bizTypeMap: Record<string, ImageType> = {
				'CBF_JTCY_TEMP_SFZFM': 'attachmentsfzfmFileIds',
				'CBF_JTCY_TEMP_SFZZM': 'attachmentsfzzmFileIds',
				'CBF_JTCY_TEMP_ZMCL': 'attachmentszmclFileIds'
			};
			console.log(123321,editForm.value)
			console.log(222,info.attachments)
			if (info.attachments && Array.isArray(info.attachments)) {
				info.attachments.forEach((item: any) => {
					const type = bizTypeMap[item.bizType];
					if (type && item.filePath && item.id) {
						const fullImgUrl = imgBaseURL + item.filePath;
						imageList.value[type].img.push(fullImgUrl);
						imageList.value[type].number.push(String(item.id));
					}
				});
			}
		}
	});
</script>

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

	.page-container {
		padding-bottom: 40rpx;
	}

	.section {
		margin-bottom: 40rpx;
	}

	.section-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20rpx;
		padding-left: 10rpx;
	}

	.section-title {
		font-size: 36rpx;
		font-weight: bold;
		color: #333;
	}

	.header-right {
		display: flex;
		align-items: center;
		gap: 20rpx;
	}

	.info-icon {
		width: 48rpx;
		height: 48rpx;
		border-radius: 50%;
		border: 2rpx solid #f56c6c;
		color: #f56c6c;
		font-size: 28rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		line-height: 48rpx;
	}

	.delete-btn-top {
		background-color: #f56c6c;
		color: #fff;
		font-size: 32rpx;
		font-weight: 500;
		padding: 10rpx 40rpx;
		border-radius: 40rpx;
	}

	.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;
		}
	}

	.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;
		background: transparent;

		&::placeholder {
			color: #c9cdd4;
		}

		&:disabled {
			color: #333;
			opacity: 1;
		}
	}

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

		&:last-child {
			margin-bottom: 0;
		}
	}

	.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;
	}

	.bottom-buttons {
		display: flex;
		gap: 20rpx;
		padding: 0 20rpx;
		margin-top: 20rpx;
	}

	.btn-delete {
		flex: 1;
		height: 90rpx;
		background-color: #f56c6c;
		color: #fff;
		font-size: 36rpx;
		font-weight: 500;
		border-radius: 45rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		box-shadow: 0 4rpx 12rpx rgba(245, 108, 108, 0.3);
	}

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