<template>
	<view class="bg-[#f5f7fa] min-h-screen pb-[40rpx]">
		<!-- 基本信息 -->
		<view class="bg-white rounded-[12rpx] mx-[20rpx] mb-[20rpx] p-[30rpx]">
			<view class="text-[32rpx] font-bold mb-[30rpx]">基本信息</view>

			<view v-if="loading" class="py-[50rpx] text-center text-[28rpx] text-[#999]">加载中...</view>
			<view v-else-if="dictLoadError" class="py-[50rpx] text-center text-[28rpx] text-[#f56c6c]">
				<view>数据加载失败</view>
				<view class="text-[24rpx] mt-[10rpx]" @click="reloadDictData">点击重新加载</view>
			</view>

			<view v-else>
				<view class="flex items-center mb-[30rpx]">
					<view class="text-[30rpx] text-[#333] w-[200rpx]">承包方姓名</view>
					<view class="flex-1 text-right text-[30rpx]">{{ editForm.cbfmc || '未填写' }}</view>
				</view>
				<view class="flex justify-between items-center mb-[30rpx]">
					<view class="text-[30rpx] text-[#666]">承包方编码</view>
					<view class="text-[30rpx] text-[#333]">{{ farmerInfo?.cbfbm || '未填写' }}</view>
				</view>
				<view class="flex items-center mb-[30rpx]">
					<view class="text-[30rpx] text-[#333] w-[200rpx]">证件类型</view>
					<view class="flex-1 text-right text-[30rpx]">{{ getDictLabel('idType', editForm.zjlx) || '未选择' }}
					</view>
				</view>
				<view class="flex items-center mb-[30rpx]">
					<view class="text-[30rpx] text-[#333] w-[200rpx]">证件号码</view>
					<view class="flex-1 text-right text-[30rpx]">{{ editForm.cbfzjhm || '未填写' }}</view>
				</view>
				<view class="flex items-center mb-[30rpx]">
					<view class="text-[30rpx] text-[#333] w-[200rpx]">承包方类型</view>
					<view class="flex-1 text-right text-[30rpx]">
						{{ getDictLabel('farmerType', editForm.cbflx) || '未选择' }}
					</view>
				</view>
				<view class="flex items-center mb-[30rpx]">
					<view class="text-[30rpx] text-[#333] w-[200rpx]">联系电话</view>
					<view class="flex-1 text-right text-[30rpx]">{{ editForm.lxdh || '未填写' }}</view>
				</view>
				<view class="flex items-center mb-[30rpx]">
					<view class="text-[30rpx] text-[#666] w-[200rpx]">邮政编码</view>
					<view class="flex-1 text-right text-[30rpx]">{{ editForm.yzbm || '未填写' }}</view>
				</view>
				<view class="flex items-start mb-[20rpx]">
					<view class="text-[30rpx] text-[#333] w-[200rpx] pt-[10rpx]">承包方地址</view>
					<view class="flex-1 text-[30rpx] leading-[1.6]">{{ editForm.cbfdz || '未填写' }}</view>
				</view>
			</view>
		</view>

		<!-- 家庭成员 -->
		<view class="bg-white rounded-[12rpx] mx-[20rpx] mb-[20rpx] p-[30rpx]">
			<view class="text-[32rpx] font-bold mb-[30rpx]">家庭成员</view>
			<view class="text-[30rpx] text-[#333] mb-[20rpx]">家庭成员信息（{{ familyMembers.length }}）</view>

			<view v-for="(item, index) in familyMembers" :key="index"
				class="bg-[#f8f9fa] rounded-[12rpx] p-[20rpx] mb-[20rpx]">
				<view v-if="hasStatus(item.bizStatus)" class="status-text mb-[10rpx]">
					状态：<text
						:class="formatStatus(item.bizStatus).className">{{ formatStatus(item.bizStatus).text }}</text>
				</view>
				<view>
					<view class="text-[30rpx] text-[#333] mb-[10rpx]">
						{{ item.cyxm }}&nbsp;&nbsp;&nbsp;&nbsp;{{ getDictLabel('cyxb', item.cyxb) }}&nbsp;&nbsp;&nbsp;&nbsp;{{ getDictLabel('yhzgx', item.yhzgx) }}
					</view>
					<view class="text-[32rpx] text-[#666] mt-[10rpx]">{{ item.cyzjhm }}</view>
				</view>
			</view>
		</view>

		<!-- 地块信息 -->
		<view class="bg-white rounded-[12rpx] mx-[20rpx] mb-[20rpx] p-[30rpx]">
			<view class="text-[32rpx] font-bold mb-[30rpx]">地块信息</view>
			<view class="text-[28rpx] text-[#666] mb-[20rpx]">地块数量&nbsp;&nbsp;{{ landList.length }}&nbsp;&nbsp;块</view>

			<view v-for="(item, index) in landList" :key="index"
				class="bg-[#f8f9fa] rounded-[12rpx] p-[20rpx] mb-[20rpx]" @click="jumpplotDetails(item)">
				<view v-if="hasStatus(item.dkDetail?.bizStatus)" class="status-text mb-[10rpx]">
					状态：<text
						:class="formatStatus(item.dkDetail?.bizStatus).className">{{ formatStatus(item.dkDetail?.bizStatus).text }}</text>
				</view>
				<view class="flex justify-between items-center mb-[10rpx]">
					<view class="text-[30rpx] text-[#007aff] flex items-center">
						<view>{{ item.dkDetail?.dkbm ? item.dkDetail.dkbm.slice(-5) : '' }}</view>
						<view class="ml-[20rpx]">{{ item.dkDetail?.dkmc || '' }}</view>
						<view class="ml-[20rpx]">{{ item.dkDetail?.scmjm || 0 }}亩</view>
					</view>
					<view class="text-[28rpx] text-[#007aff]" @click.stop="handleViewLandPosition(item)">地块位置</view>
				</view>
				<view class="text-[32rpx] text-[#666] mb-[5rpx] flex">
					<view>地块东至：{{ item.dkDetail?.dkdz || '无' }}</view>
					<view class="ml-[100rpx]">地块西至：{{ item.dkDetail?.dkxz || '无' }}</view>
				</view>
				<view class="text-[32rpx] text-[#666] flex mt-[20rpx]">
					<view>地块南至：{{ item.dkDetail?.dknz || '无' }}</view>
					<view class="ml-[100rpx]">地块北至：{{ item.dkDetail?.dkbz || '无' }}</view>
				</view>
			</view>
		</view>

		<!-- 附件 -->
		<view class="bg-white rounded-[12rpx] mx-[20rpx] mb-[20rpx] p-[30rpx]">
			<view class="flex justify-between items-center">
				<view class="text-[32rpx] font-bold">附件信息</view>
				<view class="text-[28rpx] text-[#007aff]" @click="handleUploadAttachment">
					{{ attachmentList.length > 0 ? `已上传 ${attachmentList.length} 个` : '暂无附件' }}
				</view>
			</view>
		</view>

		<!-- 审核按钮 -->
		<view class="dialog-footer" v-if="displayType === 'Auditing'">
			<view class="dialog-btn dialog-btn-cancel" @click.stop="showAuditModal(2)">驳回</view>
			<view class="dialog-btn dialog-btn-next" @click.stop="showAuditModal(1)">通过</view>
		</view>
	</view>
