<template>
	<view class="a-yjly-inputunit" :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: '300px' }">
				<view v-for="(unit, index) in sortedUnits" :key="unit.id" class="unit-option"
					:class="{ active: activeIndex === index }" @tap="selectUnitHandler(unit, index)">
					{{ showEnglishOnly ? unit.unitName.split('(')[0] : unit.unitName }}
				</view>
			</scroll-view>
		</view>
	</view>
</template>

<script>
	import useUnitStore from '@/store/modules/unitData.ts';



	export default {
		name: 'UniUnitConverter',
		emits: ['update:modelValue', 'update:unitOrder', 'conversion'],
		props: {
			unitType: {
				type: String,
				required: true,
				default: 'length'
			},
			unitOrder: {
				type: Number,
				default: 0
			},
			modelValue: {
				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.modelValue,
				unitData: [],
				showUnitSelector: false,
				currentUnit: null,
				baseUnit: null,
				inputWidth: 100,
				textUnitName: '',
				unitSelectorLeft: 0,
				unitSelectorTop: 0,
				originalValue: this.modelValue,
				originalUnit: null,
				isInternalUpdate: false,
				activeIndex: -1
			}
		},
		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());
					}
				}
			},
			modelValue(newVal) {
				if (!this.isInternalUpdate) {
					this.originalValue = newVal;
					this.originalUnit = this.currentUnit;
					this.inputValue = newVal;
				}
				this.isInternalUpdate = false;
			}
		},
		mounted() {
			this.initComponent();
		},
		methods: {
			async initComponent() {
				await this.$nextTick();
				this.updateInputWidth();
			},

			setActiveIndex(index) {
				this.activeIndex = index;
			},

			// 统一处理单位选择
			selectUnitHandler(unit, index) {
				this.selectUnit(unit);
				this.setActiveIndex(index);
			},

			handleClickOutside() {
				if (this.showUnitSelector) {
					this.showUnitSelector = false;
				}
			},

			async loadUnits(unitType) {
				try {
					let tempData = null;

					let unitStore = useUnitStore();

					tempData = unitStore.loadFromStorage();

					console.log('从存储获取的数据:', tempData);
					// 2. 缓存无数据时，调用接口获取
					if (!tempData || !tempData[unitType]) {
						console.log('缓存无对应类型数据，从接口获取');
						await unitStore.safeGetList();
						tempData = unitStore.groupedUnitData;
					}
					// 3. 赋值处理
					this.unitData = tempData[unitType] || [];

					if (this.unitData.length === 0) {
						console.warn(`未找到${unitType}类型的单位数据`);
						return;
					}

					// 4. 兼容baseUnit为'1'或'Y'的情况
					this.baseUnit = this.unitData.find((u) => u.baseUnit === 'Y' || u.baseUnit === '1') || this
						.unitData[0];

				} 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();
				});
				this.activeIndex = -1;
			},

			handleInputChange() {
				this.originalValue = this.inputValue;
				this.originalUnit = this.currentUnit;
				this.$emit('update:modelValue', 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('update:modelValue', 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>
	.a-yjly-inputunit {
		display: flex;
		align-items: center;
		position: relative;
	}

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

	.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;
		box-sizing: border-box;
	}

	.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;
		max-height: 300px;
		overflow: hidden;
	}

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

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

	.unit-option:active {
		background-color: #e0e0e0;
	}
</style>