import 'package:dio/dio.dart';

import '../models/announcement/announcement.dart';

/// 公告 & 帮助中心 API 服务
class AnnouncementService {
  const AnnouncementService(this._dio);

  final Dio _dio;

  /// 公告列表（分页）— POST uc/announcement/page
  Future<({List<AnnouncementContent> content, int totalElements})>
      getAnnouncementPage({
    int pageNo = 1,
    int pageSize = 15,
  }) async {
    final response = await _dio.post<Map<String, dynamic>>(
      'uc/announcement/page',
      data: {'pageNo': pageNo, 'pageSize': pageSize},
      options: Options(contentType: Headers.formUrlEncodedContentType),
    );
    final data = response.data?['data'];
    if (data is Map<String, dynamic>) {
      final contentList = data['content'];
      final total = data['totalElements'] as int? ?? 0;
      if (contentList is List) {
        return (
          content: contentList
              .whereType<Map<String, dynamic>>()
              .map((e) => AnnouncementContent.fromJson(e))
              .toList(),
          totalElements: total,
        );
      }
    }
    return (content: <AnnouncementContent>[], totalElements: 0);
  }

  /// 弹窗公告列表 — GET uc/announcement/popups
  Future<List<AnnouncementBean>> getPopupAnnouncements() async {
    final response = await _dio.get<Map<String, dynamic>>(
      'uc/announcement/popups',
    );
    final data = response.data?['data'];
    if (data is List) {
      return data
          .whereType<Map<String, dynamic>>()
          .map((e) => AnnouncementBean.fromJson(e))
          .toList();
    }
    return [];
  }

  /// 系统弹窗公告 — GET uc/announcement/system
  Future<AnnouncementBean?> getSystemAnnouncement() async {
    final response = await _dio.get<Map<String, dynamic>>(
      'uc/announcement/system',
    );
    final data = response.data?['data'];
    if (data is Map<String, dynamic>) {
      return AnnouncementBean.fromJson(data);
    }
    return null;
  }

  /// 公告详情 — GET uc/announcement/{id}
  Future<WebInfoContent?> getAnnouncementDetail(String id) async {
    final response = await _dio.get<Map<String, dynamic>>(
      'uc/announcement/$id',
    );
    final data = response.data?['data'];
    if (data is Map<String, dynamic>) {
      return WebInfoContent.fromJson(data);
    }
    return null;
  }

  /// 帮助中心分组列表 — POST uc/ancillary/more/help
  Future<List<HelpInfo>> getHelpList({String lang = 'zh_CN'}) async {
    final response = await _dio.post<Map<String, dynamic>>(
      'uc/ancillary/more/help',
      data: {'lang': lang},
      options: Options(contentType: Headers.formUrlEncodedContentType),
    );
    final data = response.data?['data'];
    if (data is List) {
      return data
          .whereType<Map<String, dynamic>>()
          .map((e) => HelpInfo.fromJson(e))
          .toList();
    }
    return [];
  }

  /// 帮助详情（通用）— POST uc/ancillary/more/help/detail
  Future<WebInfoContent?> getHelpDetail(String id) async {
    final response = await _dio.post<Map<String, dynamic>>(
      'uc/ancillary/more/help/detail',
      data: {'id': id},
      options: Options(contentType: Headers.formUrlEncodedContentType),
    );
    final data = response.data?['data'];
    if (data is Map<String, dynamic>) {
      return WebInfoContent.fromJson(data);
    }
    return null;
  }

  /// 协议列表 — GET cms/help/list?categoryCode=...
  Future<List<WebInfoContent>> getProtocolList({
    String categoryCode = 'PROTOCOL',
    String lang = 'zh_CN',
  }) async {
    final response = await _dio.get<Map<String, dynamic>>(
      'cms/help/list',
      queryParameters: {'categoryCode': categoryCode, 'lang': lang},
    );
    final data = response.data?['data'];
    if (data is List) {
      return data
          .whereType<Map<String, dynamic>>()
          .map((e) => WebInfoContent.fromJson(e))
          .toList();
    }
    return [];
  }

  /// 帮助详情（特殊类型）— POST uc/ancillary/more/help/{type}
  /// type: desclaimer / privacy / follow
  Future<WebInfoContent?> getHelpSpecial(String type) async {
    final response = await _dio.post<Map<String, dynamic>>(
      'uc/ancillary/more/help/$type',
    );
    final data = response.data?['data'];
    if (data is Map<String, dynamic>) {
      return WebInfoContent.fromJson(data);
    }
    return null;
  }

  /// 公告未读数 — GET uc/announcement/unread-count
  /// 返回 { unreadCount, hasUnread, latestId, readIds }
  Future<({int unreadCount, bool hasUnread, int? latestId, List<int> readIds})>
      getUnreadCount() async {
    final response = await _dio.get<Map<String, dynamic>>(
      'uc/announcement/unread-count',
    );
    final data = response.data?['data'];
    if (data is Map<String, dynamic>) {
      final unread = (data['unreadCount'] as num?)?.toInt() ?? 0;
      final has = data['hasUnread'] == true || unread > 0;
      final latest = (data['latestId'] as num?)?.toInt();
      final rawIds = data['readIds'];
      final readIds = rawIds is List
          ? rawIds.whereType<num>().map((e) => e.toInt()).toList()
          : <int>[];
      return (unreadCount: unread, hasUnread: has, latestId: latest, readIds: readIds);
    }
    return (unreadCount: 0, hasUnread: false, latestId: null, readIds: <int>[]);
  }

  /// 标记指定公告为已读 — POST uc/announcement/mark-read?id=xxx
  Future<void> markRead(int id) async {
    await _dio.post<Map<String, dynamic>>(
      'uc/announcement/mark-read',
      queryParameters: {'id': id},
      options: Options(contentType: Headers.formUrlEncodedContentType),
    );
  }
}
