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

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

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

        if ([uuid, session, 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
            })

        const time = new Date().getTime()

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

        let sql, r

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

            msg.push(message)
            const systemMsg = {
                time,
                content: '您的问题已收到，我们将会尽快处理您的问题，请耐心等待，感谢您的支持理解。',
                uuid: 'e4fe0277-0b1a-41a1-b25f-8b6e4cec3281',
                type: 'system'
            }
            msg.push(systemMsg)

            sql = 'INSERT INTO work_order (title, email, msg, create_user, create_time, update_time) VALUES (?, ?, ?, ?, ?, ?)'
            r = await db.query(sql, [title, email, msg, uuid, time, time])
        } else {
            const selectSql = 'SELECT msg, state, email FROM work_order WHERE id = ? AND create_user = ?'
            const selectRows = await db.query(selectSql, [id, uuid])
            if (!selectRows || selectRows.length !== 1 || selectRows[0].state === 2)
                return res.json({
                    ...BaseStdResponse.ERR,
                    msg: '工单异常或已关闭，请提交新工单'
                })

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

            sql = 'UPDATE work_order SET msg = ?, update_time = ?, state = 0 WHERE id = ? AND create_user = ?'
            r = await db.query(sql, [msg, time, id, uuid])
        }

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

                let kefuSql = `
                    SELECT email FROM users
                    WHERE JSON_CONTAINS(permission, '"admin"') OR JSON_CONTAINS(permission, '"service"')
                `

                let kefuRows = await db.query(kefuSql);

                let emails = [...new Set(kefuRows.map(row => row.email))]

                for (const email of emails) {
                    if(!email) break
                    await EmailTemplate.orderNewReply(email, { id: r.insertId || id, content, files })
                }
            } else {
                return res.json({ ...BaseStdResponse.ERR, msg: '提交工单失败！数据库错误' })
            }
        } catch (err) {
            this.logger.error(`提交工单失败！${err.stack}`)
            res.json({
                ...BaseStdResponse.ERR,
                msg: "提交工单失败！",
            })
        }
    }
}

module.exports.CreateOrder = CreateOrder