<template>
	<view class="work-container">
		<!-- 轮播图 -->
		<uni-swiper-dot class="uni-swiper-dot-box" :info="data" :current="current" field="content">
			<swiper class="swiper-box" :current="swiperDotIndex" @change="changeSwiper">
				<swiper-item v-for="(item, index) in data" :key="index">
					<view class="swiper-item" @click="clickBannerItem(item)">
						<image :src="item.image" mode="aspectFill" :draggable="false" />
					</view>
				</swiper-item>
			</swiper>
		</uni-swiper-dot>

		<!-- 宫格组件 -->
		<!-- 使用原生 view 实现网格布局 -->
		<view class="grid-body" v-for="(group, groupIndex) in moudlesGroups" :key="groupIndex">
			<uni-section :title="group.name" type="line"></uni-section>
			<view class="custom-grid-view">
				<view v-for="(item, itemIndex) in group.items" :key="itemIndex" class="custom-grid-item"
					@click="navigateToMoudles(item)">
					<view class="grid-item-box">
						<uni-icons :type="item.icon" size="30"></uni-icons>
						<text class="text">{{item.name}}</text>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		onMounted
	} from "vue";
	import modal from "@/plugins/modal"

	import {
		extractModuleData
	} from '@/utils/moudlesData.ts';

	import useUnitStore from '@/store/modules/unitData.ts';
	import {
		getToken,
		setToken,
		removeToken
	} from "@/utils/auth";

	const unitStore = useUnitStore();


	const current = ref(0);
	const swiperDotIndex = ref(0);
	const data = ref([{
			image: 'https://ngtools.cn:3000/static/images/banner/banner01.jpg'
		},
		{
			image: 'https://ngtools.cn:3000/static/images/banner/banner02.jpg'
		},
		{
			image: 'https://ngtools.cn:3000/static/images/banner/banner03.jpg'
		}
	]);

	// 核心数据：计算分组和功能项定义
	const moudlesGroups = ref([]);

	// 登录状态校验函数
	const checkLoginStatus = () => {
		// 1. 检查本地token是否存在
		const token = getToken();

		console.log(token)
		// 2. 无token/用户信息，直接跳转登录
		if (!token) {
			uni.reLaunch({
				url: '/pages/login'
			});
			return false; // 未登录
		}
		return true; // 已登录
	};

	onMounted(async () => {
		// 第一步：优先校验登录状态（核心修复）
		const isLogin = checkLoginStatus();
		if (!isLogin) return; // 未登录则终止后续逻辑
		moudlesGroups.value = extractModuleData(['流量计算', '参数计算'], false)
		// 优先从本地缓存恢复，再请求最新数据
		unitStore.restoreUnitDataFromLocal();
		try {
			await unitStore.getList();
		} catch (error) {
			console.error('获取单位数据失败:', error);

			if (error.code === 401 ||
				(error.message &&
					(error.message.includes('会话过期') ||
						error.message.includes('无效的会话')))) {

				// 清除本地存储
				uni.removeStorageSync('token');
				uni.removeStorageSync('userInfo');

				// 跳转到登录页
				uni.reLaunch({
					url: '/pages/login/'
				});
			} else {
				// 其他错误：显示具体错误信息
				const errorMsg = error.message || '数据加载失败，请稍后重试';
				modal.showToast({
					title: errorMsg,
					mask: false,
					icon: 'none',
					duration: 2000
				});
			}
		}
	});

	function navigateToMoudles(item) {
		console.log(item)
		uni.navigateTo({
			url: item.path + "?dMeterType=" + item.params
		});
	};

	function clickBannerItem(item) {
		console.info(item)
	};

	function changeSwiper(e) {
		current.value = e.detail.current
	}

	function changeGrid(e) {
		modal.showToast({
			title: '模块建设中',
			mask: false,
			icon: 'loading',
			duration: 1000
		});
	}
</script>

<style lang="scss">
	/* 原生网格布局样式 */
	.custom-grid-view {
		display: flex;
		flex-wrap: wrap;
		width: 100%;
		justify-content: flex-start;
	}

	.custom-grid-item {
		width: 25%;
		box-sizing: border-box;
		padding: 10rpx;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.grid-item-box {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 20rpx 0;
		width: 100%;
		background-color: #f8f8f8;
		border-radius: 10rpx;
	}

	.text {
		text-align: center;
		font-size: 24rpx;
		margin-top: 10rpx;
		color: #333;
	}


	/* #ifndef APP-NVUE */
	page {
		display: flex;
		flex-direction: column;
		box-sizing: border-box;
		background-color: #fff;
		min-height: 100%;
		height: auto;
	}

	view {
		font-size: 14px;
		line-height: inherit;
	}

	/* #endif */

	.work-container {
		width: 100%;
	}

	.text {
		text-align: center;
		font-size: 26rpx;
		margin-top: 10rpx;
		/* #ifdef MP-WEIXIN */
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
		width: 100%;
		/* #endif */
	}

	.grid-item-box {
		flex: 1;
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 15px 0;
		width: 100%;
		box-sizing: border-box;
	}

	/* 修复小程序中的网格布局 */
	/* #ifdef MP-WEIXIN */
	.custom-grid {
		width: 100% !important;
		display: flex !important;
		flex-wrap: wrap !important;
	}

	.custom-grid .uni-grid-item {
		width: 25% !important;
		box-sizing: border-box !important;
		flex: none !important;
	}

	.grid-item {
		width: 25% !important;
		flex-shrink: 0 !important;
	}

	/* #endif */

	.uni-margin-wrap {
		width: 690rpx;
		width: 100%;
	}

	.swiper {
		height: 300rpx;
	}

	.swiper-box {
		height: 150px;
	}

	.swiper-item {
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		flex-direction: column;
		justify-content: center;
		align-items: center;
		color: #fff;
		height: 300rpx;
		line-height: 300rpx;
	}

	.grid-body {
		width: 100%;
		padding: 0 20rpx;
		box-sizing: border-box;
	}

	@media screen and (min-width: 500px) {
		.uni-swiper-dot-box {
			width: 400px;
			/* #ifndef APP-NVUE */
			margin: 0 auto;
			/* #endif */
			margin-top: 8px;
		}

		.image {
			width: 100%;
		}
	}
</style>