import {Context} from "koa";
import axios from "axios";

import {ChannelHandler, LoginResult, PaymentResult} from "../interfaces/ChannelHandler";
import {ChannelConfig} from "../../config/channelConfig";
import {SignatureVerifier} from "../../utils/SignatureVerifier";
import {PaymentHelper} from "../../utils/PaymentHelper";

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

/**
 * 晴天SDK渠道处理器（渠道21）
 * 负责登录验证与支付回调处理
 */
export class QingtianChannelHandler implements ChannelHandler {

    /**
     * 晴天SDK 登录验证
     * @param ctx Koa上下文
     * @param config 渠道配置
     */
    async handleLogin(ctx: Context, config: ChannelConfig): Promise<LoginResult> {
        const data = ctx.request.body as any;
        const {token, uid, channel_code, product_code} = data || {};
        const finalProductCode = product_code || config.loginConfig?.productCode;

        if (!token || !uid) {
            logger.warn("晴天SDK登录验证失败: 缺少必要参数", {token, uid});
            return {code: 0, msg: "缺少必要参数 token 或 uid"};
        }

        if (!finalProductCode) {
            logger.error("晴天SDK登录验证失败: 未配置productCode");
            return {code: 0, msg: "服务器未配置productCode"};
        }

        const requestUrl = "https://gdk.qkyx.online/api/v1/quick/checkUser";
        const params: Record<string, string> = {
            access_token:token,
            user_id:uid,
        };
        logger.info("晴天SDK登录验证请求", {url: requestUrl, params});

        try {
            const response = await axios.post(requestUrl, params);
            logger.info("晴天SDK登录验证响应", {data: response.data});

            if (response.data.code == 200) {
                return {code: 1, msg: "success"};
            }

            logger.warn("晴天SDK登录验证失败: 接口返回非1", {data: response.data});
            return {code: 0, msg: "登录验证失败"};
        } catch (error) {
            logger.error("晴天SDK登录验证异常", error);
            return {code: 0, msg: "登录验证异常"};
        }
    }

    /**
     * 晴天SDK 支付回调
     * @param ctx Koa上下文
     * @param config 渠道配置
     */
    async handlePayment(ctx: Context, config: ChannelConfig): Promise<PaymentResult> {
        const data = ctx.request.body as any;
        logger.info("晴天SDK支付回调参数", {url: ctx.href, params: data,headerSign:ctx.request.headers["x-platform-sign"]});

        const {extras_params, channel_order_id, status, amount} = data || {};
        if (!channel_order_id || !status || !amount) {
            logger.warn("晴天SDK支付回调失败: 缺少必要参数", {extras_params, channel_order_id, status, amount});
            return {code: 0, msg: "缺少必要参数"};
        }
        if (!extras_params) {
            logger.warn("晴天SDK支付回调失败: 缺少extras_params", {channel_order_id});
            return {code: 0, msg: "缺少extras_params"};
        }

        const md5Key = config.paymentConfig?.callbackKey;
        if (!md5Key) {
            logger.error("晴天SDK支付回调失败: 未配置密钥");
            return {code: 0, msg: "服务器未配置渠道密钥"};
        }

        const headerSign = ctx.request.headers["x-platform-sign"] as string;
        if (!headerSign) {
            logger.warn("晴天SDK支付回调失败: 请求头缺少X-Platform-Sign");
            return {code: 0, msg: "缺少签名请求头"};
        }

        if (!SignatureVerifier.verifyQingtianSign(data, md5Key, headerSign)) {
            logger.warn("晴天SDK支付回调失败: 签名验证失败");
            return {code: 0, msg: "签名验证失败"};
        }

        if (status !== "completed") {
            logger.warn("晴天SDK支付状态非成功", {status});
            return {code: 0, msg: "支付状态失败"};
        }

        try {
            const parsedAmount = parseFloat(amount);
            const orderId = extras_params;
            const outTradeNo = channel_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;
            if (Number(orderInfo.amount) !== parsedAmount) {
                logger.warn("晴天SDK支付金额不匹配", {
                    orderId,
                    requestAmount: parsedAmount,
                    orderAmount: orderInfo.amount
                });
                return {code: 0, msg: "订单金额不一致"};
            }

            logger.info(`晴天SDK支付订单${orderId}开始发货`);
            const result = await PaymentHelper.deliverOrder(
                orderInfo,
                ctx.request.ip,
                validation.url,
                outTradeNo
            );
            logger.info(`晴天SDK支付订单${orderId}发货完成`, {result});
            return result;
        } catch (error) {
            logger.error("晴天SDK支付回调解析异常", error);
            return {code: 0, msg: "回调解析异常"};
        }
    }
}
