import 'package:domain/entity/feedback_detail_entity.dart';
import 'package:domain/entity/home_list_entity.dart';
import 'package:domain/entity/latest_news_detail_entity.dart';
import 'package:domain/entity/latest_news_page_entity.dart';
import 'package:domain/entity/notification_page_entity.dart';
import 'package:domain/entity/visitor_page_entity.dart';
import 'package:plugin_platform/platform_export.dart';
import 'package:plugin_platform/http/dio_engine.dart';
import 'package:plugin_platform/http/http_result.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:shared/utils/log_utils.dart';
import 'package:shared/utils/util.dart';

import '../constants/api_constants.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:plugin_basic/provider/http_provider/http_provider.dart';

import '../entity/feedback_list_entity.dart';
import '../entity/id_name_entity.dart';
import '../entity/property_news_entity.dart';

part 'main_repository.g.dart';

@Riverpod(keepAlive: true)
MainRepository mainRepository(Ref ref) {
  final dioEngine = ref.watch(dioEngineProvider);
  return MainRepository(dioEngine: dioEngine);
}

/*
 * 首页的数据仓库
 */
class MainRepository {
  DioEngine dioEngine;

  MainRepository({required this.dioEngine});

  /// 获取反馈的分类
  Future<HttpResult<IdNameEntity>> fetchFeedbackCategory({
    CancelToken? cancelToken,
  }) async {
    final result = await dioEngine.requestNetResult(
      ApiConstants.apiFeedbackCategory,
      method: HttpMethod.GET,
      isShowLoadingDialog: true,
      networkDebounce: true,
      cancelToken: cancelToken,
    );

    if (result.isSuccess) {
      final jsonList = result.getListJson();

      //获取List数据 需要转换一次
      var list = jsonList
          ?.map((value) {
            if (value is Map<String, dynamic>) {
              return IdNameEntity.fromJson(value);
            } else {
              return null;
            }
          })
          .where((item) => item != null)
          .cast<IdNameEntity>()
          .toList();

      return result.convert<IdNameEntity>(list: list);
    }
    return result.convert<IdNameEntity>();
  }

  /// 发布反馈
  Future<HttpResult> postFeedback({
    required String? categoryId,
    required String? title,
    required String? content,
    List<String>? paths,
    CancelToken? cancelToken,
  }) async {
    Map<String, String> params = {};
    params['category_id'] = categoryId!;
    params['title'] = title!;
    params['content'] = content!;

    Map<String, String> files = {};
    if (paths != null && paths.isNotEmpty) {
      paths.asMap().forEach((index, path) {
        files["resources[$index]"] = path;
      });
    }

    final result = await dioEngine.requestNetResult(
      ApiConstants.apiFeedbackPost,
      params: params,
      paths: files,
      method: HttpMethod.POST,
      isShowLoadingDialog: true,
      networkDebounce: true,
      cancelToken: cancelToken,
    );

    if (result.isSuccess) {
      return result.convert();
    }
    return result.convert();
  }

  /// 已发布的反馈列表
  Future<HttpResult<FeedbackListEntity>> fetchFeedbackList({
    required String status,
    required int curPage,
    CancelToken? cancelToken,
  }) async {
    Map<String, String> params = {};
    params['status'] = status;
    params['page'] = curPage.toString();
    params['limit'] = "10";

    final result = await dioEngine.requestNetResult(
      ApiConstants.apiFeedbackList,
      params: params,
      method: HttpMethod.GET,
      cancelToken: cancelToken,
    );

    if (result.isSuccess) {
      final json = result.getDataJson();
      var data = FeedbackListEntity.fromJson(json!);
      return result.convert<FeedbackListEntity>(data: data);
    }
    return result.convert();
  }

