import 'package:dio/dio.dart';
import 'package:openim_common/openim_common.dart';

import '../auth/auth_api.dart';
import '../config/app_endpoints.dart';

class DirectoryUser {
  final String userID;
  final String nickname;
  final String department;
  final String title;
  final String faceURL;

  DirectoryUser({
    required this.userID,
    required this.nickname,
    required this.department,
    required this.title,
    required this.faceURL,
  });

  factory DirectoryUser.fromJson(Map<String, dynamic> json) => DirectoryUser(
        userID: json['userID']?.toString() ?? '',
        nickname: json['nickname']?.toString() ?? '',
        department: json['department']?.toString() ?? '',
        title: json['title']?.toString() ?? '',
        faceURL: json['faceURL']?.toString() ?? '',
      );
}

/// 员工目录。数据来自账号服务 GET /api/directory，发起好友仍走官方 SDK。
class DirectoryApi {
  DirectoryApi({Dio? dio})
      : _dio = dio ??
            Dio(BaseOptions(
              baseUrl: AppEndpoints.authApiBase,
              connectTimeout: const Duration(seconds: 10),
              receiveTimeout: const Duration(seconds: 10),
            ));

  final Dio _dio;

  Future<List<DirectoryUser>> search({String keyword = '', int limit = 20}) async {
    final token = DataSp.imToken;
    if (token == null || token.isEmpty) {
      throw AuthException('登录已过期，请重新登录');
    }
    try {
      final resp = await _dio.get(
        '/api/directory',
        queryParameters: {'keyword': keyword, 'limit': limit},
        options: Options(headers: {'Authorization': 'Bearer $token'}),
      );
      final body = resp.data;
      if (body is Map && body['code'] == 0 && body['data'] is Map) {
        final items = (body['data']['items'] as List?) ?? const [];
        return items
            .whereType<Map>()
            .map((e) => DirectoryUser.fromJson(Map<String, dynamic>.from(e)))
            .where((e) => e.userID.isNotEmpty)
            .toList();
      }
      final msg = body is Map ? body['msg']?.toString() : null;
      throw AuthException((msg != null && msg.isNotEmpty) ? msg : '员工目录暂不可用');
    } on DioException catch (e) {
      final data = e.response?.data;
      if (data is Map && data['msg'] != null && data['msg'].toString().isNotEmpty) {
        throw AuthException(data['msg'].toString());
      }
      throw AuthException('网络异常，请稍后重试', network: true);
    }
  }
}
