import {
    getAdvertList
} from '@/common/server/interface/advert'
import {
    ref
} from 'vue';
import { getReservationList, getReservationDetail } from '@/common/server/interface/sq'
import { parseTimeString, formatTime, calculateTimeRange } from '@/common/system/timeUtile'
// 响应式数据定义
// 首页核心数据（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;
};

/**
 * 将后端预约数据映射为首页列表展示项结构
 * @param {*} item 原始预约数据
 * @returns {*} 映射后的展示项
 */
export const mapReservationItem = (item) => {
    console.log(item);

    let start_time = parseTimeString(item.start_time);
    let end_time = parseTimeString(item.end_time);
    let timeStr = calculateTimeRange(start_time, end_time);
    let time = formatTime(start_time, "HH:MM") + " ~ " + formatTime(end_time, "HH:MM") + " 共" + timeStr;
    let requirementsList = [item.game_type, item.game_rule];
    if (item.is_smoking == 1) {
        requirementsList.push("禁烟");
    }
    if (item.gender_limit == 1) {
        requirementsList.push("男性");
    }
    if (item.gender_limit == 2) {
        requirementsList.push("女性");
    }
    if (item.credit_limit > 0) {
        requirementsList.push("信誉分≧" + item.credit_limit);
    }
    if (item.min_age > 0) {
        requirementsList.push("最小年龄≧" + item.min_age);
    }
    if (item.max_age > 0) {
        requirementsList.push("最大年龄≦" + item.max_age);
    }
    if (item.deposit_fee > 0) {
        requirementsList.push("鸽子费≧" + item.deposit_fee);
    }
    let requirements = requirementsList.join(",");
    return {
        id: item.id,
        data: item,
        status: item.status,
        description: item.title,
        dateStr: formatTime(start_time, "yyyy-MM-dd"),
        time: time,
        room: item.room_name,
        requirements: requirements,
        extra_info: item.extra_info,
        personCount: item.player_count,
        joinPerson: item.participants.map(participant => {
            return {
                id: participant.id,
                name: participant.userName,
                avatar: participant.avatarImage,
                userBlackStatus: participant.userBlackStatus,
                joinTime: participant.join_time,
                role: participant.role,
            };
        }),
    };
}

/**
 * 获取预约记录
 * @param {*} index 
 * @returns 
 */
export const getReservation = async (index = 1, size = 20) => {
    const res = await getReservationList(index, size);
    if (res != null && res.length > 0) {

        console.log("记录", res);
        var list = res.map(mapReservationItem);

        return list;

    }
    return [];
}

export const getDetail = async (id) => {
    const res = await getReservationDetail(id);
    if (res != null) {
        return mapReservationItem(res);
    }
    return null;
}