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

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

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

        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
            })

        const time = new Date().getTime()

        let msg = []
        const systemMsg = {
            time,
            content: '当前工单已关闭，若仍有疑问可提交新工单哦~~',
            uuid: 'e4fe0277-0b1a-41a1-b25f-8b6e4cec3281',
            type: 'system'
        }

        const selectSql = 'SELECT msg, state, create_user FROM work_order WHERE id = ?'
        const selectRows = await db.query(selectSql, [id])
        if (!selectRows || selectRows.length !== 1 || selectRows[0].state === 2)
            return res.json({
                ...BaseStdResponse.ERR,
                msg: '工单异常或已关闭，请提交新工单'
            })

        let permission = await AccessControl.getPermission(uuid)
        if(selectRows[0].create_user !== uuid && !permission.includes("admin") && !permission.includes("service"))
            return res.json({
                ...BaseStdResponse.PERMISSION_DENIED,
                msg: '无操作权限'
            })

        msg = selectRows[0].msg
        msg.push(systemMsg)

        let sql = 'UPDATE work_order SET msg = ?, update_time = ?, state = 2 WHERE id = ?'
        let r = await db.query(sql, [msg, time, id])

        try {
            if (r && r.affectedRows > 0) {
                res.json({
                    ...BaseStdResponse.OK,
                    data: r.insertId
                })
            } else {
                return res.json({ ...BaseStdResponse.ERR, msg: '关闭工单失败！数据库错误' })
            }
        } catch (err) {
            this.logger.error(`关闭工单失败！${err.stack}`)
            res.json({
                ...BaseStdResponse.ERR,
                msg: "关闭工单失败！",
            })
        }
    }
}

module.exports.CloseOrder = CloseOrder