import 'package:dio/dio.dart';

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

class AuthResult {
  final String userID;
  final String imToken;
  final String nickname;

  AuthResult({required this.userID, required this.imToken, required this.nickname});

  factory AuthResult.fromJson(Map<String, dynamic> json) => AuthResult(
        userID: json['userID']?.toString() ?? '',
        imToken: json['imToken']?.toString() ?? '',
        nickname: json['nickname']?.toString() ?? '',
      );
}

class AuthException implements Exception {
  final String message;
  final bool network;

  AuthException(this.message, {this.network = false});

  @override
  String toString() => message;
}

/// 公司工号登录。只走账号服务 POST /api/login，不改 OpenIM Server。
class AuthApi {
  AuthApi({Dio? dio})
      : _dio = dio ??
            Dio(BaseOptions(
              baseUrl: AppEndpoints.authApiBase,
              connectTimeout: const Duration(seconds: 10),
              receiveTimeout: const Duration(seconds: 10),
            ));

  final Dio _dio;

  Map<String, dynamic> _unwrap(dynamic body) {
    if (body is Map<String, dynamic>) {
      if (body['code'] == 0 && body['data'] is Map) {
        return Map<String, dynamic>.from(body['data'] as Map);
      }
      final msg = body['msg']?.toString() ?? '';
      throw AuthException(msg.isNotEmpty ? msg : '工号或密码不正确');
    }
    throw AuthException('工号或密码不正确');
  }

  Future<AuthResult> login({
    required String staffNo,
    required String password,
    required int platformID,
  }) async {
    try {
      final resp = await _dio.post('/api/login', data: {
        'staffNo': staffNo,
        'password': password,
        'platformID': platformID,
      });
      final result = AuthResult.fromJson(_unwrap(resp.data));
      if (result.userID.isEmpty || result.imToken.isEmpty) {
        throw AuthException('工号或密码不正确');
      }
      return result;
    } 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);
    } on AuthException {
      rethrow;
    } catch (_) {
      throw AuthException('网络异常，请稍后重试', network: true);
    }
  }
}
