<template>
	<view class="page-container">
		<!-- 基本信息区域 -->
		<view class="section-title">基本信息</view>
		<view class="form-list">
			<!-- 变更理由 -->
			<view class="form-item">
				<text class="label">变更理由*</text>
				<text class="value">{{ getDictLabel('bgly', detailData.changeReason) || '无' }}</text>
			</view>

			<!-- 地块编号 -->
			<view class="form-item">
				<text class="label">地块编号*</text>
				<text class="value">{{ detailData.dkbm || '无' }}</text>
			</view>

			<!-- 地块名称 -->
			<view class="form-item">
				<text class="label">地块名称</text>
				<text class="value">{{ detailData.dkmc || '无' }}</text>
			</view>

			<!-- 确权面积 -->
			<view class="form-item">
				<text class="label">确权面积*</text>
				<text class="value">{{ detailData.htmjm || 0 }} 亩</text>
			</view>

			<!-- 所有权性质 -->
			<view class="form-item">
				<text class="label">所有权性质*</text>
				<text class="value">{{ getDictLabel('syqxz', detailData.syqxz) || '无' }}</text>
			</view>

			<!-- 地块类别 -->
			<view class="form-item">
				<text class="label">地块类别*</text>
				<text class="value">{{ getDictLabel('dklb', detailData.dklb) || '无' }}</text>
			</view>

			<!-- 利用类型 -->
			<view class="form-item">
				<text class="label">利用类型*</text>
				<text class="value">{{ getDictLabel('lylx', detailData.tdlylx) || '无' }}</text>
			</view>

			<!-- 地力等级 -->
			<view class="form-item">
				<text class="label">地力等级*</text>
				<text class="value">{{ getDictLabel('dldj', detailData.dldj) || '无' }}</text>
			</view>

			<!-- 土地用途 -->
			<view class="form-item">
				<text class="label">土地用途</text>
				<text class="value">{{ getDictLabel('tdyt', detailData.tdyt) || '无' }}</text>
			</view>

			<!-- 基本农田 -->
			<view class="form-item">
				<text class="label">基本农田*</text>
				<text class="value">{{ getDictLabel('jbnt', detailData.sfjbnt) || '无' }}</text>
			</view>

			<!-- 地块东至 -->
			<view class="form-item">
				<text class="label">地块东至*</text>
				<text class="value">{{ detailData.dkdz || '无' }}</text>
			</view>

			<!-- 地块西至 -->
			<view class="form-item">
				<text class="label">地块西至*</text>
				<text class="value">{{ detailData.dkxz || '无' }}</text>
			</view>

			<!-- 地块南至 -->
			<view class="form-item">
				<text class="label">地块南至*</text>
				<text class="value">{{ detailData.dknz || '无' }}</text>
			</view>

			<!-- 地块北至 -->
			<view class="form-item">
				<text class="label">地块北至*</text>
				<text class="value">{{ detailData.dkbz || '无' }}</text>
			</view>

			<!-- 备注信息 -->
			<view class="form-item">
				<text class="label">备注信息</text>
				<text class="value">{{ detailData.remark || '无' }}</text>
			</view>
			
			<!-- 实测面积亩 -->
			<view class="form-item">
				<text class="label">实测面积亩</text>
				<text class="value">{{ tj_scmjm || 0 }} 亩</text>
			</view>
			
			<!-- 实测面积 ㎡ -->
			<view class="form-item">
				<text class="label">实测面积</text>
				<text class="value">{{ tj_scmj || 0 }} ㎡</text>
			</view>

			<!-- 范围选择 -->
			<view class="form-item">
				<text class="label">范围选择</text>
				<text class="value link" @click="viewRange">
					{{ hasLocalData ? '重新框选地块大致范围' : '框选地块大致范围' }}
				</text>
			</view>
		</view>

		<!-- 图片信息区域 -->
		<view class="section-title">图片信息</view>
		<view class="img-section">
			<text class="img-label">现场指界</text>
			<view class="img-list">
				<image 
					v-for="(img, idx) in imageList.xczj.img" 
					:key="idx" 
					:src="img" 
					class="img-preview" 
					mode="widthFix"
					@click="previewImage(imageList.xczj.img, idx)"
				></image>
				<text v-if="!imageList.xczj.img.length" class="no-data">暂无现场指界图片</text>
			</view>

			<text class="img-label mt-[20rpx]">附件资料</text>
			<view class="img-list">
				<image 
					v-for="(img, idx) in imageList.fjzl.img" 
					:key="idx" 
					:src="img" 
					class="img-preview" 
					mode="widthFix"
					@click="previewImage(imageList.fjzl.img, idx)"
				></image>
				<text v-if="!imageList.fjzl.img.length" class="no-data">暂无附件资料</text>
			</view>
		</view>
	</view>
	<view class="submit-btn" @click="handleSubmit">确定</view>
</template>

