<template>
	<div class="app-container">
		<!-- 第一部分：常用组分 + 合计 -->
		<!-- 1. 常用组分选择行 -->
		<el-row class="form-row" :gutter="10" align="middle">
			<!-- 标签列 -->
			<el-col :span="10" class="label-col">
				<label class="form-label">常用组分</label>
			</el-col>
			<!-- 下拉控件列 -->
			<el-col :span="14" class="control-col">
				<el-select v-model="selectedComponent" @change="handleComponentChange" placeholder="请选择常用组分" clearable
					filterable :style="{ width: selectWidth + 'px' }">
					<el-option v-for="dict in ngtools_cyzf" :key="dict.value" :label="dict.label" :value="dict.value" />
				</el-select>
			</el-col>
		</el-row>

		<!-- 2. 合计显示行 -->
		<el-row class="form-row" :gutter="10" align="middle">
			<!-- 标签列 -->
			<el-col :span="10" class="label-col">
				<label class="form-label">合计</label>
			</el-col>
			<!-- 只读输入框列 -->
			<el-col :span="14" class="control-col">
				<el-input :value="totalPercentage" readonly class="total-input"
					:style="{ width: selectWidth + 'px' }" />
			</el-col>
		</el-row>

		<!-- 第二部分：循环渲染的组分字段 -->
		<el-row v-for="field in componentFields" :key="field.prop" class="form-row" :gutter="10" align="middle">
			<!-- 标签列 -->
			<el-col :span="10" class="label-col">
				<label class="form-label">{{ field.label }}</label>
			</el-col>
			<!-- 输入框列 -->
			<el-col :span="14" class="control-col">
				<el-input v-model="formData[field.prop]" controls-position="right" @change="handleValueChange"
					@focus="selectAllText" :style="{ width: selectWidth + 'px' }" />
			</el-col>
		</el-row>
	</div>
</template>


