<template>
	<div class="unit-converter" :style="{ width: width + 'px' }">
		<!-- 数值输入框 -->
		<input
			v-model.number="inputValue"
			:disabled="inputDisable"
			class="input-field"
			type="number"
			ref="inputRef"
			:style="{ width: inputWidth + 'px', height: height + 'px' }"
			@change="handleInputChange"
			@focus="selectAllText"
		/>
		<!-- 单位标签 -->
		<span v-if="enableConvert" ref="unitLabel" @click="cycleUnit" @dblclick="toggleUnitSelector" class="unit-label" :style="{ color: 'blue', height: height + 'px' }">
			{{ '  ' + textUnitName + '  ' }}
		</span>
		<span v-else ref="unitLabel" class="unit-label" :style="{ color: 'blue', height: height + 'px' }">
			{{ '  ' + textUnitName + '  ' }}
		</span>
		<!-- 单位选择弹出窗口 -->
		<div v-if="showUnitSelector" class="unit-selector" ref="unitSelector" :style="{ left: unitSelectorLeft + 'px', top: unitSelectorTop + 'px' }">
			<div v-for="unit in sortedUnits" :key="unit.id" @click="selectUnit(unit)" class="unit-option">
				{{ showEnglishOnly ? unit.unitName.split('(')[0] : unit.unitName }}
			</div>
		</div>
	</div>
</template>

<script setup>
import { ref, watch, onMounted, onBeforeUnmount, computed, nextTick } from 'vue'; 

// 定义 props
const props = defineProps({
	unitType: {
		// 当前单位类型 (required)
		type: String,
		required: true
	},
	unitOrder: {
		// 当前单位序号 (sync)
		type: Number,
		default: 0
	},
	modelValue: {
		// 输入数值 (sync)
		type: Number,
		required: true
	},
	showEnglishOnly: {
		// 是否只显示英文
		type: Boolean,
		default: false
	},
	decimalPlaces: {
		// 小数位数
		type: Number,
		default: 5,
		validator: (v) => v >= 0 && v <= 10
	},
	width: {
		type: Number,
		required: false,
		default: 180
	},
	height: {
		type: Number,
		required: false,
		default: 24
	},
	enableConvert: {
		//是否能够进行单位换算
		type: Boolean,
		default: true
	},
	userDefined: {
		//自定义输入单位显示
		type: Boolean,
		default: false
	},
	userDefinedunitName: {
		//自定义输入单位显示
		type: String,
		default: ''
	},
	inputDisable: {
		type: Boolean,
		required: false,
		default: false
	}
});

// 定义 emits
// 修改2：调整emits定义
const emits = defineEmits([
	'update:modelValue', // 替换原来的update:value
	'update:unitOrder', // 保持原有事件
	'conversion'
]);

// 定义响应式数据
// 修改3：调整所有value相关操作
const inputValue = ref(props.modelValue); // 初始化使用modelValue
const unitData = ref([]); // 原始单位数据
const showUnitSelector = ref(false); // 显示选择器
const currentUnit = ref(null); // 当前选中单位
const baseUnit = ref(null); // 基准单位
const inputWidth = ref(120); //输入框的宽度
const textUnitName = ref('');
const unitSelectorLeft = ref(0);
const unitSelectorTop = ref(0);
// 新增三个数据项
const originalValue = ref(props.value); // 原始输入值
const originalUnit = ref(null); // 原始输入单位
const isInternalUpdate = ref(false); // 更新锁定标志

// 定义 ref
const inputRef = ref(null);
const unitLabel = ref(null);
const unitSelector = ref(null);

// 计算属性
const displayUnitText = computed(() => {
	if (!currentUnit.value) return '';
	return props.showEnglishOnly ? currentUnit.value.unitName.split('(')[0].trim() : currentUnit.value.unitName;
});

const sortedUnits = computed(() => {
	return unitData.value.filter((u) => u.unitType === props.unitType).sort((a, b) => a.unitOrder - b.unitOrder);
});

const popupPosition = computed(() => {
	if (!unitLabel.value) return {};
	const rect = unitLabel.value.getBoundingClientRect();
	return {
		top: `${rect.bottom + window.scrollY}px`,
		left: `${rect.left + window.scrollX}px`
	};
});
import { useUnitStore } from '@/store/modules/unitData'

	const unitStore = useUnitStore()
// 安全宽度更新方法
const safeUpdateWidth = () => {
	if (unitLabel.value) {
		updateInputWidth();
	}
};

const selectAllText = (event) => {
	// 通过 event.target 获取触发事件的 input 元素
	const input = event.target;
	// 调用 select() 方法全选文本
	input.select();
};

