<template>
	<view class="unit-converter" :style="{ width: width + 'px' }">
		<!-- 数值输入框 -->
		<input v-model.number="inputValue" class="input-field" type="number" :ref="'inputRef'" :style="{
				width: inputWidth + 'px',
				height: height + 'px',
				lineHeight: height + 'px'
			}" @input="handleInputChange" />

		<!-- 单位标签 -->
		<view v-if="enableConvert" :ref="'unitLabel'" class="unit-label" :style="{
				color: 'blue',
				height: height + 'px',
				lineHeight: height + 'px'
			}" @tap="cycleUnit" @longpress="handleLongPress">
			{{ textUnitName }}
		</view>
		<view v-else class="unit-label" :style="{
				color: 'blue',
				height: height + 'px',
				lineHeight: height + 'px'
			}">
			{{ textUnitName }}
		</view>

		<!-- 单位选择弹出窗口 -->
		<view v-if="showUnitSelector" class="unit-selector" :style="{
				left: unitSelectorLeft + 'px',
				top: unitSelectorTop + 'px'
			}">
			<scroll-view scroll-y :style="{ maxHeight: '200px' }">
				<view v-for="unit in sortedUnits" :key="unit.id" class="unit-option" @tap="selectUnit(unit)">
					{{ showEnglishOnly ? unit.unitName.split('(')[0] : unit.unitName }}
				</view>
			</scroll-view>
		</view>
	</view>
</template>

