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:widgets/load_state_layout.dart';
import 'package:widgets/picker/date_picker_util.dart';
import 'package:widgets/widget_export.dart';

import '../widget/attendance_sign_in_out.dart';
import 'sign_in_sign_out_state.dart';

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

  var _needShowPlaceholder = true;

  //页面的列表数据
  List<AttendanceList> datas = [];
  String keyword = "";
  Rx<DateTime> startDate = DateTime.now().obs;
  Rx<DateTime> endDate = DateTime.now().obs;

  //页面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(
      keyword,
      DateTimeUtils.formatDate(startDate.value, format: "yyyy-MM-dd"),
      DateTimeUtils.formatDate(endDate.value, 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) {
      //有数据，判断是刷新还是加载更多的数据
      datas.clear();
      datas.addAll(list);
      //更新状态
      changeLoadingState(LoadState.State_Success);
    } else {
      //展示无数据的布局
      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) {
    this.keyword = keyword;
    refreshController.callRefresh();
  }

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

  @override
  void onClose() {
    super.onClose();
    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);
        },
      ),
    );
  }

  /// 重置筛选条件
  void resetFiltering() {
    keyword = "";
    state.searchController.text = "";
    startDate.value = DateTime.now();
    endDate.value = DateTime.now();
    update();

    refreshController.callRefresh();
  }

  /// 筛选开始日期
  void pickerStartDate() {
    DatePickerUtil.showCupertinoDatePicker(
      selectedDateTime: startDate.value,
      onDateTimeChanged: (date) {
        startDate.value = date;
        refreshController.callRefresh();
      },
      title: "Start Date".tr,
    );
  }
  /// 筛选结束日期
  void pickerEndDate() {
    DatePickerUtil.showCupertinoDatePicker(
      selectedDateTime: endDate.value,
      onDateTimeChanged: (date) {
        endDate.value = date;
        refreshController.callRefresh();
      },
      title: "End Date".tr,
    );
  }
}