const handleMouseMove = (event) => {
	if (showUnitSelector.value) {
		// 鼠标右下方偏移量
		const offsetX = 10;
		const offsetY = 10;
		unitSelectorLeft.value = event.clientX;
		unitSelectorTop.value = event.clientY + offsetY - 100;
		// 获取弹窗元素
		if (unitSelector.value) {
			// 检查是否超出屏幕右边界
			if (unitSelectorLeft.value + unitSelector.value.offsetWidth > window.innerWidth) {
				unitSelectorLeft.value = window.innerWidth - unitSelector.value.offsetWidth;
			}
			// 检查是否超出屏幕下边界
			if (unitSelectorTop.value + unitSelector.value.offsetHeight > window.innerHeight) {
				unitSelectorTop.value = window.innerHeight - unitSelector.value.offsetHeight;
			}
		}
	}
};

const updateInputWidth = () => {
	// 安全访问检查
	if (!unitLabel.value) {
		console.warn('Unit label ref not available');
		return;
	}

	const spanWidth = unitLabel.value.offsetWidth + 10;
	inputWidth.value = Math.max(50, props.width - spanWidth); // 添加最小宽度限制
};

// 处理全局点击事件
const handleClickOutside = (event) => {
	if (unitSelector.value && !unitSelector.value.contains(event.target)) {
		showUnitSelector.value = false;
	}
};

// 切换单位选择器的显示状态
const toggleUnitSelector = () => {
	showUnitSelector.value = !showUnitSelector.value;
};

// 加载单位数据
const loadUnits = async (unitType) => {
	try {
		
		var unitDatalist =JSON.parse( localStorage.getItem("unitData"));
		 
		 if (unitDatalist) {
			 	 
		  unitData.value = unitDatalist[unitType];
		 
		baseUnit.value = unitData.value.find((u) => u.baseUnit === 'Y');
		console.log(baseUnit.value);
		 }else{
			 	unitStore.restoreUnitDataFromLocal();
			 		await unitStore.getList();
		 }
	
		
		// const res = await listConvert({
		// 	unitType: unitType,
		// 	status: 'Y'
		// });
		// console.log(111,res)
		// unitData.value = res.rows;
		// baseUnit.value = unitData.value.find((u) => u.baseUnit === 'Y');
		
	} catch (e) {
		console.error('单位数据加载失败:', e);
	}
};

// 初始化当前单位
const initCurrentUnit = () => {
	const target = sortedUnits.value.find((u) => u.unitOrder === props.unitOrder);
	currentUnit.value = target || baseUnit.value || sortedUnits.value[0];
	// 初始化时设置原始单位（关键修复）
	originalUnit.value = currentUnit.value;
	// 安全设置单位名称
	textUnitName.value = currentUnit.value ? (props.showEnglishOnly ? currentUnit.value.unitName.split('(')[0].trim() : currentUnit.value.unitName) : '';
	nextTick(() => {
		updateInputWidth();
	});
};

// 输入变化处理
const handleInputChange = () => {
	// 记录原始值和单位
	originalValue.value = inputValue.value;
	originalUnit.value = currentUnit.value;
	emits('update:modelValue', inputValue.value); // 触发modelValue更新
};

// 循环切换单位
const cycleUnit = () => {
	const index = sortedUnits.value.findIndex((u) => u === currentUnit.value);
	const newUnit = sortedUnits.value[(index + 1) % sortedUnits.value.length];
	currentUnit.value = newUnit;
	console.log(index, newUnit, currentUnit.value);
	textUnitName.value = props.showEnglishOnly ? newUnit.unitName.split('(')[0].trim() : newUnit.unitName;
	nextTick(() => {
		if (unitLabel.value) {
			updateInputWidth();
			convertAndEmit();
		}
	});
};

// 选择单位
const selectUnit = (unit) => {
	currentUnit.value = unit;
	showUnitSelector.value = false;
	nextTick(() => {
		updateInputWidth();
		convertAndEmit(); // 触发转换
	});
};

// 执行换算并提交事件
const convertAndEmit = () => {
	// 移除参数
	if (!currentUnit.value || !baseUnit.value || !originalUnit.value) {
		return;
	}

	let newValue = 0;
	if (props.unitType === 'temperature') {
		newValue = handleTemperatureConversion(originalUnit.value, currentUnit.value);
	} else {
		// 通过基准单位进行两次精确转换
		const baseValue = originalValue.value / originalUnit.value.conversionFactor;
		newValue = baseValue * currentUnit.value.conversionFactor;
	}

	const roundedValue = roundValue(newValue);
	isInternalUpdate.value = true; // 锁定更新
	inputValue.value = roundedValue;
	// 同时触发两个更新事件
	emits('update:modelValue', roundedValue);
	emits('update:unitOrder', currentUnit.value.unitOrder);

	emits('conversion', {
		initialValue: originalValue.value,
		newValue: roundedValue,
		oldUnit: originalUnit.value.unitName,
		newUnit: currentUnit.value.unitName,
		oldOrder: originalUnit.value.unitOrder,
		newOrder: currentUnit.value.unitOrder
	});
};

