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

class GetMyAttendanceItems extends API {
    constructor() {
        super();

        this.setPath('/GetMyAttendanceItems');
        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
            });
        }

        try {
            // 查询用户考勤项目
            const sqlGetItems = `
                SELECT id, name, user, day_of_week, loopy, begintime, endtime, address
                FROM kq_items
                WHERE JSON_CONTAINS(user, JSON_QUOTE(?), '$') ORDER BY id DESC
            `;
            const items = await db.query(sqlGetItems, [uuid]);

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

            // 查询用户考勤记录
            const sqlGetRecords = `
                SELECT id, uuid, project_id, time, commit
                FROM kq_records
                WHERE uuid = ?
            `;
            const records = await db.query(sqlGetRecords, [uuid]);

            if (records === undefined) {
                return res.json({
                    ...BaseStdResponse.DATABASE_ERR,
                    endpoint: 154756
                });
            }

            res.json({
                ...BaseStdResponse.OK,
                list: items,
                records: records
            });
        } catch (error) {
            res.json({
                ...BaseStdResponse.DATABASE_ERR,
                endpoint: 154754
            });
        }
    }
}

module.exports.GetMyAttendanceItems = GetMyAttendanceItems;
