import 'package:cpt_sg/modules/job/job_applied/job_applied_page.dart';
import 'package:domain/entity/response/job_list_index_s_g_entity.dart';
import 'package:domain/entity/response/job_list_s_g_entity.dart';
import 'package:domain/repository/labour_sg_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:router/componentRouter/component_router_service.dart';
import 'package:shared/utils/date_time_utils.dart';
import 'package:widgets/dialog/app_default_dialog.dart';
import 'package:widgets/load_state_layout.dart';
import 'package:widgets/widget_export.dart';

import '../job_list_edit/job_list_edit_page.dart';
import '../../labour/labour_request_add/labour_request_add_page.dart';
import 'job_list_filter.dart';
import 'job_list_state.dart';

class JobListController extends GetxController with DioCancelableMixin {
  final LabourSGRepository _jobRepository = Get.find();
  final JobListState state = JobListState();

  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;
    fetchNotifyList();
  }

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

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

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

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

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

    //选项数据
    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<JobListSGRows>? 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 resetFiltering() {
    state.selectedStartDate = null;
    state.selectedEndDate = null;
    state.selectedStatusId = null;
    state.selectedOutletId = null;

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

  //展示筛选的弹窗
  void showFilterDialog() {
    if (state.indexOptions != null) {
      DialogEngine.show(
        widget: JobListFilter(
          optionResult: state.indexOptions!,
          selectedStartDate: state.selectedStartDate,
          selectedEndDate: state.selectedEndDate,
          selectedStatusId: state.selectedStatusId,
          selectedOutletId: state.selectedOutletId,
          selectedAgencyId: state.selectedAgencyId,
          onFilterAction: (startDate, endDate, statusId, outletId,agencyId) {
            state.selectedStartDate = startDate;
            state.selectedEndDate = endDate;
            state.selectedStatusId = statusId;
            state.selectedOutletId = outletId;
            state.selectedAgencyId = agencyId;

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

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

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

  /// 去详情页面
  void gotoJobDetailPage(int index) {
    JobListEditPage.startInstance(false, state.datas[index].jobId, null);
  }

  // 执行编辑操作
  void doEditAction(int index) {
    JobListEditPage.startInstance(true, state.datas[index].jobId, (result) {
      fetchItemByIdAndRefreshItem(state.datas[index].jobId ?? "");
    });
  }

  /// 去已申请的成员列表
  void gotoJobAppliedPage(int index) {
    JobAppliedPage.startInstance(state.datas[index].jobId, (result) {
      if (result is String?) {
        //添加成功之后刷新
        fetchItemByIdAndRefreshItem(result ?? "");
      }
    });
  }

  //执行取消操作
  void doCancelAction(int index) {
    DialogEngine.show(
        widget: AppDefaultDialog(
      title: "Confirmation".tr,
      message: "Are you sure you want to cancel this job?".tr,
      confirmAction: () {
        _requestCancel(index);
      },
    ));
  }

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

  // 请求接口删除Job
  void _requestDeactivate(int index) async {
    final item = state.datas[index];
    var result = await _jobRepository.deleteJobList(item.jobId, 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);
    }
  }

  void _requestCancel(int index) async {
    final item = state.datas[index];
    var result = await _jobRepository.cancelJobList(item.jobId, cancelToken: cancelToken);

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

      fetchItemByIdAndRefreshItem(item.jobId ?? "");
    } else {
      ToastEngine.show(result.errorMsg ?? "Network Load Error".tr);
    }
  }

  //添加新的工作
  void gotoLabourRequestAddPage() {
    LabourRequestAddPage.startInstance((result) {
      if (result is bool) {
        //添加成功之后刷新
        refreshController.callRefresh();
      }
    });
  }

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

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

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

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

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