import 'dart:convert' show json;
import 'dart:math';
import 'package:dio/dio.dart' as dio;

import 'package:app_settings/app_settings.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:jpush_flutter/jpush_flutter.dart';

import '../../environment_config.dart';
import '../index.dart';

///
/// 全局工具类
/// 全局使用的对象，包含请求API 当前登录用户 当前绑定服务器 等等
///
class O2ApiManager {
  static final O2ApiManager instance = O2ApiManager._internal();
  factory O2ApiManager() => instance;
  O2ApiManager._internal();

  // 当前服务器信息
  O2CloudServer? _o2CloudServer;
  // 当前连接服务器的center信息
  CenterServerInfo? _centerServerInfo;
  // 当前登录用户信息
  O2Person? _o2user;
  // 当前登录用户的组织列表
  final List<O2Unit> _myUnitList = [];
  // 当前服务器tokenName
  String tokenName = O2.defaultTokenName;
  // 演示版本使用 服务器列表
  List<O2CloudServer> _sampleServerList = List.empty();

  // 极光推送 对象
  final JPush _jpush = JPush();
  // 极光生成的设备id
  String _jpushRegistrationID = "";

  O2CloudServer? get o2CloudServer {
    if (_o2CloudServer == null) {
      String unit = SharedPreferenceService.to
          .getString(SharedPreferenceService.unitSpKey);
      OLogger.d("当前保存的unit: $unit");
      if (unit.isNotEmpty) {
        _o2CloudServer = O2CloudServer.fromJson(O2Utils.parseStringToJson(unit));
      }
    }
    return _o2CloudServer;
  }

  CenterServerInfo? get centerServerInfo {
    if (_centerServerInfo == null) {
      String centerJson = SharedPreferenceService.to
          .getString(SharedPreferenceService.centerServerSpKey);
      if (centerJson.isNotEmpty) {
        _centerServerInfo = CenterServerInfo.fromJson(O2Utils.parseStringToJson(centerJson));
        tokenName = _centerServerInfo?.tokenName ?? O2.defaultTokenName;
      }
    }
    return _centerServerInfo;
  }

  O2Person? get o2User => _o2user;

  ({String name, String distinguishedName, String token}) me() {
    if (_o2user == null) {
      return (name: '', distinguishedName: '', token: '');
    }
    return (name: _o2user?.name ?? '', distinguishedName: _o2user?.distinguishedName ?? '', token: _o2user?.token ?? '');
  }

  List<O2Unit> get myUnitList => _myUnitList;

  ///
  ///极光推送初始化
  ///
  Future<void> jpushInit() async {
    try {
      _jpush.setup(
        appKey: O2.jPushAppKey, //你自己应用的 AppKey
        channel: O2.jPushAppChannel,
        production: EnvironmentConfig.isRelease(),
        debug: !EnvironmentConfig.isRelease(),
      );
      // Platform messages may fail, so we use a try/catch PlatformException.
    } catch (err, stackTrace) {
      OLogger.e('极光推送初始化失败', err, stackTrace);
    }
  }

  /// ios 申请推送权限
  void _jpushAuthorityIos()  {
    _jpush.applyPushAuthority(const NotificationSettingsIOS(
      sound: true,
      alert: true,
      badge: true));
    OLogger.d('申请IOS通知权限！');
  }

  /// 检查 app 是否开启了通知权限
  Future<void> jpushCheckIsNotificationEnabled() async {
    if (!GetPlatform.isMobile) {
      return;
    }
    if (GetPlatform.isIOS) {
      _jpushAuthorityIos();
    } else {
      final enable = await _jpush.isNotificationEnabled();
      OLogger.i('检测 app 是否开启通知权限 $enable');
      if (!enable) {
        _gotoNotificationSetting();
      }
    }
  }

  /// 去系统通知设置页面
  void _gotoNotificationSetting() {
    final context = Get.context;
    if (context!=null) {
      O2UI.showConfirm(context, 'common_notification_not_enable_confirm'.tr , okPressed: () => AppSettings.openNotificationSettings());
    }
  }

