const API = require("../../../../lib/API.js");
const db = require("../../../../plugin/DataBase/db.js");
const { BaseStdResponse } = require("../../../../BaseStdResponse.js");
const AccessControl = require("../../../../lib/AccessControl.js");
const EmailTemplate = require('../../../../plugin/Email/emailTemplate')

class ReplyOrder extends API {
    constructor() {
        super();

        this.setPath('/Admin/Kefu/Order')
        this.setMethod('PUT')
    }

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

        if ([uuid, session, id, content].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 permission = await AccessControl.getPermission(uuid)
        if (!permission.includes("admin") && !permission.includes("service"))
            return res.json({
                ...BaseStdResponse.PERMISSION_DENIED
            })

        const time = new Date().getTime()

        let msg = []
        let message = {
            time,
            content,
            files: files ?? [],
            uuid,
            type: 'server'
        }

        const selectSql = 'SELECT msg, state, email 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: '工单异常或已关闭'
            })

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

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

        try {
            if (r && r.affectedRows > 0) {
                res.json({
                    ...BaseStdResponse.OK,
                    data: r.insertId
                })

                if (selectRows[0].email) {
                    await EmailTemplate.orderNewReply(selectRows[0].email, { id, content, files })
                }
            } else {
                return res.json({ ...BaseStdResponse.ERR, msg: '回复工单失败！数据库错误' })
            }
        } catch (err) {
            this.logger.error(`回复工单失败！${err.stack}`)
            res.json({
                ...BaseStdResponse.ERR,
                msg: "回复工单失败！",
            })
        }
    }
}

module.exports.ReplyOrder = ReplyOrder