import 'package:domain/entity/response/job_title_edit_index_entity.dart';
import 'package:domain/entity/response/job_title_s_g_entity.dart';
import 'package:domain/repository/labour_sg_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:widgets/dialog/app_default_dialog.dart';
import 'package:widgets/load_state_layout.dart';
import 'package:widgets/widget_export.dart';

import '../job_template_list/job_template_list_page.dart';
import 'job_title_add_dialog.dart';
import 'job_title_list_state.dart';

class JobTitleListController extends GetxController with DioCancelableMixin {
  final LabourSGRepository _labourRepository = Get.find();
  final JobTitleListState state = JobTitleListState();

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

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

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

  /// 获取服务器数据，通知消息列表
  Future fetchNotifyList() async {
    if (_needShowPlaceholder) {
      changeLoadingState(LoadState.State_Loading);
    }

    var listResult = await _labourRepository.fetchJobTitleList(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<JobTitleSGRows>? 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);
      }
    }
  }

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

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

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

  @override
  void onReady() {
    super.onReady();
    fetchNotifyList();
  }

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

  // 请求数据并展示添加JobTitle的弹窗
  void requireAddNewDialog() async {
    if (state.jobAddIndexEntity == null) {
      //做了个新增的缓存
      var result = await _labourRepository.fetchJobTitleAddIndex(cancelToken: cancelToken);

      if (result.isSuccess) {
        state.jobAddIndexEntity = result.data;
        _showAddNewDialog(state.jobAddIndexEntity, false);
      } else {
        ToastEngine.show(result.errorMsg ?? "Network Load Error".tr);
      }
    } else {
      _showAddNewDialog(state.jobAddIndexEntity, false);
    }
  }

  // 请求详情数据，并展示弹窗去编辑
  void requireEditDialog(String titleId) async {
    var result = await _labourRepository.fetchJobTitleEditIndex(titleId, cancelToken: cancelToken);

    if (result.isSuccess) {
      _showAddNewDialog(result.data, true);
    } else {
      ToastEngine.show(result.errorMsg ?? "Network Load Error".tr);
    }
  }

  // 展示新增或者编辑的弹窗
  void _showAddNewDialog(JobTitleEditIndexEntity? entity, bool isEdit) {
    DialogEngine.show(
      widget: AddJobTitleDialog(
        editIndexEntity: entity,
        confirmAction: (jobTitleId, jobTitle, templateId, sort) {
          if (isEdit) {
            _requestEditJobTitle(jobTitleId, jobTitle, templateId, sort);
          } else {
            _requestAddJobTitle(jobTitle, templateId, sort);
          }
        },
      ),
    );
  }

  // 请求接口添加工作标题
  void _requestAddJobTitle(String jobTitle, String? templateId, String? sort) async {
    var result = await _labourRepository.addJobTitleSubmit(jobTitle, sort, templateId, cancelToken: cancelToken);

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

  // 请求接口编辑工作标题
  void _requestEditJobTitle(String jobTitleId, String jobTitle, String? templateId, String? sort) async {
    var result = await _labourRepository.editJobTitleSubmit(jobTitleId, jobTitle, sort, templateId, cancelToken: cancelToken);

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

  // 去模板列表页面
  void gotoTemplateListPage() {
    JobTemplateListPage.startInstance();
  }

  // 删除JobTitle的逻辑
  void deleteJobTitle(int index) {
    DialogEngine.show(
        widget: AppDefaultDialog(
      title: "Confirmation".tr,
      message: "Are you sure you want to delete this job title?".tr,
      confirmAction: () {
        _requestDeactivate(index);
      },
    ));
  }

  // 请求接口删除JobTitle
  void _requestDeactivate(int index) async {
    final item = state.datas[index];
    var result = await _labourRepository.deleteJobTitleSubmit(item.id.toString(), cancelToken: cancelToken);

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

      if (state.datas.length <= 1) {
        refreshController.callRefresh();
      } else {
        state.datas.removeAt(index);
        update();
      }
    } else {
      ToastEngine.show(result.errorMsg ?? "Network Load Error".tr);
    }
  }

  /// 根据ID获取Item对象，用于刷新
  void fetchItemByIdAndRefreshItem(String ids) async {
    var result = await _labourRepository.fetchJobTitleListByIds(
      ids,
      cancelToken: cancelToken,
    );

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

        // 创建一个 Map 来加速查找
        Map<int, JobTitleSGRows> newItemMap = {for (var item in newItem) item.id: item};

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

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

}