  /// 清除通知和角标
  void jpushClearNotifyBadge() {
    _jpush.clearAllNotifications(); // 清除通知
    _jpush.setBadge(0); // 清除角标
  }

  Future<void> sendLocalNotification(
      int notificationId, String title, String content) async {
    final localNotification = LocalNotification(
      id: notificationId,
      title: title,
      buildId: 1,
      content: content,
      fireTime: DateTime.now(),
    );
    _jpush.sendLocalNotification(localNotification).then((res) {
      OLogger.i('发送通知失败 $res');
    }).catchError((e) {
      OLogger.e('发送通知失败 $e');
    });
  }

  /// 极光推送 远程获取设备id
  /// 如果极光的 appkey 和包名不匹配 这里获取 id 会卡住  rid 不返回结果
  Future<String> getJPushDeviceIdRemote() async {
    // 本地存储是否已经有deviceId
    String deviceId = SharedPreferenceService.to
        .getString(SharedPreferenceService.jpushDeviceIdSpKey);
    if (deviceId.isEmpty) {
      var rid = await _jpush.getRegistrationID();
      if (rid.isNotEmpty) {
        _jpushRegistrationID = rid;
        SharedPreferenceService.to.putString(
            SharedPreferenceService.jpushDeviceIdSpKey, _jpushRegistrationID);
      }
      OLogger.i("极光推送 get registration id : $_jpushRegistrationID");
    } else {
      _jpushRegistrationID = deviceId;
    }
    return _jpushRegistrationID;
  }

  // 极光推送 设备id
  String get deviceID => _jpushRegistrationID;

  ///
  ///是否管理员
  ///
  bool isAdministrator() {
    if (_o2user == null) {
      return false;
    }
    List<String>? roles = _o2user!.roleList;
    if (roles != null && roles.isNotEmpty) {
      return roles.where((element) {
        if (element.contains('@')) {
          var first = element.split('@')[0];
          return ((first.toLowerCase() == 'manager' ||
              'CRMManager'.toLowerCase() == first.toLowerCase()));
        } else {
          return ((element.toLowerCase() == 'manager' ||
              'CRMManager'.toLowerCase() == element.toLowerCase()));
        }
      }).isNotEmpty;
    }
    return false;
  }

  //
  O2Person? loadUserFromSP() {
    String pJson =
        SharedPreferenceService.to.getString(SharedPreferenceService.userSpKey);
    if (pJson.isNotEmpty) {
      O2Person user = O2Person.fromJson(O2Utils.parseStringToJson(pJson));
      _o2user = user;
      return user;
    }
    return null;
  }

  //初始化当前登录用户信息 登录成功后调用
  Future<void> setupUser(O2Person user) async {
    await SharedPreferenceService.to.putStringToJsonStringify(
        SharedPreferenceService.userSpKey, user.toJson());
    _o2user = user;
    loadCurrentUserUnitList();
  }

  /// 加载当前用户的组织列表
  Future<void> loadCurrentUserUnitList() async {
    _myUnitList.clear();
    List<String> ids = [];
    if (_o2user?.identityList?.isNotEmpty == true) {
      for (var element in _o2user!.identityList!) {
        if (element.unit?.isNotEmpty == true) {
          ids.add(element.unit!);
        }
      }
    }
    if (ids.isNotEmpty) {
      final list = await OrganizationControlService.to.unitList(ids);
      if (list != null && list.isNotEmpty) {
        _myUnitList.addAll(list);
      }
    }
  }

  /// 清除用户信息 登出的时候使用
  Future<void> cleanUser() async {
    await SharedPreferenceService.to
        .putString(SharedPreferenceService.userSpKey, '');
    _o2user = null;
    _myUnitList.clear();
  }

  ///
  /// 设置O2OA服务器连接配置信息
  ///
  Future<void> putO2UnitJson2SP(O2CloudServer unit) async {
    await SharedPreferenceService.to
        .putStringToJsonStringify(SharedPreferenceService.unitSpKey, unit);
    _o2CloudServer = unit;
  }

