import 'package:get/get.dart';
import 'package:kaer_with_panels/app/services/api_service/kr_api.user.dart';
import '../../../common/app_run_data.dart';
import '../../../model/response/kr_user_online_duration.dart';
import '../../../modules/kr_home/controllers/kr_home_controller.dart';
import '../../../utils/kr_common_util.dart';
import '../../../utils/kr_log_util.dart';
import 'package:kaer_with_panels/app/localization/app_translations.dart';
import 'package:easy_refresh/easy_refresh.dart';

class KRStatisticsController extends GetxController {
  /// VPN连接状态
  final RxString kr_vpnStatus = ''.obs;

  /// IP地址
  final RxString kr_ipAddress = ''.obs;

  /// 连接时间
  final RxString kr_connectTime = ''.obs;

  /// 协议类型
  final RxString kr_protocol = ''.obs;

  /// 当前连续记录(天)
  final RxInt kr_currentStreak = 0.obs;

  /// 最高记录(天)
  final RxInt kr_highestStreak = 0.obs;

  /// 最长连接时间(天)
  final RxInt kr_longestConnection = 0.obs;

  /// 每周保护时间数据
  final RxList<double> kr_weeklyData = <double>[0, 0, 0, 0, 0, 0, 0].obs;

  final RxBool kr_isConnected = false.obs;

  late final KRHomeController kr_homeController;

    /// 开始时间
  final RxInt kr_startTime = 0.obs;
  
  /// 结束时间
  final RxInt kr_endTime = 0.obs;

  /// 最后连接日期
  final RxString kr_lastConnectDate = ''.obs;

  final KRUserApi kr_userApi = KRUserApi();
  final EasyRefreshController refreshController = EasyRefreshController(
    controlFinishRefresh: true,
  );

  @override
  void onInit() {
    super.onInit();
    kr_homeController = Get.find<KRHomeController>();
    _kr_initializeListeners();
    _kr_initializeValues();
    kr_isConnected.value = kr_homeController.kr_isConnected.value;
    ever(kr_homeController.kr_isConnected, (bool connected) {
      kr_isConnected.value = connected;
    });

    ever(KRAppRunData.getInstance().kr_isLogin, (bool isLogin) {
      if (!isLogin) {
        kr_currentStreak.value = 0;
        kr_longestConnection.value = 0;
        kr_highestStreak.value = 0;
        kr_weeklyData.value = <double>[0, 0, 0, 0, 0, 0, 0];
        return;
      }

      kr_getUserSubscribeTrafficLogs();
    });
  }

  /// 初始化监听器
  void _kr_initializeListeners() {
    ever(kr_homeController.kr_connectText, _kr_updateVpnStatus);
    ever(kr_homeController.kr_currentIp, _kr_updateIpAddress);
    ever(kr_homeController.kr_connectionTime, _kr_updateConnectionTime);
    ever(kr_homeController.kr_currentProtocol, _kr_updateProtocol);
  }

  /// 初始化值
  void _kr_initializeValues() {
    kr_vpnStatus.value = kr_homeController.kr_connectText.value;
    kr_ipAddress.value = kr_homeController.kr_currentIp.value;
    kr_connectTime.value = kr_homeController.kr_connectionTime.value;
    kr_protocol.value = kr_homeController.kr_currentProtocol.value;

    // 这里可以添加其他统计数据的初始化
    _kr_updateStatistics();

    kr_getUserSubscribeTrafficLogs();
  }

