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

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

        this.setPath('/Admin/Lepao/Account')
        this.setMethod('get')
    }

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

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

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

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

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

        // 检查权限
        let permission = await AccessControl.getPermission(uuid)
        if (!permission.includes("admin") && !permission.includes("service"))
            return res.json({
                ...BaseStdResponse.PERMISSION_DENIED
            })

        // 计算分页的 offset
        const offset = (current - 1) * pagesize

        let sql = `
                SELECT 
                    l.id,
                    u.username AS create_user,
                    u.avatar,
                    l.name,
                    l.email,
                    l.student_num,
                    l.create_time,
                    l.update_time,
                    l.user_avatar,
                    l.academy_name,
                    l.sex,
                    l.area,
                    l.grade_id,
                    l.class_id,
                    l.identifyCode,
                    l.mobileNumber,
                    l.homeAddr,
                    l.total_num,
                    l.term_num,
                    l.auto_run,
                    l.auto_time,
                    l.today_auto_time,
                    l.state,
                    l.auto_day,
                    l.notes,
                    l.deviceModel,
                    l.userAgent,
                    l.mobileNumber,
                    l.homeAddr,
                    l.identifyCode,
                    l.target_count,
                    l.auto_run_distance_min_km,
                    l.auto_run_distance_max_km,
                    l.pace_min_sec_per_km,
                    l.pace_max_sec_per_km,
                    l.notice_type,
                    f.bind_code,
                    f.bot_account,
                    f.bot_umo,
                    f.state AS face_state,
                    f.create_time AS face_time,
                    f.url AS face_url
                FROM 
                    lepao_account l
                LEFT JOIN 
                    users u
                ON 
                    l.create_user = u.uuid
                LEFT JOIN 
                    lepao_extra f 
                ON
                    l.student_num = f.student_num
                WHERE 
                    1 = 1
            `

        let countSql = `
            SELECT COUNT(*) AS total
            FROM 
                lepao_account l
            LEFT JOIN 
                users u
            ON 
                l.create_user = u.uuid
            LEFT JOIN 
                lepao_extra f 
            ON
                l.student_num = f.student_num
            WHERE 1 = 1
        `

        let params = []
        let countParams = []

        if (user_uuid) {
            sql += ` AND l.create_user = ?`
            countSql += ` AND l.create_user = ?`
            params.push(user_uuid)
            countParams.push(user_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 (bind_code) {
            sql += ` AND f.bind_code = ?`
            countSql += ` AND f.bind_code = ?`
            params.push(bind_code)
            countParams.push(bind_code)
        }

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

        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.GetAccountList = GetAccountList