<route lang="json5" type="page">
	{
	layout: 'default',
	style: {
	navigationStyle: 'custom',
	navigationBarTitleText: '主页',
	},
	}
</route>
<template>
	<PageLayout :navbarShow="false">
		<view class="nav">
			<view class="nav_box">
				<view class="weather_calender">
					<view class="position position-left">
						<image src="@/static/index/index/position.png"></image>
						<text>{{!appStore.position?'暂未定位':appStore.position}}</text>
					</view>
					<view class="position position-center">
						<image style="height:60rpx;width:60rpx;"
							:src="`http://openweathermap.org/img/w/${appStore.weather}.png`"></image>
						<text>{{appStore.temperature}}℃</text>
					</view>
					<view class="position position-right">
						<image src="@/static/index/index/calendar.png"></image>
						<text>{{getTime()}}</text>
					</view>
				</view>
			</view>
		</view>

		<!-- 滚动内容区 -->
		<scroll-view class="scrollView" :scroll-y="true" scroll-with-animation>
			<swiper class="swiper" :indicator-dots="true" :circular="true" :autoplay="true" :interval="5000"
				:duration="500">
				<swiper-item v-for="(item, index) in carouselList" :key="index">
					<image :src="getFileAccessHttpUrl(item)" mode="aspectFill"></image>
				</swiper-item>
			</swiper>

			<wd-row>
				<wd-col :span="12" @click="goToProcess">
					<wd-img :width="50" :height="50"
						:src="getFileAccessHttpUrl('https://static.jeecg.com/upload/test/line2_icon1_1595818065964.png')"></wd-img>
					<view class="textBox">
						<wd-badge :modelValue="badge">
							<wd-text text="个人审批"></wd-text>
						</wd-badge>
					</view>
				</wd-col>
				<wd-col :span="12" @click="goToMyApplyProcess">
					<wd-img :width="50" :height="50"
						:src="getFileAccessHttpUrl('https://static.jeecg.com/upload/test/line2_icon2_1595818070168.png')"></wd-img>
					<view class="textBox">
						<wd-text text="我发起流程"></wd-text>
					</view>
				</wd-col>
			</wd-row>

			<view class="serveBox">
				<view class="title">
					<view class="dot"></view>
					<wd-text text="常用服务"></wd-text>
				</view>
				<Grid :column="4" v-model="usList" @itemClik="goPage"></Grid>
			</view>

			<view class="serveBox">
				<view class="title">
					<view class="dot"></view>
					<wd-text text="其他服务"></wd-text>
				</view>
				<Grid :column="4" v-model="osList" @itemClik="goPage"></Grid>
			</view>
		</scroll-view>
	</PageLayout>
</template>

