import {
    getAdvertList
} from '@/common/server/interface/advert'
import {
    ref
} from 'vue';

// 响应式数据定义
// 首页核心数据（banner + 通知）
export const homeData = ref(null);

// 全局加载状态
export const isLoading = ref(false);
// 错误信息
export const error = ref(null);

// 缓存控制（防重复请求）
const CACHE_TIMEOUT = 5 * 60 * 1000; // 5分钟缓存
let lastLoadTime = 0;

/**
 * 预加载首页核心数据（banner + 通知+分类）
 */
export const preloadHomeData = async () => {
    if (shouldUseCache()) return;

    isLoading.value = true;
    error.value = null;
    try {
        const res = await Promise.all([
            getAdvertList("TplIndexBanner1").catch(() => null),
        ]);

        let [advertList] = res;

        // 删除 banner 数据源 createTime和updateTime
        if (advertList) {
            advertList = advertList.map(it => {
                let _it = {
                    ...it
                };
                delete _it.createTime;
                delete _it.updateTime;
                return _it;
            });
        }


        homeData.value = {
            advertList
        };
        console.log("首页数据源", homeData.value);
        lastLoadTime = Date.now();
    } catch (err) {
        error.value = err;
        console.error('首页数据预加载失败:', err);
    } finally {
        isLoading.value = false;
    }
};


// 私有工具函数
const shouldUseCache = () => {
	return homeData.value && Date.now() - lastLoadTime < CACHE_TIMEOUT;
};