import 'package:fpdart/fpdart.dart';
import 'package:kaer_with_panels/app/utils/kr_log_util.dart';
import 'dart:io' show Platform;

import '../../model/response/kr_config_data.dart';
import '../../model/response/kr_kr_affiliate_count.dart';
import '../../model/response/kr_message_list.dart';
import '../../model/response/kr_user_info.dart';
import '../../model/response/kr_user_online_duration.dart';
import '../../model/response/kr_web_text.dart';
import '../../network/base_response.dart';
import '../../network/http_error.dart';
import '../../network/http_util.dart';
import 'api.dart';

class KRUserApi {
  // 创建一个单例实例
  static final KRUserApi _instance = KRUserApi._internal();
  factory KRUserApi() => _instance;

  // 私有构造函数
  KRUserApi._internal();

  /// 获取当前系统的 user_agent
  String _kr_getUserAgent() {
    if (Platform.isAndroid) {
      return 'android';
    } else if (Platform.isIOS) {
      return 'ios';
    } else if (Platform.isMacOS) {
      return 'mac';
    } else if (Platform.isWindows) {
      return 'windows';
    } else if (Platform.isLinux) {
      return 'linux';
    } else if (Platform.isFuchsia) {
      return 'harmony';
    } else {
      return 'unknown';
    }
  }

  Future<Either<HttpError, KRMessageList>> kr_getMessageList(
      int page, int size, {bool? popup}) async {
    final Map<String, dynamic> data = <String, dynamic>{};
    data['page'] = page;
    data['size'] = size;
    if (popup != null) {
      data['popup'] = popup;
    }
    BaseResponse<dynamic> baseResponse =
        await HttpUtil.getInstance().request<KRMessageList>(
      Api.kr_getMessageList,
      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, KRUserOnlineDurationResponse>> kr_getUserOnlineTimeStatistics(
     ) async {
    final Map<String, dynamic> data = <String, dynamic>{};
   
    BaseResponse<KRUserOnlineDurationResponse> baseResponse =
        await HttpUtil.getInstance().request<KRUserOnlineDurationResponse>(
      Api.kr_getUserOnlineTimeStatistics,
      data,
      method: HttpMethod.GET,
      isShowLoading: false,
    );
    KRLogUtil.kr_i('获取用户在线时长统计: ${baseResponse.model}');
    if (!baseResponse.isSuccess) {
      return left(
          HttpError(msg: baseResponse.retMsg, code: baseResponse.retCode));
    }
    return right(baseResponse.model);
  }

  /// 获取用户信息（包含邀请码、余额、佣金等）
  static Future<Either<HttpError, KRUserInfo>> kr_getUserInfo() async {
    final Map<String, dynamic> data = <String, dynamic>{};
    BaseResponse<KRUserInfo> baseResponse =
    await HttpUtil.getInstance().request<KRUserInfo>(
      Api.kr_getUserInfo,
      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, KRAffiliateCount>> kr_getAffiliateCount() async {
    final Map<String, dynamic> data = <String, dynamic>{};
    BaseResponse<dynamic> baseResponse =
        await HttpUtil.getInstance().request<KRAffiliateCount>(
      Api.kr_getAffiliateCount,
      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, KRConfigData>> kr_config() async {
    final Map<String, dynamic> data = <String, dynamic>{};
    data['user_agent'] = _kr_getUserAgent();
    BaseResponse<KRConfigData> baseResponse =
        await HttpUtil.getInstance().request<KRConfigData>(
      Api.kr_config,
      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<Map<String, dynamic>>>> kr_getUserDevices() async {
    final Map<String, dynamic> data = <String, dynamic>{};

    BaseResponse<dynamic> baseResponse =
        await HttpUtil.getInstance().request<dynamic>(
      Api.kr_getUserDevices,
      data,
      method: HttpMethod.GET,
      isShowLoading: false,
    );

    if (!baseResponse.isSuccess) {
      return left(
          HttpError(msg: baseResponse.retMsg, code: baseResponse.retCode));
    }

    // 返回设备列表数据
    try {
      // 响应格式: { data: { list: [...], total: N } }
      final responseData = baseResponse.model;
      final List<Map<String, dynamic>> devices =
          (responseData['list'] as List)
              .map((item) => item as Map<String, dynamic>)
              .toList();
      return right(devices);
    } catch (e) {
      KRLogUtil.kr_e('解析设备列表失败: $e', tag: 'KRUserApi');
      return left(HttpError(msg: '数据解析失败', code: -1));
    }
  }

  /// 解绑用户设备
  Future<Either<HttpError, void>> kr_unbindUserDevice(String deviceId) async {
    final Map<String, dynamic> data = <String, dynamic>{};

    // 将字符串 ID 转换为整数
    try {
      data['id'] = int.parse(deviceId);
    } catch (e) {
      KRLogUtil.kr_e('设备ID格式错误: $deviceId', tag: 'KRUserApi');
      return left(HttpError(msg: '设备ID格式错误', code: -1));
    }

    BaseResponse<dynamic> baseResponse =
        await HttpUtil.getInstance().request<dynamic>(
      Api.kr_unbindUserDevice,
      data,
      method: HttpMethod.PUT,
      isShowLoading: true,
    );

    if (!baseResponse.isSuccess) {
      return left(
          HttpError(msg: baseResponse.retMsg, code: baseResponse.retCode));
    }

    return right(null);
  }

  /// 绑定样式
  Future<Either<HttpError, void>> hi_inviteCode(String inviteCode, {bool isSilentInvite = false}) async {
    final Map<String, dynamic> data = <String, dynamic>{};

    // 将字符串 ID 转换为整数
    try {
      data['invite_code'] = inviteCode;
    } catch (e) {
      return left(HttpError(msg: '邀请码错误', code: -1));
    }

    BaseResponse<dynamic> baseResponse =
        await HttpUtil.getInstance().request<dynamic>(
      Api.hi_invite_code,
      data,
      method: HttpMethod.POST,
      isShowLoading: !isSilentInvite,
      isSilentInvite: isSilentInvite,
    );

    if (!baseResponse.isSuccess) {
      return left(
          HttpError(msg: baseResponse.retMsg, code: baseResponse.retCode));
    }

    return right(null);
  }

}