  /// 获取反馈详情
  Future<HttpResult<FeedbackDetailEntity>> fetchFeedbackDetail({
    required String? id,
    CancelToken? cancelToken,
  }) async {
    Map<String, String> params = {};
    params['id'] = id ?? "";

    final result = await dioEngine.requestNetResult(
      ApiConstants.apiFeedbackDetail,
      method: HttpMethod.GET,
      params: params,
      isShowLoadingDialog: true,
      networkDebounce: true,
      cancelToken: cancelToken,
    );

    if (result.isSuccess) {
      final json = result.getDataJson();
      var data = FeedbackDetailEntity.fromJson(json!);
      return result.convert<FeedbackDetailEntity>(data: data);
    }
    return result.convert();
  }

  /// 创建访客的信息
  Future<HttpResult> createVisitor({
    required String? name,
    required String? phone,
    required String? nric,
    required String? vehicleNumber,
    required String? accessDate,
    required String? note,
    CancelToken? cancelToken,
  }) async {
    Map<String, String> params = {};
    params['name'] = name ?? "";
    params['phone'] = phone ?? "";
    params['nric'] = nric ?? "";
    params['access_date'] = accessDate ?? "";

    if (Utils.isNotEmpty(vehicleNumber)) {
      params['vehicle_number'] = vehicleNumber!;
    }
    if (Utils.isNotEmpty(note)) {
      params['note'] = note!;
    }

    final result = await dioEngine.requestNetResult(
      ApiConstants.apiCreateVisitor,
      params: params,
      method: HttpMethod.POST,
      isShowLoadingDialog: true,
      networkDebounce: true,
      cancelToken: cancelToken,
    );

    if (result.isSuccess) {
      return result.convert();
    }
    return result.convert();
  }

  /// 已创建的访客列表
  Future<HttpResult<VisitorPageEntity>> fetchVisitorList({
    required String type,
    required int curPage,
    CancelToken? cancelToken,
  }) async {
    Map<String, String> params = {};
    params['type'] = type;
    params['page'] = curPage.toString();
    params['limit'] = "10";

    final result = await dioEngine.requestNetResult(
      ApiConstants.apiVisitorList,
      params: params,
      method: HttpMethod.GET,
      cancelToken: cancelToken,
    );

    if (result.isSuccess) {
      final json = result.getDataJson();
      var data = VisitorPageEntity.fromJson(json!);
      return result.convert<VisitorPageEntity>(data: data);
    }
    return result.convert();
  }

  /// 首页列表的获取
  Future<HttpResult<HomeListEntity>> fetchHomeIndex({
    bool needLoading = true,
    CancelToken? cancelToken,
  }) async {
    final result = await dioEngine.requestNetResult(
      ApiConstants.apiHomeList,
      method: HttpMethod.GET,
      isShowLoadingDialog: needLoading,
      networkDebounce: true,
      cancelToken: cancelToken,
    );

    if (result.isSuccess) {
      final json = result.getDataJson();
      var data = HomeListEntity.fromJson(json!);
      return result.convert<HomeListEntity>(data: data);
    }
    return result.convert();
  }

  /// 获取首页最新新闻的列表
  Future<HttpResult<LatestNewsPageEntity>> fetchLatestNewsList({
    required String type,
    required int curPage,
    CancelToken? cancelToken,
  }) async {
    Map<String, String> params = {};
    params['page'] = curPage.toString();
    params['limit'] = "10";
    params['type'] = type.toString();

    final result = await dioEngine.requestNetResult(
      ApiConstants.apiLatestNewsList,
      params: params,
      method: HttpMethod.GET,
      cancelToken: cancelToken,
    );

    if (result.isSuccess) {
      final json = result.getDataJson();
      var data = LatestNewsPageEntity.fromJson(json!);
      return result.convert<LatestNewsPageEntity>(data: data);
    }
    return result.convert();
  }

