import 'package:domain/entity/response/t_h_o_a_labour_table_entity.dart';
import 'package:plugin_platform/engine/notify/notify_engine.dart';
import 'package:plugin_platform/engine/toast/toast_engine.dart';

import '../../job_er/job_list_er/widget/pre_selected_staff.dart';
import '../labour_request_add/labour_request_add_page.dart';
import 'package:domain/entity/response/labour_request_index_entity.dart';
import 'package:domain/repository/th_oa_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/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/widget_export.dart';

import '../labour_request_workflow/labour_request_workflow_page.dart';
import 'dialog/oa_attach_list_controller.dart';
import 'dialog/oa_attach_list_dialog.dart';
import 'labour_request_filter.dart';
import 'labour_request_list_state.dart';

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

  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 {
    state.totalNum = 0;
    _curPage = 1;
    fetchLabourRequestList();
  }

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

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

  /// 获取列表数据
  Future fetchLabourRequestList() async {
    if (_needShowPlaceholder) {
      changeLoadingState(LoadState.State_Loading);
    }

    // 并发执行两个请求
    var futures = [
      _thRepository.fetchLabourRequestTable(
        startDate: DateTimeUtils.formatDate(state.selectedStartDate, format: "yyyy-MM-dd"),
        endDate: DateTimeUtils.formatDate(state.selectedEndDate, format: "yyyy-MM-dd"),
        status: state.selectedStatusId,
        outletId: state.selectedDepartmentId,
        divisionId: state.selectedDivisionId,
        curPage: _curPage,
        cancelToken: cancelToken,
      ),
      state.indexOptions == null
          ? _thRepository.fetchLabourRequestIndex(
              cancelToken: cancelToken,
            )
          : Future(() => HttpResult(isSuccess: true).convert(data: state.indexOptions!)),
    ];

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

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

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

    // 最后赋值
    _needShowPlaceholder = false;
  }

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

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

  // 清空搜索条件
  void resetFiltering() {
    state.keyword = "";
    state.searchController.text = "";

    state.selectedStartDate = null;
    state.selectedEndDate = null;
    state.selectedStatusId = null;
    state.selectedDepartmentId = null;

    //赋值之后刷新
    refreshController.callRefresh();
  }

  //展示筛选的弹窗
  void showFilterDialog() {
    if (state.indexOptions != null) {
      DialogEngine.show(
        widget: LabourRequestFilter(
          optionResult: state.indexOptions!,
          selectedStartDate: state.selectedStartDate,
          selectedEndDate: state.selectedEndDate,
          selectedStatusId: state.selectedStatusId,
          selectedDepartmentId: state.selectedDepartmentId,
          selectedDivisionId: state.selectedDivisionId,
          onFilterAction: (startDate, endDate, statusId, departmentId, divisionId) {
            state.selectedStartDate = startDate;
            state.selectedEndDate = endDate;
            state.selectedStatusId = statusId;
            state.selectedDepartmentId = departmentId;
            state.selectedDivisionId = divisionId;

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

  /// 执行Recall请求
  void requestRecall(String requestId) async {
    var recallResult = await _thRepository.recallLabourRequest(
      requestId,
      cancelToken: cancelToken,
    );

    //处理数据
    if (recallResult.isSuccess) {
      NotifyEngine.showSuccess("Successful".tr);
      fetchItemByIdAndRefreshItem(requestId);
    } else {
      ToastEngine.show(recallResult.errorMsg ?? "Network Load Error".tr);
    }
  }

  //执行删除操作
  void doDeleteAction(String requestId, int index) {
    DialogEngine.show(
        widget: AppDefaultDialog(
      title: "Confirmation".tr,
      message: "Are you sure you want to delete this job?".tr,
      confirmAction: () {
        _requestDeactivate(requestId, index);
      },
    ));
  }

  // 请求接口删除Job
  void _requestDeactivate(String requestId, int index) async {
    var result = await _thRepository.deleteLabourRequest(requestId, cancelToken: cancelToken);

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

      if (state.datas.length <= 1) {
        refreshController.callRefresh();
      } else {
        state.datas.removeAt(index);
        update();
      }
    } else {
      ToastEngine.show(result.errorMsg ?? "Network Load Error".tr);
    }
  }

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

    //处理数据
    if (result.isSuccess) {
      var data = result.data;
      if (data != null && data.rows.isNotEmpty) {
        final requestItem = data.rows[0];

        //找到当前数据中的此 requestId，并替换对象，再刷新
        var index = state.datas.indexWhere((element) => element.id == requestItem.id);
        if (index >= 0) {
          state.datas[index] = requestItem;
          update();
        }
      }
    } else {
      ToastEngine.show(result.errorMsg ?? "Network Load Error".tr);
    }
  }

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

    registerEventBus();
  }

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

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

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

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

  //跳转到添加页面
  void gotoAddLabourPage() {
    LabourRequestAddPage.startInstance(0, "", false, (result) {
      refreshController.callRefresh();
    });
  }

  //去详情页面
  void gotoDetailPage(THOALabourTableRows data) {
    LabourRequestAddPage.startInstance(2, data.id.toString(), false, null);
  }

  //去编辑页面
  void gotoEditPage(THOALabourTableRows data) {
    LabourRequestAddPage.startInstance(1, data.id.toString(), false, (result) {
      fetchItemByIdAndRefreshItem(data.id.toString());
    });
  }

  //去状态工作流的页面
  void gotoWorkflowPage(THOALabourTableRows data) {
    LabourRequestWorkflowPage.startInstance(data.id.toString());
  }

  void doRecall(THOALabourTableRows data) {
    DialogEngine.show(
        widget: AppDefaultDialog(
      title: "Message".tr,
      message: "Are you sure you want to recall?".tr,
      confirmAction: () {
        requestRecall(data.id.toString());
      },
    ));
  }

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

  // 预选的弹窗
  void doPreSelectedAction(THOALabourTableRows data) {
    DialogEngine.show(
      widget: PreSelectedStaff(
        requestId: data.id,
        jobStatus: data.status??0,
      ),
    );
  }

}
