import 'dart:typed_data';

import 'package:domain/entity/response/attendance_entity.dart';
import 'package:domain/entity/response/u_k_security_attendance_entity.dart';
import 'package:domain/entity/response/u_k_security_attendance_option_entity.dart';
import 'package:domain/repository/job_repository.dart';
import 'package:domain/repository/uk_attendance_repository.dart';
import 'package:get/get.dart';
import 'package:plugin_platform/engine/dialog/dialog_engine.dart';
import 'package:plugin_platform/engine/notify/notify_engine.dart';
import 'package:plugin_platform/engine/toast/toast_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 '../security_registration/widget/job_list_filter.dart';
import '../../job/job_applied_staff_detail/applied_staff_detail_page.dart';
import 'security_registration_state.dart';
import 'widget/security_edit_dialog.dart';

class SecurityRegistrationController extends GetxController with DioCancelableMixin {
  final UKAttendanceRepository _attendanceRepository = Get.find();
  final EAttendanceListState state = EAttendanceListState();

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

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

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

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

    // 并发执行两个请求
    var futures = [
      _attendanceRepository.fetchSecurityAttendanceList(
        startDate: DateTimeUtils.formatDate(state.selectedStartDate, format: "yyyy-MM-dd"),
        endDate: DateTimeUtils.formatDate(state.selectedEndDate, format: "yyyy-MM-dd"),
        keyword: state.selectedStaffName,
        departmentId: state.selectedDepartmentId,
        curPage: _curPage,
        cancelToken: cancelToken,
      ),
      state.indexOptions == null
          ? _attendanceRepository.fetchSecurityAttendanceOptions(
              cancelToken: cancelToken,
            )
          : Future(() => HttpResult(isSuccess: true).convert(data: state.indexOptions!)),
    ];

    //拿到结果
    var results = await Future.wait(futures);
    var listResult = results[0] as HttpResult<UKSecurityAttendanceEntity>;
    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<UKSecurityAttendanceRows>? 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() async {
    super.onReady();
    fetchAttendanceList();
  }

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

  /// 展示标题栏的 Filter 弹窗
  void showFilterDialog() {
    if (state.indexOptions == null) return;

    DialogEngine.show(
      widget: JobListFilter(
        selectedStartDate: state.selectedStartDate,
        selectedEndDate: state.selectedEndDate,
        staffName: state.selectedStaffName,
        selectedDepartmentId: state.selectedDepartmentId,
        departmentList: state.indexOptions?.departmentList,
        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(UKSecurityAttendanceRows data) {
    // UKAppliedStaffDetailPage.startInstance(data.staffName.toString());
  }

  /// 展示编辑的弹窗
  void showEditDialog(UKSecurityAttendanceRows data) {
    String? dateStr = data.jobTime?.split(" ")[0];
    String? startStr = data.jobTime?.split(" ").sublist(1).join(" ").split(" ~ ")[0];
    String? endStr = data.jobTime?.split(" ").sublist(1).join(" ").split(" ~ ")[1];

    if (dateStr == null || startStr == null || endStr == null) return;

    DialogEngine.show(
      widget: SecurityEditDialog(
        startTime: DateTimeUtils.getDateTime("$dateStr $startStr"),
        endTime: DateTimeUtils.getDateTime("$dateStr $endStr"),
        securityInTime: DateTimeUtils.getDateTime(data.securityIn?.time == null ? "" : "$dateStr ${data.securityIn?.time}"),
        securityOutTime: DateTimeUtils.getDateTime(data.securityOut?.time == null ? "" : "$dateStr ${data.securityOut?.time}"),
        staffName: data.staffName ?? "",
        confirmAction: (inTime, outTime) {
          _submitAttendance(data.id, inTime, outTime);
        },
      ),
    );
  }

  /// 请求接口提交门卫签到数据
  void _submitAttendance(String? appliedId, DateTime? inTime, DateTime? outTime) async {
    final result = await _attendanceRepository.submitSecurityAttendanceEdit(
      appliedId: appliedId,
      formView: "security",
      securityIn: DateTimeUtils.formatDate(inTime),
      securityOut: DateTimeUtils.formatDate(outTime),
      cancelToken: cancelToken,
    );

    if (result.isSuccess) {
      NotifyEngine.showSuccess("Successful".tr);

      //把签到的时间赋值给列表
       _updateItems(appliedId,DateTimeUtils.formatDate(inTime),DateTimeUtils.formatDate(outTime));

    } else {
      ToastEngine.show(result.errorMsg ?? "Network Load Error".tr);
    }
  }

  // 遍历当前列表找到对应的Item更新签到签出的时间
  void _updateItems(String? appliedId, String inTime, String outTime) {
    UKSecurityAttendanceRows? element = state.datas.firstWhereOrNull(
          (element) => element.id == appliedId,
    );

    if (element != null) {
      element.securityIn ??= UKSecurityInOut();
      element.securityIn?.time = inTime;
      element.securityIn?.changed = 1;

      element.securityOut ??= UKSecurityInOut();
      element.securityOut?.time = outTime;
      element.securityOut?.changed = 1;

      update();
    }
  }

}
