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

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

        this.setPath('/Admin/Kefu/Order')
        this.setMethod('get')
    }

    async onRequest(req, res) {
        let { uuid, session, id, state, 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 
                a.id,
                a.title,
                a.state,
                a.email,
                a.create_time,
                a.update_time,
                u.username,
                u.avatar
            FROM 
                work_order a
            LEFT JOIN 
                users u 
            ON 
                a.create_user = u.uuid
            WHERE 
                1 = 1
        `

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

        let params = []
        let countParams = []

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

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

        sql += `
            ORDER BY a.update_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.GetOrderList = GetOrderList