import 'dart:typed_data';

import 'package:domain/entity/response/attendance_entity.dart';
import 'package:domain/entity/response/check_success_entity.dart';
import 'package:domain/repository/job_repository.dart';
import 'package:get/get.dart';
import 'package:plugin_basic/service/user_service.dart';
import 'package:plugin_platform/engine/dialog/dialog_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/date_time_utils.dart';
import 'package:shared/utils/log_utils.dart';
import 'package:widgets/load_state_layout.dart';
import 'package:widgets/picker/date_picker_util.dart';
import 'package:widgets/widget_export.dart';

import '../../job/job_applied_staff_detail/applied_staff_detail_page.dart';
import 'e_attendance_list_state.dart';
import 'widget/attendance_sign_in_out.dart';
import 'widget/job_list_filter.dart';

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

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

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

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

    //获取到数据
    var result = await _jobRepository.fetchAttendanceList(
      state.keyword,
      DateTimeUtils.formatDate(state.selectedStartDate, format: "yyyy-MM-dd"),
      DateTimeUtils.formatDate(state.selectedEndDate, format: "yyyy-MM-dd"),
      cancelToken: cancelToken,
    );

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

    //最后赋值
    _needShowPlaceholder = false;
  }

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

  /// 签到签出
  void requestCheckInCheckOut(bool isCheckIn, AttendanceList item, ByteData byteData) async {
    //请求接口

    var result = await _jobRepository.submitCheckInOut(
      item.appliedId.toString(),
      byteData,
      isCheckIn: isCheckIn,
      cancelToken: cancelToken,
    );

    if (result.isSuccess) {
      CheckSuccessEntity entity = result.data!;
      if (isCheckIn) {
        item.checkInImg = entity.checkImg;
        item.checkInTime = entity.checkTime;
      } else {
        item.checkOutImg = entity.checkImg;
        item.checkOutTime = entity.checkTime;
      }
      //更新状态
      update();
    } else {
      errorMessage = result.errorMsg;
      ToastEngine.show(errorMessage ?? "Network Load Error".tr);
    }
  }

  //执行搜索
  void doSearch(String keyword) {
    state.keyword = keyword;
    refreshController.callRefresh();
  }

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

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

  /// 用户签到
  void userSignIn(AttendanceList item) {
    DialogEngine.show(
      widget: AttendanceSignInOut(
        confirmAction: (byteData) {
          requestCheckInCheckOut(true, item, byteData);
        },
      ),
    );
  }

  /// 用户签出
  void userSignOut(AttendanceList item) {
    DialogEngine.show(
      widget: AttendanceSignInOut(
        confirmAction: (byteData) {
          requestCheckInCheckOut(false, item, byteData);
        },
      ),
    );
  }


  /// 展示标题栏的 Filter 弹窗
  void showFilterDialog() {
    DialogEngine.show(
      widget: JobListFilter(
        selectedStartDate: state.selectedStartDate,
        selectedEndDate: state.selectedEndDate,
        staffName: state.selectedStaffName,
        selectedDepartmentId: state.selectedDepartmentId,
        onFilterAction: (startDate, endDate, staffName, departmentId) {
          Log.d("startDate:$startDate endDate:$endDate staffName:$staffName departmentId:$departmentId");

          state.selectedStartDate = startDate;
          state.selectedEndDate = endDate;
          state.selectedStaffName = staffName;
          state.selectedDepartmentId = departmentId;

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

  //查看UK员工的详情
  void gotoStaffDetailPage(AttendanceList data) {
    UKAppliedStaffDetailPage.startInstance(data.staffId.toString());
  }

}
