import 'package:domain/entity/home_module.dart';
import 'package:domain/entity/response/hotel_info_entity.dart';
import 'package:get/get.dart';
import 'package:plugin_basic/service/user_service.dart';
import 'package:plugin_platform/http/dio/dio_cancelable_mixin.dart';
import 'package:shared/utils/log_utils.dart';
import 'package:widgets/widget_export.dart';
import '../agency_list/agency_list_page.dart';
import '../contract_list/contract_list_page.dart';
import '../position_list/position_list_page.dart';
import 'agency_category_state.dart';

/*
 * 中介相关的子模块分类列表
 */
class AgencyCategoryController extends GetxController with DioCancelableMixin {
  final AgencyCategoryState state = AgencyCategoryState();

  // Refresh 控制器
  final EasyRefreshController refreshController = EasyRefreshController(
    controlFinishRefresh: false,
    controlFinishLoad: false,
  );

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

  /// 筛选展示 Agency 的数据
  void setupAgencyList() async {
    final hotelInfo = UserService.to.getHotelInfo;

    List<HotelInfoMenusChildren>? list = hotelInfo.menus?.firstWhereOrNull((element) => element.key == "agency")?.children;

    Log.d("list:$list");

    if (list != null && list.isNotEmpty) {
      //有数据，判断是刷新还是加载更多的数据
      state.datas.clear();

      //如果是管理员登录，根据Key筛选需要展示的模块
      for (var children in list) {
        if (children.key != null) {
          state.datas.addAll(_filterModulesByKey(children.key!));
        }
      }
    } else {
      //清除
      state.datas.clear();
    }

    update();
  }

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

  /// 跳转到指定的模块中去
  void gotoModulePage(HomeModule module) {
    switch (module.key) {
      case 'agencyList':
        SGAgencyListPage.startInstance();
        break;
      case 'contract':
        SGContractListPage.startInstance();
        break;
      case 'position':
        SGPositionListPage.startInstance();
        break;

    }
  }

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