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

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

        this.setPath('/Attendance');
        this.setMethod('DELETE');
    }

    async onRequest(req, res) {

        let {
            uuid,
            session,
            project_id
        } = req.body;

        // 检查必需的参数是否缺失
        if ([uuid, session, project_id].some(value => value === '' || value === null || value === undefined)) {
            res.json({
                ...BaseStdResponse.MISSING_PARAMETER,
                endpoint: 1513123
            });
            return;
        }

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

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

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

        let projectData = projectResult[0];

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

        // 删除考勤项目
        const sqlDeleteProject = 'DELETE FROM kq_items WHERE id = ?';
        let deleteResult = await db.query(sqlDeleteProject, [project_id]);

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

        // 删除考勤记录
        const sqlDeleteRecords = 'DELETE FROM kq_records WHERE project_id = ?';
        let deleteRecordsResult = await db.query(sqlDeleteRecords, [project_id]);

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

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

module.exports.DeleteAttendanceItem = DeleteAttendanceItem;
