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

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

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

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

        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;
        }

        // 确认权限
        let permission = await AccessControl.getPermission(uuid);
        if (!permission.includes('admin') && !permission.includes('manage')) {
            res.json({
                ...BaseStdResponse.PERMISSION_DENIED,
                endpoint: 481454
            });
            return;
        }

        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 sql = `INSERT INTO kq_items (name, createUser, createTime, user, day_of_week, loopy, begintime, endtime, position, radius, address, admin)
                     VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`;

        const values = [
            name,
            uuid,
            new Date().getTime(),
            JSON.stringify(uuids),
            day_of_week,
            loopy,
            begintime,
            endtime,
            JSON.stringify(position),
            radius,
            address,
            JSON.stringify(admins)
        ];

        try {
            const result = await db.query(sql, values);

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

            res.json({
                ...BaseStdResponse.OK
            });
        } catch (error) {
            res.json({
                ...BaseStdResponse.DATABASE_ERR,
                endpoint: 513513,
                msg: error.message
            });
        }
    }

    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.AddAttendanceItems = AddAttendanceItems;
