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

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

        this.setPath('/Lepao/Account')
        this.setMethod('GET')
    }

    async onRequest(req, res) {
        let { uuid, session, email, area, username, student_num, state, auto_time, queryTime, pagesize, current } = req.query

        if ([uuid, session, pagesize, current].some(value => value === '' || value === null || value === undefined))
            return res.json({
                ...BaseStdResponse.MISSING_PARAMETER,
                endpoint: 1513126
            })

        // 校验分页参数
        if (isNaN(pagesize) || pagesize <= 0 || pagesize > 50) {
            return res.json({
                ...BaseStdResponse.ERR,
                msg: '参数错误'
            })
        }

        if (isNaN(current) || current <= 0) {
            return res.json({
                ...BaseStdResponse.ERR,
                msg: '参数错误'
            })
        }

        if (!await AccessControl.checkSession(uuid, session))
            return res.status(401).json({
                ...BaseStdResponse.ACCESS_DENIED
            })

        const offset = (current - 1) * pagesize

        let sql = `
                SELECT 
                    l.id,
                    l.name,
                    l.student_num,
                    l.create_time,
                    l.update_time,
                    l.state,
                    l.area,
                    l.auto_time,
                    l.total_num,
                    l.term_num,
                    l.academy_name,
                    l.sex,
                    l.user_avatar,
                    l.grade_id,
                    l.email,
                    l.auto_run,
                    l.today_auto_time,
                    l.notes,
                    l.target_count,
                    l.auto_day,
                    l.notice_type,
                    f.bind_code,
                    f.bot_account,
                    f.create_time AS face_time,
                    f.state AS face_state
                FROM 
                    lepao_account l
                LEFT JOIN 
                    lepao_extra f 
                ON
                    l.student_num = f.student_num
                WHERE 
                    l.create_user = ?
            `

        let countSql = `
            SELECT COUNT(*) AS total
            FROM 
                lepao_account l
            WHERE l.create_user = ?
        `

        let params = [uuid]
        let countParams = [uuid]

        if (email) {
            sql += ` AND l.email = ?`
            countSql += ` AND l.email = ?`
            params.push(email)
            countParams.push(email)
        }

        if (area) {
            sql += ` AND l.area = ?`
            countSql += ` AND l.area = ?`
            params.push(area)
            countParams.push(area)
        }

        if (student_num) {
            sql += ` AND l.student_num LIKE ?`
            countSql += ` AND l.student_num LIKE ?`
            params.push(`%${student_num}%`)
            countParams.push(`%${student_num}%`)
        }

        if (username) {
            sql += ` AND l.name LIKE ?`
            countSql += ` AND l.name LIKE ?`
            params.push(`%${username}%`)
            countParams.push(`%${username}%`)
        }

        if (auto_time !== 0) {
            sql += ` AND l.auto_time = ?`
            countSql += ` AND l.auto_time = ?`
            params.push(auto_time)
            countParams.push(auto_time)
        }

        if (state !== -1) {
            sql += ` AND l.state = ?`
            countSql += ` AND l.state = ?`
            params.push(state)
            countParams.push(state)
        }

        if(queryTime || (Array.isArray(queryTime) && queryTime.length === 2)) {
            sql += ` AND ((l.update_time >= ? AND l.update_time < ?) OR (l.create_time >= ? AND l.create_time < ?))`
            countSql += ` AND ((l.update_time >= ? AND l.update_time < ?) OR (l.create_time >= ? AND l.create_time < ?))`
            params.push(queryTime[0], queryTime[1], queryTime[0], queryTime[1])
            countParams.push(queryTime[0], queryTime[1], queryTime[0], queryTime[1])
        }

        sql += `
            ORDER BY l.create_time DESC
            LIMIT ? OFFSET ?;
        `
        params.push(String(pagesize), String(offset))

        let rows = await db.query(sql, params)
        let countResult = await db.query(countSql, countParams)

        if (!rows || !countResult)
            return res.json({
                ...BaseStdResponse.MISSING_FILE,
                msg: '获取乐跑账号数据失败！'
            })

        let total = countResult[0].total

        res.json({
            ...BaseStdResponse.OK,
            data: rows,
            pagination: {
                current,
                pagesize,
                total
            }
        })
    }
}

module.exports.GetAccount = GetAccount;