import 'package:domain/entity/response/labour_review_status_entity.dart';
import 'package:domain/repository/th_oa_repository.dart';
import 'package:get/get.dart';
import 'package:plugin_platform/http/dio/dio_cancelable_mixin.dart';
import 'package:widgets/load_state_layout.dart';
import 'package:widgets/widget_export.dart';

import 'labour_request_workflow_state.dart';


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

  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: false,
  );

  // Refresh 刷新事件
  Future onRefresh() async {
    fetchWorkFlowList();
  }

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

  /// 获取服务器数据，成员考勤列表
  Future fetchWorkFlowList() async {
    if (_needShowPlaceholder) {
      changeLoadingState(LoadState.State_Loading);
    }

    //获取到数据
    var result = await _thRepository.fetchLabourReviewStatusView(
      state.requestId,
      cancelToken: cancelToken,
    );

    //处理数据
    if (result.isSuccess) {
      handleList(result.data?.records);
      refreshController.finishRefresh(IndicatorResult.success);
    } else {
      errorMessage = result.errorMsg;
      changeLoadingState(LoadState.State_Error);
      refreshController.finishRefresh(IndicatorResult.fail);
    }

    //最后赋值
    _needShowPlaceholder = false;
  }

  // 处理数据与展示的逻辑
  void handleList(List<LabourReviewStatusRecords>? list) {
    if (list != null && list.isNotEmpty) {
      //有数据，判断是刷新还是加载更多的数据
      state.datas.clear();
      state.datas.addAll(list);
      //更新状态
      changeLoadingState(LoadState.State_Success);
    } else {
      //展示无数据的布局
      state.datas.clear();
      changeLoadingState(LoadState.State_Empty);
    }
  }

  @override
  void onReady() async {
    super.onReady();
    fetchWorkFlowList();
  }

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