import { Context } from 'koa';
import { ChannelHandler, LoginResult, PaymentResult } from '../interfaces/ChannelHandler';
import { ChannelConfig } from '../../config/channelConfig';
import { PaymentHelper } from '../../utils/PaymentHelper';
import CryptoJS from 'crypto-js';
const logger = require('../../utils/log');

export class QQChannelHandler implements ChannelHandler {
  async handleLogin(ctx: Context, config: ChannelConfig): Promise<LoginResult> {
    const data = ctx.request.body as any;
        logger.info("QQ登录请求参数:", { data });
        
        // 验证签名
        const signStr = data.uid + config.loginConfig?.signKey;
        const newSign = CryptoJS.MD5(signStr).toString();
        
        if (data.token != newSign) {
            logger.info(`QQ签名错误: 签名串 ${signStr} newSign ${newSign} token ${data.token}`);
            return {
                code: 0,
                msg: "签名错误"
            };
        }
        
        return {
            code: 1,
            msg: "success"
        };
    }

    async handlePayment(ctx: Context, config: ChannelConfig): Promise<PaymentResult> {
        const data = ctx.request.body as any;
        logger.info("QQ支付回调参数:", { url: ctx.href, params: data });
        
        // 验证签名
        if (!this.verifyQQSign(data, config.paymentConfig?.callbackKey)) {
            logger.error("QQ支付签名验证失败");
            return {
                code: 0,
                msg: "签名错误"
            };
        }
        
        // 验证订单
        const orderId = data.app_order_id;
        const out_trade_no = data.order_id;
        
        const validation = await PaymentHelper.validateOrder(orderId);
        if (!validation.valid) {
            return {
                code: validation.message?.includes("重复发货") ? 1 : 0,
                msg: validation.message || "订单验证失败"
            };
        }
        
        const orderInfo = validation.orderInfo;
        
        // 发货处理
        logger.info(`QQ支付订单${orderId}通知游戏发货开始`);
        const result = await PaymentHelper.deliverOrder(
            orderInfo,
            ctx.request.ip,
            validation.url,
            out_trade_no
        );
        logger.info(`QQ支付订单${orderId}通知游戏发货结束，结果:`, result);
        
        return result;
    }
    
    // 验证QQ支付签名
    private verifyQQSign(data: any, secretKey?: string): boolean {
        if (!secretKey) {
            logger.error("缺少secretKey配置");
            return false;
        }
        
        try {
            // 获取签名
            const sign = data.sig;
            if (!sign) {
                logger.error("QQ支付回调缺少签名参数");
                return false;
            }
            
            // 移除签名字段
            const params = { ...data };
            delete params.sig;
            
            // 按照字母顺序排序参数
            const keys = Object.keys(params).sort();
            
            // 构建签名字符串
            let signStr = "";
            for (const key of keys) {
                signStr += `${key}=${params[key]}&`;
            }
            
            // 添加密钥
            signStr += `app_key=${secretKey}`;
            
            // 计算MD5签名
            const calculatedSign = CryptoJS.MD5(signStr).toString().toUpperCase();
            
            logger.info("QQ支付签名验证:", {
                signStr: signStr,
                calculatedSign: calculatedSign,
                receivedSign: sign
            });
            
            return calculatedSign === sign;
        } catch (error) {
            logger.error("QQ支付签名验证出错:", error);
            return false;
        }
    }
}