import 'dart:ffi';

import 'package:fpdart/fpdart.dart';
import 'package:kaer_with_panels/app/common/app_config.dart';
import 'package:kaer_with_panels/app/services/api_service/api.dart';
import 'package:kaer_with_panels/app/model/response/kr_login_data.dart';
import 'package:kaer_with_panels/app/model/response/kr_node_list.dart';
import 'package:kaer_with_panels/app/model/response/kr_package_list.dart';
import 'package:kaer_with_panels/app/network/base_response.dart';
import 'package:kaer_with_panels/app/network/http_error.dart';
import 'package:kaer_with_panels/app/network/http_util.dart';
import 'package:kaer_with_panels/app/utils/kr_log_util.dart';

import '../../model/response/kr_already_subscribe.dart';
import '../../model/response/kr_node_group_list.dart';
import '../../model/response/kr_order_status.dart';
import '../../model/response/kr_payment_methods.dart';
import '../../model/response/kr_purchase_order_no.dart';
import '../../model/response/kr_status.dart';
import '../../model/response/kr_user_available_subscribe.dart';

/// 订阅相关
class KRSubscribeApi {
  /// 获取可购买套餐
  Future<Either<HttpError, KRPackageList>> kr_getPackageListList() async {
    final Map<String, dynamic> data = <String, dynamic>{};

    BaseResponse<KRPackageList> baseResponse =
        await HttpUtil.getInstance().request<KRPackageList>(
      Api.kr_getPackageList,
      data,
      method: HttpMethod.GET,
      isShowLoading: false,
    );
    if (!baseResponse.isSuccess) {
      return left(
          HttpError(msg: baseResponse.retMsg, code: baseResponse.retCode));
    }

    return right(baseResponse.model);
  }

  /// 获取节点列表
  Future<Either<HttpError, KRNodeList>> kr_nodeList(int id) async {
    final Map<String, dynamic> data = <String, dynamic>{};
    data['id'] = id;
    BaseResponse<KRNodeList> baseResponse =
        await HttpUtil.getInstance().request<KRNodeList>(
      Api.kr_nodeList,
      data,
      method: HttpMethod.GET,
      isShowLoading: false,
    );
    if (!baseResponse.isSuccess) {
      return left(
          HttpError(msg: baseResponse.retMsg, code: baseResponse.retCode));
    }

    // 将请求的 subscribeId 传入节点列表模型中
    final nodeList = baseResponse.model;

    // 将请求ID添加到模型中用于查找匹配的订阅项
    // 使用 body 字段重新解析，以便能够找到正确的订阅项
    if (baseResponse.body.isNotEmpty && baseResponse.body.containsKey('list')) {
      try {
        // 添加订阅ID信息到解析参数中
        baseResponse.body['subscribeId'] = id.toString();
        final reparsed = KRNodeList.fromJson(baseResponse.body);
        return right(reparsed);
      } catch (e) {
        // 如果重新解析失败，使用原始模型
        KRLogUtil.kr_w('重新解析节点列表失败: $e，使用原始模型', tag: 'SubscribeApi');
      }
    }

    return right(nodeList);
  }

  /// 获取用户可用订阅
  Future<Either<HttpError, List<KRUserAvailableSubscribeItem>>>
      kr_userAvailableSubscribe({bool containsNodes = false}) async {
    final Map<String, dynamic> data = <String, dynamic>{};
    data['contains_nodes'] = containsNodes;

    BaseResponse<KRUserAvailableSubscribeList> baseResponse =
        await HttpUtil.getInstance().request<KRUserAvailableSubscribeList>(
      Api.kr_userAvailableSubscribe,
      data,
      method: HttpMethod.GET,
      isShowLoading: false,
    );
    if (!baseResponse.isSuccess) {
      return left(
          HttpError(msg: baseResponse.retMsg, code: baseResponse.retCode));
    }

    return right(baseResponse.model.list);
  }

  /// 获取分组节点
  Future<Either<HttpError, List<KRNodeGroupListItem>>>
      kr_nodeGroupList() async {
    final Map<String, dynamic> data = <String, dynamic>{};

    BaseResponse<KRNodeGroupList> baseResponse =
        await HttpUtil.getInstance().request<KRNodeGroupList>(
      Api.kr_nodeGroupList,
      data,
      method: HttpMethod.GET,
      isShowLoading: false,
    );
    if (!baseResponse.isSuccess) {
      return left(
          HttpError(msg: baseResponse.retMsg, code: baseResponse.retCode));
    }

    return right(baseResponse.model.list);
  }

