
import 'package:get/get.dart';

import '../../../common/api/index.dart';
import '../../../common/models/index.dart';
import '../../../common/routers/index.dart';
import '../../../common/services/index.dart';
import '../../../common/utils/index.dart';
import '../../../common/values/index.dart';
import '../../common/portal/index.dart';
import 'index.dart';

class AppsController extends GetxController {
  AppsController();

  final state = AppsState();
  final _eventBus = EventBus();
  final _eventId = 'home_app';

  /// 在 widget 内存中分配后立即调用。
  @override
  void onInit() {
    super.onInit();
  }

  /// 在 onInit() 之后调用 1 帧。这是进入的理想场所
  @override
  void onReady() {
    state.title = 'home_tab_apps'.tr;
    _loadAppList();
    _eventBus.on(EventBus.processWorkCloseMsg, _eventId, (arg){
      _loadAppList();
      OLogger.d('流程工作文档 关闭后刷新 app 数据。。。。。');
    });
    _eventBus.on(EventBus.portalCloseMsg, _eventId, (arg){
      _loadAppList();
      OLogger.d('门户 关闭后刷新 app 数据。。。。。');
    });
    super.onReady();
  }
  @override
  void onClose() {
    _eventBus.off(EventBus.portalCloseMsg, _eventId);
    _eventBus.off(EventBus.processWorkCloseMsg, _eventId);
    super.onClose();
  }

  /// 加载应用数据
  _loadAppList() async {
    _loadMyAppList();
    var nativeList = ProgramCenterService.to.getCurrentNativeAppList();
    var portalList = ProgramCenterService.to.getCurrentPortalAppList();
    var myMobilePortalList = await PortalSurfaceService.to.portalMobileList();
    state.portalList.clear();
    if (myMobilePortalList != null && myMobilePortalList.isNotEmpty) {
      List<AppFrontData?> newList = [];
      // 判断 portalList 中的门户应用当前用户是否有权限
      for (var element in portalList) {
        if (element == null) {
          continue;
        }
        var first = myMobilePortalList
            .firstWhereOrNull((p) => p.id == element.portalId);
        if (first != null) {
          newList.add(element);
        }
      }
      state.portalList.addAll(newList);
    }
    state.nativeList.clear();
    state.nativeList.addAll(nativeList);
    _loadWorkNumbers();
    _loadPortalNumbers();
  }

  /// 我的应用列表
  _loadMyAppList() async {
    state.myAppList.clear();
    var myApp = await OrganizationPersonalService.to
        .getMyCustomData(O2.myCustomNameMyAppList);
    if (myApp != null && myApp.isNotEmpty) {
      Map<String, dynamic> m = O2Utils.parseStringToJson(myApp);
      List<dynamic>? myAppList = m[O2.myCustomNameMyAppList];
      if (myAppList != null && myAppList.isNotEmpty) {
        List<AppFrontData?> newList = [];
        for (var element in myAppList) {
          AppFrontData app = AppFrontData.fromJson(element);
          if (app.nativeEnum != null && app.nativeEnum?.name != null) {
            app.name = app.nativeEnum!.name; // 多语言问题
          }
          newList.add(app);
        }
        state.myAppList.addAll(newList);
      }
    }
  }

  /// 待办 待阅等数量查询
  _loadWorkNumbers() async {
    final person = O2ApiManager.instance.o2User?.distinguishedName ?? '';
    if (person.isEmpty) {
      return;
    }
    final workCount =
        await ProcessSurfaceService.to.workCountWithPerson(person);
    if (workCount != null) {
      final list = state.nativeList.toList();
      for (var element in list) {
        if (element != null) {
          switch (element.nativeEnum) {
            case O2NativeAppEnum.task:
              element.showNumber = workCount.task ?? 0;
              break;
            // case O2NativeAppEnum.taskcompleted:
            //   element.showNumber = workCount.taskCompleted ?? 0;
            //   break;
            case O2NativeAppEnum.read:
              element.showNumber = workCount.read ?? 0;
              break;
            // case O2NativeAppEnum.readcompleted:
            //   element.showNumber = workCount.readCompleted ?? 0;
            //   break;
            default:
              break;
          }
        }
      }
      state.nativeList.clear();
      state.nativeList.addAll(list);
    }
  }

  _loadPortalNumbers() async {
    final list = state.portalList.toList();
    for (var element in list) {
      if (element != null && element.portalId != null) {
        final count = await PortalSurfaceService.to.portalCornerMarkNumber(element.portalId!);
        if (count != null && count.count != null && count.count! > 0) {
          element.showNumber = count.count;
        }
      }
    }
    state.portalList.clear();
    state.portalList.addAll(list);
  }

  ///
  /// 打开应用
  ///
  void openApp(AppFrontData? data) {
    if (data != null) {
      if (data.type == O2AppTypeEnum.native) {
        if (data.flutterPath != null) {
          var routerPath = data.flutterPath!;
          if (O2OARoutes.appAttendance == routerPath || O2OARoutes.appAttendanceOld == routerPath) {
            FastCheckInService.instance.stop(); // 进入考勤 先关闭极速打卡
          }
          if (data.displayName?.trim().isNotEmpty == true) {
            if (routerPath.contains('?')) {
              routerPath += '&displayName=${data.displayName}';
            } else {
              routerPath += '?displayName=${data.displayName}';
            }
          }
          Get.toNamed(routerPath);
        }
      } else if (data.type == O2AppTypeEnum.portal) {
        if (data.portalId != null) {
          PortalPage.open(data.portalId!, title: data.name ?? '');
        }
      }
    }
  }

  ///
  /// 点击右上角按钮
  ///
  void clickEditMyAppTopBtn() {
    if (state.isEdit) {
      // 保存数据
      saveMyAppToLocal();
      OLogger.d('保存数据！');
    }
    state.isEdit = !state.isEdit; // 切换状态
  }

  ///
  /// 保存我的应用
  ///
  void saveMyAppToLocal() async {
    final list = state.myAppList;
    var map = <String, dynamic>{};
    List<Map<String, dynamic>> newList = [];
    for (var element in list) {
      var m = element?.toJson();
      if (m != null) {
        newList.add(m);
      }
    }
    map[O2.myCustomNameMyAppList] = newList;
    var result = await OrganizationPersonalService.to
        .saveMyCustomData(O2.myCustomNameMyAppList, map);
    OLogger.d('保存我的app $result');
    _eventBus.emit(EventBus.myAppChangeMsg);
  }

  void addApp2MyList(AppFrontData data) {
    OLogger.d('添加主页app');
    // if (state.myAppList.length >= 4) {
    //   Loading.toast('app_msg_my_app_more'.tr);
    //   return;
    // }
    state.myAppList.add(data);
  }

  void removeApp2MyList(AppFrontData data) {
    OLogger.d('删除主页app');
    state.myAppList.remove(data);
  }

  ///
  /// 当前是否在主页列表中
  bool isInMyApp(AppFrontData data) {
    if (state.myAppList.isEmpty) {
      return false;
    }
    var isIn = false;
    for (var element in state.myAppList) {
      if (element?.key != null && element?.key == data.key) {
        isIn = true;
      }
    }
    return isIn;
  }
}
