import 'package:domain/entity/response/job_applied_edit_index_s_g_entity.dart';
import 'package:domain/entity/response/job_applied_list_s_g_entity.dart';
import 'package:domain/repository/job_sg_repository.dart';
import 'package:domain/repository/labour_sg_repository.dart';
import 'package:flutter/material.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:get/get.dart';
import 'package:plugin_basic/constants/app_constant.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/date_time_utils.dart';
import 'package:shared/utils/event_bus.dart';
import 'package:shared/utils/log_utils.dart';
import 'package:shared/utils/util.dart';
import 'package:widgets/dialog/app_default_dialog.dart';
import 'package:widgets/load_state_layout.dart';
import 'package:widgets/picker/option_pick_util.dart';
import 'package:widgets/widget_export.dart';

import '../applied_staff/applied_staff_page.dart';
import '../applied_staff_detail/applied_staff_detail_page.dart';
import '../revise_applied/revise_applied_page.dart';
import 'applied_staff_reviews.dart';
import 'dialog_applied_butch_modify.dart';
import 'dialog_applied_modify.dart';
import 'drop_down_status.dart';
import 'job_applied_state.dart';

class JobAppliedController extends GetxController with DioCancelableMixin {
  final JobSGRepository _jobRepository = Get.find();
  final LabourSGRepository _labourRepository = Get.find();
  final JobAppliedState state = JobAppliedState();

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

    if (state.appliedIndexEntity == null) {
      //不是并发的，顺序执行接口
      var jobInfoResult = await _jobRepository.fetchJobAppliedIndex(
        state.jobId,
        cancelToken: cancelToken,
      );

      if (jobInfoResult.isSuccess) {
        state.appliedIndexEntity = jobInfoResult.data;
        update();
      } else {
        errorMessage = jobInfoResult.errorMsg;
        changeLoadingState(LoadState.State_Error);
        return;
      }
    }

    // 获取 Applied 列表
    var listResult = await _jobRepository.fetchJobAppliedList(
      state.jobId,
      state.selectedStatusId,
      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<JobAppliedListSGRows>? 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();
    registerEventBus();
  }

  @override
  void onClose() {
    unregisterEventBus();
    state.cb?.call(state.jobId);
    state.datas.clear();
    super.onClose();
  }

  // EventBus 的事件接收
  Subscription? subscribe;

  void registerEventBus() {
    subscribe = bus.on(AppConstant.eventAppliedListRefresh, (arg) {
      var appliedId = arg as String;
      if (Utils.isNotEmpty(appliedId)) {
        fetchItemByIdAndRefreshItem(appliedId);
      } else {
        refreshController.callRefresh();
      }
    });
  }

  void unregisterEventBus() {
    bus.off(AppConstant.eventAppliedListRefresh, subscribe);
  }

  /// 搜索员工
  void doSearch(String keyword) {
    state.keyword = keyword;
    //赋值之后刷新
    refreshController.callRefresh();
  }

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

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

  /// 展示添加员工的弹窗
  void gotoAddStaffPage() {
    AppliedStaffPage.startInstance(state.jobId);
  }

  /// 展示编辑员工信息的弹窗
  void showAppliedEditDialog(JobAppliedListSGRows data) async {
    var result = await _jobRepository.fetchEditJobAppliedIndex(data.appliedId.toString());

    if (result.isSuccess) {
      //接口数据获取成功，展示弹窗
      DialogEngine.show(
        widget: DialogAppliedModify(
          editIndexOption: result.data!,
          confirmAction: (entity) {
            if (entity != null) {
              _requestSubmitEditApplied(entity);
            }
          },
        ),
      );
    } else {
      ToastEngine.show(result.errorMsg ?? "Network Load Error".tr);
      return;
    }
  }

