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

class CancelOrder extends API {
    constructor() {
        super()
        this.setPath('/Order/CancelOrder')
        this.setMethod('POST')
    }

    async onRequest(req, res) {
        const { uuid, session, orderId } = req.body

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

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

        try {
            const rows = await db.query(
                'SELECT state FROM orders WHERE orderId = ? AND create_user = ? LIMIT 1',
                [orderId, uuid]
            )
            if (!rows || rows.length !== 1) {
                return res.json({ ...BaseStdResponse.ERR, msg: '订单不存在' })
            }

            if (Number(rows[0].state) !== 0) {
                return res.json({ ...BaseStdResponse.ERR, msg: '仅未支付订单可取消' })
            }

            const closeResult = await closePendingOrder({ orderId, operatorUuid: uuid, logger: this.logger })
            if (!closeResult.closed) {
                return res.json({ ...BaseStdResponse.ERR, msg: '取消订单失败，订单状态可能已变更' })
            }

            this.logger.info(`用户取消订单成功，订单号：${orderId}`)
            return res.json({ ...BaseStdResponse.OK, msg: '订单已取消' })
        } catch (error) {
            this.logger.error(`取消订单失败 ${orderId}: ${error.stack || error}`)
            return res.json({ ...BaseStdResponse.ERR, msg: '取消订单失败，请稍后再试' })
        }
    }
}

module.exports.CancelOrder = CancelOrder