<script setup>
	import {
		getFileAccessHttpUrl
	} from '@/common/uitls'
	import {
		useToast
	} from 'wot-design-uni'
	import {
		useRouter
	} from '@/plugin/uni-mini-router'
	import Grid from '@/components/Grid/Grid.vue'
	import {
		queryCarouselApi,
		getUserPermissionApi
	} from '@/api/system'
	import {
		getEnvBaseUrl
	} from '@/utils/index'
	import {
		useUserStore
	} from '@/store/user'
	import {
		useAppStore
	} from '@/store'
	import {
		taskListApi
	} from '@/api/process'
	import {
		isH5
	} from '@/utils/platform'

	defineOptions({
		name: 'index',
		options: {
			// apply-shared‌：当前页面样式会影响到子组件样式.(小程序)
			// shared‌：当前页面样式影响到子组件，子组件样式也会影响到当前页面.(小程序)
			styleIsolation: 'shared',
		},
	})
	const toast = useToast()
	const router = useRouter()
	const carouselList = ref([])
	const middleApps = ref([])
	const usList = ref([])
	const osList = ref([])
	const msgCount = ref(0)
	const dot = ref({
		mailHome: false
	})
	const userStore = useUserStore()
	const appStore = useAppStore()
	const badge = ref(0)
	const res = wx.getSystemInfoSync();
	const statusHeight = res.statusBarHeight; //状态栏高度
	const cusnavbarheight = (statusHeight + 30) + "px";

	const goPage = (item) => {
		uni.navigateTo({
			url: `${item.path}?title=${item.text}`
		})
	}

	const goToProcess = () => {
		uni.navigateTo({
			url: '/pages-process/approvalTabbar'
		})
	}

	const goToMyApplyProcess = () => {
		uni.navigateTo({
			url: '/pages-process/myApplyProcess'
		})
	}

	const goPageMore = (page) => {
		router.replace({
			name: 'more',
			params: {
				backRouteName: 'index',
				type: page
			}
		})
	}

	const queryCarousel = async () => {
		// 1. 尝试从缓存获取
		const cachedData = await getCarouselCache();
		// 2. 如果有未过期的缓存，直接使用
		if (cachedData) {
			carouselList.value = cachedData.data;
			// 3. 只有当缓存快过期时(例如剩余25%有效期)，才在后台更新
			const cacheAge = Date.now() - cachedData.timestamp;
			if (cacheAge > 24 * 60 * 60 * 1000 * 7 * 0.75) {   // 24小时 * 7缓存有效期
				fetchAndUpdateCarousel(); // 后台静默更新
			}
			return;
		}
		// 4. 没有有效缓存，强制获取最新数据
		await fetchAndUpdateCarousel();
	};

	const fetchAndUpdateCarousel = async () => {
		try {
			const res = await queryCarouselApi({
				zslb: 6
			});
			if (res.success) {
				const arr = res.result.records[0].wenjian.split(',');
				const newData = arr.map(item => getEnvBaseUrl() + '/sys/common/static/' + item);
				carouselList.value = newData;
				setCarouselCache(newData);
			}
		} catch (error) {
			console.error('更新轮播图失败:', error);
		}
	};

	// 获取缓存（带时间戳验证）
	const getCarouselCache = () => {
		const cacheStr = uni.getStorageSync('carousel_data')
		if (!cacheStr) return null;
		try {
			const {
				data,
				timestamp
			} = JSON.parse(cacheStr);
			if (Date.now() - timestamp < 24 * 60 * 60 * 1000 * 7) {
				return {
					data,
					timestamp
				};
			}
			uni.removeStorageSync('carousel_data');
			return null;
		} catch {
			return null;
		}
	};

	// 设置缓存（带时间戳）
	const setCarouselCache = (data) => {
		const cacheData = {
			data,
			timestamp: Date.now()
		};
		uni.setStorageSync('carousel_data', JSON.stringify(cacheData))
	};

	const queryModule = () => {
		getUserPermissionApi({
			token: userStore.userInfo.token,
		}).then((res) => {
			if (res.success) {
				let data = res.result.menu
				data = data.filter(e => e.name == 'APP')[0] //保留APP菜单
				let userfulServer = data.children.filter(e => e.name == 'usefulServer') //常用服务
				usList.value = userfulServer[0].children.map(item => ({
					...item,
					text: item.meta.title,
					img: `/static/index/index/${item.meta.icon}.png`,
					itemKey: item.meta.sort
				}))
				let otherServer = data.children.filter(e => e.name == 'otherServer') //其他服务
				osList.value = otherServer[0].children.map(item => ({
					...item,
					text: item.meta.title,
					img: `/static/index/index/${item.meta.icon}.png`,
					itemKey: item.meta.sort
				}))
				osList.value.push({
					text: '更多',
					img: '/static/index/index/more.png',
					routeIndex: 'common',
					itemKey: 'common',
				})
			}
		})
	}

	/**
	 * 获取年月日
	 */
	const getTime = () => {
		let date = new Date(); //Fri Oct 29 2021 16:37:56 GMT+0800 (CST)
		let y = date.getFullYear(); //获取完整的年份(4位)
		let m = (date.getMonth() + 1).toString().padStart(2, 0); //获取当前月份(0-11,0代表1月)
		let d = (date.getDate()).toString().padStart(2, 0); //获取当前日(1-31)
		return `${y}-${m}-${d}`
	}

	const queryTaskBadge = () => {
		taskListApi().then((res) => {
			if (res.success) {
				badge.value = res.result.total
			}
		})
	}

	onShow(() => {
		queryTaskBadge()
	})

	onLoad(() => {
		queryCarousel()
		queryModule()
	})
</script>


<style lang="scss" scoped>
	.nav {
		width: calc(100%);
		height: v-bind(cusnavbarheight);
		font-size: 24rpx;
		color: #333333;
		position: fixed;
		z-index: 99;
		background-image: url('@/static/navbg.png');
		background-repeat: no-repeat;
		background-size: 750rpx 458rpx;
	}

	.nav_box {
		position: absolute;
		bottom: 6rpx;
		width: calc(100% - 60rpx);
		left: 30rpx;
		right: 30rpx;
	}

	.weather_calender {
		display: flex;
		justify-content: space-between;
		align-items: center;
		flex-wrap: nowrap;

		.position {
			display: flex;
			align-items: center;
			white-space: nowrap;

			image {
				width: 36rpx;
				height: 36rpx;
				margin-right: 8rpx;
			}
		}

		/* 左对齐 */
		.position-left {
			justify-content: flex-start;
		}

		/* 居中 */
		.position-center {
			justify-content: center;
		}

		/* 右对齐 */
		.position-right {
			justify-content: flex-end;
		}
	}

	.scrollView {
		height: 110%;
		display: flex;
		flex-direction: column;
		min-height: 0;
		background-color: #f1f1f1;

		:deep(.wd-row) {
			background-color: #fff;
			margin-bottom: 32upx;

			.wd-col {
				display: flex;
				align-items: center;
				justify-content: center;

				.wd-img {
					margin: 20upx;
					margin-left: 0;
				}

				.textBox {
					text-align: center;
					display: flex;
					flex-direction: column;

					.wd-text {
						color: #666;
					}
				}
			}
		}

		.serveBox {
			margin-bottom: 32upx;
			background-color: #fff;

			.title {
				display: flex;
				align-items: center;
				padding-left: 30upx;
				height: 52px;

				.dot {
					width: 14upx;
					height: 14upx;
					background-color: #0081ff;
					border-radius: 100%;
					margin-right: 20upx;
				}

				.wd-text {
					color: #666;
					font-size: 15px;
				}
			}
		}
	}

	.swiper {
		height: 575upx;
		flex: none;

		image {
			width: 100%;
			display: block;
			height: 100%;
			margin: 0;
		}

	}
</style>