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 GetAttendanceItemDetail extends API {
    constructor() {
        super();
        
        this.setPath('/GetAttendanceItemDetail');
        this.setMethod('GET');
    }

    async onRequest(req, res) {
        const { uuid, session, project_id } = req.query;

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

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

        try {
            // 获取考勤项目详情
            const sqlGetProject = 'SELECT * FROM kq_items WHERE id = ?';
            let projectResult = await db.query(sqlGetProject, [project_id]);

            if (!projectResult || projectResult.length === 0) {
                return res.json({
                    ...BaseStdResponse.DATABASE_ERR,
                    endpoint: 154754511
                });
            }

            // 获取考勤记录
            const sqlGetRecords = 'SELECT id, uuid, time, commit FROM kq_records WHERE project_id = ?';
            let records = await db.query(sqlGetRecords, [project_id]);

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

            projectResult.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: projectResult[0],
                    userInfo: {},
                    records
                });
            }

            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: projectResult[0],
                userInfo,
                records
            });
        } catch (error) {
            res.json({
                ...BaseStdResponse.DATABASE_ERR,
                endpoint: 154754511
            });
        }
    }
}

module.exports.GetAttendanceItemDetail = GetAttendanceItemDetail;