  ///
  ///绑定sample服务器 并且重新加载APP
  ///
  Future putSampleUnitServerAndReload() async {
    var cloud = O2CloudServer(
        id: 'sample',
        name: 'sample.o2oa.net',
        centerHost: 'sample.o2oa.net',
        centerContext: '/x_program_center',
        centerPort: 443,
        httpProtocol: 'https');

    await O2ApiManager.instance.putO2UnitJson2SP(cloud);
    Get.offNamed(O2OARoutes.splash);
  }

  ///
  ///清除绑定信息 重新绑定用
  ///
  Future<void> cleanO2UnitAndSp() async {
    await SharedPreferenceService.to
        .putString(SharedPreferenceService.unitSpKey, '');
    _o2CloudServer = null;
  }

  /// 读取o2oa服务器配置信息
  Future<String?> _loadServersJsonFile() async {
    return await rootBundle.loadString('assets/json/servers.json');
  }

  /// app 默认配置的服务器地址信息
  Future<O2CloudServer?> readAssetsServerJson() async {
    String? unitJson = await _loadServersJsonFile();
    if (unitJson != null) {
      Iterable l = json.decode(unitJson);
      List<O2CloudServer> list = List<O2CloudServer>.from(l.map((e) => O2CloudServer.fromJson(e)));
      return list.isEmpty ? null : list.first;
    }
    return null;
  }

  /// 获取O2OA服务器连接配置信息
  /// 查询存储在 sp 中的配置信息，如果没有 
  /// 直连模式就直接读取 assets/json/servers.json 中的配置， 否则按照默认的绑定模式来
  Future<bool> loadO2UnitFromSP() async {
    String unit = SharedPreferenceService.to
          .getString(SharedPreferenceService.unitSpKey);
    OLogger.i("读取到服务器信息: $unit");
    if (unit.isNotEmpty) {
      _o2CloudServer = O2CloudServer.fromJson(O2Utils.parseStringToJson(unit));
      return true;
    }
    OLogger.e('没有服务器配置信息。。。。');
    if (EnvironmentConfig.isDirectConnectMode()) {
      OLogger.i("直接连接 模式========");
      // 本地没有数据 读取servers.json配置文件
      O2CloudServer? server = await readAssetsServerJson();
      if (server != null) {
        _sampleServerList = [server];
        _o2CloudServer = server;
        putO2UnitJson2SP(server);
        return true;
      } else {
        OLogger.i("servers.json 读取失败，没有数据！");
        return false;
      }
    }
    OLogger.i("bind 模式========");
    return false;
  }

  ///
  /// 设置当前连接的O2OA center服务器 以及 application服务器的信息
  /// @param centerServerJson
  ///
  Future<void> putCenterServerJson2SP(String centerServerJson) async {
    await SharedPreferenceService.to
        .putString(SharedPreferenceService.centerServerSpKey, centerServerJson);
    if (centerServerJson.isNotEmpty) {
      _centerServerInfo =
          CenterServerInfo.fromJson(O2Utils.parseStringToJson(centerServerJson));
      tokenName = _centerServerInfo?.tokenName ?? O2.defaultTokenName;
    }
  }

  /// 处理 代理地址
  String _urlTransfer2Mapping(String url) {
    if (_o2CloudServer == null) {
      return url;
    }
    final urlMapping = _o2CloudServer!.urlMapping;
    if (urlMapping == null || urlMapping.isEmpty) {
      return url;
    }
    try {
      Map<String, dynamic> urlMap = O2Utils.parseStringToJson(urlMapping);
      for (var element in urlMap.entries) {
        final key = element.key;
        final value = element.value;
        if (url.contains(key) && value is String) {
          url = url.replaceAll(key, value);
        }
      }
      return url;
    } on Exception {
      return url;
    }
    
  }

