import 'package:cpt_main/modules/notification/notification_group_data.dart';
import 'package:cs_resources/generated/l10n.dart';
import 'package:domain/entity/notification_page_entity.dart';
import 'package:domain/repository/main_repository.dart';
import 'package:plugin_platform/engine/dialog/dialog_engine.dart';
import 'package:plugin_platform/engine/notify/notify_engine.dart';
import 'package:plugin_platform/engine/toast/toast_engine.dart';
import 'package:plugin_platform/http/dio/dio_cancelable_mixin.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:router/componentRouter/component_service_manager.dart';
import 'package:shared/utils/date_time_utils.dart';
import 'package:shared/utils/log_utils.dart';
import 'package:widgets/dialog/app_default_dialog.dart';
import 'package:widgets/load_state_layout.dart';
import 'package:widgets/widget_export.dart';

import 'notification_state.dart';

part 'notification_view_model.g.dart';

@riverpod
class NotificationViewModel extends _$NotificationViewModel with DioCancelableMixin {
  late final MainRepository _mainRepository;

  @override
  NotificationState build() {
    _mainRepository = ref.read(mainRepositoryProvider);
    return NotificationState(datas: []);
  }

  var _curPage = 1; //请求参数当前的页面
  var _needShowPlaceholder = true; //是否展示LoadingView

  // Refresh 控制器
  final EasyRefreshController refreshController = EasyRefreshController(
    controlFinishRefresh: true, //允许刷新
    controlFinishLoad: true, //允许加载
  );

  //刷新页面状态
  void changeLoadingState(LoadState loadState, String? errorMsg) {
    state = state.copyWith(loadingState: loadState, errorMessage: errorMsg);
  }

  // Refresh 刷新事件
  Future onRefresh() async {
    _curPage = 1;
    fetchList();
  }

  // Refresh 加载事件
  Future loadMore() async {
    _curPage++;
    fetchList();
  }

  // 重试请求
  Future retryRequest() async {
    _curPage = 1;
    _needShowPlaceholder = true;
    fetchList();
  }

  /// 获取服务器数据
  Future fetchList() async {
    if (_needShowPlaceholder) {
      changeLoadingState(LoadState.State_Loading, null);
    }

    // 获取列表
    var listResult = await _mainRepository.fetchNotificationList(
      curPage: _curPage,
      cancelToken: cancelToken,
    );

    // 处理数据
    if (listResult.isSuccess) {
      handleList(listResult.data?.list);
    } else {
      changeLoadingState(LoadState.State_Error, listResult.errorMsg);
    }

    // 最后赋值
    _needShowPlaceholder = false;
  }

// 处理数据与展示的逻辑
  void handleList(List<NotificationPageList>? list) {
    if (list != null && list.isNotEmpty) {
      //有数据，处理转换数据

      List<NotificationGroupData> newDatas;
      //先从当的数据中找到 groupId 比对获取到的list 是否有匹配的 groupId
      if (_curPage == 1) {
        newDatas = []; // 重新加载数据
      } else {
        newDatas = List.from(state.datas); // 获取当前状态的数据的副本去添加数据
      }

      for (var item in list) {
        String? createAt = item.createdAt!.split(" at ")[0];
        //处理 groupId 的显示字段  21 May 2025
        DateTime? dateTime = DateTimeUtils.parseCustomDate(createAt.trim(), format: 'dd MMM yyyy');
        String itemGroupId;
        if (dateTime != null) {
          if (DateTimeUtils.isTodayByDateTime(dateTime)) {
            itemGroupId = S.current.today;
          } else {
            itemGroupId = "${DateTimeUtils.getWeekday(dateTime, languageCode: 'en')} ${DateTimeUtils.formatDate(dateTime, format: 'dd MMM yyyy')}";
          }
        } else {
          itemGroupId = createAt;
        }

        // 尝试在当前分组中找到匹配的 createdAt
        var curGroup = newDatas.firstWhere((element) => element.groupId == itemGroupId, orElse: () => NotificationGroupData(null, []));

        // 如果有匹配的 createdAt，则添加进去
        if (curGroup.groupId != null) {
          curGroup.groupDatas!.add(item); // 添加通知到现有组
        } else {
          // 如果没有匹配的 createdAt，则创建新的分组
          newDatas.add(NotificationGroupData(itemGroupId, [item])); // 创建新组
        }
      }

      if (_curPage == 1) {
        //刷新的方式
        state = state.copyWith(datas: newDatas);
        refreshController.finishRefresh();

        //更新展示的状态
        changeLoadingState(LoadState.State_Success, null);
      } else {
        //加载更多
        state.datas.addAll(newDatas);
        refreshController.finishLoad();
      }
    } else {
      if (_curPage == 1) {
        //展示无数据的布局
        state = state.copyWith(datas: []);
        changeLoadingState(LoadState.State_Empty, null);
        refreshController.finishRefresh();
      } else {
        //展示加载完成，没有更多数据了
        refreshController.finishLoad(IndicatorResult.noMore);
      }
    }
  }

