import 'package:cpt_th/modules/job_er/applied_er_edit/applied_er_edit_page.dart';
import 'package:domain/entity/response/t_h_applied_index_entity.dart';
import 'package:domain/entity/response/t_h_applied_table_entity.dart';
import 'package:domain/repository/th_er_repository.dart';
import 'package:get/get.dart';
import 'package:plugin_basic/constants/app_constant.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/event_bus.dart';
import 'package:shared/utils/util.dart';
import 'package:widgets/dialog/app_default_dialog.dart';
import 'package:widgets/load_state_layout.dart';
import 'package:widgets/picker/option_pick_util.dart';
import 'package:widgets/widget_export.dart';
import '../applied_er_staff_detail/applied_er_staff_detail_page.dart';
import '../applied_er_workflow/applied_er_workflow_page.dart';
import 'applied_er_state.dart';
import 'widget/er_applied_add_staff.dart';
import 'widget/er_applied_butch_modify.dart';
import 'widget/er_applied_staff_reviews.dart';

class AppliedErController extends GetxController with DioCancelableMixin {
  final THERRepository _erRepository = Get.find();
  final AppliedErState state = AppliedErState();

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

  //页面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 = [
      _erRepository.fetchERAppliedTable(
        jobId: state.jobId,
        curPage: _curPage,
        status: state.selectedStatusId,
        keyword: state.keyword,
        cancelToken: cancelToken,
      ),
      state.jobInfo == null
          ? _erRepository.fetchERAppliedOption(
              jobId: state.jobId,
              cancelToken: cancelToken,
            )
          : Future(() => HttpResult(isSuccess: true).convert(data: state.jobInfo!)),
    ];

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

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

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

    // 最后赋值
    _needShowPlaceholder = false;
  }

  // 处理数据与展示的逻辑
  void handleList(List<THAppliedTableRows>? 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();
    registerEventBus();
  }

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

  // EventBus 的事件接收
  Subscription? subscribe;

  void registerEventBus() {
    subscribe = bus.on(AppConstant.eventAppliedListRefresh, (arg) {
      var appliedId = arg as String;
      if (Utils.isNotEmpty(appliedId)) {
        fetchItemByIdAndRefreshItem(appliedId);
      } else {
        refreshController.callRefresh();
      }
    });
  }

  void unregisterEventBus() {
    bus.off(AppConstant.eventAppliedListRefresh, subscribe);
  }

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

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

  /// 展示添加员工的弹窗
  void showAddStaffDialog() {
    DialogEngine.show(
      widget: ErAppliedAddStaff(
        jobId: state.jobId!,
        confirmAction: (selectedIds) {
          //调用接口添加员工
          _requestAddStaff2Applied(selectedIds);
        },
      ),
    );
  }

  //调用接口添加员工
  void _requestAddStaff2Applied(String selectedIds) async {
    var result = await _erRepository.addStaff2Job(state.jobId, selectedIds, cancelToken: cancelToken);

    if (result.isSuccess) {
      var addStaffEntity = result.data;
      List<String> filteredMessages = [];
      if (addStaffEntity != null && addStaffEntity.resultList?.isNotEmpty == true) {
        filteredMessages = addStaffEntity.resultList!
            .where((resultList) => resultList.result == false && Utils.isNotEmpty(resultList.msg))
            .map((resultList) => '${resultList.name} : ${resultList.msg!}')
            .toList();
      }

      if (filteredMessages.isNotEmpty) {
        //有错误信息
        NotifyEngine.showFailure(filteredMessages.join(" , "));
      } else {
        //无错误信息
        NotifyEngine.showSuccess("Successful".tr);
        //添加成功之后刷新页面
        refreshController.callRefresh();
      }
    } else {
      ToastEngine.show(result.errorMsg ?? "Network Load Error".tr);
      return;
    }
  }

  /// 去编辑员工信息页面
  void gotoAppliedEditPage(THAppliedTableRows data) {
    AppliedErEditPage.startInstance(data.id.toString());
  }

  /// 展示评论的弹窗
  void showRemarkDialog(THAppliedTableRows data) async {
    // 请求接口获取到已评论的数据
    var result = await _erRepository.fetchAppliedStaffReviewView(data.id.toString());

    if (result.isSuccess) {
      //接口数据获取成功，展示弹窗
      DialogEngine.show(
        widget: ErAppliedStaffReviews(
          appliedReviews: result.data!,
          confirmAction: (attitudeRate, performanceRate, experienceRate, groomingRate, content) async {
            //请求接口，提交评论
            var submitResult = await _erRepository.remarkAppliedSingleStaffSubmit(
              data.id,
              attitudeRate,
              groomingRate,
              performanceRate,
              experienceRate,
              content,
            );

            if (submitResult.isSuccess) {
              NotifyEngine.showSuccess("Successful".tr);
            } else {
              ToastEngine.show(submitResult.errorMsg ?? "Network Load Error".tr);
            }
          },
        ),
      );
    } else {
      ToastEngine.show(result.errorMsg ?? "Network Load Error".tr);
      return;
    }
  }

  /// 去展示员工状态的审核流程页面
  void gotoAppliedWorkflowPage(THAppliedTableRows data) {
    AppliedErWorkflowPage.startInstance(data.id.toString());
  }

  /// 去查看员工详情页面
  void gotoStaffDetailPage(THAppliedTableRows data) {
    AppliedErStaffDetailPage.startInstance(data.memberId);
  }

  /// Item选中与未选中设置
  void doSelectedOrNot(THAppliedTableRows data) {
    //只有 Approve = 3 的状态才能选中
    // if (data.status == 3) {
    data.isSelected = !data.isSelected;
    update();
    // }
  }

  /// 批量修改的弹窗
  void showBatchModifyDialog() async {
    // if (state.jobInfo == null) return;
    //找出已经选中的员工(只有状态为3 Approve的状态才能修改)
    var selectedList = state.datas.where((element) => element.isSelected /*&& element.status == 3*/).toList(growable: false);
    if (selectedList.isNotEmpty) {
      var ids = selectedList.map((e) => e.id.toString()).toList(growable: false);
      var separatedIds = ids.join(',');

      DialogEngine.show(
          widget: ErAppliedButchModify(
              selectedStartDate: DateTimeUtils.getDateTimeByMs((state.jobInfo?.job?.startTime ?? 0) * 1000),
              selectedEndDate: DateTimeUtils.getDateTimeByMs((state.jobInfo?.job?.endTime ?? 0) * 1000),
              confirmAction: (start, end) {
                _requestBatchModify(start, end, separatedIds);
              }));
    } else {
      ToastEngine.show("Please select the applied record".tr);
    }
  }

  /// 执行批量修改的请求
  void _requestBatchModify(DateTime start, DateTime end, String separatedIds) async {
    //执行请求
    var result = await _erRepository.batchEditStaffCheckTime(
      separatedIds,
      DateTimeUtils.formatDate(start, format: 'HH:mm:ss'),
      DateTimeUtils.formatDate(end, format: 'HH:mm:ss'),
      cancelToken: cancelToken,
    );

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

      //调用接口刷新指定的Staff的信息
      fetchItemByIdAndRefreshItem(separatedIds);
    } else {
      ToastEngine.show(result.errorMsg ?? "Network Load Error".tr);
      return;
    }
  }

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

      // Are you sure 的弹窗
      DialogEngine.show(
        widget: AppDefaultDialog(
          title: "Message".tr,
          message: "Are you sure you want to setting approved?".tr,
          confirmAction: () async {
            //执行请求
            var result = await _erRepository.submitBatchStaffApprove(separatedIds, cancelToken: cancelToken);

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

              //调用接口刷新指定的Staff的信息
              fetchItemByIdAndRefreshItem(separatedIds);
            } else {
              ToastEngine.show(result.errorMsg ?? "Network Load Error".tr);
              return;
            }
          },
        ),
      );
    } else {
      ToastEngine.show("Please select the applied record".tr);
    }
  }

  /// 根据ID获取Item对象，用于刷新
  void fetchItemByIdAndRefreshItem(String appliedIds) async {
    var result = await _erRepository.fetchItemByAppliedIds(
      state.jobId,
      appliedIds,
      cancelToken: cancelToken,
    );

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

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

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

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

  //全部选中
  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();
  }

  /// 筛选状态
  void pickerStatus() {
    if (state.jobInfo == null) return;

    int selectedStatusIndex;
    if (state.selectedStatusId == null) {
      selectedStatusIndex = 0;
    } else {
      selectedStatusIndex = state.jobInfo!.statusList.indexWhere((department) => department.value.toString() == state.selectedStatusId);
    }

    if (selectedStatusIndex < 0) {
      selectedStatusIndex = 0;
    }

    OptionPickerUtil.showCupertinoOptionPicker(
      items: state.jobInfo!.statusList.map((e) => e.txt!).toList(growable: false),
      initialSelectIndex: selectedStatusIndex,
      onPickerChanged: (_, index) {
        state.selectedStatusId = state.jobInfo!.statusList[index].value!.toString();
        state.selectedStatusName = state.jobInfo!.statusList[index].txt!.toString();
        update();
        refreshController.callRefresh();
      },
    );
  }
}