  // 提交编辑的接口
  void _requestSubmitEditApplied(JobAppliedEditIndexSGEntity entity) async {
    Log.d("选中的数据为：${entity.toString()}");

    var result = await _jobRepository.submitEditJobApplied(
      entity.appliedId,
      entity.startTime,
      entity.endTime,
      entity.securityIn,
      entity.securityOut,
      entity.workIn,
      entity.workOut,
      entity.adjustHours,
      entity.status == 0 ? "" : entity.status.toString(),
      cancelToken: cancelToken,
    );

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

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

  /// 展示评论的弹窗
  void showRemarkDialog(JobAppliedListSGRows data) async {
    //请求接口获取到已评论的数据
    var result = await _jobRepository.fetchJobAppliedRemarkView(data.appliedId.toString());

    if (result.isSuccess) {
      //接口数据获取成功，展示弹窗
      DialogEngine.show(
        widget: AppliedStaffReviews(
          appliedReviews: result.data!,
          confirmAction: (attitudeRate, performanceRate, experienceRate, groomingRate, content) async {
            //请求接口，提交评论
            var submitResult = await _jobRepository.submitAppliedRemark(
              data.appliedId.toString(),
              attitudeRate,
              groomingRate,
              performanceRate,
              experienceRate,
              content,
            );

            if (submitResult.isSuccess) {
              NotifyEngine.showSuccess("Successful".tr);
            } else {
              ToastEngine.show(submitResult.errorMsg ?? "Network Load Error".tr);
            }
          },
        ),
      );
    } else {
      ToastEngine.show(result.errorMsg ?? "Network Load Error".tr);
      return;
    }
  }

  /// 去 Revise Applied 的页面
  void gotoReviseAppliedPage(JobAppliedListSGRows item) {
    ReviseAppliedPage.startInstance(item.appliedId, state.appliedIndexEntity?.jobTitle, state.appliedIndexEntity?.jobDate);
  }

  /// 去查看员工详情页面
  void gotoStaffDetailPage(JobAppliedListSGRows data) {
    AppliedStaffDetailPage.startInstance(data.memberId);
  }

  /// Item选中与未选中设置
  void doSelectedOrNot(JobAppliedListSGRows data) {
    data.isSelected = !data.isSelected;
    update();
  }

  /// 批量修改的弹窗
  void showBatchModifyDialog() async {
    if (state.appliedIndexEntity == null) return;
    //找出已经选中的员工
    var selectedList = state.datas.where((element) => element.isSelected).toList(growable: false);
    if (selectedList.isNotEmpty) {
      var ids = selectedList.map((e) => e.appliedId.toString()).toList(growable: false);
      var separatedIds = ids.join(',');

      DialogEngine.show(
          widget: DialogAppliedButchModify(
              selectedStartDate: null,
              selectedEndDate: null,
              confirmAction: (start, end, hour, status) {
                _requestBatchModify(start, end, hour, status, separatedIds);
              }));
    } else {
      ToastEngine.show("Please select the applied record".tr);
    }
  }

  /// 执行批量修改的请求
  void _requestBatchModify(DateTime? start, DateTime? end, String? hour, String? status, String separatedIds) async {
    //执行请求
    var result = await _jobRepository.batchEditJobApplied(
      state.jobId,
      separatedIds,
      start == null ? "" : DateTimeUtils.formatDate(start, format: "HH:mm:ss"),
      end == null ? "" : DateTimeUtils.formatDate(end, format: "HH:mm:ss"),
      hour,
      status,
      cancelToken: cancelToken,
    );

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

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

  /// 根据ID获取Item对象，用于刷新
  void fetchItemByIdAndRefreshItem(String? appliedIds) async {
    var result = await _jobRepository.fetchItemByAppliedIds(
      state.jobId,
      appliedIds,
      cancelToken: cancelToken,
    );

    //处理数据
    if (result.isSuccess) {
      var data = result.data;
      if (data != null && data.rows.isNotEmpty) {
        List<JobAppliedListSGRows> newItem = data.rows;

        // 创建一个 Map 来加速查找
        Map<String, JobAppliedListSGRows> newItemMap = {for (var item in newItem) item.appliedId ?? "": item};

        // 遍历 state.datas 进行替换
        for (int i = 0; i < state.datas.length; i++) {
          if (newItemMap.containsKey(state.datas[i].appliedId)) {
            state.datas[i] = newItemMap[state.datas[i].appliedId]!;
          }
        }

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

  /// 请求接口发送电子考勤，确定考勤
  void confirmJob() {
    //如果当前没有员工则无需发送考勤
    if (state.datas.isEmpty) {
      ToastEngine.show('There are no staff for this job, E-Attendance cannot be sent');
      return;
    }

    //找出已经选中的员工
    var selectedList = state.datas.where((element) => element.isSelected).toList(growable: false);
    if (selectedList.isNotEmpty) {

      var ids = selectedList.map((e) => e.appliedId.toString()).toList(growable: false);
      var separatedIds = ids.join(',');

      //调用接口-发送到 Attendance Review 列表
      _requestSendEAttendance(separatedIds);

    } else {
      ToastEngine.show("Please select the applied record".tr);
    }
  }

  //发送接口
  void _requestSendEAttendance(String appliedIds) async {
    var result = await _labourRepository.approveAppliedJob(
      appliedIds,
      cancelToken: cancelToken,
    );

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

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

  // 顶部的筛选状态
  void pickStatus() {
    if (state.appliedIndexEntity == null) {
      return;
    }

    int selectedTemplateIndex;
    if (state.selectedStatusId == null) {
      selectedTemplateIndex = 0;
    } else {
      selectedTemplateIndex = state.appliedIndexEntity!.statusList.indexWhere((department) => department.value.toString() == state.selectedStatusId);
    }

    if (selectedTemplateIndex < 0) {
      selectedTemplateIndex = 0;
    }

    OptionPickerUtil.showCupertinoOptionPicker(
      items: state.appliedIndexEntity!.statusList.map((e) => e.txt!).toList(growable: false),
      initialSelectIndex: selectedTemplateIndex,
      onPickerChanged: (_, index) {
        state.selectedStatusId = state.appliedIndexEntity!.statusList[index].value!.toString();
        state.selectedStatusTxt = state.appliedIndexEntity!.statusList[index].txt!.toString();
        update();

        refreshController.callRefresh();
      },
    );
  }

  // 下拉选选择修改状态
  void dropDownStatus(int index, BuildContext context) {
    final statusOptions = state.datas[index].statusList;
    if (statusOptions.isEmpty) return;

    DialogEngine.showAttach(
      targetContext: context,
      position: DialogPosition.bottom,
      widget: DropDownStatus(
        list: statusOptions,
        onSelectedAction: (item) {
          _changeMemberStatus(state.datas[index].appliedId, item.value, index);
        },
      ),
    );
  }

  // 请求接口修改用户的状态
  void _changeMemberStatus(String? appliedId, String? statusId, int index) async {
    //执行请求
    var result = await _jobRepository.submitEditAppliedStatus(
      appliedId,
      statusId,
      cancelToken: cancelToken,
    );

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

      if ("4" == statusId) {
        //如果是拒绝了，移除这个Item
        if (state.datas.length > 1) {
          state.datas.removeAt(index);
          update();
        } else {
          refreshController.callRefresh();
        }
      } else {
        //其他状态刷新当前Item，调用接口刷新指定的Staff的信息
        fetchItemByIdAndRefreshItem(appliedId);
      }
    } else {
      ToastEngine.show(result.errorMsg ?? "Network Load Error".tr);
      return;
    }
  }
}