  /// 获取本周的流量日志
  Future<void> kr_getUserSubscribeTrafficLogs() async {
    if (!KRAppRunData.getInstance().kr_isLogin.value) {
      return;
    }

    final either0 = await KRUserApi().kr_getUserInfo();
    either0.fold(
      (error) => KRCommonUtil.kr_showToast(error.msg),
      (userInfo) {
        // kr_homeController.kr_userId.value = userInfo.id.toString();
      },
    );

    // 获取本周的开始和结束时间戳
    final DateTime now = DateTime.now();
    final DateTime weekStart = now.subtract(Duration(days: now.weekday - 1));
    final DateTime weekStartDate = DateTime(weekStart.year, weekStart.month, weekStart.day);
    final DateTime weekEndDate = weekStartDate.add(const Duration(days: 7));
    
    final int startTimestamp = weekStartDate.millisecondsSinceEpoch ~/ 1000;
    final int endTimestamp = weekEndDate.millisecondsSinceEpoch ~/ 1000;

    // 更新时间戳
    kr_startTime.value = startTimestamp;
    kr_endTime.value = endTimestamp;

    final either = await KRUserApi().kr_getUserOnlineTimeStatistics();
    
    either.fold(
      (error) => KRCommonUtil.kr_showToast(error.msg),
      (trafficLogs) {
        // 处理流量日志数据
        _kr_processTrafficLogs(trafficLogs);
      },
    );
  }

  /// 处理流量日志数据
  void _kr_processTrafficLogs(KRUserOnlineDurationResponse trafficLogs) {
    try {
      // 更新连续记录数据
      kr_currentStreak.value = trafficLogs.connectionRecords.currentContinuousDays;
      kr_highestStreak.value = trafficLogs.connectionRecords.historyContinuousDays;
      // 将小时转换为天数并向上取整
      kr_longestConnection.value = (trafficLogs.connectionRecords.longestSingleConnection / 24).ceil();

      // 更新每周数据
      final List<double> weeklyHours = List.filled(7, 0.0);
      for (final stat in trafficLogs.weeklyStats) {
        if (stat.day >= 1 && stat.day <= 7) {
          weeklyHours[stat.day - 1] = stat.hours;
        }
      }
      kr_weeklyData.value = weeklyHours;
    } catch (e) {
      KRCommonUtil.kr_showToast('处理流量日志数据失败');
      KRLogUtil.kr_e('处理流量日志数据失败: $e', tag: 'Statistics');
    }
  }

  void _kr_updateVpnStatus(String value) {
    kr_vpnStatus.value = value;
  }

  void _kr_updateIpAddress(String value) {
    kr_ipAddress.value = value.isEmpty ? '0.0.0.0' : value;
  }

  void _kr_updateConnectionTime(String value) {
    kr_connectTime.value = value.isEmpty ? '00:00:00' : value;
  }

  void _kr_updateProtocol(String value) {
    kr_protocol.value = value.isEmpty ? 'UDP' : value;
  }

  /// 更新统计数据
  void _kr_updateStatistics() {
    // 不再需要本地更新统计数据，完全依赖接口返回
  }

  @override
  void onReady() {
    super.onReady();
  }

  @override
  void onClose() {
    refreshController.dispose();
    super.onClose();
  }

  /// 获取根据当前日期调整后的星期标题数组
  List<String> kr_getAdjustedWeekTitles() {
    final DateTime now = DateTime.now();
    final int currentWeekday = now.weekday; // 1-7，1代表周一，7代表周日
    
    final List<String> weekTitles = [
      AppTranslations.kr_statistics.monday,
      AppTranslations.kr_statistics.tuesday,
      AppTranslations.kr_statistics.wednesday,
      AppTranslations.kr_statistics.thursday,
      AppTranslations.kr_statistics.friday,
      AppTranslations.kr_statistics.saturday,
      AppTranslations.kr_statistics.sunday
    ];
    
    // 重新排序数组，使当前日期对应的星期显示在最后
    final List<String> adjustedTitles = [
      ...weekTitles.sublist(currentWeekday),
      ...weekTitles.sublist(0, currentWeekday)
    ];
    
    return adjustedTitles;
  }

  // 刷新数据
  Future<void> kr_onRefresh() async {
    if (!KRAppRunData.getInstance().kr_isLogin.value) {
      refreshController.finishRefresh();
      return;
    }
    
    try {
      await kr_getUserSubscribeTrafficLogs();
    } finally {
      refreshController.finishRefresh();
    }
  }
}
