import 'package:domain/entity/response/job_applied_staff_s_g_entity.dart';
import 'package:domain/repository/job_sg_repository.dart';
import 'package:get/get.dart';
import 'package:plugin_basic/constants/app_constant.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:shared/utils/event_bus.dart';
import 'package:shared/utils/util.dart';
import 'package:widgets/load_state_layout.dart';
import 'package:widgets/widget_export.dart';

import 'applied_staff_state.dart';

class AppliedStaffController extends GetxController with DioCancelableMixin {
  final JobSGRepository _jobRepository = Get.find();
  final AppliedStaffState state = AppliedStaffState();

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

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

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

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

    // 获取 Applied 列表
    var listResult = await _jobRepository.searchJobAppliedStaff(
      state.jobId,
      state.keyword,
      curPage: _curPage,
      cancelToken: cancelToken,
    );

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

    // 最后赋值
    _needShowPlaceholder = false;
  }

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

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

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

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

  /// Item选中与未选中设置
  void doSelectedOrNot(JobAppliedStaffSGRows data) {
    //如果此人没有在工作中，可以选中与未选中
    if (data.applyState == 0){
      data.isSelected = !data.isSelected;
      update();
    }

  }

  /// 提交选中的成员
  void doSubmit() async {
    //筛选选中的员工
    final ids = state.datas.where((element) => element.isSelected).map((e) => e.id).toList();

    if (ids.isEmpty) {
      ToastEngine.show("Choose Staff".tr);
      return;
    }

    var result = await _jobRepository.addStaff2AppliedJob(state.jobId, ids.join(","), cancelToken: cancelToken);

    if (result.isSuccess) {
      NotifyEngine.showSuccess("Successful".tr);
      Get.back();
      bus.emit(AppConstant.eventAppliedListRefresh, "");
    } else {
      ToastEngine.show(result.errorMsg ?? "Network Load Error".tr);
      return;
    }
  }

}
