import 'package:domain/entity/response/labour_request_index_entity.dart';
import 'package:domain/entity/response/t_h_o_a_labour_review_table_entity.dart';
import 'package:domain/repository/th_oa_repository.dart';
import 'package:get/get.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:plugin_platform/http/http_result.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 '../labour_request_add/labour_request_add_page.dart';
import '../labour_request_list/dialog/oa_attach_list_dialog.dart';
import '../labour_review_workflow/labour_request_workflow_page.dart';
import 'labour_review_filter.dart';
import 'labour_review_reject_dialog.dart';
import 'labour_review_state.dart';

class LabourReviewController extends GetxController with DioCancelableMixin {
  final THOARepository _thRepository = Get.find();
  final LabourReviewState state = LabourReviewState();

  var isSelectAll = false;
  var _curPage = 1;
  var _needShowPlaceholder = true;

  //页面PlaceHolder的展示
  LoadState loadingState = LoadState.State_Success;
  String? errorMessage;

  //刷新页面状态
  void changeLoadingState(LoadState state) {
    loadingState = state;
    update();
  }

  // Refresh 控制器
  final EasyRefreshController refreshController = EasyRefreshController(
    controlFinishRefresh: true,
    controlFinishLoad: true,
  );

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

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

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

  /// 获取服务器数据，通知消息列表
  Future fetchAppliedStaffList() async {
    if (_needShowPlaceholder) {
      changeLoadingState(LoadState.State_Loading);
    }

    // 并发执行两个请求
    var futures = [
      _thRepository.fetchLabourReviewList(
        state.keyword,
        DateTimeUtils.formatDate(state.selectedStartDate, format: "yyyy-MM-dd"),
        DateTimeUtils.formatDate(state.selectedEndDate, format: "yyyy-MM-dd"),
        state.selectedDepartmentId,
        curPage: _curPage,
        cancelToken: cancelToken,
      ),
      state.indexOptions == null
          ? _thRepository.fetchLabourReviewIndex(
              cancelToken: cancelToken,
            )
          : Future(() => HttpResult(isSuccess: true).convert(data: state.indexOptions!)),
    ];

    //拿到结果
    var results = await Future.wait(futures);
    var listResult = results[0] as HttpResult<THOALabourReviewTableEntity>;
    var optionResult = results[1] as HttpResult<LabourRequestIndexEntity>;

    //选项数据
    if (state.indexOptions == null && optionResult.isSuccess) {
      state.indexOptions = optionResult.data!;
    }

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

    // 最后赋值
    _needShowPlaceholder = false;
  }

