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

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

    async onRequest(req, res) {
        let { uuid, session, id } = req.query

        if ([uuid, session, id].some(value => value === '' || value === null || value === undefined))
            return res.json({
                ...BaseStdResponse.MISSING_PARAMETER
            })

        if (!await AccessControl.checkSession(uuid, session))
            return res.status(401).json({
                ...BaseStdResponse.ACCESS_DENIED
            })

        let sql = `
                    SELECT 
                        id,
                        title,
                        msg,
                        state,
                        email,
                        create_time,
                        update_time
                    FROM 
                        work_order
                    WHERE 
                        create_user = ? AND id = ?
                `

        let rows = await db.query(sql, [uuid, id])

        if (!rows || rows.length !== 1) {
            return res.json({
                ...BaseStdResponse.DATABASE_ERR,
                msg: '工单异常，请提交新工单'
            })
        }

        let order = rows[0]
        let uuidSet = new Set()

        order.msg.forEach(msg => {
            if (msg.uuid) uuidSet.add(msg.uuid)
        })

        let uuidList = [...uuidSet]

        if (uuidList.length === 0) {
            return res.json({
                ...BaseStdResponse.SUCCESS,
                data: {
                    ...order,
                    userInfo: {}
                }
            })
        }

        // 合并查询
        const placeholders = uuidList.map(() => '?').join(', ')
        const userSql = `SELECT uuid, username, avatar FROM users WHERE uuid IN (${placeholders})`
        const userRows = await db.query(userSql, uuidList)

        if (!userRows || userRows.length === 0) {
            return res.json({
                ...BaseStdResponse.DATABASE_ERR,
                msg: '用户信息获取失败'
            })
        }

        let userInfo = {}
        userRows.forEach(user => {
            userInfo[user.uuid] = {
                username: user.username,
                avatar: user.avatar
            }
        })

        res.json({
            ...BaseStdResponse.OK,
            data: {
                ...order,
                userInfo
            }
        })
    }
}

module.exports.GetOrderDetail = GetOrderDetail