  /// 获取首页最新新闻的详情
  Future<HttpResult<LatestNewsDetailEntity>> fetchLatestNewsDetail({
    required String id,
    CancelToken? cancelToken,
  }) async {
    Map<String, String> params = {};
    params['id'] = id;

    final result = await dioEngine.requestNetResult(
      ApiConstants.apiLatestNewsDetail,
      params: params,
      method: HttpMethod.GET,
      isShowLoadingDialog: true,
      networkDebounce: true,
      cancelToken: cancelToken,
    );

    if (result.isSuccess) {
      final json = result.getDataJson();
      var data = LatestNewsDetailEntity.fromJson(json!);
      return result.convert<LatestNewsDetailEntity>(data: data);
    }
    return result.convert();
  }

  // 获取 房产 news 列表
  Future<HttpResult<PropertyNewsEntity>> fetchPropertyNewsList({
    required int curPage,
    CancelToken? cancelToken,
  }) async {
    Map<String, dynamic> params = {};
    params['page'] = curPage.toString();
    params['limit'] = "10";

    final result = await dioEngine.requestNetResult(
      '/api/v1/user/property/news/list', // api 地址
      params: params,
      method: HttpMethod.GET,
      cancelToken: cancelToken,
    );

    if (result.isSuccess) {
      final json = result.getDataJson();
      var data = PropertyNewsEntity.fromJson(json!);
      return result.convert<PropertyNewsEntity>(data: data);
    }
    return result.convert();
  }

  /// 获取首页管理员指引的列表
  Future<HttpResult<LatestNewsPageEntity>> fetchManageGuideList({
    required int curPage,
    CancelToken? cancelToken,
  }) async {
    Map<String, String> params = {};
    params['page'] = curPage.toString();
    params['limit'] = "10";

    final result = await dioEngine.requestNetResult(
      ApiConstants.apiManageGuideList,
      params: params,
      method: HttpMethod.GET,
      cancelToken: cancelToken,
    );

    if (result.isSuccess) {
      final json = result.getDataJson();
      var data = LatestNewsPageEntity.fromJson(json!);
      return result.convert<LatestNewsPageEntity>(data: data);
    }
    return result.convert();
  }

  /// 获取首页管理员指引的详情
  Future<HttpResult<LatestNewsDetailEntity>> fetchManageGuideDetail({
    required String id,
    CancelToken? cancelToken,
  }) async {
    Map<String, String> params = {};
    params['id'] = id;

    final result = await dioEngine.requestNetResult(
      ApiConstants.apiManageGuideDetail,
      params: params,
      method: HttpMethod.GET,
      isShowLoadingDialog: true,
      networkDebounce: true,
      cancelToken: cancelToken,
    );

    if (result.isSuccess) {
      final json = result.getDataJson();
      var data = LatestNewsDetailEntity.fromJson(json!);
      return result.convert<LatestNewsDetailEntity>(data: data);
    }
    return result.convert();
  }

  /// 通知列表
  Future<HttpResult<NotificationPageEntity>> fetchNotificationList({
    required int curPage,
    CancelToken? cancelToken,
  }) async {
    Map<String, String> params = {};
    params['page'] = curPage.toString();
    params['limit'] = "10";

    final result = await dioEngine.requestNetResult(
      ApiConstants.apiNotificationList,
      params: params,
      method: HttpMethod.GET,
      cancelToken: cancelToken,
    );

    if (result.isSuccess) {
      final json = result.getDataJson();
      var data = NotificationPageEntity.fromJson(json!);
      return result.convert<NotificationPageEntity>(data: data);
    }
    return result.convert();
  }

  /// 设置通知已读
  Future<HttpResult> setNotificationRead({
    String? id,
    CancelToken? cancelToken,
  }) async {
    Map<String, String> params = {};
    if (Utils.isNotEmpty(id)) {
      params['id'] = id!;
    }

    final result = await dioEngine.requestNetResult(
      ApiConstants.apiNotificationRead,
      params: params,
      method: HttpMethod.POST,
      isShowLoadingDialog: true,
      networkDebounce: true,
      cancelToken: cancelToken,
    );

    if (result.isSuccess) {
      return result.convert();
    }
    return result.convert();
  }
}
