import 'package:fis_common/logger/logger.dart';
import 'package:fis_jsonrpc/rpc.dart';
import 'package:flyinsono/architecture/states/states.dart';
import 'package:flyinsono/managers/interfaces/user_info.dart';
import 'package:flyinsono/managers/base_manager.dart';
import 'package:flyinsono/pages/remedical/consultation/widgets/muti_select.dart';
import 'package:flyinsono/rpc.dart';
import 'package:flyinsono/views/desktop/real_time_consultation/widgets/simple_Info.dart';
import 'package:fis_common/event/event_type.dart';
import 'package:fis_i18n/i18n.dart';

class UserInfoManager extends BaseManager implements IUserInfoManager {
  UserInfoManager();

  /// 第二窗口状态改变
  final FEventHandler<bool> onSecondWindowStateChange = FEventHandler<bool>();

  ///获取用户信息
  @override
  Future<UserDTO> getUserInfoAsync() async {
    try {
      final result = await rpc.user.getUserInfoAsync(
        GetUserInfoRequest(token: Store.user.token),
      );
      Store.user.avatar = result.headImageUrl ?? '';
      Store.user.handleUserSyncUpdate(result);
      return result;
    } catch (e) {
      logger.e('UserInfoManager getUserInfoAsync ex:' + e.toString());
      return UserDTO();
    }
  }

  @override
  Future<OrganizationDTO> getOrganizationByCode(String orgCode) async {
    final result = await rpc.organization.getOrganizationByCodeAsync(
      GetOrganizationByCodeRequest(
        token: token,
        organizationCode: orgCode,
      ),
    );
    return result;
  }

  @override
  Future<PageCollection<OrganizationSimplifyDTO>>
      getOrganizationByUserAndDevices({
    int pageIndex = 1,
    int pageSize = 100,
    bool isIncloudReferral = true,
    String? keyword,
    bool onlyOrganization = false,
  }) async {
    final result = await rpc.organization.getOrganizationByUserAndDevicesAsync(
      GetOrganizationByUserAndDevicesRequest(
        token: token,
        pageIndex: pageIndex,
        pageSize: pageSize,
        isIncloudReferral: isIncloudReferral,
        onlyOrganization: onlyOrganization,
        keyword: keyword,
      ),
    );
    return result;
  }

  @override
  Future<List<FMutiSelectModel>> getSelectOrganizations({
    int pageIndex = 1,
    int pageSize = 100,
    bool isIncloudReferral = true,
    String? keyword,
    bool onlyOrganization = false,
  }) async {
    final result = await getOrganizationByUserAndDevices(
      pageSize: pageSize,
      isIncloudReferral: isIncloudReferral,
      keyword: keyword,
      onlyOrganization: onlyOrganization,
      pageIndex: pageIndex,
    );
    List<FMutiSelectModel> organizationLocatedList = [];
    for (OrganizationSimplifyDTO i in result.pageData ?? []) {
      organizationLocatedList.add(
        FMutiSelectModel(
          code: i.organizationCode!,
          name: i.organizationName!,
        ),
      );
    }
    return organizationLocatedList;
  }

  @override
  Future<PageCollection<SelectItemDTO>> getPersonDeviceDropdownPage({
    List<String>? restrictOrgCodes,
    int index = 1,
    int pageSize = 100,
    String? keyword,
    bool isIncloudReferral = true,
  }) async {
    final result = await rpc.device.getPersonDeviceDropdownPageAsync(
      GetPersonDeviceDropdownPageRequest(
        token: token,
        pageIndex: index,
        pageSize: pageSize,
        restrictOrgCodes: restrictOrgCodes,
        isIncloudReferral: isIncloudReferral,
        keyWord: keyword,
      ),
    );
    return result;
  }

  @override
  Future<List<FMutiSelectModel>> getSelectPersonDevices({
    List<String>? restrictOrgCodes,
    int index = 1,
    int pageSize = 100,
    String? keyword,
    bool isIncloudReferral = true,
  }) async {
    var result = await getPersonDeviceDropdownPage(
      index: index,
      restrictOrgCodes: restrictOrgCodes,
      pageSize: pageSize,
      keyword: keyword,
      isIncloudReferral: isIncloudReferral,
    );
    return result.pageData
            ?.map(
                (e) => FMutiSelectModel(code: e.key ?? '', name: e.value ?? ''))
            .toList() ??
        [];
  }

  @override
  Future<OrganizationDTO> queryOrganizationsByShortCodeAsync(
      {required String shortCode}) async {
    return await rpc.organization
        .queryOrganizationsByShortCodeAsync(QueryOrganizationsRequest(
      shortCode: shortCode,
      token: token,
    ));
  }

  @override
  Future<List<OrganizationDTO>> searchOrganizationsAsync(
      {String keyword = '',
      String parentShortCode = '',
      int pageIndex = 1,
      int pageSize = 50}) async {
    final ogranizations = await rpc.organization.searchOrganizationsAsync(
      SearchOrganizationsRequest(
        token: Store.user.token,
        keyword: keyword,
        parentCode: "",
        pageSize: pageSize,
        pageIndex: pageIndex,
        parentShortCode: parentShortCode,
        organizationType: OrganizationTypeEnum.Corporation,
      ),
    );
    return ogranizations;
  }

  @override
  Future<List<SimpleInfoItem>> getUserPages({
    required String organizationCode,
    required List<String> roleCodes,
    int pageIndex = 1,
    String? keyword,
    int pageSize = 100,
  }) async {
    List<SimpleInfoItem> result = [];
    var rpcResult = await rpc.user.getUserPagesAsync(
      GetUserPageRequest(
        keyword: keyword,
        token: token,
        organizationCode: organizationCode,
        roleCodes: roleCodes,
        pageIndex: pageIndex,
        pageSize: pageSize,
        exceptSelf: true,
        language: i18nBook.locale.toCodeString('-'),
      ),
    );
    for (UserExtendDTO u in rpcResult.pageData ?? []) {
      result.add(SimpleInfoItem(
        itemCode: u.userCode!,
        name: u.displayName ?? '',
        role: u.roleName,
        des: u.fieldList,
      ));
    }
    return result;
  }

  @override
  Future<UserInfoByCodeDTO> getUserByCode(String userCode) async {
    return await rpc.user.getUserByCodeAsync(GetUserByCodeRequest(
      token: token,
      userCode: userCode,
    ));
  }
}
