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

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

    async onRequest(req, res) {
        let {
            uuid,
            session,
            id,
            name,
            user,
            day_of_week,
            loopy,
            begintime,
            endtime,
            position,
            radius,
            address,
            admin
        } = req.body;

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

        if (radius <= 0 || radius >= 1000000) {
            return res.json({
                ...BaseStdResponse.ERR,
                msg: '打卡半径不在限制范围内！'
            })
        }

        if(!this.getTime(begintime, endtime)) {
            return res.json({
                ...BaseStdResponse.ERR,
                msg: '考勤时间不合法！'
            })
        }
            
        // 检查 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, [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 (projectData.createUser !== uuid && !permission.includes('admin') && !projectData.admin.includes(uuid)) {
            return res.json({
                ...BaseStdResponse.PERMISSION_DENIED,
                endpoint: 481454,
                msg: '你不是该考勤项目管理员，无操作权限'
            });
        }

        user = user.split('|');
        admin = admin.split('|');

        let uuids = [], admins = [];
        try {
            uuids = await AccessControl.checkUser(user);
            if (admin != '')
                admins = await AccessControl.checkUser(admin, true);
        } catch (error) {
            return res.json({
                ...BaseStdResponse.ERR,
                endpoint: 513513,
                msg: error.message
            });
        }

        // 更新考勤项目
        const sqlUpdateProject = `
            UPDATE kq_items 
            SET 
                name = ?,
                user = ?,
                day_of_week = ?,
                loopy = ?,
                begintime = ?,
                endtime = ?,
                position = ?,
                radius = ?,
                address = ?,
                admin = ?
            WHERE id = ?
        `;
        let updateResult = await db.query(sqlUpdateProject, [
            name,
            JSON.stringify(uuids),
            day_of_week,
            loopy,
            begintime,
            endtime,
            JSON.stringify(position),
            radius,
            address,
            JSON.stringify(admins),
            id
        ]);

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

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

    getTime(begintime, endtime) {
        const [bhours, bminutes, bseconds] = begintime.split(':').map(Number);
        const [ehours, eminutes, eseconds] = endtime.split(':').map(Number);
        const begin = bhours * 3600 + bminutes * 60 + bseconds;
        const end = ehours * 3600 + eminutes * 60 + eseconds;
        return begin < end
    }
}

module.exports.EditAttendanceItems = EditAttendanceItems;
