import { Context } from "koa";
import {
  ChannelHandler,
  LoginResult,
  PaymentResult,
} from "../interfaces/ChannelHandler";
import { ChannelConfig } from "../../config/channelConfig";
import { PaymentHelper } from "../../utils/PaymentHelper";
import QuickAsy from "../../utils/quickAsy";
import { parseString } from "xml2js";
import { SignatureVerifier } from "../../utils/SignatureVerifier";
import axios from "axios";

const logger = require("../../utils/log");

export class QiAiH5ChannelHandler implements ChannelHandler {
  async handleLogin(ctx: Context, config: ChannelConfig): Promise<LoginResult> {
    const data = ctx.request.body as any;

    // 构建七艾登录验证请求URL
    const reqUrl = `http://checkuser.quickapi.net/v2/checkUserInfo?token=${data.token}&uid=${data.uid}&product_code=${config.loginConfig?.productCode}`;

    logger.info("七艾登录验证请求", { params: data, url: reqUrl });

    try {
      const res = await axios.get(reqUrl);
      logger.info("七艾登录验证响应", { res: res.data });

      if (res.data == "1") {
        return {
          code: 1,
          msg: "success",
        };
      } else {
        return {
          code: 0,
          msg: "fail",
        };
      }
    } catch (error) {
      logger.error("七艾登录验证请求失败", { error });
      return {
        code: 0,
        msg: "验证请求失败",
      };
    }
  }

  async handlePayment(
    ctx: Context,
    config: ChannelConfig
  ): Promise<PaymentResult> {
    const data = ctx.request.body as any;

    logger.info("七艾支付回调参数:", { url: ctx.href, params: data });
    let ntData = data.nt_data;

    if (
      !SignatureVerifier.verifyQuickSign(data, config.paymentConfig.signKey)
    ) {
      logger.error("quick支付签名验证失败");
      return {
        code: 0,
        msg: "签名验证失败",
      };
    }

    // 解析XML数据
    let xmlData = QuickAsy.decode(ntData, config.paymentConfig.callbackKey);
    const result = await new Promise((resolve, reject) => {
      parseString(xmlData, (err, result) => {
        if (err) {
          return reject(err);
        }
        resolve(result);
      });
    });

    logger.info("支付解密result", { result: result });

    const message = (result as any).quicksdk_message.message[0];
    const orderId = message.game_order[0]; // cp单号
    const out_trade_no = message.order_no[0]; // sdk订单号
    const status = message.status[0]; // 0成功
    const amount = message.amount[0]; // 0成功

    if (status == 1) {
      logger.info("quick支付状态失败", { status });
      return {
        code: 0,
        msg: "quick支付状态失败",
      };
    }

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

    const orderInfo = validation.orderInfo;

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

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

    return payResult;
  }
}