  /// 通过该接口判断订单状态
  Future<Either<HttpError, KROrderStatus>> kr_orderDetail(
      String orderId) async {
    final Map<String, dynamic> data = <String, dynamic>{};
    data['order_no'] = orderId;

    BaseResponse<KROrderStatus> baseResponse =
        await HttpUtil.getInstance().request<KROrderStatus>(
      Api.kr_orderDetail,
      data,
      method: HttpMethod.GET,
      isShowLoading: false,
    );
    if (!baseResponse.isSuccess) {
      return left(
          HttpError(msg: baseResponse.retMsg, code: baseResponse.retCode));
    }

    return right(baseResponse.model);
  }

  /// 查询订单状态（公开接口，用于支付轮询）
  Future<Either<HttpError, KROrderStatus>> kr_queryOrderStatus(
      String orderNo) async {
    final Map<String, dynamic> data = <String, dynamic>{};
    data['order_no'] = orderNo;

    BaseResponse<KROrderStatus> baseResponse =
        await HttpUtil.getInstance().request<KROrderStatus>(
      Api.kr_queryOrderStatus,
      data,
      method: HttpMethod.GET,
      isShowLoading: false,
    );
    if (!baseResponse.isSuccess) {
      return left(
          HttpError(msg: baseResponse.retMsg, code: baseResponse.retCode));
    }

    return right(baseResponse.model);
  }

  /// 获取支付方式
  Future<Either<HttpError, List<KRPaymentMethod>>>
      kr_getPaymentMethods() async {
    final Map<String, dynamic> data = <String, dynamic>{};

    BaseResponse<KRPaymentMethods> baseResponse =
        await HttpUtil.getInstance().request<KRPaymentMethods>(
      Api.kr_getPaymentMethods,
      data,
      method: HttpMethod.GET,
      isShowLoading: false,
    );
    if (!baseResponse.isSuccess) {
      return left(
          HttpError(msg: baseResponse.retMsg, code: baseResponse.retCode));
    }

    return right(baseResponse.model.list);
  }

  /// 进行下单
  Future<Either<HttpError, String>> kr_purchase(
      int planId, int quantity, int payment, String coupon) async {
    final Map<String, dynamic> data = <String, dynamic>{};
    data['subscribe_id'] = planId;
    data['quantity'] = quantity;
    data['payment'] = payment;
    data['coupon'] = "";

    BaseResponse<KRPurchaseOrderNo> baseResponse =
        await HttpUtil.getInstance().request<KRPurchaseOrderNo>(
      Api.kr_purchase,
      data,
      method: HttpMethod.POST,
      isShowLoading: true,
    );
    if (!baseResponse.isSuccess) {
      return left(
          HttpError(msg: baseResponse.retMsg, code: baseResponse.retCode));
    }

    return right(baseResponse.model.orderNo);
  }

  /// 续费
  Future<Either<HttpError, String>> kr_renewal(
      int planId, int quantity, int payment, String coupon) async {
    final Map<String, dynamic> data = <String, dynamic>{};
    data['user_subscribe_id'] = planId;
    data['quantity'] = quantity;
    data['payment'] = payment;
    data['coupon'] = "";

    BaseResponse<KRPurchaseOrderNo> baseResponse =
        await HttpUtil.getInstance().request<KRPurchaseOrderNo>(
      Api.kr_renewal,
      data,
      method: HttpMethod.POST,
      isShowLoading: true,
    );
    if (!baseResponse.isSuccess) {
      return left(
          HttpError(msg: baseResponse.retMsg, code: baseResponse.retCode));
    }

    return right(baseResponse.model.orderNo);
  }

  /// 获取用户已订阅套餐
  Future<Either<HttpError, List<KRAlreadySubscribe>>>
      kr_getAlreadySubscribe({String? includeExpired}) async {
    final Map<String, dynamic> data = <String, dynamic>{};
    if (includeExpired != null) {
      data['includeExpired'] = includeExpired;
    }

    BaseResponse<KRAlreadySubscribeList> baseResponse =
        await HttpUtil.getInstance().request<KRAlreadySubscribeList>(
      Api.kr_getAlreadySubscribe,
      data,
      method: HttpMethod.GET,
      isShowLoading: false,
    );
    if (!baseResponse.isSuccess) {
      return left(
          HttpError(msg: baseResponse.retMsg, code: baseResponse.retCode));
    }

    return right(baseResponse.model.list);
  }