<script>
	// 兼容 Vue2/Vue3 的写法
	// import unitDatalist from './yjly-UnitData';

	export default {
		name: 'UniUnitConverter',
		emits: ['input', 'update:unitOrder', 'conversion'],
		props: {
			unitType: {
				type: String,
				required: true,
				default: 'length'
			},
			unitOrder: {
				type: Number,
				default: 0
			},
			value: {
				type: Number,
				required: true
			},
			showEnglishOnly: {
				type: Boolean,
				default: false
			},
			decimalPlaces: {
				type: Number,
				default: 5,
				validator: (v) => v >= 0 && v <= 10
			},
			width: {
				type: Number,
				default: 180
			},
			height: {
				type: Number,
				default: 32
			},
			enableConvert: {
				type: Boolean,
				default: true
			},
			userDefined: {
				type: Boolean,
				default: false
			},
			userDefinedunitName: {
				type: String,
				default: ''
			}
		},
		data() {
			return {
				inputValue: this.value,
				unitData: [],
				showUnitSelector: false,
				currentUnit: null,
				baseUnit: null,
				inputWidth: 100,
				textUnitName: '',
				unitSelectorLeft: 0,
				unitSelectorTop: 0,

				// unitDatalist: [],

				/* 新增三个数据项 */
				originalValue: this.value, // 原始输入值
				originalUnit: null, // 原始输入单位
				isInternalUpdate: false // 更新锁定标志
			};
		},
		mounted() {
			this.initComponent();
			this.setGlobalClickHandler();
		},
		beforeDestroy() {
			this.removeGlobalClickHandler();
			unitOrder;
		},
		computed: {
			sortedUnits() {
				return this.unitData.filter((u) => u.unitType === this.unitType).sort((a, b) => a.unitOrder - b.unitOrder);
			}
		},
		watch: {
			unitType: {
				immediate: true,
				async handler(newType) {
					if (this.userDefined) {
						this.textUnitName = this.userDefinedunitName;
						this.$nextTick(() => this.updateInputWidth());
					} else {
						await this.loadUnits(newType);
						this.initCurrentUnit();
					}
				}
			},
			unitOrder(newOrder) {
				if (this.userDefined) {
					this.textUnitName = this.userDefinedunitName;
					this.$nextTick(() => this.updateInputWidth());
				} else {
					const target = this.sortedUnits.find((u) => u.unitOrder === newOrder);
					if (target) {
						this.currentUnit = target;
						this.textUnitName = this.showEnglishOnly ? target.unitName.split('(')[0].trim() : target.unitName;
						this.$nextTick(() => this.updateInputWidth());
					}
				}
			},
			value(newVal) {
				if (!this.isInternalUpdate) {
					// 外部更新时重置原始值
					this.originalValue = newVal;
					this.originalUnit = this.currentUnit;
					this.inputValue = newVal;
				}
				this.isInternalUpdate = false;
			}
		},
		methods: {
			async initComponent() {
				await this.$nextTick();
				this.updateInputWidth();
			},

			setGlobalClickHandler() {
				if (typeof document !== 'undefined') {
					document.addEventListener('click', this.handleClickOutside);
				}
			},

			removeGlobalClickHandler() {
				if (typeof document !== 'undefined') {
					document.removeEventListener('click', this.handleClickOutside);
				}
			},

			handleClickOutside(event) {
				if (!this.showUnitSelector) return;

				const selector = this.$refs.unitSelector;
				if (!selector) return;

				const isOutside = !selector.$el.contains(event.target);
				if (isOutside) {
					this.showUnitSelector = false;
				}
			},

			async loadUnits(unitType) {
				try {
					// 后台的API可自行开发，这里提供了js数据格式
					// const res = await listSysUnitConvert({ unitType: unitType, status: 'Y' });
					// this.unitData = res.rows;
					var unitDatalist =JSON.parse( localStorage.getItem("unitData"));
					console.log(unitDatalist);
					this.unitData = unitDatalist[unitType];
					console.log(this.unitData);
					this.baseUnit = this.unitData.find((u) => u.baseUnit === 'Y');
					console.log(this.baseUnit);
				} catch (e) {
					console.error('单位数据加载失败:', e);
				}
			},

			/* 初始化当前单位补充 */
			initCurrentUnit() {
				const target = this.sortedUnits.find((u) => u.unitOrder === this.unitOrder);
				this.currentUnit = target || this.baseUnit || this.sortedUnits[0];
				// 初始化原始单位
				this.originalUnit = this.currentUnit;
				this.textUnitName = this.showEnglishOnly ? this.currentUnit.unitName.split('(')[0].trim() : this
					.currentUnit.unitName;
				this.$nextTick(() => this.updateInputWidth());
			},

			updateInputWidth() {
				const query = uni.createSelectorQuery().in(this);
				query
					.select('.unit-label')
					.boundingClientRect((res) => {
						if (res) {
							this.inputWidth = this.width - res.width - 4;
						}
					})
					.exec();
			},

			handleLongPress() {
				this.toggleUnitSelector();
				this.positionUnitSelector();
			},

			positionUnitSelector() {
				const query = uni.createSelectorQuery().in(this);
				query
					.select('.unit-label')
					.boundingClientRect((res) => {
						if (res) {
							this.unitSelectorLeft = res.left;
							this.unitSelectorTop = res.bottom + 5;
						}
					})
					.exec();
			},

			/* 修改单位切换方法 */
			cycleUnit() {
				const index = this.sortedUnits.findIndex((u) => u === this.currentUnit);
				const newUnit = this.sortedUnits[(index + 1) % this.sortedUnits.length];
				this.currentUnit = newUnit;
				this.textUnitName = this.showEnglishOnly ? newUnit.unitName.split('(')[0].trim() : newUnit.unitName;

				this.$nextTick(() => {
					this.updateInputWidth();
					this.convertAndEmit();
				});
			},

			toggleUnitSelector() {
				this.showUnitSelector = !this.showUnitSelector;
				if (this.showUnitSelector) {
					this.positionUnitSelector();
				}
			},

			/* 修改单位选择方法 */
			selectUnit(unit) {
				this.currentUnit = unit;
				this.showUnitSelector = false;
				this.$nextTick(() => {
					this.updateInputWidth();
					this.convertAndEmit();
				});
			},

			/* 修改输入处理 */
			handleInputChange() {
				// 记录原始值和单位
				this.originalValue = this.inputValue;
				this.originalUnit = this.currentUnit;
				this.$emit('input', this.inputValue);
			},

			/* 优化后的转换方法 */
			convertAndEmit() {
				if (!this.currentUnit || !this.baseUnit || !this.originalUnit) return;

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

				const roundedValue = this.roundValue(newValue);
				this.isInternalUpdate = true; // 锁定更新
				this.inputValue = roundedValue;
				this.$emit('input', roundedValue);
				this.$emit('update:unitOrder', this.currentUnit.unitOrder);

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

			/* 优化温度转换方法 */
			handleTemperatureConversion() {
				const oldUnit = this.originalUnit;
				const newUnit = this.currentUnit;
				const oldOrder = oldUnit.unitOrder;
				const newOrder = newUnit.unitOrder;

				// 使用原始值计算
				let celsius;
				switch (oldOrder) {
					case 0:
						celsius = this.originalValue;
						break;
					case 1:
						celsius = ((this.originalValue - 32) * 5) / 9;
						break;
					case 2:
						celsius = this.originalValue - 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('无效温度单位');
				}
			},

			// 四舍六入五成双
			roundValue(value) {
				const multiplier = Math.pow(10, this.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;
				}
			}
		}
	};
</script>

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

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

	.unit-label {
		display: inline-flex;
		align-items: center;
		padding: 0 10px;
		border: 1px solid #d6d5d5;
		border-radius: 4px;
		font-size: 12px;
		white-space: nowrap;
		margin-left: 2px;
	}

	.unit-selector {
		position: fixed;
		z-index: 9999;
		background-color: #ffffff;
		border: 1px solid #cccccc;
		border-radius: 4px;
		box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
		min-width: 120px;
	}

	.unit-option {
		padding: 8px 12px;
		font-size: 14px;
	}

	.unit-option:hover {
		background-color: #f0f0f0;
	}

	scroll-view {
		max-height: 200px;
	}
</style>