import 'package:domain/entity/response/attendance_entity.dart';
import 'package:domain/entity/response/labour_request_index_entity.dart';
import 'package:domain/entity/response/u_k_report_attendance_entity.dart';
import 'package:domain/entity/response/u_k_security_attendance_option_entity.dart';
import 'package:domain/repository/uk_report_repository.dart';
import 'package:get/get.dart';
import 'package:plugin_platform/engine/dialog/dialog_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/log_utils.dart';

import 'package:widgets/load_state_layout.dart';
import 'package:widgets/widget_export.dart';
import 'widget/attendance_report_filter.dart';
import 'attendance_report_state.dart';

class AttendanceReportController extends GetxController with DioCancelableMixin {
  final UKReportRepository _reportRepository = Get.find();
  final AttendanceReportState state = AttendanceReportState();

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

    // 并发执行两个请求,拿到选项数据与列表数据
    var futures = [
      _reportRepository.fetchReportAttendanceList(
        keyword: state.staffName,
        startDate: DateTimeUtils.formatDate(state.selectedStartDate, format: "yyyy-MM-dd"),
        endDate: DateTimeUtils.formatDate(state.selectedEndDate, format: "yyyy-MM-dd"),
        departmentId: state.selectedDepartmentId,
        curPage: _curPage,
        cancelToken: cancelToken,
      ),
      state.indexOptions == null
          ? _reportRepository.fetchReportOptions(
        cancelToken: cancelToken,
      )
          : Future(() => HttpResult(isSuccess: true).convert(data: state.indexOptions!)),
    ];

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

    //选项数据
    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<UKReportAttendanceRows>? 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 showFilterDialog() {
    if (state.indexOptions != null) {
      DialogEngine.show(
        widget: AttendanceReportFilter(
          optionResult: state.indexOptions!,
          selectedStartDate: state.selectedStartDate,
          selectedEndDate: state.selectedEndDate,
          selectedDepartmentId: state.selectedDepartmentId,
          staffName: state.staffName,
          onFilterAction: (startDate, endDate, departmentId, staffName) {
            state.selectedStartDate = startDate;
            state.selectedEndDate = endDate;
            state.selectedDepartmentId = departmentId;
            state.staffName = staffName;

            Log.d("筛选的值为：startDate：$startDate endDate：$endDate departmentId：$departmentId title：$staffName");

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

}
