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

import '../template_add/template_add_page.dart';
import 'template_list_state.dart';

class TemplateListController extends GetxController with DioCancelableMixin {
  final UKJobRepository _labourRepository = Get.find();
  final TemplateListState state = TemplateListState();

  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.fetchJobTemplateList(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<UKTemplateRows>? 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();
  }

  //去添加模板的页面
  void gotoTemplateAddPage() {
    UKTemplateAddPage.startInstance("", (result) {
      if (result is String) {
        refreshController.callRefresh();
      }
    });
  }

  //去编辑的页面
  void gotoEditPage(String templateId) {
    UKTemplateAddPage.startInstance(templateId, (result) {
      if (result is String) {
        //编辑完成之后刷机吧
        refreshController.callRefresh();
      }
    });
  }

  //删除工作模板
  void deleteJobTitle(int index) {
    DialogEngine.show(
        widget: AppDefaultDialog(
      title: "Confirmation".tr,
      message: "Are you sure you want to delete this job template?".tr,
      confirmAction: () {
        _requestDeactivate(index);
      },
    ));
  }

  // 请求接口删除JobTitle
  void _requestDeactivate(int index) async {
    final item = state.datas[index];
    var result = await _labourRepository.deleteJobTemplate(templateId: item.id, 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);
    }
  }
}