<script setup lang="ts">
	import { ref, computed, watch } from 'vue'
	import { onLoad,onShow } from '@dcloudio/uni-app';
	import { getdkxxxxData, getDictData,updateLandInfo } from '@/api/farmerApi.js';
	import { imgBaseURL } from '@/utils/request.js';

	// 详情数据
	const detailData = ref({})
	// 地块编号（接收页面参数）
	const xq_Dkbm = ref('')
	const xq_Cbfbm = ref('')
	const cd_List = ref({})
	
	// 图片列表
	const imageList = ref({
		xczj: { img: [], number: [] }, // 现场指界
		fjzl: { img: [], number: [] }  // 附件资料
	})

	// 本地存储KEY（按地块编号区分）
	// const LOCAL_STORAGE_KEY = computed(() => `land_map_data_${xq_Dkbm.value}`)

	// 判断是否有本地数据（控制文字显示）
	const hasLocalData = ref(false)

	// ==================== 字典数据 ====================
	const dictData = ref<any>({
		bgly: [],    // 变更理由
		syqxz: [],   // 所有权性质
		dklb: [],    // 地块类别
		dldj: [],    // 地力等级
		tdyt: [],    // 土地用途
		jbnt: [],     // 基本农田
		lylx: []     // 利用类型
	})

	// 地图选择数据
	const coordinateData = ref<Array>([])
	const tj_scmjm = ref<number | string>(0) // 实测面积亩 → 默认 0
	const tj_scmj = ref<number | string>(0)  // 实测面积㎡ → 默认 0
	
	// 字典格式转换
	const transformDictFormat = (originalDict : Record<string | number, string>) => {
		if (!originalDict || typeof originalDict !== 'object') return []
		return Object.entries(originalDict).map(([key, value]) => ({
			value: String(key),
			label: value as string
		}))
	}

	// 字典标签匹配
	const getDictLabel = (dictType : string, value : string | number | undefined) => {
		if (!value || !dictData.value[dictType]?.length) return ''
		const item = dictData.value[dictType].find((item : any) => String(item.value) === String(value))
		return item?.label || ''
	}

	// 加载字典数据
	const loadDictData = async () => {
		try {
			const [resBgly, resSyqxz, resDklb, resDldj, resTdyt, resJbnt, resLylx] = await Promise.all([
				getDictData('dic_bgly'),
				getDictData('dic_syqxz'),
				getDictData('dic_dklb'),
				getDictData('dic_dldj'),
				getDictData('dic_tdyt'),
				getDictData('dic_sf'),
				getDictData('dic_tdlylx')
			])

			dictData.value.bgly = resBgly?.code === 200 ? transformDictFormat(resBgly.data) : []
			dictData.value.syqxz = resSyqxz?.code === 200 ? transformDictFormat(resSyqxz.data) : []
			dictData.value.dklb = resDklb?.code === 200 ? transformDictFormat(resDklb.data) : []
			dictData.value.dldj = resDldj?.code === 200 ? transformDictFormat(resDldj.data) : []
			dictData.value.tdyt = resTdyt?.code === 200 ? transformDictFormat(resTdyt.data) : []
			dictData.value.jbnt = resJbnt?.code === 200 ? transformDictFormat(resJbnt.data) : []
			dictData.value.lylx = resLylx?.code === 200 ? transformDictFormat(resLylx.data) : []
		} catch (err) {
			console.error('字典加载失败：', err)
		}
	}

	// ==================== 本地存储核心方法 ====================
	// 保存地图数据到本地
	const saveMapDataToLocal = (data) => {
		try {
			uni.setStorageSync('LOCAL_STORAGE_KEY', JSON.stringify(data));
			// uni.setStorageSync(LOCAL_STORAGE_KEY.value, JSON.stringify(data))
			// 保存后更新状态
			hasLocalData.value = true
		} catch (e) {
			console.error('保存地图数据失败', e)
		}
	}

	// 从本地获取地图数据
	const getMapDataFromLocal = () => {
		try {
			const data = uni.getStorageSync('LOCAL_STORAGE_KEY')
			return data ? JSON.parse(data) : null
		} catch (e) {
			console.error('获取地图数据失败', e)
			return null
		}
	}

	// 检查本地是否有数据
	const checkLocalData = () => {
		const localData = getMapDataFromLocal()
		hasLocalData.value = !!(localData && (localData.areaMu > 0 || localData.areaM2 > 0))
	}

	// 初始化：页面加载 → 读本地 → 有值显示，无值显示0
	const initLocalMapData = () => {
		const localData = getMapDataFromLocal()
		if (localData) {
			coordinateData.value = localData.points || []
			tj_scmjm.value = localData.areaMu || 0
			tj_scmj.value = localData.areaM2 || 0
			console.log('✅ 从本地加载实测数据：', localData)
		} else {
			// 无本地数据 → 重置为0
			coordinateData.value = []
			tj_scmjm.value = 0
			tj_scmj.value = 0
		}
		// 检查本地数据状态
		checkLocalData()
	}

	// ==================== 接口请求 & 数据绑定 ====================
	const getTotal = async (dkbm) => {
		try {
			uni.showLoading({ title: '加载中...' })
			const res = await getdkxxxxData({ dkbm: dkbm});
			uni.hideLoading()
			
			if (res.code === 200 && res.data?.length) {
				const item = res.data[0];
				xq_Cbfbm.value = item.cbdkxxTemp?.cbfbm || '';
				cd_List.value = item.dkTemp || {};
				detailData.value = { ...item.dkTemp }
				detailData.value.htmjm = item.cbdkxxTemp?.htmjm || 0;
				
				// 图片绑定
				const attachments = item.attachments || {}
				if (attachments.xczj?.length) {
					attachments.xczj.forEach((imgItem) => {
						imageList.value.xczj.img.push(imgBaseURL + imgItem.filePath)
						imageList.value.xczj.number.push(String(imgItem.id))
					})
				}
				if (attachments.fjzl?.length) {
					attachments.fjzl.forEach((imgItem) => {
						imageList.value.fjzl.img.push(imgBaseURL + imgItem.filePath)
						imageList.value.fjzl.number.push(String(imgItem.id))
					})
				}
			}
		} catch (e) {
			uni.hideLoading()
			uni.showToast({ title: '加载失败', icon: 'none' })
			console.error(e)
		}
	};

	// ==================== 页面方法 ====================
	// 查看地块范围
	const viewRange = () => {
		uni.navigateTo({
			url: `/pages/map/map?type=investigator&displayType=all&memberInfo=${encodeURIComponent(JSON.stringify(xq_Cbfbm.value))}`
		});
	}

	// 图片预览
	const previewImage = (urls, current) => {
		uni.previewImage({
			urls: urls,
			current: current
		})
	}
	
	// ==================== 提交 ====================
	const handleSubmit = async () => {
		if (!cd_List.value.bsm) {
			uni.showToast({ title: '数据异常，无法提交', icon: 'none' })
			return
		}
		
		const dkTemp = {
			bsm: cd_List.value.bsm || '',   
			scmj: tj_scmj.value || 0,
			scmjm: tj_scmjm.value || 0,
			status: cd_List.value.status
		};

		const submitData = {
			dkTemp,
			geoJson: [coordinateData.value] || [],
		};

		uni.showLoading({ title: '提交中...' });
		try {
			const res = await updateLandInfo(submitData);
			if (res.code === 200) {
				uni.showToast({ title: '提交成功', icon: 'success' });
				setTimeout(() => {
					uni.navigateBack();
				}, 1500);
			} else {
				uni.showToast({ title: res.msg || '提交失败', icon: 'none' });
			}
		} catch (err) {
			uni.showToast({ title: '提交失败', icon: 'none' });
		} finally {
			uni.hideLoading();
		}
	};

	// ==================== 生命周期 ====================
	onLoad(async (options) => {
		xq_Dkbm.value = options.code || '';
		await loadDictData()
		await getTotal(xq_Dkbm.value);
		initLocalMapData(); // 加载本地存储数据
	});

	onShow(() => {
		const pages = getCurrentPages()
		const currentPage = pages[pages.length - 1]
		
		// 从地图返回 → 接收数据
		if (currentPage.$vm.selectedLandData) {
			const data = currentPage.$vm.selectedLandData
			console.log('✅ 地图返回实测数据：', data);
			
			// 赋值页面 → 实时显示
			coordinateData.value = data.points || [];
			tj_scmjm.value = data.areaMu;
			tj_scmj.value = data.areaM2;
			
			// 保存到本地
			saveMapDataToLocal(data)
			currentPage.$vm.selectedLandData = null
		}
		
		// 每次显示都检查本地数据状态
		checkLocalData()
	})