  ///
  /// 获取当前连接的O2OA 中心服务器地址
  ///
  String? getCenterBaseUrl() {
    if (_o2CloudServer == null) {
      return null;
    }
    String? context = _o2CloudServer!.centerContext;
    if (context == null || context.isEmpty) {
      return null;
    }
    String url = '${_getProtocol()}://${_o2CloudServer!.centerHost}:${_o2CloudServer!.centerPort}/$context/';
    if (context.contains('/')) {
      url = '${_getProtocol()}://${_o2CloudServer!.centerHost}:${_o2CloudServer!.centerPort}$context/';
    }
    return _urlTransfer2Mapping(url);
  }

  /// web 服务器根地址 比如  http://app.o2oa.net:80
  String? webBaseUrl() {
    if (_centerServerInfo == null) {
      return null;
    }
    var web = _centerServerInfo?.webServer;
    var port = 80;
    var host = ''; 
    if (web != null) {
      port = web.port ?? 80;
      host = web.host ?? '';
    }
    if (_centerServerInfo?.standalone == true) {
      port = _o2CloudServer?.centerPort ?? 80;
      host = _o2CloudServer?.centerHost ?? '';
    }
    String url = "${_getProtocol()}://$host:$port";
    return _urlTransfer2Mapping(url);
  }

  /// http https
  String _getProtocol() {
    return _o2CloudServer == null
        ? 'http'
        : _o2CloudServer?.httpProtocol ?? 'http';
  }

  ///
  /// web服务器host
  /// 返回比如： dd.o2oa.net | 192.168.1.11
  String getWebHost() {
    var web = _centerServerInfo?.webServer;
    var host = ''; 
    if (web != null) {
      host =  web.host ?? "";
    }
    if (_centerServerInfo?.standalone == true) {
      host = _o2CloudServer?.centerHost ?? '';
    }
    return host;
  }

  /// config.json 配置文件读取的内容
  Map<String, dynamic>? configJsonData;

  /// 获取前端配置文件
  /// /x_desktop/res/config/config.json
  Future<Map<String, dynamic>?> getWebConfigJson() async {
    if (configJsonData != null) {
      return configJsonData;
    }
    final web = webBaseUrl();
    if (web != null) {
      String url = "$web/x_desktop/res/config/config.json";
      url = _urlTransfer2Mapping(url);
      configJsonData = await _loadWebConfigJsonData(url);
    }
    return configJsonData;
  }

  ///  请求在线 app 版本信息
  Future<Map<String, dynamic>?> _loadWebConfigJsonData(String jsonUrl) async {
    try {
      final r = Random();
      final s = r.nextInt(1000); // 添加一个随机数 防止缓存
      String url = '$jsonUrl?t=$s';
      dio.Response<dynamic> response = await O2HttpClient.instance.getOuter(url);
      return response.data;
    } catch (err, stackTrace) {
      OLogger.e('读取 config.json 配置', err, stackTrace);
    }
    return null;
  }

  ///工作表单URL草稿模式 draft对象
  String? getProcessDraftUrl(String draft) {
    if (_centerServerInfo == null) {
      return null;
    }
    final web = webBaseUrl();
    if (web != null) {
      String url = "$web/x_desktop/workmobilewithaction.html?draft=$draft";
      final isDebugger = SharedPreferenceService.to.getBool(SharedPreferenceService.webviewDebuggerKey);
      if (isDebugger) {
        url += "&debugger";
      }
      return _urlTransfer2Mapping(url);
    }
    return null;
  }

  ///工作表单URL 草稿模式 draftId
  String? getProcessDraftUrlById(String draftId) {
    if (_centerServerInfo == null) {
      return null;
    }
    final web = webBaseUrl();
    if (web != null) {
      String url = "$web/x_desktop/workmobilewithaction.html?draftId=$draftId";
      final isDebugger = SharedPreferenceService.to.getBool(SharedPreferenceService.webviewDebuggerKey);
      if (isDebugger) {
        url += "&debugger";
      }
      return _urlTransfer2Mapping(url);
    }
    return null;
  }

  

