<template>
	<view class="form-container">
		<scroll-view scroll-y :style="{ height: scrollViewHeight + 'px' }" class="scroll-container">
			<view class="form-content">
				<view class="form-grid">
					<!-- 流量计类别 -->
					<view class="form-item" v-if="['0', '1', '2', '3'].includes(meterPar.dMeterType)">
						<view class="form-label">流量计类别</view>
						<view class="form-control">
							<uni-data-select class="uni-data-select_class" :key="'meter-type-' + meterPar.dMeterType"
								v-model="meterPar.dMeterType" :localdata="ngtools_lljlx" placeholder="请选择流量计类别"
								clearable></uni-data-select>
						</view>
					</view>

					<!-- 计算标准 -->
					<view class="form-item" v-if="meterPar.dMeterType === '0'">
						<view class="form-label">计算标准</view>
						<view class="form-control">
							<uni-data-select class="uni-data-select_class" v-model="meterPar.dFlowCalbz"
								:localdata="ngtools_lljsbz" placeholder="请选择计算标准" clearable></uni-data-select>
						</view>
					</view>

					<!-- 压缩因子计算标准 -->
					<view class="form-item">
						<view class="form-label">压缩因子计算标准</view>
						<view class="form-control">
							<uni-data-select class="uni-data-select_class" v-model="meterPar.dZcalbz"
								:localdata="ngtools_ysyzjsbz" placeholder="请选择压缩因子计算标准" clearable></uni-data-select>
						</view>
					</view>

					<!-- 计量参比条件压力 -->
					<view class="form-item">
						<view class="form-label">计量参比条件压力</view>
						<view class="form-control">
							<uni-data-select class="uni-data-select_class" v-model="meterPar.dCbtj"
								:localdata="ngtools_cbtj" placeholder="请选择计量参比条件压力" clearable></uni-data-select>
						</view>
					</view>

					<!-- 节流装置类型 -->
					<view class="form-item" v-if="meterPar.dMeterType === '0'">
						<view class="form-label">节流装置类型</view>
						<view class="form-control">
							<uni-data-select class="uni-data-select_class" v-model="meterPar.dCoreType"
								:localdata="ngtools_jlzzlx" placeholder="请选择节流装置类型" clearable></uni-data-select>
						</view>
					</view>

					<!-- 取压方式 -->
					<view class="form-item" v-if="meterPar.dMeterType === '0'">
						<view class="form-label">取压方式</view>
						<view class="form-control">
							<uni-data-select class="uni-data-select_class" v-model="meterPar.dPtmode"
								:localdata="ngtools_qyfs" placeholder="请选择取压方式" clearable></uni-data-select>
						</view>
					</view>

					<!-- 管道类型 -->
					<view class="form-item" v-if="meterPar.dMeterType === '0'">
						<view class="form-label">管道类型</view>
						<view class="form-control">
							<uni-data-select class="uni-data-select_class" v-model="meterPar.dPipeType"
								:localdata="ngtools_gdlx" placeholder="请选择管道类型" clearable></uni-data-select>
						</view>
					</view>

					<!-- 管道材料 -->
					<view class="form-item" v-if="meterPar.dMeterType === '0'">
						<view class="form-label">管道材料</view>
						<view class="form-control">
							<uni-data-select class="uni-data-select_class" v-model="meterPar.dPipeMaterial"
								:localdata="ngtools_gdcz" placeholder="请选择管道材料" clearable></uni-data-select>
						</view>
					</view>

					<!-- 孔板材料 -->
					<view class="form-item" v-if="meterPar.dMeterType === '0'">
						<view class="form-label">孔板材料</view>
						<view class="form-control">
							<uni-data-select class="uni-data-select_class" v-model="meterPar.dOrificeMaterial"
								:localdata="ngtools_gdcz" placeholder="请选择孔板材料" clearable></uni-data-select>
						</view>
					</view>

					<!-- 管道内径 -->
					<view class="form-item" v-if="meterPar.dMeterType === '0' || meterPar.dMeterType === '3'">
						<view class="form-label">管道内径</view>
						<view class="form-control">
							<a-yjly-inputunit class="unit-input-class" v-model="meterPar.dPipeD" :unit-type="'length'"
								:unitOrder.sync="meterPar.dLenUnit" :show-english-only="true" :decimal-places="5"
								:width="selectWidth" />
						</view>
					</view>

					<!-- 孔板孔径 -->
					<view class="form-item" v-if="meterPar.dMeterType === '0'">
						<view class="form-label">孔板孔径</view>
						<view class="form-control">
							<a-yjly-inputunit class="unit-input-class" v-model="meterPar.dOrificeD"
								:unit-type="'length'" :unitOrder.sync="meterPar.dOrificeUnit" :show-english-only="true"
								:decimal-places="5" :width="selectWidth" />
						</view>
					</view>

					<!-- 喉部直径 -->
					<view class="form-item" v-if="meterPar.dMeterType === '3'">
						<view class="form-label">喉部直径</view>
						<view class="form-control">
							<a-yjly-inputunit class="unit-input-class" v-model="meterPar.dOrificeD"
								:unit-type="'length'" :unitOrder.sync="meterPar.dOrificeUnit" :show-english-only="true"
								:decimal-places="5" :width="selectWidth" />
						</view>
					</view>

					<!-- 压力类型 -->
					<view class="form-item">
						<view class="form-label">压力类型</view>
						<view class="form-control">
							<uni-data-select class="uni-data-select_class" v-model="meterPar.dPfType"
								:localdata="ngtools_yllx" placeholder="请选择压力类型" clearable></uni-data-select>
						</view>
					</view>

					<!-- 当地大气压 -->
					<view class="form-item" v-if="meterPar.dPfType === '0'">
						<view class="form-label">当地大气压</view>
						<view class="form-control">
							<a-yjly-inputunit class="unit-input-class" v-model="meterPar.dPatm" :unit-type="'pressure'"
								:unitOrder.sync="meterPar.dPatmUnit" :show-english-only="true" :decimal-places="6"
								:width="selectWidth" />
						</view>
					</view>

					<!-- 输入压力 -->
					<view class="form-item">
						<view class="form-label">输入压力</view>
						<view class="form-control">
							<a-yjly-inputunit class="unit-input-class" v-model="meterPar.dPf" :unit-type="'pressure'"
								:unitOrder.sync="meterPar.dPfUnit" :show-english-only="true" :decimal-places="5"
								:width="selectWidth" />
						</view>
					</view>

					<!-- 输入温度 -->
					<view class="form-item">
						<view class="form-label">输入温度</view>
						<view class="form-control">
							<a-yjly-inputunit class="unit-input-class" v-model="meterPar.dTf" :unit-type="'temperature'"
								:unitOrder.sync="meterPar.dTfUnit" :show-english-only="true" :decimal-places="5"
								:width="selectWidth" />
						</view>
					</view>

					<!-- 输入差压 -->
					<view class="form-item" v-if="meterPar.dMeterType === '0'">
						<view class="form-label">输入差压</view>
						<view class="form-control">
							<a-yjly-inputunit class="unit-input-class" v-model="meterPar.dDp" :unit-type="'pressure'"
								:unitOrder.sync="meterPar.dDpUnit" :show-english-only="true" :decimal-places="5"
								:width="selectWidth" />
						</view>
					</view>

					<!-- 流出系数 -->
					<view class="form-item" v-if="meterPar.dMeterType === '3'">
						<view class="form-label">流出系数</view>
						<view class="form-control">
							<uni-easyinput v-model="meterPar.dCd" placeholder="请输入流出系数" />
						</view>
					</view>

					<!-- 仪表系数 -->
					<view class="form-item" v-if="meterPar.dMeterType === '1' || meterPar.dMeterType === '2'">
						<view class="form-label">仪表系数</view>
						<view class="form-control">
							<uni-easyinput v-model="meterPar.dMeterFactor" placeholder="请输入仪表系数" />
						</view>
					</view>

					<!-- 脉冲数 -->
					<view class="form-item" v-if="meterPar.dMeterType === '1' || meterPar.dMeterType === '2'">
						<view class="form-label">脉冲数</view>
						<view class="form-control">
							<a-yjly-inputunit class="unit-input-class" v-model="meterPar.dPulseNum" :unit-type="'user'"
								:unitOrder.sync="meterPar.dVGscUnit" :show-english-only="true" :decimal-places="5"
								:user-defined="true" :user-definedunit-name="'个'" :enable-convert="false"
								:width="selectWidth" />
						</view>
					</view>

					<!-- 管束车容积 -->
					<view class="form-item" v-if="meterPar.dMeterType === '8'">
						<view class="form-label">管束车容积</view>
						<view class="form-control">
							<a-yjly-inputunit class="unit-input-class" v-model="meterPar.dVGsc" :unit-type="'volume'"
								:unitOrder.sync="meterPar.dVGscUnit" :show-english-only="true" :decimal-places="5"
								:width="selectWidth" />
						</view>
					</view>

					<!-- 最大体积流量 -->
					<view class="form-item" v-if="meterPar.dBqdd === '1'">
						<view class="form-label">最大体积流量</view>
						<view class="form-control">
							<a-yjly-inputunit class="unit-input-class" v-model="meterPar.dVFlowMax"
								:unit-type="'volumeflow'" :unitOrder.sync="meterPar.dVFlowUnit"
								:show-english-only="true" :decimal-places="5" :width="selectWidth" />
						</view>
					</view>

					<!-- 最小体积流量 -->
					<view class="form-item" v-if="meterPar.dBqdd === '1'">
						<view class="form-label">最小体积流量</view>
						<view class="form-control">
							<a-yjly-inputunit class="unit-input-class" v-model="meterPar.dVFlowMin"
								:unit-type="'volumeflow'" :unitOrder.sync="meterPar.dVFlowUnit"
								:show-english-only="true" :decimal-places="5" :width="selectWidth" />
						</view>
					</view>

					<!-- 常用流量 -->
					<view class="form-item" v-if="meterPar.dBqdd === '1'">
						<view class="form-label">常用流量</view>
						<view class="form-control">
							<a-yjly-inputunit class="unit-input-class" v-model="meterPar.dVFlowCon"
								:unit-type="'volumeflow'" :unitOrder.sync="meterPar.dVFlowUnit"
								:show-english-only="true" :decimal-places="5" :enable-convert="true"
								:width="selectWidth" />
						</view>
					</view>

					<!-- 压力量程下限 -->
					<view class="form-item" v-if="meterPar.dBqdd === '1'">
						<view class="form-label">压力量程下限</view>
						<view class="form-control">
							<a-yjly-inputunit class="unit-input-class" v-model="meterPar.dPfRangeMin"
								:unit-type="'pressure'" :unitOrder.sync="meterPar.dPfUnit" :show-english-only="true"
								:decimal-places="5" :width="selectWidth" />
						</view>
					</view>

					<!-- 压力量程上限 -->
					<view class="form-item" v-if="meterPar.dBqdd === '1'">
						<view class="form-label">压力量程上限</view>
						<view class="form-control">
							<a-yjly-inputunit class="unit-input-class" v-model="meterPar.dPfRangeMax"
								:unit-type="'pressure'" :unitOrder.sync="meterPar.dPfUnit" :show-english-only="true"
								:decimal-places="5" :width="selectWidth" />
						</view>
					</view>

					<!-- 差压量程下限 -->
					<view class="form-item" v-if="meterPar.dBqdd === '1'">
						<view class="form-label">差压量程下限</view>
						<view class="form-control">
							<a-yjly-inputunit class="unit-input-class" v-model="meterPar.dDpRangeMin"
								:unit-type="'pressure'" :unitOrder.sync="meterPar.dDpUnit" :show-english-only="true"
								:decimal-places="5" :width="selectWidth" />
						</view>
					</view>

					<!-- 差压量程上限 -->
					<view class="form-item" v-if="meterPar.dBqdd === '1'">
						<view class="form-label">差压量程上限</view>
						<view class="form-control">
							<a-yjly-inputunit class="unit-input-class" v-model="meterPar.dDpRangeMax"
								:unit-type="'pressure'" :unitOrder.sync="meterPar.dDpUnit" :show-english-only="true"
								:decimal-places="5" :width="selectWidth" />
						</view>
					</view>

					<!-- 温度计量程下限 -->
					<view class="form-item" v-if="meterPar.dBqdd === '1'">
						<view class="form-label">温度计量程下限</view>
						<view class="form-control">
							<a-yjly-inputunit class="unit-input-class" v-model="meterPar.dTfRangeMin"
								:unit-type="'temperature'" :unitOrder.sync="meterPar.dTfUnit" :show-english-only="true"
								:decimal-places="5" :width="selectWidth" />
						</view>
					</view>

					<!-- 温度计量程上限 -->
					<view class="form-item" v-if="meterPar.dBqdd === '1'">
						<view class="form-label">温度计量程上限</view>
						<view class="form-control">
							<a-yjly-inputunit class="unit-input-class" v-model="meterPar.dTfRangeMax"
								:unit-type="'temperature'" :unitOrder.sync="meterPar.dTfUnit" :show-english-only="true"
								:decimal-places="5" :width="selectWidth" />
						</view>
					</view>
				</view>
			</view>
		</scroll-view>
	</view>