</script>

<style scoped>
	.page-container {
		padding: 16rpx;
		background-color: #f5f5f5;
		min-height: 100vh;
	}

	.section-title {
		font-size: 32rpx;
		font-weight: bold;
		margin-bottom: 16rpx;
		color: #333;
	}

	.form-list {
		background-color: #fff;
		border-radius: 12rpx;
		padding: 16rpx;
		margin-bottom: 16rpx;
	}

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

	.form-item:last-child {
		border-bottom: none;
	}

	.label {
		font-size: 28rpx;
		color: #666;
	}

	.value {
		font-size: 28rpx;
		color: #333;
		text-align: right;
		max-width: 60%;
		word-break: break-all;
	}

	.link {
		color: #409eff;
	}

	.img-section {
		background-color: #fff;
		border-radius: 12rpx;
		padding: 16rpx;
	}

	.img-label {
		font-size: 28rpx;
		color: #666;
		display: block;
		margin-bottom: 12rpx;
	}

	.img-list {
		display: flex;
		flex-wrap: wrap;
		gap: 12rpx;
		margin-bottom: 20rpx;
	}

	.img-preview {
		width: 220rpx;
		height: 220rpx;
		border-radius: 8rpx;
		background-color: #f5f5f5;
	}

	.no-data {
		font-size: 28rpx;
		color: #999;
		line-height: 220rpx;
	}

	.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: 40rpx auto;
		box-shadow: 0 4rpx 12rpx rgba(64, 158, 255, 0.3);
	}
</style>