<script>
	import {
		ref,
	} from 'vue';
	import {
		listConvert
	} from '@/api/system/unitConverter/sysUnitConverter.js';

	const queryParams = ref({
		pageNum: 1,
		pageSize: 1000,
		unitType: null,
		unitName: null,
		baseUnit: null,
		conversionFactor: null,
		unitTypeName: null,
		status: null,
		unitOrder: null
	});

	// 保留原有单位换算方法
	const groupByUnitType = (data) => {
		if (!data || !Array.isArray(data)) {
			console.warn('groupByUnitType: 数据为空或不是数组');
			return {};
		}

		return data.reduce((acc, unit) => {
			const type = unit.unitType;
			if (!acc[type]) acc[type] = [];
			acc[type].push({
				id: unit.id,
				unitType: unit.unitType,
				unitName: unit.unitName,
				conversionFactor: unit.conversionFactor,
				unitOrder: unit.unitOrder,
				baseUnit: unit.baseUnit,
				status: unit.status,
				unitTypeName: unit.unitTypeName
			});
			return acc;
		}, {});
	};

	const getList = async () => {
		try {
			console.log('开始请求单位数据...');
			const response = await listConvert(queryParams.value);
			console.log('API响应:', response);

			if (!response || !response.rows) {
				console.error('API响应格式错误');
				return;
			}

			if (response.rows.length === 0) {
				console.warn('单位数据为空数组');
				return;
			}

			const unitDataGrouped = groupByUnitType(response.rows);
			console.log('分组后的单位数据:', unitDataGrouped);

			// #ifdef APP || APP-PLUS
			try {
				// 使用正确的同步写法
				uni.setStorageSync('unitData', unitDataGrouped);
				console.log('APP端缓存成功');

				// 立即验证
				const verifyData = uni.getStorageSync('unitData');
				console.log('APP缓存验证:', verifyData ? '成功' : '失败', verifyData);
			} catch (storageError) {
				console.error('APP缓存设置失败:', storageError);
			}
			// #endif

			// #ifdef H5
			try {
				localStorage.setItem('unitData', JSON.stringify(unitDataGrouped));
				console.log('H5端缓存成功');
			} catch (storageError) {
				console.error('H5缓存设置失败:', storageError);
			}
			// #endif

		} catch (error) {
			console.error('获取单位数据失败:', error);
		}
	};

	export default {
		onLaunch: function() {
			console.log('App Launch - 开始初始化');
			getList();
		},
		onShow: function() {
			console.log('App Show');
		},
		onHide: function() {
			console.log('App Hide');
		}
	}
</script>

<style lang="scss">
	@import "uview-plus/index.scss";
	@import '@/static/scss/index.scss';
</style>