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 MuZiChannelHandler implements ChannelHandler {
  async handleLogin(ctx: Context, config: ChannelConfig): Promise<LoginResult> {
    const data = ctx.request.body as any;
    logger.info("360登录请求参数:", { data });

    // 验证签名
    const signStr = data.uid + config.loginConfig?.signKey;
    const newSign = CryptoJS.MD5(signStr).toString();

    if (data.token != newSign) {
      logger.info(
        `360签名错误: 签名串 ${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("360支付回调参数:", { url: ctx.href, params: data });

    // 验证签名
    if (!this.verify360Sign(data, config.paymentConfig?.signKey)) {
      logger.error("360支付签名验证失败");
      return {
        code: 0,
        msg: "签名错误",
      };
    }

    // 验证订单
    const orderId = data.cpOrder;
    const out_trade_no = data.orderId;

    const validation = await PaymentHelper.validateOrder(orderId);
    if (!validation.valid) {
      return {
        code: validation.message?.includes("重复发货") ? 1 : 0,
        msg: validation.message || "订单验证失败",
      };
    }

    const orderInfo = validation.orderInfo;

    // 修改订单信息以适应360支付的特殊参数
    const modifiedOrderInfo = {
      ...orderInfo,
      uid: data.uid,
      amount: data.skuPrice,
    };

    if (orderInfo.amount != modifiedOrderInfo.amount) {
      logger.info("订单金额不一致", {
        "orderInfo.amount": orderInfo.amount,
        amount: modifiedOrderInfo.amount,
      });
      return {
        code: 0,
        msg: "订单金额不一致",
      };
    }

    // 发货处理
    logger.info(`muzi支付订单${orderId}通知游戏发货开始`);

    logger.info(`muzi支付订单${orderId}通知游戏发货开始:`, validation);
        const result = await PaymentHelper.deliverOrder(
      modifiedOrderInfo,
      ctx.request.ip,
      validation.url,
      out_trade_no
    );
    logger.info(`muzi支付订单${orderId}通知游戏发货结束，结果:`, result);

    return result;
  }

  // 验证360支付签名
  private verify360Sign(data: any, secretKey?: string): boolean {
    if (!secretKey) {
      logger.error("缺少secretKey配置");
      return false;
    }

    try {
      // 获取签名
      const sign = data.sign;
      if (!sign) {
        logger.error("360支付回调缺少签名参数");
        return false;
      }

      // 移除签名字段
      const params = { ...data };
      delete params.sign;

      // 按照字母顺序排序参数
      const keys = Object.keys(params).sort();

      // 构建签名字符串
      let signStr = "";
      for (const key of keys) {
        signStr += `${params[key]}`;
      }

      // 添加密钥
      signStr += secretKey;

      // 计算MD5签名
      const calculatedSign = CryptoJS.MD5(signStr).toString().toLowerCase();

      logger.info("360支付签名验证:", {
        signStr: signStr,
        calculatedSign: calculatedSign,
        receivedSign: sign,
      });

      return calculatedSign === sign;
    } catch (error) {
      logger.error("360支付签名验证出错:", error);
      return false;
    }
  }
}