  // 处理数据与展示的逻辑
  void handleList(List<THOALabourReviewTableRows>? list) {
    if (list != null && list.isNotEmpty) {
      //有数据，判断是刷新还是加载更多的数据
      if (_curPage == 1) {
        //刷新的方式
        state.datas.clear();
        state.datas.addAll(list);
        refreshController.finishRefresh();

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

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

  @override
  void onClose() {
    state.datas.clear();
    super.onClose();
  }

  /// 搜索
  void doSearch(String keyword) {
    state.keyword = keyword;
    //赋值之后刷新
    refreshController.callRefresh();
  }

  /// 清空筛选条件
  void resetFiltering() {
    state.keyword = "";
    state.searchController.text = "";
    state.selectedStartDate = null;
    state.selectedEndDate = null;
    state.selectedDepartmentId = null;
    //赋值之后刷新
    refreshController.callRefresh();
  }

  /// Item选中与未选中设置
  void doSelectedOrNot(THOALabourReviewTableRows data) {
    data.isSelected = !data.isSelected;
    Log.d("isSelected:${data.isSelected}");
    update();
  }

  /// 执行批量同意
  void _requestBatchApprove(String recordIds) async {
    // //执行请求
    var result = await _thRepository.batchActionLabourReviews(
      recordIds: recordIds,
      type: 'approve',
      cancelToken: cancelToken,
    );

    if (result.isSuccess) {
      NotifyEngine.showSuccess("Successful".tr);

      _removeItemsByList(recordIds);
    } else {
      ToastEngine.show(result.errorMsg ?? "Network Load Error".tr);
      return;
    }
  }

  /// 执行批量拒绝
  void _requestBatchReject(String recordIds, String? reason) async {
    // //执行请求
    var result = await _thRepository.batchActionLabourReviews(
      recordIds: recordIds,
      type: 'reject',
      auditMark: reason,
      cancelToken: cancelToken,
    );

    if (result.isSuccess) {
      NotifyEngine.showSuccess("Successful".tr);

      _removeItemsByList(recordIds);
    } else {
      ToastEngine.show(result.errorMsg ?? "Network Load Error".tr);
      return;
    }
  }

  /// 批准的操作
  void operationApprove() async {
    //找出已经选中的员工(只有状态为3 Approve的状态才能修改)
    var selectedList = state.datas.where((element) => element.isSelected).toList(growable: false);
    if (selectedList.isNotEmpty) {
      var ids = selectedList.map((e) => e.recordId.toString()).toList(growable: false);
      var recordIds = ids.join(',');

      // Are you sure 的弹窗
      DialogEngine.show(
        widget: AppDefaultDialog(
          title: "Message".tr,
          message: "Are you sure you want to setting approved?".tr,
          confirmAction: () {
            _requestBatchApprove(recordIds);
          },
        ),
      );
    } else {
      ToastEngine.show("Please select the record".tr);
    }
  }

  /// 拒绝的操作
  void operationReject() async {
    //找出已经选中的员工(只有状态为3 Approve的状态才能修改)
    var selectedList = state.datas.where((element) => element.isSelected).toList(growable: false);
    if (selectedList.isNotEmpty) {
      var ids = selectedList.map((e) => e.recordId.toString()).toList(growable: false);
      var recordIds = ids.join(',');

      // Are you sure 的弹窗
      DialogEngine.show(
        widget: LabourReviewRejectDialog(
          confirmAction: (reason) {
            //请求接口，提交评论
            _requestBatchReject(recordIds, reason);
          },
        ),
      );
    } else {
      ToastEngine.show("Please select the record".tr);
    }
  }

  /// 删除对应的recordId的Item数据
  void _removeItemsByList(String recordIds) {
    // 将逗号分隔的字符串转换为数组
    List<String> recordIdList = recordIds.split(',');

    // 移除列表中符合条件的项
    state.datas.removeWhere((e) => recordIdList.contains(e.recordId));

    update();
  }

  /// 展示顶部的筛选
  void showFilterDialog() {
    if (state.indexOptions != null) {
      DialogEngine.show(
        widget: LabourReviewFilter(
          optionResult: state.indexOptions!,
          selectedStartDate: state.selectedStartDate,
          selectedEndDate: state.selectedEndDate,
          selectedDepartmentId: state.selectedDepartmentId,
          onFilterAction: (startDate, endDate, departmentId) {
            state.selectedStartDate = startDate;
            state.selectedEndDate = endDate;
            state.selectedDepartmentId = departmentId;

            //赋值之后刷新
            refreshController.callRefresh();
          },
        ),
        position: DialogPosition.top,
        animType: DialogAnimation.fade,
      );
    }
  }

  /// 去详情页面
  void gotoDetailPage(THOALabourReviewTableRows data) {
    LabourRequestAddPage.startInstance(2, data.requestId.toString(), true, null);
  }

  /// 去编辑页面
  void gotoEditPage(THOALabourReviewTableRows data) {
    LabourRequestAddPage.startInstance(1, data.requestId.toString(), true, (result) {
      fetchItemByIdAndRefreshItem(data.requestId.toString());
    });
  }

  /// 去用工审核流程页面
  void gotoStatusViewPage(THOALabourReviewTableRows data) {
    LabourReviewWorkflowPage.startInstance(data.orderId);
  }

  /// 根据ID获取Item对象，用于刷新
  void fetchItemByIdAndRefreshItem(String? requestId) async {
    var result = await _thRepository.fetchItemByRecordId(
      requestId,
      cancelToken: cancelToken,
    );

    //处理数据
    if (result.isSuccess) {
      var data = result.data;
      if (data != null && data.rows.isNotEmpty) {
        List<THOALabourReviewTableRows> newItem = data.rows;

        // 创建一个 Map 来加速查找
        Map<String, THOALabourReviewTableRows> newItemMap = {for (var item in newItem) item.recordId ?? "": item};

        // 遍历 state.datas 进行替换
        for (int i = 0; i < state.datas.length; i++) {
          if (newItemMap.containsKey(state.datas[i].recordId)) {
            state.datas[i] = newItemMap[state.datas[i].recordId]!;
          }
        }

        //刷新
        update();
      }
    } else {
      ToastEngine.show(result.errorMsg ?? "Network Load Error".tr);
    }
  }

  /// 展示附件弹窗
  void showAttachmentDialog(THOALabourReviewTableRows data) {
    DialogEngine.show(
      widget: OaAttachListDialog(
        requestId: data.requestId.toString(),
        jobTitle: data.jobTitle ?? "-",
        jobDate: data.jobDate ?? "-",
      ),
    );
  }

  // 全部选择
  void operationSelectAll() {
    if (!isSelectAll) {
      for (var element in state.datas) {
        element.isSelected = true;
      }
      isSelectAll = true;
    } else {
      for (var element in state.datas) {
        element.isSelected = false;
      }
      isSelectAll = false;
    }
    update();
  }
}
