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

    if (!data.iaaq) {
      console.log("未获取到iaaq参数");
      return;
    }
    let decryptedObject = {};

    try {
      const encrypted = data.iaaq;
      const key = CryptoJS.enc.Utf8.parse(config.loginConfig?.signKey);
      const iv = CryptoJS.enc.Utf8.parse("1P4QaZdA0HUk4qT0");

      const decrypted = CryptoJS.AES.decrypt(encrypted, key, {
        iv: iv,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7,
      });

      decryptedObject = JSON.parse(decrypted.toString(CryptoJS.enc.Utf8));

      console.log("解码成功:", decryptedObject);
    } catch (error) {
      console.log("解码失败:", error);
    }

    return {
      code: 1,
      msg: "success",
      data: decryptedObject,
    };
  }

  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.product_order_id;
    const out_trade_no = data.trade_code;

    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: orderInfo.uid,
      amount: data.pay_amount / 100,
    };

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

    // 发货处理
    logger.info(`360支付订单${orderId}通知游戏发货开始`);
    const result = await PaymentHelper.deliverOrder(
      modifiedOrderInfo,
      ctx.request.ip,
      validation.url,
      out_trade_no
    );
    logger.info(`360支付订单${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 signData = Object.keys(data)
      .sort()
      .filter((key) => key !== "sign");

      const signStr =
      signData.map((key) => `${key}=${data[key]}`).join("&") +
      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;
    }
  }
}