</template>

<style scoped>
	.form-container {
		padding: 10rpx;
		box-sizing: border-box;
		width: 100%;
	}

	.scroll-container {
		width: 100%;
	}

	.form-content {
		padding: 20rpx;
		box-sizing: border-box;
	}

	.form-grid {
		display: grid;
		gap: 20rpx;
	}

	.form-item {
		width: 100%;
		display: flex;
		flex-direction: column;
	}

	.form-label {
		font-size: 12px;
		color: #606266;
		margin-bottom: 8rpx;
		font-weight: 300;
	}

	.form-control {
		width: 100%;
	}

	.uni-data-select_class {
		background-color: white;
		font-weight: 400;
	}

	.unit-input-class {
		background-color: white;
		font-weight: 400;
	}

	/* 移动端：2列 */
	@media screen and (max-width: 768px) {
		.form-grid {
			grid-template-columns: repeat(2, 1fr);
		}
	}

	/* 桌面：3列 */
	@media screen and (min-width: 1200px) {
		.form-grid {
			grid-template-columns: repeat(3, 1fr);
		}
	}
</style>
<script setup>
	import {
		ref,
		watch,
		onMounted,
		computed,
		nextTick
	} from 'vue';
	// 1. 导入 useDict（确保路径正确）
	import {
		useDict
	} from '@/utils/dict';

	// 定义组件名称
	const __name = 'meterParComponents';
	// 2. 调用 useDict 获取字典（返回的是 Ref 对象集合）
	const dictRefs = useDict(
		'ngtools_cbtj',
		'ngtools_jlzzlx',
		'ngtools_lljlx',
		'ngtools_qyfs',
		'ngtools_gdcz',
		'ngtools_lcxsjsff',
		'ngtools_gdlx',
		'ngtools_yllx',
		'ngtools_lljsbz',
		'ngtools_ysyzjsbz'
	);
	// 3. 解构出每个字典的 Ref 对象，并通过 computed 简化 .value 取值（可选，但更优雅）
	const ngtools_cbtj = computed(() => {
		return (dictRefs.ngtools_cbtj.value || []).map(item => ({
			value: item.value,
			text: item.label
		}))
	});
	const ngtools_jlzzlx = computed(() => {
		return (dictRefs.ngtools_jlzzlx.value || []).map(item => ({
			value: item.value,
			text: item.label
		}))
	});
	const ngtools_lljlx = computed(() => {
		return (dictRefs.ngtools_lljlx.value || []).map(item => ({
			value: item.value,
			text: item.label
		}))
	});
	const ngtools_qyfs = computed(() => {
		return (dictRefs.ngtools_qyfs.value || []).map(item => ({
			value: item.value,
			text: item.label
		}))
	});
	const ngtools_gdcz = computed(() => {
		return (dictRefs.ngtools_gdcz.value || []).map(item => ({
			value: item.value,
			text: item.label
		}))
	});
	const ngtools_lcxsjsff = computed(() => {
		return (dictRefs.ngtools_lcxsjsff.value || []).map(item => ({
			value: item.value,
			text: item.label
		}))
	});
	const ngtools_gdlx = computed(() => {
		return (dictRefs.ngtools_gdlx.value || []).map(item => ({
			value: item.value,
			text: item.label
		}))
	});
	const ngtools_yllx = computed(() => {
		return (dictRefs.ngtools_yllx.value || []).map(item => ({
			value: item.value,
			text: item.label
		}))
	});
	const ngtools_lljsbz = computed(() => {
		return (dictRefs.ngtools_lljsbz.value || []).map(item => ({
			value: item.value,
			text: item.label
		}))
	});
	const ngtools_ysyzjsbz = computed(() => {
		return (dictRefs.ngtools_ysyzjsbz.value || []).map(item => ({
			value: item.value,
			text: item.label
		}))
	});

	// 4. 添加字典加载状态，避免初始空渲染
	const dictLoaded = computed(() => {
		// 检查所有必需字典是否已加载（至少有一条数据）
		return ngtools_lljlx.value.length > 0 && ngtools_jlzzlx.value.length > 0;
	});

	// 修复深拷贝函数（确保所有属性被复制）
	const deepClone = (obj) => {
		if (obj === null || typeof obj !== 'object') {
			return obj;
		}
		// 处理数组和对象
		let clone = Array.isArray(obj) ? [...obj] : {
			...obj
		};
		// 递归复制嵌套属性
		Object.keys(clone).forEach(key => {
			clone[key] = deepClone(clone[key]);
		});
		return clone;
	};

	// 简化对象比较（暂时移除复杂判断，优先保证更新）
	const isObjectEqual = (obj1, obj2) => {
		// 基础类型直接比较
		if (obj1 === obj2) return true;
		// 非对象类型直接返回不等
		if (typeof obj1 !== 'object' || typeof obj2 !== 'object' || obj1 === null || obj2 === null) {
			return false;
		}
		// 简单比较键值对（忽略深层嵌套的复杂比较，避免误判）
		const keys1 = Object.keys(obj1);
		const keys2 = Object.keys(obj2);
		if (keys1.length !== keys2.length) return false;
		return keys1.every(key => {
			return obj1[key] === obj2[key]; // 仅比较表层值（适合表单场景）
		});
	};

	// 定义 props
	const props = defineProps({
		modelValue: {
			type: Object,
			default: () => ({
				dFlowCalbz: null,
				dZcalbz: null,
				dCbtj: null,
				dpbM: null,
				dtbM: null,
				dpbE: null,
				dtbE: null,
				dPatm: null,
				dPatmUnit: null,
				dngCompents: null,
				dMeterType: null,
				dCoreType: null,
				dPtmode: null,
				dPipeType: null,
				dPipeD: null,
				dLenUnit: null,
				dPipeDtemp: null,
				dPileDtempU: null,
				dPipeMaterial: null,
				dOrificeD: null,
				dOrificeUnit: null,
				dOrificeDtemp: null,
				dOrificeDtempUnit: null,
				dOrificeMaterial: null,
				dOrificeSharpness: null,
				dOrificeRk: null,
				dOrificeRkLenU: null,
				dPf: null,
				dPfUnit: null,
				dPfType: null,
				dTf: null,
				dTfUnit: null,
				dDp: null,
				dDpUnit: null,
				dVFlowUnit: 0,
				dVFlowWorkUnit: 0,
				dMFlowUnit: 0,
				dEFlowUnit: 6,
				dCd: null,
				dCdCalMethod: null,
				dMeterFactor: null,
				dPulseNum: null,
				dVFlowMax: null,
				dVFlowMin: null,
				dVFlowCon: null,
				dPfRangeMin: null,
				dPfRangeMax: null,
				dDpRangeMin: null,
				dDpRangeMax: null,
				dTfRangeMin: null,
				dTfRangeMax: null,
				dVGsc: null,
				dCalcType: 0, // 0 流量 1  天然气  3 管束车
				dBqdd: 0 // 0 不计算，1 计算
			})
		},
		elFormWidth: {
			type: Number,
			default: 180
		},
		otherComHeight: {
			type: Number,
			default: 120
		},
	});

	// 定义 emits
	const emits = defineEmits(['update:modelValue'])
	// 定义响应式数据
	const selectWidth = ref(0);
	// 修复：确保 meterPar 有初始值
	const meterPar = ref(deepClone(props.modelValue || {}));
	const isUpdating = ref(false);
	// 定义响应式数据
	watch(
		() => props.otherComHeight,
		(newVal) => {
			calculateScrollViewHeight(newVal)
		})
	// 定义响应式数据
	const scrollViewHeight = ref(0);

	// 获取屏幕高度并计算scroll-view高度
	const calculateScrollViewHeight = (h) => {
		try {
			// 获取系统信息
			let systemInfo = {};
			
			// #ifdef MP-WEIXIN
			// 微信小程序平台
			try {
			  // 获取窗口信息
			  const windowInfo = wx.getWindowInfo();
			  // 获取设备信息
			  const deviceInfo = wx.getDeviceInfo();
			  
			  // 将两个新API获取到的信息合并成一个对象，方便使用
			  systemInfo = {
			    ...windowInfo,
			    ...deviceInfo
			  };
			  
			  // 注意：如果你还需要获取系统设置或授权信息，可以按需添加
			  // const systemSetting = wx.getSystemSetting();
			  // const appAuthorizeSetting = wx.getAppAuthorizeSetting();
			  // systemInfo = { ...systemInfo, ...systemSetting, ...appAuthorizeSetting };
			  
			} catch (e) {
			  console.error("获取微信小程序系统信息失败:", e);
			}
			// #endif
			
			// #ifdef H5 || APP-PLUS
			// H5 或 App 平台
			try {
			  systemInfo = uni.getSystemInfoSync();
			} catch (e) {
			  console.error("获取系统信息失败:", e);
			}
			// #endif
			
			
			const screenHeight = systemInfo.windowHeight;
			// 计算scroll-view高度
			scrollViewHeight.value = screenHeight - h - 20;

		} catch (error) {
			console.error('获取系统信息失败:', error);
			// 设置默认高度
			scrollViewHeight.value = 400;
		}
	};
	// 修复：添加组件挂载状态检查
	const isMounted = ref(false);
	// 在挂载后设置 selectWidth
	onMounted(() => {
		isMounted.value = true;
		selectWidth.value = props.elFormWidth;
		// 挂载后再次同步父组件数据（防止父组件数据延迟）
		if (!isObjectEqual(props.modelValue, meterPar.value)) {
			meterPar.value = deepClone(props.modelValue);
		}
	});

	// 对 meterPar 进行深度监听
	watch(
		() => meterPar.value,
		(newVal) => {
			// console.log(11111, newVal)
			if (!isObjectEqual(newVal, props.modelValue)) {
				// console.log('Emit to parent', newVal);
				emits('update:modelValue', deepClone(newVal));
			}
		}, {
			deep: true
		}
	);

	// 对 elFormWidth 进行监听
	watch(
		() => props.elFormWidth,
		(newVal) => {
			selectWidth.value = newVal;
		}, {
			deep: true
		}
	);

	// 对 value 进行深度监听
	watch(
		() => props.modelValue,
		(newVal) => {
			if (!isObjectEqual(newVal, meterPar.value)) {
				// console.log('Update from parent', newVal);
				meterPar.value = deepClone(newVal);
			}
		}, {
			deep: true,
			immediate: true
		}
	);
</script>