<script setup>
	import {
		ref,
		watch,
		onMounted,
		computed,
		getCurrentInstance
	} from 'vue';
	import {
		listComponents,
		getComponents,
		delComponents,
		addComponents,
		updateComponents
	} from '@/api/ngtools/components';
	const {
		proxy
	} = getCurrentInstance();
	const {
		ngtools_cyzf
	} = proxy.useDict('ngtools_cyzf');
	// 字段配置元数据
	const COMPONENT_FIELDS = [{
			prop: 'ngC1',
			label: '甲烷C1'
		},
		{
			prop: 'ngN2',
			label: '氮气N2'
		},
		{
			prop: 'ngCo2',
			label: '二氧化碳CO2'
		},
		{
			prop: 'ngC2',
			label: '乙烷C2'
		},
		{
			prop: 'ngC3',
			label: '丙烷C3'
		},
		{
			prop: 'ngH2o',
			label: '水H2O'
		},
		{
			prop: 'ngH2s',
			label: '硫化氢H2S'
		},
		{
			prop: 'ngH2',
			label: '氢气H2'
		},
		{
			prop: 'ngCo',
			label: '一氧化碳CO'
		},
		{
			prop: 'ngO2',
			label: '氧气O2'
		},
		{
			prop: 'ngIc4',
			label: '异丁烷iC4'
		},
		{
			prop: 'ngNc4',
			label: '正丁烷nC4'
		},
		{
			prop: 'ngIc5',
			label: '异戊烷iC5'
		},
		{
			prop: 'ngNc5',
			label: '正戊烷nC5'
		},
		{
			prop: 'ngC6',
			label: '己烷C6'
		},
		{
			prop: 'ngC7',
			label: '庚烷C7'
		},
		{
			prop: 'ngC8',
			label: '辛烷C8'
		},
		{
			prop: 'ngC9',
			label: '壬烷C9'
		},
		{
			prop: 'ngC10',
			label: '癸烷C10'
		},
		{
			prop: 'ngHe',
			label: '氦气He'
		},
		{
			prop: 'ngAr',
			label: '氩气Ar'
		}
	];

	// 定义 props
	const props = defineProps({
		modelValue: {
			type: String,
			default: ''
		},
		elFormWidth: {
			type: Number,
			default: 180
		}
	});

	// 定义 emits
	const emits = defineEmits(['update:modelValue']);

	// 定义响应式数据
	const selectWidth = ref(0);
	const selectedComponent = ref(null);
	const formData = ref(initFormData());
	const componentFields = ref(COMPONENT_FIELDS);

	// 计算属性
	const totalPercentage = computed(() => {
		return Object.values(formData.value)
			.reduce((sum, val) => sum + (parseFloat(val) || 0), 0)
			.toFixed(4);
	});

	// 初始化表单数据
	function initFormData() {
		return COMPONENT_FIELDS.reduce((acc, field) => {
			acc[field.prop] = 0;
			return acc;
		}, {});
	}

	// 全选输入框文本
	function selectAllText(event) {
		const inputElement = event.target;
		inputElement.select();
	}

	// 解析传入的字符串值
	function parseValueString(valueStr) {
		const values = (valueStr || '').split('_');
		componentFields.value.forEach((field, index) => {
			const value = parseFloat(values[index]) || 0;
			formData.value[field.prop] = value;
		});
	}

	// 生成要输出的字符串值
	function generateValueString() {
		return Object.values(formData.value)
			.map((v) => v.toFixed(4))
			.join('_');
	}

	// 处理组件选择变化
	async function handleComponentChange(value) {
		if (!value) return;
		console.log(value);
		try {
			const temp = value.replace(/\\'"/g, '"').replace(/'/g, '"');
			const componentData = Object.assign({}, formData.value, JSON.parse(temp));
			Object.keys(formData.value).forEach((key) => {
				formData.value[key] = parseFloat(componentData[key]) || 0;
			});
			emitUpdate();
		} catch (error) {
			// 这里假设使用了 ElementPlus 的消息提示，需要根据实际情况修改
			ElMessage.error('获取标准组分失败');
			console.error(error);
		}
	}

	// 处理值变化
	function handleValueChange() {
		nextTick(() => {
			emitUpdate();
		});
	}

	// 触发更新事件
	function emitUpdate() {
		if (Math.abs(parseFloat(totalPercentage.value) - 100) > 0.0001) {
			// 这里假设使用了 ElementPlus 的消息提示，需要根据实际情况修改
			ElMessage.warning('组分合计不等于100%，请检查输入');
		}
		console.log(generateValueString());
		emits('update:modelValue', generateValueString());
	}

	// 获取组分数据
	async function fetchComponentData(params) {
		try {
			const {
				data
			} = await getComponents(params);
			parseValueString(data.componentStr);
		} catch (error) {
			console.error('获取组分数据失败:', error);
		}
	}

	// 监听 elFormWidth 的变化
	watch(
		() => props.elFormWidth,
		(newVal) => {
			selectWidth.value = newVal;
		}, {
			deep: true
		}
	);

	// 监听 value 的变化
	watch(
		() => props.modelValue,
		(newVal) => {
			parseValueString(newVal);
		}, {
			immediate: true
		}
	);

	// 挂载后设置 selectWidth
	onMounted(() => {
		selectWidth.value = props.elFormWidth;
	});
</script>
<style scoped>
	/* 整体容器间距 */
	.app-container {
		padding: 10px;
	}

	/* 每行间距，匹配原inline表单的紧凑感 */
	.form-row {
		margin-bottom: 12px;
	}

	/* 标签列样式：右对齐、统一颜色和字号 */
	.label-col {
		text-align: right;
		padding-right: 10px;
	}

	.form-label {
		font-size: 12px;
		color: #606266;
		/* 匹配Element UI默认标签色 */
		font-weight: 300;
		line-height: 32px;
		/* 匹配输入框高度，垂直居中 */
	}

	/* 控件列样式：左间距 */
	.control-col {
		padding-left: 10px;
	}

	/* 合计输入框样式（保留原有类名） */
	.total-input {
		background-color: #f5f7fa;
		/* 只读输入框默认背景色 */
	}

	/* 小屏幕适配：标签和控件堆叠显示 */
	@media (max-width: 768px) {
		.form-row .el-col {
			span: 24 !important;
		}

		.label-col {
			text-align: left;
			margin-bottom: 4px;
			padding-right: 0;
		}

		.control-col {
			padding-left: 0;
		}
	}
</style>