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/Order/List')
        this.setMethod('get')
    }

    async onRequest(req, res) {
        let {
            uuid,
            session,
            orderId,
            username,
            user_email,
            goods_name,
            state,
            pay_type,
            queryTime,
            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: '参数错误'
            })
        }

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

        const offset = (current - 1) * pagesize

        let sql = `
            SELECT
                o.orderId,
                o.state,
                o.create_time,
                o.pay_time,
                o.price,
                o.pay_type,
                o.pay_id,
                o.goods_id,
                g.name AS goods_name,
                u.username,
                u.avatar,
                u.email AS user_email,
                o.create_user
            FROM
                orders o
            LEFT JOIN
                goods g ON o.goods_id = g.id
            LEFT JOIN
                users u ON o.create_user = u.uuid
            WHERE
                1 = 1
        `

        let countSql = `
            SELECT COUNT(*) AS total
            FROM
                orders o
            LEFT JOIN
                goods g ON o.goods_id = g.id
            LEFT JOIN
                users u ON o.create_user = u.uuid
            WHERE
                1 = 1
        `

        let params = []
        let countParams = []

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

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

        if (user_email) {
            sql += ` AND u.email LIKE ?`
            countSql += ` AND u.email LIKE ?`
            params.push(`%${user_email}%`)
            countParams.push(`%${user_email}%`)
        }

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

        if (state !== undefined && state !== '' && state !== '-1' && Number(state) !== -1) {
            sql += ` AND o.state = ?`
            countSql += ` AND o.state = ?`
            params.push(Number(state))
            countParams.push(Number(state))
        }

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

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

        sql += `
            ORDER BY o.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: '获取订单数据失败！'
            })

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

module.exports.GetOrderList = GetOrderList