  String? getAttendanceCheckUrl() {
    if (_centerServerInfo == null) {
      return null;
    }
    final web = webBaseUrl();
    if (web != null) {
      String url = "$web/x_desktop/appMobile.html?app=attendancev2&option={\"route\":\"mobile\"}";
      final isDebugger = SharedPreferenceService.to.getBool(SharedPreferenceService.webviewDebuggerKey);
      if (isDebugger) {
        url += "&debugger";
      }
      return _urlTransfer2Mapping(url);
    }
    return null;
  }

  ///
  ///工作表单URL
  ///
  String? getWorkUrl(String workId) {
    if (_centerServerInfo == null) {
      return null;
    }
    final web = webBaseUrl();
    if (web != null) {
      String url = "$web/x_desktop/workmobilewithaction.html?workid=$workId";
      final isDebugger = SharedPreferenceService.to.getBool(SharedPreferenceService.webviewDebuggerKey);
      if (isDebugger) {
        url += "&debugger";
      }
      return _urlTransfer2Mapping(url);
    }
    return null;
  }

  ///
  ///工作表单URL
  ///
  String? getWorkUrlInPC(String workId) {
    if (_centerServerInfo == null) {
      return null;
    }
    final web = webBaseUrl();
    if (web != null) {
      String url = "$web/x_desktop/work.html?workid=$workId";
      final isDebugger = SharedPreferenceService.to.getBool(SharedPreferenceService.webviewDebuggerKey);
      if (isDebugger) {
        url += "&debugger";
      }
      return _urlTransfer2Mapping(url);
    }
    return null;
  }

  ///
  ///已完成的工作表单URL
  ///
  String? getWorkCompletedUrl(String workcompletedId) {
    final web = webBaseUrl();
    if (web != null) {
      String url = "$web/x_desktop/workmobilewithaction.html?workcompletedid=$workcompletedId";
      final isDebugger = SharedPreferenceService.to.getBool(SharedPreferenceService.webviewDebuggerKey);
      if (isDebugger) {
        url += "&debugger";
      }
      return _urlTransfer2Mapping(url);
    }
    return null;
  }

  ///
  /// 门户应用地址
  ///
  String? getPortalUrl(String portalId, {String? pageId, String? portalParameters}) {
    final web = webBaseUrl();
    if (web != null) {
      String url =  "$web/x_desktop/portalmobile.html?id=$portalId";
      if (pageId?.isNotEmpty == true) {
        url += "&page=$pageId";
      }
      if (portalParameters?.isNotEmpty == true) {
        url += "&parameters=$portalParameters";
      }
      final isDebugger = SharedPreferenceService.to.getBool(SharedPreferenceService.webviewDebuggerKey);
      if (isDebugger) {
        url += "&debugger";
      }
      return _urlTransfer2Mapping(url);
    }
    return null;
  }

  ///
  /// cms 文档地址
  ///
  String? getCmsDocumentUrl(String documentId) {
    final web = webBaseUrl();
    if (web != null) {
      String url = "$web/x_desktop/cmsdocMobile.html?id=$documentId";
      final isDebugger = SharedPreferenceService.to.getBool(SharedPreferenceService.webviewDebuggerKey);
      if (isDebugger) {
        url += "&debugger";
      }
      return _urlTransfer2Mapping(url);
    }
    return null;
  }

  ///
  /// cms 文档地址 可以编辑的
  ///
  String? getCmsDocumentEditUrl(String documentId) {
    final web = webBaseUrl();
    if (web != null) {
      String url = "$web/x_desktop/cmsdocmobilewithaction.html?id=$documentId";
      final isDebugger = SharedPreferenceService.to.getBool(SharedPreferenceService.webviewDebuggerKey);
      if (isDebugger) {
        url += "&debugger";
      }
      return _urlTransfer2Mapping(url);
    }
    return null;
  }

  ///
  /// bbs 主题地址
  ///
  String? getBBSSubjectUrl(String documentId) {
    final web = webBaseUrl();
    if (web != null) {
      String url = "$web/x_desktop/forumdocMobile.html?id=$documentId&page=1";
      final isDebugger = SharedPreferenceService.to.getBool(SharedPreferenceService.webviewDebuggerKey);
      if (isDebugger) {
        url += "&debugger";
      }
      return _urlTransfer2Mapping(url);
    }
    return null;
  }