</template>

<script setup lang="ts">
	import { ref } from 'vue'
	import { onLoad } from '@dcloudio/uni-app';
	// @ts-ignore
	import { getfarmerLoginData, getDictData, getCbfjtcyData, getCbfdkxxData, getdkxxxxData } from '@/api/farmerApi.js';
	import { submitbatchSubmitList, submitbatchVillageAuditList, investigatordksubmit } from '@/api/SubmitApi.js';

	const loading = ref(false);
	const dictLoadError = ref(false);
	const displayType = ref('');
	const farmerInfo = ref(null);
	const dictData = ref({ idType: [], farmerType: [], cyxb: [], yhzgx: [] });
	const editForm = ref({ cbfmc: '', zjlx: '', cbfzjhm: '', cbflx: '', lxdh: '', yzbm: '', cbfdz: '' });
	const familyMembers = ref([]);
	const landList = ref([]);
	const attachmentList = ref([]);
	const submittype = ref(null)
	// 判断是否需要提交
	const hasStatus = (status) => {
		return status === 1 || status === 2 || status === '1' || status === '2';
	};

	// 状态文本
	const formatStatus = (status) => {
		const num = Number(status);
		switch (num) {
			case 1: return { text: '新增数据', className: 'status-add' };
			case 2: return { text: '修改数据', className: 'status-edit' };
			default: return { text: '', className: '' };
		}
	};

	// 字典
	const transformDictFormat = (originalDict) => {
		if (!originalDict || typeof originalDict !== 'object') return [];
		return Object.entries(originalDict).map(([key, value]) => ({ value: String(key), label: String(value) }));
	};
	const getDictLabel = (dictType, value) => {
		if (!value || !dictData.value[dictType]?.length) return '未知';
		const item = dictData.value[dictType].find(item => String(item.value) === String(value));
		return item?.label || '未知';
	};

	// 加载
	const loadDictData = async () => {
		try {
			dictLoadError.value = false;
			const [resFarmer, resIdType, resCyxb, resYhzgx] = await Promise.all([
				getDictData('dic_cbflx'), getDictData('dic_zjlx'), getDictData('dic_xb'), getDictData('dic_yhzgx')
			]);
			dictData.value.farmerType = transformDictFormat(resFarmer.data);
			dictData.value.idType = transformDictFormat(resIdType.data);
			dictData.value.cyxb = transformDictFormat(resCyxb.data);
			dictData.value.yhzgx = transformDictFormat(resYhzgx.data);
		} catch (e) { dictLoadError.value = true; }
	};

	const reloadDictData = async () => {
		loading.value = true;
		await loadDictData();
		loading.value = false;
	};

	const getTotal = async (cbfbm) => {
		try {
			const res = await getfarmerLoginData({ cbfbm });
			if (res.data?.length) {
				const info = res.data[0];
				farmerInfo.value = info;
				editForm.value = {
					cbfmc: info.cbfmc || '', zjlx: info.cbfzjlx || '', cbfzjhm: info.cbfzjhm || '',
					cbflx: info.cbflx || '', lxdh: info.lxdh || '', yzbm: info.yzbm || '', cbfdz: info.cbfdz || ''
				};
			}
		} catch (e) { }
	};

	const getcbfjtcyTotal = async (cbfbm) => {
		try {
			const res = await getCbfjtcyData({ cbfbm });
			if (res.data) familyMembers.value = res.data;
		} catch (e) { }
	};

	const getcbfDkxxTotal = async (cbfbm) => {
		try {
			const res = await getCbfdkxxData({ cbfbm });
			if (!res.data?.length) return;
			const list = [...res.data];
			for (let i = 0; i < list.length; i++) {
				if (list[i].dkbm) {
					const dk = await getdkxxxxData({ dkbm: list[i].dkbm });
					list[i].dkDetail = dk.data[0]?.dk || dk.data[0]?.dkTemp || {};
				}
			}
			landList.value = list;
		} catch (e) { }
	};

	// ====================== 核心优化：弹出审核意见框 ======================
	const showAuditModal = (type) => {
		// 自定义弹窗（高度更高、输入区域更大）
		uni.showModal({
			title: type === 1 ? '确认通过' : '确认驳回',
			editable: true,
			placeholderText: type === 2 ? '请输入驳回原因（必填）' : '请输入审核意见（选填）',
			success: async (res) => {
				if (!res.confirm) return;
				const content = res.content?.trim() || '';

				// 驳回时必须填写意见
				if (type === 2 && !content) {
					uni.showToast({ title: '驳回必须填写原因', icon: 'none' });
					return;
				}
				// 通过时可以不填
				if(submittype.value === 'official'){
					await doSubmitAudit(type, content);
				}else if(submittype.value === 'investigator'){
					await investigatorSubmitAudit(type, content);
				}
			}
		});
	};

	// 执行提交（两个接口都能成功 ✅）
	const doSubmitAudit = async (type, opinion) => {
		try {
			// 家庭成员：把 id 转 数字！！！
			const fbfbmArray = familyMembers.value
				.filter(item => hasStatus(item?.bizStatus))
				.map(item => Number(item?.id)) // 🔥 这里必须转数字
				.filter(Boolean);
	
			// 地块正常
			const landListArray = landList.value
				.filter(item => hasStatus(item.dkDetail?.bizStatus))
				.map(item => item.dkDetail?.bsm)
				.filter(Boolean);
	
			// 两个接口都传对象格式（完全一样）
			const JtcyPostData = {
				ids: fbfbmArray,        
				type: type,            
				opinion: opinion
			};
	
			const DkxxPostDat = {
				bsms: landListArray,
				type: type,
				opinion: opinion
			};
	
			// 提交
			await submitbatchVillageAuditList(DkxxPostDat);
			await submitbatchSubmitList(JtcyPostData);
	
			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);
	
		} catch (e) {
			console.error(e);
			uni.showToast({ title: '提交失败', icon: 'none' });
		}
	};
	
	// 执行提交（两个接口都能成功 ✅）
	const investigatorSubmitAudit = async (type, opinion) => {
		try {
			// 地块正常
			const landListArray = landList.value
				.filter(item => hasStatus(item.dkDetail?.bizStatus))
				.map(item => item.dkDetail?.bsm)
				.filter(Boolean);
	
			const DkxxPostDat = {
				bsms: landListArray,
				type: type,
				opinion: opinion
			};
	
			// 提交
			await investigatordksubmit(DkxxPostDat);
			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);
		} catch (e) {
			console.error(e);
			uni.showToast({ title: '提交失败', icon: 'none' });
		}
	};

	// 附件
	const handleUploadAttachment = () => {
		uni.chooseImage({ count: 5, success: res => attachmentList.value.push(...res.tempFilePaths) });
	};

	// 地块位置
	const handleViewLandPosition = (item) => {
		if (!item?.dkbm) { uni.showToast({ title: '地块编码不存在', icon: 'none' }); return; }
		uni.navigateTo({ url: `/pages/land/landPosition?code=${item.dkbm}` });
	};
	
	// 详情
	const jumpplotDetails = (item) => {
		if (!item?.dkbm) { uni.showToast({ title: '地块编码不存在', icon: 'none' }); return; }
		uni.navigateTo({ url: `/pages/investigator/Households/plotDetails?code=${item.dkbm}` });
	};

	onLoad(async (options) => {
		submittype.value = options.typedifference;
		console.log(123321,options.typedifference,JSON.parse(decodeURIComponent(options.groupInfo)))
		
		loading.value = true;
		displayType.value = options.type || '';
		await loadDictData();
		if (options.groupInfo) {
			try {
				const info = JSON.parse(decodeURIComponent(options.groupInfo));
				if (info.cbfbm) {
					await getTotal(info.cbfbm);
					await getcbfjtcyTotal(info.cbfbm);
					await getcbfDkxxTotal(info.cbfbm);
				}
			} catch (e) { }
		}
		loading.value = false;
	});
</script>

<style lang="scss" scoped>
	page {
		background-color: #f5f7fa;
	}

	.dialog-footer {
		display: flex;
		padding: 20rpx 30rpx 30rpx;
		gap: 20rpx;
	}

	.dialog-btn {
		flex: 1;
		height: 80rpx;
		border-radius: 40rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 32rpx;
	}

	.dialog-btn-cancel {
		background: #e5e5e5;
		color: #666;
	}

	.dialog-btn-next {
		background: #409eff;
		color: #fff;
	}

	.status-text {
		font-size: 28rpx;
		color: #333;
		margin-bottom: 10rpx;
	}

	.status-add {
		color: #00b42a;
		font-weight: 500;
	}

	.status-edit {
		color: #1677ff;
		font-weight: 500;
	}

	/* 全局修改弹窗输入框高度（更高更大） */
	:deep(.uni-modal-input) {
		height: 80rpx !important;
		font-size: 28rpx !important;
		padding: 10rpx 15rpx !important;
	}

	:deep(.uni-modal) {
		min-height: 380rpx !important;
	}
</style>