// 温度单位换算
const handleTemperatureConversion = (oldUnit, newUnit) => {
	const oldOrder = oldUnit.unitOrder;
	const newOrder = newUnit.unitOrder;
	let celsius;
	switch (oldOrder) {
		case 0:
			celsius = originalValue.value;
			break;
		case 1:
			celsius = ((originalValue.value - 32) * 5) / 9;
			break;
		case 2:
			celsius = originalValue.value - 273.15;
			break;
		default:
			throw new Error('无效温度单位');
	}

	switch (newOrder) {
		case 0:
			return celsius;
		case 1:
			return (celsius * 9) / 5 + 32;
		case 2:
			return celsius + 273.15;
		default:
			throw new Error('无效温度单位');
	}
};

// 四舍六入五成双
const roundValue = (value) => {
	const multiplier = Math.pow(10, props.decimalPlaces);
	const val = value * multiplier;
	const intVal = Math.trunc(val);
	const decimalPart = val - intVal;
	if (decimalPart < 0.5) {
		return intVal / multiplier;
	} else if (decimalPart > 0.5) {
		return (intVal + 1) / multiplier;
	} else {
		return intVal % 2 === 0 ? intVal / multiplier : (intVal + 1) / multiplier;
	}
};

// 监听单位类型变化
watch(
	() => props.unitType,
	async (newType) => {
		if (props.userDefined) {
			textUnitName.value = props.userDefinedunitName;
			nextTick(() => {
				safeUpdateWidth();
			});
		} else {
			let temp = JSON.parse(localStorage.getItem('unitData'));
			unitData.value = temp ? temp[newType] : [];
			if (!unitData.value) {
				await loadUnits(newType);
			}
			nextTick(() => {
				baseUnit.value = unitData.value.find((u) => u.baseUnit === 'Y');
				safeUpdateWidth();
				initCurrentUnit();
			});
		}
	},
	{ immediate: true }
);

// 监听外部单位序号变化
watch(
	() => props.unitOrder,
	(newOrder) => {
		if (props.userDefined) {
			textUnitName.value = props.userDefinedunitName;
			nextTick(safeUpdateWidth);
			return;
		}
		// 安全查找单位
		const target = sortedUnits.value.find((u) => u.unitOrder === newOrder);
		if (!target) {
			console.warn(`单位序号 ${newOrder} 未找到，使用基准单位`);
			currentUnit.value = baseUnit.value || sortedUnits.value[0];
			textUnitName.value = currentUnit.value ? (props.showEnglishOnly ? currentUnit.value.unitName?.split('(')[0]?.trim() : currentUnit.value.unitName) : '';
			return;
		}
		currentUnit.value = target;
		textUnitName.value = props.showEnglishOnly ? target.unitName?.split('(')[0]?.trim() : target.unitName;

		nextTick(safeUpdateWidth);
	}
);

// 监听输入值变化
watch(
	() => props.modelValue,
	(newVal) => {
		console.log('收到父组件值更新:', newVal);
		if (!isInternalUpdate.value && !isNaN(newVal)) {
			originalValue.value = Number(newVal);
			inputValue.value = originalValue.value;
			console.log('外部更新处理:', {
				original: originalValue.value,
				input: inputValue.value
			});
		}
		isInternalUpdate.value = false;
	},
	{ immediate: true, deep: true }
);

onMounted(() => {
	nextTick(() => {
		safeUpdateWidth();
	});
	// 在挂载时添加全局点击事件监听器
	document.addEventListener('click', handleClickOutside);
});

onBeforeUnmount(() => {
	// 清除所有未完成的异步操作
	showUnitSelector.value = false;
	document.removeEventListener('click', handleClickOutside);

	// 清除引用
	inputRef.value = null;
	unitLabel.value = null;
	unitSelector.value = null;
});
</script>

<style scoped>
.unit-converter {
	display: flex;
	align-items: center;
	position: relative;
}

.input-field {
	border: 1px solid #d6d5d5;
	border-radius: 4px;
	font-size: 14px;
}

.unit-label {
	cursor: pointer;
	font-weight: bold;
	border: 1px solid #d6d5d5;
	border-radius: 4px;
	font-size: 12px;
	white-space: nowrap;
	padding: 0 8px; /* 可根据需要调整左右内边距 */
}

.unit-label:hover {
	background: #f0f8ff;
}

.unit-selector {
	/* 设置容器的最大高度，当内容超出这个高度时会出现滚动条 */
	max-height: 100px;
	/* 超出内容时显示纵向滚动条 */
	overflow-y: auto;
	/* 横向内容不溢出，隐藏多余部分 */
	overflow-x: hidden;
	/* 其他样式保持不变 */
	position: absolute;
	z-index: 9999;
	background-color: white;
	border: 1px solid #ccc;
	border-radius: 4px;
	box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
	padding: 2px 0;
	min-width: 180px;
	list-style-type: none;
	margin-left: 100px;
}

.unit-option {
	padding: 2px 10px;
	cursor: pointer;
	font-size: 14px;
}

.unit-option:hover {
	background-color: #f0f0f0;
}
</style>
