const API = require("../../lib/API");
const { BaseStdResponse } = require("../../BaseStdResponse");
const db = require("../../plugin/DataBase/db");
const AccessControl = require("../../lib/AccessControl");
const UserInfoCache = require("../../lib/UserInfoCache");

class GetAttendanceItemList extends API {
    constructor() {
        super();
        
        this.setPath('/Attendance');
        this.setMethod('GET');
    }

    async onRequest(req, res) {

        const { uuid, session } = req.query;

        // 检查必需的参数是否缺失
        if (!uuid || !session) {
            return res.json({
                ...BaseStdResponse.MISSING_PARAMETER,
                endpoint: 1513123
            });
        }

        // 检查 session 是否有效
        if (!await AccessControl.checkSession(uuid, session)) {
            return res.json({
                ...BaseStdResponse.ACCESS_DENIED,
                endpoint: 48153145
            });
        }

        // 确认权限
        const permission = await AccessControl.getPermission(uuid);
        const hasPermission = ['manage', 'admin'].some(group => permission.includes(group));
        if (!hasPermission) {
            return res.json({
                ...BaseStdResponse.PERMISSION_DENIED,
                endpoint: 481454
            });
        }

        try {
            // 获取考勤项目列表
            const sqlGetItems = 'SELECT * FROM kq_items ORDER BY id DESC';
            const items = await db.query(sqlGetItems);

            if (!items) {
                return res.json({
                    ...BaseStdResponse.DATABASE_ERR,
                    endpoint: 1547544
                });
            }

            // 收集需要查询的用户 UUID
            const userUuids = new Set();
            const addUserUuid = (uuid) => userUuids.add(uuid);

            items.forEach(item => {
                addUserUuid(item.createUser);
                item.user.forEach(addUserUuid);
                item.admin.forEach(addUserUuid);
                addUserUuid(item.createUser);
            });

            // 如果没有需要查询的用户，直接返回结果
            if (userUuids.size === 0) {
                return res.json({
                    ...BaseStdResponse.OK,
                    data: items,
                    userInfo: {}
                });
            }

            const userInfo = {};

            // 从缓存中获取用户信息
            await Promise.all(Array.from(userUuids).map(async (uuid) => {
                const userCache = await UserInfoCache.getUserByUuid(uuid);
                userInfo[uuid] = {
                    ...userCache
                };

            }));

            res.json({
                ...BaseStdResponse.OK,
                data: items,
                userInfo
            });
        } catch (error) {
            this.logger.error(`获取考勤列表时出错：${error.stack}`);
            res.json({
                ...BaseStdResponse.DATABASE_ERR,
                endpoint: 154754511,
            });
        }
    }
}

module.exports.GetAttendanceItemList = GetAttendanceItemList;
