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 SupplementRecord extends API {
    constructor() {
        super();

        this.setPath('/SupplementRecord');
        this.setMethod('GET');
    }

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

        // 检查必需的参数是否缺失
        if (!uuid || !session || !user || !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 user, createUser, begintime, loopy, day_of_week, admin
                FROM kq_items
                WHERE id = ?
            `;
            const projectData = await db.query(sqlGetProject, [project_id]);

            if (!projectData.length) {
                return res.json({
                    ...BaseStdResponse.DATABASE_ERR,
                    endpoint: 1544511
                });
            }

            const item = projectData[0];

            // 检查权限
            const permission = await AccessControl.getPermission(uuid);
            if (item.createUser !== uuid && !permission.includes('admin') && !item.admin.includes(uuid)) {
                return res.json({
                    ...BaseStdResponse.PERMISSION_DENIED,
                    endpoint: 481454,
                    msg: '你不是该考勤项目管理员，无操作权限'
                });
            }

            // 获取用户 UUID
            const sqlGetUserUUID = `
                SELECT uuid
                FROM users
                WHERE username = ?
            `;
            const userUUIDData = await db.query(sqlGetUserUUID, [user]);

            if (!userUUIDData.length) {
                return res.json({
                    ...BaseStdResponse.DATABASE_ERR,
                    endpoint: 154711,
                    msg: '未找到用户'
                });
            }

            const userUUID = userUUIDData[0].uuid;
            if (!item.user.includes(userUUID)) {
                return res.json({
                    ...BaseStdResponse.ERR,
                    endpoint: 481454,
                    msg: '用户不在考勤名单中'
                });
            }

            // 检查是否已有考勤记录
            const sqlCheckRecords = `
                SELECT id, uuid, time
                FROM kq_records
                WHERE project_id = ? AND uuid = ?
            `;
            const records = await db.query(sqlCheckRecords, [project_id, userUUID]);

            if (records.length !== 0 && this.hasRecord(item, records, userUUID)) {
                return res.json({
                    ...BaseStdResponse.ERR,
                    endpoint: 513523,
                    msg: '用户在本考勤周期已有考勤记录！'
                });
            }

            // 添加考勤记录
            const userInfo = await UserInfoCache.getUserByUuid(uuid);
            const sqlInsertRecord = `
                INSERT INTO kq_records (project_id, uuid, time, commit)
                VALUES (?, ?, ?, ?)
            `;
            const result = await db.query(sqlInsertRecord, [
                project_id,
                userUUID,
                new Date().getTime(),
                `${userInfo.username}补卡`
            ]);

            if (!result || result.affectedRows !== 1) {
                return res.json({
                    ...BaseStdResponse.DATABASE_ERR,
                    endpoint: 513514
                });
            }

            res.json({
                ...BaseStdResponse.OK
            });

        } catch (error) {
            res.json({
                ...BaseStdResponse.ERR,
                endpoint: 154511
            });
            this.logger.error(`添加补卡记录时出错！${error.stack}`)
        }
    }

    hasRecord(attendanceData, records, uuid) {
        const { day_of_week, begintime, loopy } = attendanceData;
        if (!loopy) {
            return records.some(record => record.uuid === uuid);
        }
        const now = new Date();
        const dayOfWeek = now.getDay();
        const nowTime = now.getTime();

        function getTimestamp() {
            // 计算今天与目标星期几的差值
            // 目标星期几应当是从0到6的范围，0是星期日，6是星期六
            const daysUntilTarget = (day_of_week - dayOfWeek + 7) % 7;
            // 计算目标日期
            const targetDate = new Date(now);
            targetDate.setDate(now.getDate() + daysUntilTarget);
            const [hours, minutes, seconds] = begintime.split(':').map(Number);
            targetDate.setHours(hours, minutes, seconds, 0);
            return targetDate.getTime();
        }

        const begin = getTimestamp();

        if (nowTime >= begin) {
            return records.some(record => record.time >= begin && record.uuid === uuid);
        }

        return records.some(record => record.time >= begin - 604800000 && record.uuid === uuid);
    }

}

module.exports.SupplementRecord = SupplementRecord;
