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

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

        this.setPath('/Lepao/GetPathList')
        this.setMethod('post')
    }

    async onRequest(req, res) {
        let { uuid, session, area, max_distance, min_distance, state, pagesize, current, path_id } = req.body

        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("path"))
            return res.json({
                ...BaseStdResponse.PERMISSION_DENIED
            })

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

        let sql = `
            SELECT
                id, distance, run_zone_name, time, count, speed, state 
            FROM
                path_data
            WHERE 
                1 = 1
        `

        let countSql = `
            SELECT COUNT(*) AS total
            FROM path_data
            WHERE 1 = 1
        `

        let params = []
        let countParams = []

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

        if (min_distance) {
            sql += ` AND distance >= ?`
            countSql += ` AND distance >= ?`
            params.push(min_distance)
            countParams.push(min_distance)
        }

        if (max_distance) {
            sql += ` AND distance <= ?`
            countSql += ` AND distance <= ?`
            params.push(max_distance)
            countParams.push(max_distance)
        }

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

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

        sql += `
            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.GetPathList = GetPathList