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

class MyList extends API {
    constructor() {
        super()
        this.setPath('/Lepao/Count/Ledger/MyList')
        this.setMethod('GET')
    }

    async onRequest(req, res) {
        let { uuid, session, current = 1, pagesize = 20, biz_type, remark, start_time, end_time } = req.query
        current = Number(current)
        pagesize = Number(pagesize)
        const startTimeNum = start_time === undefined || start_time === null || start_time === '' ? null : Number(start_time)
        const endTimeNum = end_time === undefined || end_time === null || end_time === '' ? null : Number(end_time)

        if ([uuid, session].some(v => v === '' || v === null || v === undefined)) {
            return res.json({ ...BaseStdResponse.MISSING_PARAMETER })
        }
        if (!Number.isInteger(current) || current < 1 || !Number.isInteger(pagesize) || pagesize < 1 || pagesize > 100) {
            return res.json({ ...BaseStdResponse.ERR, msg: '参数错误' })
        }
        if ((startTimeNum !== null && !Number.isFinite(startTimeNum)) || (endTimeNum !== null && !Number.isFinite(endTimeNum))) {
            return res.json({ ...BaseStdResponse.ERR, msg: '时间参数错误' })
        }
        if (!await AccessControl.checkSession(uuid, session)) {
            return res.status(401).json({ ...BaseStdResponse.ACCESS_DENIED })
        }

        const where = ['l.user_uuid = ?']
        const params = [uuid]
        const sumWhere = ['user_uuid = ?']
        const sumParams = [uuid]
        const offset = (current - 1) * pagesize

        if (biz_type) {
            where.push('l.biz_type = ?')
            params.push(biz_type)
            sumWhere.push('biz_type = ?')
            sumParams.push(biz_type)
        }
        if (remark) {
            where.push('l.remark LIKE ?')
            params.push(`%${remark}%`)
            sumWhere.push('remark LIKE ?')
            sumParams.push(`%${remark}%`)
        }

        if (startTimeNum !== null) {
            where.push('l.created_at >= FROM_UNIXTIME(? / 1000)')
            params.push(startTimeNum)
            sumWhere.push('created_at >= FROM_UNIXTIME(? / 1000)')
            sumParams.push(startTimeNum)
        }
        if (endTimeNum !== null) {
            where.push('l.created_at <= FROM_UNIXTIME(? / 1000)')
            params.push(endTimeNum)
            sumWhere.push('created_at <= FROM_UNIXTIME(? / 1000)')
            sumParams.push(endTimeNum)
        }

        const whereSql = where.join(' AND ')
        const listSql = `
            SELECT
                l.id,
                l.user_uuid,
                l.delta,
                l.balance_before,
                l.balance_after,
                l.biz_type,
                l.biz_id,
                l.operator_uuid,
                l.remark,
                UNIX_TIMESTAMP(l.created_at) * 1000 AS created_at
            FROM lepao_count_ledger l
            WHERE ${whereSql}
            ORDER BY l.id DESC
            LIMIT ${pagesize} OFFSET ${offset}
        `
        const countSql = `SELECT COUNT(*) AS total FROM lepao_count_ledger l WHERE ${whereSql}`
        const summarySql = `
            SELECT
                COALESCE(SUM(delta), 0) AS total_delta,
                COUNT(*) AS total_records
            FROM lepao_count_ledger
            WHERE ${sumWhere.join(' AND ')}
        `

        const rows = await db.query(listSql, params)
        const countRows = await db.query(countSql, params)
        const summaryRows = await db.query(summarySql, sumParams)
        if (!rows || !countRows || !summaryRows) {
            return res.json({ ...BaseStdResponse.DATABASE_ERR })
        }

        return res.json({
            ...BaseStdResponse.OK,
            data: rows,
            summary: summaryRows[0] || { total_delta: 0, total_records: 0 },
            pagination: {
                current,
                pagesize,
                total: Number(countRows[0]?.total || 0)
            }
        })
    }
}

module.exports.MyList = MyList