  /// 点击标记全部
  void markAll() {
    DialogEngine.show(
        widget: AppDefaultDialog(
      message: S.current.read_all_msg,
      confirmAction: () {
        _requestReadAll();
      },
    ));
  }

  ///设置单个已读
  void setReadStatus(NotificationPageList item) async {
    // 创建新的数据列表
    List<NotificationGroupData> newDatas = List.from(state.datas); // 复制一份当前数据

    // 找到对应的组并更新状态
    for (var group in newDatas) {
      for (var notification in group.groupDatas!) {
        if (notification.id == item.id) {
          // 假设 item 有一个唯一的 id 字段
          notification.read = true; // 更新状态为已读
          break; // 找到并更新后可以退出循环
        }
      }
    }

    // 更新状态，通知 UI 刷新
    state = state.copyWith(datas: newDatas);

    //转转详情
    _godoDetailPage(item);

    // 发送请求设置服务器已读
    final result = await _mainRepository.setNotificationRead(id: item.id);

    if (result.isSuccess) {
      Log.d("设置 ${item.id} 的消息已读成功！");
    } else {
      ToastEngine.show(result.errorMsg ?? "UnKnow Error");
    }
  }

  ///跳转到详情页
  void _godoDetailPage(NotificationPageList item) {
    NotificationPageListData? data = item.data;
    if (data == null) return;
    // 1、加入unit成功  ApprovedJoinUnitNotification
    // 2、加入unit失败  RejectedJoinUnitNotification
    // 3、online form批准了  ApprovedApplyOnlineFormNotification
    // 4、online form拒绝了  RejectedApplyOnlineFormNotification
    // 5、facility 预定成功了(不需要，因为支付了就是预定成功了)
    // 6、facility 预定失败了(长时间未支付，被系统取消了)  FacilityBookingNotPaidCancelNotification
    // 7、每月物业费账单生成了
    // 8、每月停车费账单生成了
    // 9、服务订单长时间未支付  PaidServiceOrderNotPaidCancelNotification

    String? type = data.type;
    if (type == 'ApprovedApplyOnlineFormNotification' || type == 'RejectedApplyOnlineFormNotification') {
      //去 Form 详情
      ComponentServiceManager().formService.startFormDetailPage(data.estateOnlineFormId ?? "", data.id ?? "", data.onlineFormTypeId ?? "");
    }
  }

  /// 请求设置全部已读
  void _requestReadAll() async {
    // 发送请求设置服务器已读
    final result = await _mainRepository.setNotificationRead();

    if (result.isSuccess) {
      Log.d("设置全部的消息已读成功！");
      NotifyEngine.showSuccess(S.current.successful);

      // 创建新的数据列表
      List<NotificationGroupData> newDatas = List.from(state.datas); // 复制一份当前数据

      // 找到对应的组并更新状态
      for (var group in newDatas) {
        for (var notification in group.groupDatas!) {
          notification.read = true; // 更新状态为已读
        }
      }

      // 更新状态，通知 UI 刷新
      state = state.copyWith(datas: newDatas);
    } else {
      ToastEngine.show(result.errorMsg ?? "UnKnow Error");
    }
  }
}
