<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.bgly" :range-key="'label'"
						:value="getDictIndex('bgly', editForm.changeReason)" @change="handleDictChange('bgly', $event)">
						<view class="item-picker">
							{{ getDictLabel('bgly', 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.dkmc" placeholder="请输入"
						placeholder-class="input-placeholder" />
				</view>

				<view class="form-item">
					<view class="item-label">确权面积（合同）<text class="required">*</text></view>
					<input class="item-input" v-model="editForm.htmj" placeholder="请输入"
						placeholder-class="input-placeholder" type="digit" />
					<view class="unit">亩</view>
				</view>

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

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

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

				<view class="form-item">
					<view class="item-label">地力等级<text class="required">*</text></view>
					<picker :range="dictData.dldj" :range-key="'label'" :value="getDictIndex('dldj', editForm.dldj)"
						@change="handleDictChange('dldj', $event)">
						<view class="item-picker">
							{{ getDictLabel('dldj', editForm.dldj) || '请选择' }}
							<text class="picker-arrow">▼</text>
						</view>
					</picker>
				</view>

				<view class="form-item">
					<view class="item-label">土地用途<text class="required">*</text></view>
					<picker :range="dictData.tdyt" :range-key="'label'" :value="getDictIndex('tdyt', editForm.tdyt)"
						@change="handleDictChange('tdyt', $event)">
						<view class="item-picker">
							{{ getDictLabel('tdyt', editForm.tdyt) || '请选择' }}
							<text class="picker-arrow">▼</text>
						</view>
					</picker>
				</view>

				<view class="form-item">
					<view class="item-label">基本农田<text class="required">*</text></view>
					<picker :range="dictData.jbnt" :range-key="'label'" :value="getDictIndex('jbnt', editForm.sfjbnt)"
						@change="handleDictChange('jbnt', $event)">
						<view class="item-picker">
							{{ getDictLabel('jbnt', editForm.sfjbnt) || '请选择' }}
							<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.dkdz" placeholder="请输入"
						placeholder-class="input-placeholder" />
				</view>

				<view class="form-item">
					<view class="item-label">地块西至<text class="required">*</text></view>
					<input class="item-input" v-model="editForm.dkxz" placeholder="请输入"
						placeholder-class="input-placeholder" />
				</view>

				<view class="form-item">
					<view class="item-label">地块南至<text class="required">*</text></view>
					<input class="item-input" v-model="editForm.dknz" placeholder="请输入"
						placeholder-class="input-placeholder" />
				</view>

				<view class="form-item">
					<view class="item-label">地块北至<text class="required">*</text></view>
					<input class="item-input" v-model="editForm.dkbz" placeholder="请输入"
						placeholder-class="input-placeholder" />
				</view>

				<!-- <view class="form-item">
					<view class="text-[30rpx] text-[#666]">范围选择</view>
					<view class="text-[30rpx] text-[#333]" @click="handleChooseRange">在地图上打点框选大致范围</view>
				</view> -->

				<view class="form-item form-item-textarea">
					<view class="item-label">备注信息</view>
					<textarea class="item-textarea" v-model="editForm.remark" 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.xczj.img" :key="idx">
							<image :src="img" class="upload-img" mode="aspectFill" />
							<view class="del-btn" @click.stop="delImg('xczj', idx)">×</view>
						</view>
						<view class="upload-box add-box" @click="handleUploadImage('xczj')">
							<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.fjzl.img" :key="idx">
							<image :src="img" class="upload-img" mode="aspectFill" />
							<view class="del-btn" @click.stop="delImg('fjzl', idx)">×</view>
						</view>
						<view class="upload-box add-box" @click="handleUploadImage('fjzl')">
							<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,onShow } from '@dcloudio/uni-app';
	import { uploadFile } from '@/utils/upload.js';
	import { getDictData, updateLandInfo } from '@/api/farmerApi.js';

	// ==================== 类型定义（完全匹配后端字段） ====================
	interface DictItem {
		value : string;
		label : string;
	}
	interface DictData {
		bgly : DictItem[];
		syqxz : DictItem[];
		dklb : DictItem[];
		lylx : DictItem[];
		dldj : DictItem[];
		tdyt : DictItem[];
		jbnt : DictItem[];
	}
	// 后端 dkTemp 完整字段结构
	interface DkTemp {
		auditOpinion : string;
		bizStatus : number;
		bsm : number;
		changeReason : string;
		dkbm : string;
		dkbz : string;
		dkbzxx : string;
		dkdz : string;
		dklb : string;
		dkmc : string;
		dknz : string;
		dkxz : string;
		dldj : string;
		kjzb : string;
		remark : string;
		scmj : number;
		htmj : number;
		sfjbnt : string;
		status : number;
		syqxz : string;
		tdlylx : string;
		tdyt : string;
		ysdm : string;
		zjrxm : string;
	}
	interface EditForm {
		// 页面绑定字段（映射后端）
		changeReason : string;
		dkmc : string;
		htmj : string;
		syqxz : string;
		dklb : string;
		tdlylx : string;
		dldj : string;
		tdyt : string;
		sfjbnt : string;
		dkdz : string;
		dkxz : string;
		dknz : string;
		dkbz : string;
		remark : string;
	}
	interface ImageItem {
		img : string[];
		number : string[];
	}
	interface ImageList {
		xczj : ImageItem;
		fjzl : ImageItem;
	}
	type DictType = keyof DictData;

	// ==================== 响应式数据 ====================
	const rowData = ref<any>({});
	const addCbfbm = ref<any>({});
	const fbfbmcd = ref<any>({});
	const dictData = ref<DictData>({
		bgly: [], syqxz: [], dklb: [], lylx: [], dldj: [], tdyt: [], jbnt: []
	});
	const editForm = ref<EditForm>({
		changeReason: '',
		dkmc: '',
		htmj: '',
		syqxz: '',
		dklb: '',
		tdlylx: '',
		dldj: '',
		tdyt: '',
		sfjbnt: '',
		dkdz: '',
		dkxz: '',
		dknz: '',
		dkbz: '',
		remark: ''
	});
	const coordinateData = ref<Array>([])

	// ✅ 和家庭成员完全一样的图片结构
	const imageList = ref<ImageList>({
		xczj: { img: [], number: [] },
		fjzl: { 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;
		// 字段映射：根据字典类型对应到 editForm 字段
		if (dictType === 'bgly') {
			editForm.value.changeReason = list[e.detail.value]?.value || '';
		} else if (dictType === 'lylx') {
			editForm.value.tdlylx = list[e.detail.value]?.value || '';
		} else if (dictType === 'jbnt') {
			editForm.value.sfjbnt = list[e.detail.value]?.value || '';
		} else {
			editForm.value[dictType as keyof EditForm] = list[e.detail.value]?.value || '';
		}
	};

	// ==================== 字典加载 ====================
	const loadDictData = async () => {
		try {
			const [bgly, syqxz, dklb, lylx, dldj, tdyt, jbnt] = await Promise.all([
				getDictData('dic_bgly'), getDictData('dic_syqxz'), getDictData('dic_dklb'),
				getDictData('dic_tdlylx'), getDictData('dic_dldj'), getDictData('dic_tdyt'), getDictData('dic_sf')
			]);
			dictData.value.bgly = transformDictFormat(bgly.data);
			dictData.value.syqxz = transformDictFormat(syqxz.data);
			dictData.value.dklb = transformDictFormat(dklb.data);
			dictData.value.lylx = transformDictFormat(lylx.data);
			dictData.value.dldj = transformDictFormat(dldj.data);
			dictData.value.tdyt = transformDictFormat(tdyt.data);
			dictData.value.jbnt = transformDictFormat(jbnt.data);
		} catch (err) {
			uni.showToast({ title: '字典加载失败', icon: 'none' });
		}
	};

	// ==================== ✅ 完全和家庭成员一样的上传方法 ====================
	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);
				imageList.value[type].number.push(result.data.id);
				uni.showToast({ title: '上传成功', icon: 'success' });
			} else {
				uni.showToast({ title: '上传失败', icon: 'none' });
			}
		} catch (err) {
			uni.showToast({ title: '取消上传', icon: 'none' });
		} finally {
			uni.hideLoading();
		}
	};

	// ==================== ✅ 删除：和家庭成员完全一样 ====================
	const delImg = (type : keyof ImageList, index : number) => {
		imageList.value[type].img.splice(index, 1);
		imageList.value[type].number.splice(index, 1);
	};

	// ==================== 初始化回显（支持旧字段名自动映射） ====================
	const initEditForm = () => {
		if (!rowData.value || !rowData.value.dkTemp) return;
		const dkTemp = rowData.value.dkTemp;
		// 回填页面字段
		editForm.value = {
			changeReason: dkTemp.changeReason || '',
			dkmc: dkTemp.dkmc || '',
			htmj: dkTemp.htmj || '',
			syqxz: dkTemp.syqxz || '',
			dklb: dkTemp.dklb || '',
			tdlylx: dkTemp.tdlylx || '',
			dldj: dkTemp.dldj || '',
			tdyt: dkTemp.tdyt || '',
			sfjbnt: dkTemp.sfjbnt || '',
			dkdz: dkTemp.dkdz || '',
			dkxz: dkTemp.dkxz || '',
			dknz: dkTemp.dknz || '',
			dkbz: dkTemp.dkbz || '',
			remark: dkTemp.remark || ''
		};

		// 图片回显
		imageList.value.xczj.img = rowData.value.xczjUrl ? [rowData.value.xczjUrl] : [];
		imageList.value.xczj.number = rowData.value.attachmentxczjFileIds || [];
		imageList.value.fjzl.img = rowData.value.fjzlUrl ? [rowData.value.fjzlUrl] : [];
		imageList.value.fjzl.number = rowData.value.attachmentfjzlFileIds || [];
	};

	// ==================== 表单校验 ====================
	const validateForm = () : boolean => {
		const { changeReason, dkmc, htmj, syqxz, dklb, tdlylx, dldj, tdyt, sfjbnt, dkdz, dkxz, dknz, dkbz } = editForm.value;
		if (!changeReason) { uni.showToast({ title: '请选择变更理由', icon: 'none' }); return false; }
		if (!dkmc?.trim()) { uni.showToast({ title: '请输入地块名称', icon: 'none' }); return false; }
		if (!htmj?.trim()) { uni.showToast({ title: '请输入确权面积', icon: 'none' }); return false; }
		if (!syqxz) { uni.showToast({ title: '请选择所有权性质', icon: 'none' }); return false; }
		if (!dklb) { uni.showToast({ title: '请选择地块类别', icon: 'none' }); return false; }
		if (!tdlylx) { uni.showToast({ title: '请选择利用类型', icon: 'none' }); return false; }
		if (!dldj) { uni.showToast({ title: '请选择地力等级', icon: 'none' }); return false; }
		if (!tdyt) { uni.showToast({ title: '请选择土地用途', icon: 'none' }); return false; }
		if (!sfjbnt) { uni.showToast({ title: '请选择基本农田', icon: 'none' }); return false; }
		if (!dkdz?.trim()) { uni.showToast({ title: '请输入东至', icon: 'none' }); return false; }
		if (!dkxz?.trim()) { uni.showToast({ title: '请输入西至', icon: 'none' }); return false; }
		if (!dknz?.trim()) { uni.showToast({ title: '请输入南至', icon: 'none' }); return false; }
		if (!dkbz?.trim()) { uni.showToast({ title: '请输入北至', icon: 'none' }); return false; }
		if (imageList.value.fjzl.number.length === 0) { uni.showToast({ title: '请上传附件资料', icon: 'none' }); return false; }
		return true;
	};

	// ==================== 提交（完全匹配后端结构，空值自动补全） ====================
	const handleSubmit = async () => {
		if (!validateForm()) return;

		// 1. 构建 dkTemp 对象，完全匹配后端字段，未填写的自动补空/0
		const dkTemp : DkTemp = {
			auditOpinion: '', // 页面无输入，固定空
			bizStatus: '',     // 页面无输入，固定0
			bsm: '',           // 页面无输入，固定0
			changeReason: editForm.value.changeReason || '',
			dkbm: fbfbmcd.value,       // 页面无输入，固定空
			dkbz: editForm.value.dkbz || '',
			dkbzxx: '',       // 页面无输入，固定空
			dkdz: editForm.value.dkdz || '',
			dklb: editForm.value.dklb || '',
			dkmc: editForm.value.dkmc || '',
			dknz: editForm.value.dknz || '',
			dkxz: editForm.value.dkxz || '',
			dldj: editForm.value.dldj || '',
			kjzb: '',         // 页面无输入，固定空
			remark: editForm.value.remark || '',
			scmj: '',          // 页面无输入，固定0
			htmj: Number(editForm.value.htmj) || '', // 字符串转数字，空则0
			sfjbnt: editForm.value.sfjbnt || '',
			status: '',        // 页面无输入，固定0
			syqxz: editForm.value.syqxz || '',
			tdlylx: editForm.value.tdlylx || '',
			tdyt: editForm.value.tdyt || '',
			ysdm: '',         // 页面无输入，固定空
			zjrxm: ''         // 页面无输入，固定空
		};

		// 2. 构建完整提交数据，完全匹配后端结构
		const submitData = {
			dkTemp,
			attachmentxczjFileIds: imageList.value.xczj.number || [],
			attachmentfjzlFileIds: imageList.value.fjzl.number || [],
			// geoJson: [coordinateData.value] || [],
			geoJson: [],
			cbdkxxTemp: {
				cbfbm: addCbfbm.value,
				fbfbm: fbfbmcd.value
			}
		};
		uni.showLoading({ title: '提交中...' });
		try {
			const res = await updateLandInfo(submitData);
			if (res.code === 200) {
				uni.showToast({ title: '添加成功', 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);
			} else {
				uni.showToast({ title: res.msg || '提交失败', icon: 'none' });
			}
		} catch (err) {
			uni.showToast({ title: '提交失败', icon: 'none' });
		} finally {
			uni.hideLoading();
		}
	};


	const handleChooseRange = () => {
		uni.navigateTo({ url: `/pages/map/map?memberInfo=${encodeURIComponent(JSON.stringify(addCbfbm.value))}` })
	};

	// ==================== 入口 ====================
	onLoad(async (options) => {
		fbfbmcd.value = options.cbfbm.substring(0, 14);
		addCbfbm.value = options.cbfbm;
		await loadDictData();
		initEditForm();

	});
	// addLand.vue
	onShow(() => {
	  const pages = getCurrentPages()
	  const currentPage = pages[pages.length - 1]
	
	  // 接收从 map.vue 回来的数据
	  if (currentPage.$vm.selectedLandData) {
	    // console.log('✅ addLand 收到地图返回的数据：', currentPage.$vm.selectedLandData)
	    
	    // 你可以直接赋值给表单
	    coordinateData.value = currentPage.$vm.selectedLandData.points
	    // console.log('收到地图返回的数据',coordinateData.value)
	    // 用完清空，防止重复
	    currentPage.$vm.selectedLandData = null
	  }
	})
</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;
	}

	.unit {
		margin-left: 10rpx;
		font-size: 28rpx;
		color: #666;
	}

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