import 'package:domain/entity/response/staff_detail_entity.dart';
import 'package:domain/entity/response/staff_labour_history_entity.dart';
import 'package:domain/repository/job_repository.dart';
import 'package:get/get.dart';
import 'package:plugin_platform/engine/loading/loading_engine.dart';
import 'package:plugin_platform/http/dio/dio_cancelable_mixin.dart';
import 'package:plugin_platform/http/http_result.dart';
import 'package:widgets/load_state_layout.dart';
import 'package:widgets/widget_export.dart';

import '../job_applied_staff_reviews/applied_staff_reviews_page.dart';
import 'applied_staff_detail_state.dart';

class AppliedStaffDetailController extends GetxController with DioCancelableMixin {
  final JobRepository _jobRepository = Get.find();
  final AppliedStaffDetailState state = AppliedStaffDetailState();

  var _curPage = 1;
  var _isSearch = false;
  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;
    fetchStaffDetail();
  }

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

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

  /// 获取列表数据
  Future fetchStaffDetail() async {
    if (_needShowPlaceholder) {
      changeLoadingState(LoadState.State_Loading);
    } else if (_isSearch) {
      LoadingEngine.show();
    }

    // 并发执行两个请求
    var futures = [
      _jobRepository.fetchStaffLabourHistory(
        state.memberId,
        state.keyword,
        curPage: _curPage,
        cancelToken: cancelToken,
      ),
      state.detail == null
          ? _jobRepository.fetchStaffDetail(state.memberId, cancelToken: cancelToken)
          : Future(() => HttpResult(isSuccess: true).convert(data: state.detail!)),
    ];

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

    //详情数据
    if (state.detail == null && detailResult.isSuccess) {
      state.detail = detailResult.data!;
    }

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

    _isSearch = false;
    LoadingEngine.dismiss();
    // 最后赋值
    _needShowPlaceholder = false;
  }

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

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

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

  // 去员工的评论列表页面
  void gotoRemarkHistoryPage() {
    UKAppliedStaffReviewsPage.startInstance(state.memberId,state.detail?.name,state.detail?.remRate,state.detail?.remNum.toString());
  }

}
