import 'package:domain/entity/response/attendance_review_entity.dart';
import 'package:domain/repository/job_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:shared/utils/log_utils.dart';
import 'package:widgets/dialog/app_default_dialog.dart';
import 'package:widgets/load_state_layout.dart';
import 'package:widgets/widget_export.dart';

import 'attendance_review_reject_dialog.dart';
import 'attendance_review_state.dart';

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

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

    // 并发执行两个请求
    final listResult = await _jobRepository.fetchAttendanceReviewList(
      state.keyword,
      curPage: _curPage,
      cancelToken: cancelToken,
    );

    // 处理数据
    if (listResult.isSuccess) {
      handleList(listResult.data?.rows);
    } else {
      errorMessage = listResult.errorMsg;
      changeLoadingState(LoadState.State_Error);
    }

    // 最后赋值
    _needShowPlaceholder = false;
  }

  // 处理数据与展示的逻辑
  void handleList(List<AttendanceReviewRows>? 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 doSearch(String keyword) {
    state.keyword = keyword;
    //赋值之后刷新
    refreshController.callRefresh();
  }

  /// 清空筛选条件
  void resetFiltering() {
    state.keyword = "";
    state.searchController.text = "";

    //赋值之后刷新
    refreshController.callRefresh();
  }

  /// Item选中与未选中设置
  void doSelectedOrNot(AttendanceReviewRows data) {
    data.isSelected = !data.isSelected;
    Log.d("isSelected:${data.isSelected}");
    update();
  }

  /// 执行批量同意
  void _requestBatchApprove(String recordIds) async {
    //执行请求
    var result = await _jobRepository.approveAttendanceReviews(
      recordIds,
      cancelToken: cancelToken,
    );

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

      //调用接口刷新指定的Staff的信息
      _removeItemsByList(recordIds);
    } else {
      ToastEngine.show(result.errorMsg ?? "Network Load Error".tr);
      return;
    }
  }

  /// 执行批量拒绝
  void _requestBatchReject(String recordIds, String? reason) async {
    //执行请求
    var result = await _jobRepository.rejectLabourReviews(
      recordIds,
      reason,
      cancelToken: cancelToken,
    );

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

      //调用接口刷新指定的Staff的信息
      _removeItemsByList(recordIds);
    } else {
      ToastEngine.show(result.errorMsg ?? "Network Load Error".tr);
      return;
    }
  }

  /// 批准的操作
  void operationApprove() async {
    //找出已经选中的员工(只有状态为3 Approve的状态才能修改)
    var selectedList = state.datas.where((element) => element.isSelected).toList(growable: false);
    if (selectedList.isNotEmpty) {
      var ids = selectedList.map((e) => e.recordId.toString()).toList(growable: false);
      var recordIds = ids.join(',');

      // Are you sure 的弹窗
      DialogEngine.show(
        widget: AppDefaultDialog(
          title: "Message".tr,
          message: "Are you sure you want to setting approved?".tr,
          confirmAction: () {
            _requestBatchApprove(recordIds);
          },
        ),
      );
    } else {
      ToastEngine.show("Please select the record".tr);
    }
  }

  /// 拒绝的操作
  void operationReject() async {
    //找出已经选中的员工(只有状态为3 Approve的状态才能修改)
    var selectedList = state.datas.where((element) => element.isSelected).toList(growable: false);
    if (selectedList.isNotEmpty) {
      var ids = selectedList.map((e) => e.recordId.toString()).toList(growable: false);
      var recordIds = ids.join(',');

      // Are you sure 的弹窗
      DialogEngine.show(
        widget: AttendaceReviewRejectDialog(
          confirmAction: (reason) {
            //请求接口，提交评论
            _requestBatchReject(recordIds, reason);
          },
        ),
      );
    } else {
      ToastEngine.show("Please select the record".tr);
    }
  }

  /// 删除对应的recordId的Item数据
  void _removeItemsByList(String recordIds) {
    // 将逗号分隔的字符串转换为数组
    List<String> recordIdList = recordIds.split(',');

    // 移除列表中符合条件的项
    state.datas.removeWhere((e) => recordIdList.contains(e.recordId));

    update();
  }

  /// 去用工审核流程页面
  void gotoStatusViewPage(AttendanceReviewRows data) {}
}
