<template>
	<div class="app-container">
		<el-form label-position="top" size="small" :inline="true" class="component-form">
			<!-- <el-row> -->
			<!-- 常用组分选择框 -->
			<!-- <el-col :span="10"> -->
			<el-form-item label="常用组分" :style="{ width: selectWidth + 'px' }">
				<el-select v-model="selectedComponent" @change="handleComponentChange" placeholder="请选择常用组分" clearable filterable>
					<el-option v-for="dict in ngtools_cyzf" :key="dict.value" :label="dict.label" :value="dict.value" />
				</el-select>
			</el-form-item>
			<!-- </el-col> -->
			<!-- 合计输入框 -->
			<!-- <el-col :span="6"> -->
			<el-form-item label="合计" :style="{ width: selectWidth + 'px' }">
				<el-input :value="totalPercentage" readonly class="total-input" />
			</el-form-item>
			<!-- </el-col> -->
			<!-- </el-row> -->
		</el-form>

		<el-form :model="formData" label-position="top" size="small" :inline="true" class="component-form">
			<el-form-item v-for="field in componentFields" :key="field.prop" :label="field.label" :prop="field.prop" :style="{ width: selectWidth + 'px' }">
				<el-input v-model="formData[field.prop]" controls-position="right" @change="handleValueChange" @focus="selectAllText" />
			</el-form-item>
		</el-form>
	</div>
</template>

<script setup>
import { ref, watch, onMounted, computed } 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>
.component-form {
	display: grid;
	/* 优化后的自适应规则 */
	grid-template-columns: repeat(auto-fit, minmax(min(200px, 100%), 1fr));
	gap: 5px;
}

/* 在 Vue 3 中使用 :deep() 替代 >>> */
:deep(.total-input .el-input__inner) {
	font-weight: bold;
	color: #409eff;
}
</style>