  Future<Either<HttpError, String>> kr_prePurchase(
      int planId, int quantity, String payment, String coupon) async {
    final Map<String, dynamic> data = <String, dynamic>{};
    data['subscribe_id'] = planId;
    data['quantity'] = quantity;
    data['payment'] = payment;
    data['coupon'] = "";

    BaseResponse<KRPurchaseOrderNo> baseResponse =
        await HttpUtil.getInstance().request<KRPurchaseOrderNo>(
      Api.kr_preOrder,
      data,
      method: HttpMethod.POST,
      isShowLoading: true,
    );
    if (!baseResponse.isSuccess) {
      return left(
          HttpError(msg: baseResponse.retMsg, code: baseResponse.retCode));
    }

    return right(baseResponse.model.orderNo);
  }

  /// 获取支付地址,跳转到付款地址（新版本：支持多种支付类型）
  Future<Either<HttpError, KRCheckoutResponse>> kr_checkout(
      String orderId) async {
    final Map<String, dynamic> data = <String, dynamic>{};
    data['orderNo'] = orderId;
    data['returnUrl'] = AppConfig.getInstance().baseUrl;

    BaseResponse<KRCheckoutResponse> baseResponse =
        await HttpUtil.getInstance().request<KRCheckoutResponse>(
      Api.kr_checkout,
      data,
      method: HttpMethod.POST,
      isShowLoading: true,
    );
    if (!baseResponse.isSuccess) {
      return left(
          HttpError(msg: baseResponse.retMsg, code: baseResponse.retCode));
    }

    return right(baseResponse.model);
  }

  /// 重置订阅周期
  Future<Either<HttpError, bool>> kr_resetSubscribePeriod(
      int userSubscribeId) async {
    final Map<String, dynamic> data = <String, dynamic>{};
    data['user_subscribe_id'] = userSubscribeId;
    BaseResponse<KRStatus> baseResponse =
        await HttpUtil.getInstance().request<KRStatus>(
      Api.kr_resetSubscribePeriod,
      data,
      method: HttpMethod.POST,
      isShowLoading: true,
    );
    if (!baseResponse.isSuccess) {
      return left(
          HttpError(msg: baseResponse.retMsg, code: baseResponse.retCode));
    }

    return right(baseResponse.model.kr_bl);
  }

  /// 获取公开的支付方式列表
  Future<Either<HttpError, dynamic>> kr_getPublicPaymentMethods() async {
    final Map<String, dynamic> data = <String, dynamic>{};

    BaseResponse<dynamic> baseResponse =
        await HttpUtil.getInstance().request<dynamic>(
      Api.kr_getPublicPaymentMethods,
      data,
      method: HttpMethod.GET,
      isShowLoading: false,
    );
    if (!baseResponse.isSuccess) {
      return left(
          HttpError(msg: baseResponse.retMsg, code: baseResponse.retCode));
    }

    return right(baseResponse.model);
  }

  Future<Either<HttpError, bool>> kr_attachAppleIapTransaction(
      String jwsData, String orderNo) async {
    final Map<String, dynamic> data = <String, dynamic>{};
    data['signed_transaction_jws'] = jwsData;
    data['order_no'] = orderNo;

    BaseResponse<KRStatus> baseResponse =
        await HttpUtil.getInstance().request<KRStatus>(
      Api.kr_attachAppleIapTransaction,
      data,
      method: HttpMethod.POST,
      isShowLoading: false,
    );
    if (!baseResponse.isSuccess) {
      return left(
          HttpError(msg: baseResponse.retMsg, code: baseResponse.retCode));
    }

    return right(baseResponse.model.kr_bl);
  }

  Future<Either<HttpError, bool>> kr_restoreAppleIapTransaction(
      String transactionId, String orderNo) async {
    final Map<String, dynamic> data = <String, dynamic>{};
    data['transaction_id'] = [transactionId];
    data['order_no'] = orderNo;

    BaseResponse<KRStatus> baseResponse =
        await HttpUtil.getInstance().request<KRStatus>(
      Api.kr_restoreAppleIap,
      data,
      method: HttpMethod.POST,
      isShowLoading: false,
    );
    if (!baseResponse.isSuccess) {
      return left(
          HttpError(msg: baseResponse.retMsg, code: baseResponse.retCode));
    }

    return right(baseResponse.model.kr_bl);
  }
}
