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 GetOrderList extends API {
    constructor() {
        super();

        this.setPath('/Kefu/Order')
        this.setMethod('GET')
    }

    async onRequest(req, res) {
        let { uuid, session, 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) {
            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
            })

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

        let sql = `
                SELECT 
                    id,
                    title,
                    state,
                    email,
                    create_time,
                    update_time
                FROM 
                    work_order
                WHERE 
                    create_user = ?
                ORDER BY update_time DESC
                LIMIT ? OFFSET ?
            `
        let countSql = `
            SELECT COUNT(*) AS total
            FROM work_order
            WHERE create_user = ?
        `

        let rows = await db.query(sql, [uuid, String(pagesize), String(offset)])
        let countResult = await db.query(countSql, [uuid])

        if (!rows || !countResult)
            return res.json({
                ...BaseStdResponse.DATABASE_ERR
            })

        let total = countResult[0].total

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

module.exports.GetOrderList = GetOrderList