import 'package:cpt_th/modules/job_er/applied_er/applied_er_page.dart';
import 'package:cpt_th/modules/labour_er/labour_request_er_add/labour_request_er_add_page.dart';
import 'package:domain/entity/response/job_list_e_r_option_entity.dart';
import 'package:domain/entity/response/labour_list_e_r_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/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:widgets/dialog/app_default_dialog.dart';
import 'package:widgets/load_state_layout.dart';
import 'package:widgets/widget_export.dart';

import 'job_list_er_filter.dart';
import 'job_list_er_state.dart';
import 'widget/pre_selected_staff.dart';

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

  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 = [
      _erRepository.fetchERJobListTable(
        keyword: state.keyword,
        startDate: DateTimeUtils.formatDate(state.selectedStartDate, format: "yyyy-MM-dd"),
        endDate: DateTimeUtils.formatDate(state.selectedEndDate, format: "yyyy-MM-dd"),
        status: state.selectedStatusId,
        outletId: state.selectedOutletId,
        trending: state.selectedTrending,
        curPage: _curPage,
        cancelToken: cancelToken,
      ),
      state.indexOptions == null
          ? _erRepository.fetchERJobListOption(
              date: DateTimeUtils.formatDate(state.selectedStartDate, format: "yyyy-MM-dd"),
              cancelToken: cancelToken,
            )
          : Future(() => HttpResult(isSuccess: true).convert(data: state.indexOptions!)),
    ];

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

    //选项数据
    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<LabourListERRows>? 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.selectedOutletId = null;

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

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

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

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

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

  /// 去编辑页面
  void gotoJobEditPage(LabourListERRows data) {
    LabourRequestERAddPage.startInstance(1, data.jobId, (result) {
      refreshController.callRefresh();
    });
  }

  /// 去已申请的成员列表
  void gotoJobAppliedPage(LabourListERRows data) {
    AppliedErPage.startInstance(data.jobId);
  }

  /// 删除当前的工作
  void doDeleteAction(LabourListERRows data) {
    DialogEngine.show(
        widget: AppDefaultDialog(
      title: "Confirmation".tr,
      message: "Are you sure you want to delete this job?".tr,
      confirmAction: () {
        _requestDelete(data);
      },
    ));
  }

  /// 请求接口确认删除
  void _requestDelete(LabourListERRows data) async {
    //请求接口
    var result = await _erRepository.deleteJobListERSubmit(jobId: data.jobId!, type: 'delete', cancelToken: cancelToken);

    //处理数据
    if (result.isSuccess) {
      //清除数据，去首页
      state.datas.removeWhere((element) => element.jobId == data.jobId);
      update();
      //发送通知Labour Request 列表刷新
      bus.emit(AppConstant.eventLabourRequestRefresh, data.jobId);
    } else {
      ToastEngine.show(result.errorMsg ?? "Network Load Error".tr);
    }
  }

  /// 预选员工
  void doPreSelectedAction(LabourListERRows data) {
    DialogEngine.show(
      widget: PreSelectedStaff(
        jobId: data.jobId,
        jobStatus: data.status,
      ),
    );
  }
}
