import 'package:domain/entity/response/staff_request_report_entity.dart';
import 'package:domain/repository/other_repository.dart';
import 'package:get/get.dart';
import 'package:plugin_platform/http/dio/dio_cancelable_mixin.dart';
import 'package:shared/utils/date_time_utils.dart';
import 'package:widgets/load_state_layout.dart';
import 'package:widgets/picker/date_picker_util.dart';

import 'report_labour_state.dart';

class ReportLabourController extends GetxController with DioCancelableMixin {
  final OtherRepository _otherRepository = Get.find();
  final ReportLabourState state = ReportLabourState();

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

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

  //重试
  void retryRequest() {
    fetchReportData();
  }

  // 获取当前列表数据
  void fetchReportData() async {
    changeLoadingState(LoadState.State_Loading);

    var result = await _otherRepository.fetchReportLabour(
      DateTimeUtils.formatDate(state.startDateTime, format: "yyyy-MM-dd"),
      DateTimeUtils.formatDate(state.endDateTime, format: "yyyy-MM-dd"),
      cancelToken: cancelToken,
    );

    if (result.isSuccess) {
      state.entity = result.data;
      state.datas = result.data?.rows ?? [];
      if (state.datas.isNotEmpty) {
        changeLoadingState(LoadState.State_Success);
      } else {
        changeLoadingState(LoadState.State_Empty);
      }
    } else {
      errorMessage = result.errorMsg ?? "Network Load Error".tr;
      changeLoadingState(LoadState.State_Error);
    }
  }

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

  /// 筛选开始日期
  void pickerStartDate() {
    DatePickerUtil.showCupertinoDatePicker(
      selectedDateTime: state.startDateTime,
      onDateTimeChanged: (date) {
        state.startDateTime = date;
        update();
        fetchReportData();
      },
      title: "Start Date".tr,
    );
  }

  /// 筛选结束日期
  void pickerEndDate() {
    DatePickerUtil.showCupertinoDatePicker(
      selectedDateTime: state.endDateTime ?? state.startDateTime,
      onDateTimeChanged: (date) {
        state.endDateTime = date;
        update();
        fetchReportData();
      },
      title: "End Date".tr,
    );
  }
}
