const API = require("../../lib/API.js");
const db = require("../../plugin/DataBase/db.js");
const Redis = require('../../plugin/DataBase/Redis');
const { BaseStdResponse } = require("../../BaseStdResponse.js");
const AccessControl = require("../../lib/AccessControl.js");
const { evaluateRefundEligibility } = require('../../lib/OrderRefundService');
const { getPaymentMethods } = require('../../lib/OrderPayment');
const { normalizePayBaseUrl } = require('../../lib/PaymentClient');
const { getPaymentConfig } = require('../../lib/PaymentClient');

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

        this.setPath('/Order/Detail');
        this.setMethod('GET');
    }

    async getOrderDetail(uuid, orderId) {
        const sql = `
            SELECT 
                a.orderId,
                a.create_time,
                a.price,
                a.original_price,
                a.discount_amount,
                a.coupon_code,
                a.state,
                a.pay_id,
                a.pay_type,
                a.pay_time,
                g.name,
                g.content,
                g.icon,
                g.isHot,
                g.description,
                g.category,
                g.features,
                g.lepao_count,
                g.ic_count
            FROM 
                orders a
            LEFT JOIN 
                goods g 
            ON 
                a.goods_id = g.id
            WHERE 
                a.create_user = ?
            AND 
                a.orderId = ?
        `;
        const rows = await db.query(sql, [uuid, orderId]);
        return rows?.[0] || null;
    }

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

        if (!uuid || !session || !orderId) {
            return res.json({
                ...BaseStdResponse.MISSING_PARAMETER,
                endpoint: 1513126
            });
        }

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

        let order = await this.getOrderDetail(uuid, orderId);

        if (!order) {
            return res.json({
                ...BaseStdResponse.ERR,
                msg: '订单获取失败！'
            });
        }

        const userRows = await db.query(
            'SELECT lepao_count FROM users WHERE uuid = ? LIMIT 1',
            [uuid]
        );
        const userLepaoCount = userRows?.[0]?.lepao_count ?? 0;
        const refundEligibility = evaluateRefundEligibility({
            state: order.state,
            payTime: order.pay_time,
            userLepaoCount,
            goodsLepaoCount: order.lepao_count,
            skipTimeLimit: false
        });
        order.canRefund = refundEligibility.canRefund;
        order.refundDisabledReason = refundEligibility.reason;
        order.user_lepao_count = Number(userLepaoCount || 0);
        order.canChangePayType = Number(order.state) === 0;
        order.paymentMethods = await getPaymentMethods();

        // 订单未支付
        if (order.state === 0) {
            let payData = await Redis.get(`payData:${order.orderId}`);
            if (!payData) {
                // 标记为过期订单
                // await db.query('UPDATE orders SET state = 3 WHERE orderId = ?', [order.orderId]);

                // 重新获取订单信息（更新后的）
                order = await this.getOrderDetail(uuid, orderId);
                if (!order) {
                    return res.json({
                        ...BaseStdResponse.ERR,
                        msg: '订单获取失败！'
                    });
                }

                order.canChangePayType = Number(order.state) === 0;
                order.paymentMethods = await getPaymentMethods();

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

            let paymentConfig
            try {
                paymentConfig = await getPaymentConfig();
            } catch (error) {
                this.logger.warn(`读取支付配置失败，订单详情不返回支付表单 ${order.orderId}: ${error.message || error}`)
                return res.json({
                    ...BaseStdResponse.OK,
                    data: order
                });
            }
            return res.json({
                ...BaseStdResponse.OK,
                data: order,
                payData: {
                    payUrl: `${normalizePayBaseUrl(paymentConfig?.url)}/submit.php`,
                    payData: JSON.parse(payData),
                    autoSubmit: true
                }
            });
        }

        // 订单已支付或其他状态
        return res.json({
            ...BaseStdResponse.OK,
            data: order
        });
    }
}

module.exports.GetAccount = GetAccount;
