import 'package:cpt_auth/modules/setting/setting_page.dart';
import 'package:domain/entity/home_module.dart';
import 'package:domain/entity/response/hotel_info_entity.dart';
import 'package:domain/repository/auth_repository.dart';
import 'package:get/get.dart';
import 'package:plugin_basic/constants/app_constant.dart';
import 'package:plugin_basic/service/user_service.dart';
import 'package:plugin_platform/engine/sp/sp_util.dart';
import 'package:plugin_platform/engine/toast/toast_engine.dart';
import 'package:router/componentRouter/component_router_service.dart';
import 'package:widgets/load_state_layout.dart';
import 'package:widgets/widget_export.dart';

import 'main_state.dart';

class MainController extends GetxController {
  final AuthRepository _authRepository = Get.find();
  final MainState state = MainState();

  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: false,
  );

  // Refresh 刷新事件
  Future onRefresh() async {
    fetchHomeData();
  }

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

  /// 获取首页的数据
  void fetchHomeData() async {
    if (_needShowPlaceholder) {
      changeLoadingState(LoadState.State_Loading);
    }

    //获取到数据
    var result = await _authRepository.fetchHotelInfo();

    //处理数据
    if (result.isSuccess) {
      final hotelInfo = result.data;

      if (hotelInfo != null) {
        UserService.to.hotelInfo.value = hotelInfo;

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

    //停止刷新
    refreshController.finishRefresh();
    //最后赋值
    _needShowPlaceholder = false;
  }

  // 处理数据与展示的逻辑
  void _handleList(List<HotelInfoMenus>? list) {
    if (list != null && list.isNotEmpty) {
      //有数据，判断是刷新还是加载更多的数据
      state.datas.clear();

      int? isAdmin = SPUtil.getInt(AppConstant.storageIsAdmin);
      if (isAdmin == 1) {
        //如果是管理员登录，根据Key筛选需要展示的模块
        for (var hotelInfo in list) {
          if (hotelInfo.key != null) {
            state.datas.addAll(_filterModulesByKey(hotelInfo.key!));
          }
        }
      } else {
        //如果只是签到签出模式，手动的添加模块
        state.datas.addAll(_filterModulesByKey("sign"));
      }

      //更新状态
      changeLoadingState(LoadState.State_Success);
    } else {
      //展示无数据的布局
      state.datas.clear();
      changeLoadingState(LoadState.State_Empty);
    }
  }

  List<HomeModule> _filterModulesByKey(String key) {
    return state.modules.where((module) => module.key == key).toList();
  }

  @override
  void onReady() async {
    super.onReady();
    fetchHomeData();
  }

  /// 跳转到指定的模块中去
  void gotoModulePage(HomeModule module) {
    switch (module.key) {
      case 'labReq':
        ComponentRouterServices.labourService.startLabourRequestPage();
        break;
      case 'jobList':
        ComponentRouterServices.jobService.startJobListPage();
        break;
      case 'sign':
        ComponentRouterServices.jobService.startSignInSignOutPage();
        break;
      case 'devices':
        ToastEngine.show("进入 Devices 模块");
        break;
      case 'reqReview':
        ToastEngine.show("进入 Labour Request Review 模块");
        break;
      case 'attReview':
        ToastEngine.show("进入 Attendance Review 模块");
        break;
      case 'template':
        ToastEngine.show("进入 Default Job Title 模块");
        break;
      case 'report':
        ToastEngine.show("进入 Report 模块");
        break;
    }
  }

  /// 跳转到设置页面
  void gotoSettingPage() {
    SettingPage.startInstance();
  }
}