  /// 热图图片地址
  /// 
  /// http://host:port/x_file_assemble_control/jaxrs/file/${pId}/download/stream
  String? getHotPictureUrl(String pid) {
    final fileBaseUrl =
        getModuleBaseUrl(O2DistributeModuleEnum.x_file_assemble_control);
    if (fileBaseUrl == null) {
      return null;
    }
    String url = '${fileBaseUrl}jaxrs/file/$pid/download/stream';
    return _urlTransfer2Mapping(url);
  }

  /// 门户icon地址
  String? getPortalIconUrl(String portalId) {
    final portalBaseUrl =
        getModuleBaseUrl(O2DistributeModuleEnum.x_portal_assemble_surface);
    if (portalBaseUrl == null) {
      return null;
    }
    String url = '${portalBaseUrl}jaxrs/portal/$portalId/icon';
    return _urlTransfer2Mapping(url);
  }

  /// 文件地址
  String getFileURL(String? fileId) {
    //http://dev.o2oa.net:20020/x_file_assemble_control/jaxrs/file/b871a896-93f7-4245-8e5a-100fd4a67d9d/download/stream
    String? baseUrl =
        getModuleBaseUrl(O2DistributeModuleEnum.x_file_assemble_control);
    if (fileId != null &&
        fileId != 'null' &&
        fileId.isNotEmpty &&
        baseUrl != null &&
        baseUrl.isNotEmpty) {
      String url = '${baseUrl}jaxrs/file/$fileId/download/stream';
      return _urlTransfer2Mapping(url);
    } else {
      return '';
    }
  }

  /// 获取websocket地址
  String? websocketUrl() {
    var serverInfo =
        _centerServerInfo?.assembles?.x_message_assemble_communicate;
    if (serverInfo == null) {
      return null;
    }
    String tokenName = O2ApiManager.instance.tokenName;
    String token = O2ApiManager.instance.o2User?.token ?? '';
    if (tokenName.isEmpty || token.isEmpty) {
      return null;
    }
    String protocol = _getProtocol() == 'https' ? 'wss' : 'ws';
    var port = serverInfo.port;
    var host = serverInfo.host;
    if (_centerServerInfo?.standalone == true) {
      port = _o2CloudServer?.centerPort;
      host = _o2CloudServer?.centerHost;
    }
    String url =
        "$protocol://$host:$port${serverInfo.context}/ws/collaboration?$tokenName=$token";
    return _urlTransfer2Mapping(url);
  }

