import 'package:domain/entity/response/t_h_pre_selected_option_entity.dart';
import 'package:domain/entity/response/t_h_pre_selected_table_entity.dart';
import 'package:domain/repository/th_er_repository.dart';
import 'package:plugin_basic/basic_export.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/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 'pre_add_staff.dart';

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

  String? jobId;
  String? requestId;
  var _curPage = 1;
  var _needShowPlaceholder = true;

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

  List<THPreSelectedTableRows> datas = [];
  THPreSelectedOptionEntity? indexOptions;

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

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

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

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

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

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

    // 并发执行两个请求
    var futures = [
      _erRepository.fetchPreSelectedTable(
        jobId: jobId,
        requestId: requestId,
        curPage: _curPage,
        cancelToken: cancelToken,
      ),
      indexOptions == null
          ? _erRepository.fetchPreSelectedOption(
              jobId: jobId,
              requestId: requestId,
              cancelToken: cancelToken,
            )
          : Future(() => HttpResult(isSuccess: true).convert(data: indexOptions!)),
    ];

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

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

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

    // 最后赋值
    _needShowPlaceholder = false;
  }

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

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

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

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

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

  //从预选列表中删除指定的员工
  void doDeleteAction(THPreSelectedTableRows item) {
    DialogEngine.show(
        widget: AppDefaultDialog(
      title: "Confirmation".tr,
      message: "Are you sure you want to remove this employee from the pre-selected list?".tr,
      confirmAction: () {
        _requestDeleteStaff(item.id);
      },
    ));
  }

  //网络请求-删除员工
  void _requestDeleteStaff(String? staffId) async {
    var result = await _erRepository.deleteStaffFormPreSelected(selectedId: staffId, cancelToken: cancelToken);

    //处理数据
    if (result.isSuccess) {
      datas.removeWhere((element) => element.id == staffId);
      update();

      //刷新指定JobId 的 JobList 列表
      bus.emit(AppConstant.eventLabourRequestRefresh, jobId);
    } else {
      ToastEngine.show(result.errorMsg ?? "Network Load Error".tr);
    }
  }

  //网络请求-添加员工
  void _requestAddStaff2Pre(String selectedIds) async {
    var result = await _erRepository.submitStaff2PreSelected(jobId: jobId, requestId: requestId, staffIds: selectedIds, cancelToken: cancelToken);

    //处理数据
    if (result.isSuccess) {
      refreshController.callRefresh();

      //刷新指定JobId 的 JobList 列表
      bus.emit(AppConstant.eventLabourRequestRefresh, jobId);
    } else {
      ToastEngine.show(result.errorMsg ?? "Network Load Error".tr);
    }
  }
}