  ///
  /// 获取模块的url地址
  ///
  String? getModuleBaseUrl(O2DistributeModuleEnum module) {
    if (_centerServerInfo == null) {
      return null;
    }
    ModuleServerInfo? serverInfo;
    switch (module) {
      case O2DistributeModuleEnum.x_file_assemble_control:
        serverInfo = _centerServerInfo?.assembles?.x_file_assemble_control;
        break;
      case O2DistributeModuleEnum.x_meeting_assemble_control:
        serverInfo = _centerServerInfo?.assembles?.x_meeting_assemble_control;
        break;
      case O2DistributeModuleEnum.x_attendance_assemble_control:
        serverInfo =
            _centerServerInfo?.assembles?.x_attendance_assemble_control;
        break;
      case O2DistributeModuleEnum.x_bbs_assemble_control:
        serverInfo = _centerServerInfo?.assembles?.x_bbs_assemble_control;
        break;
      case O2DistributeModuleEnum.x_hotpic_assemble_control:
        serverInfo = _centerServerInfo?.assembles?.x_hotpic_assemble_control;
        break;
      case O2DistributeModuleEnum.x_processplatform_service_processing:
        serverInfo =
            _centerServerInfo?.assembles?.x_processplatform_service_processing;
        break;
      case O2DistributeModuleEnum.x_processplatform_assemble_bam:
        serverInfo =
            _centerServerInfo?.assembles?.x_processplatform_assemble_bam;
        break;
      case O2DistributeModuleEnum.x_cms_assemble_control:
        serverInfo = _centerServerInfo?.assembles?.x_cms_assemble_control;
        break;
      case O2DistributeModuleEnum.x_organization_assemble_control:
        serverInfo =
            _centerServerInfo?.assembles?.x_organization_assemble_control;
        break;
      case O2DistributeModuleEnum.x_organization_assemble_custom:
        serverInfo =
            _centerServerInfo?.assembles?.x_organization_assemble_custom;
        break;
      case O2DistributeModuleEnum.x_processplatform_assemble_surface:
        serverInfo =
            _centerServerInfo?.assembles?.x_processplatform_assemble_surface;
        break;
      case O2DistributeModuleEnum.x_organization_assemble_express:
        serverInfo =
            _centerServerInfo?.assembles?.x_organization_assemble_express;
        break;
      case O2DistributeModuleEnum.x_organization_assemble_personal:
        serverInfo =
            _centerServerInfo?.assembles?.x_organization_assemble_personal;
        break;
      case O2DistributeModuleEnum.x_component_assemble_control:
        serverInfo = _centerServerInfo?.assembles?.x_component_assemble_control;
        break;
      case O2DistributeModuleEnum.x_processplatform_assemble_designer:
        serverInfo =
            _centerServerInfo?.assembles?.x_processplatform_assemble_designer;
        break;
      case O2DistributeModuleEnum.x_organization_assemble_authentication:
        serverInfo = _centerServerInfo
            ?.assembles?.x_organization_assemble_authentication;
        break;
      case O2DistributeModuleEnum.x_portal_assemble_surface:
        serverInfo = _centerServerInfo?.assembles?.x_portal_assemble_surface;
        break;
      case O2DistributeModuleEnum.x_calendar_assemble_control:
        serverInfo = _centerServerInfo?.assembles?.x_calendar_assemble_control;
        break;
      case O2DistributeModuleEnum.x_mind_assemble_control:
        serverInfo = _centerServerInfo?.assembles?.x_mind_assemble_control;
        break;
      case O2DistributeModuleEnum.x_teamwork_assemble_control:
        serverInfo = _centerServerInfo?.assembles?.x_teamwork_assemble_control;
        break;
      case O2DistributeModuleEnum.x_wcrm_assemble_control:
        serverInfo = _centerServerInfo?.assembles?.x_wcrm_assemble_control;
        break;
      case O2DistributeModuleEnum.x_jpush_assemble_control:
        serverInfo = _centerServerInfo?.assembles?.x_jpush_assemble_control;
        break;
      case O2DistributeModuleEnum.x_message_assemble_communicate:
        serverInfo =
            _centerServerInfo?.assembles?.x_message_assemble_communicate;
        break;
      case O2DistributeModuleEnum.x_organizationPermission:
        serverInfo = _centerServerInfo?.assembles?.x_organizationPermission;
        break;
      case O2DistributeModuleEnum.x_pan_assemble_control:
        serverInfo = _centerServerInfo?.assembles?.x_pan_assemble_control;
        break;
      case O2DistributeModuleEnum.x_query_assemble_surface:
        serverInfo = _centerServerInfo?.assembles?.x_query_assemble_surface;
        break;
      case O2DistributeModuleEnum.x_app_packaging_client_assemble_control:
        serverInfo = _centerServerInfo?.assembles?.x_app_packaging_client_assemble_control;
        break;
    }
    if (serverInfo == null) {
      return null;
    }
    var port = serverInfo.port;
    var host = serverInfo.host;
    if (_centerServerInfo?.standalone == true) {
      port = _o2CloudServer?.centerPort;
      host = _o2CloudServer?.centerHost;
    }
    String url =
        "${_getProtocol()}://$host:$port${serverInfo.context}/";
    return _urlTransfer2Mapping(url);
  }
}
