import 'package:domain/entity/id_name_entity.dart';
import 'package:domain/entity/user_me_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/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/id_address_entity.dart';
import '../entity/join_estate_success_entity.dart';

part 'profile_repository.g.dart';

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

/*
 * 用户详情的数据仓库
 */
class ProfileRepository {
  DioEngine dioEngine;

  ProfileRepository({required this.dioEngine});

  /// 获取用户详情
  Future<HttpResult<UserMeEntity>> fetchUserInfo({
    CancelToken? cancelToken,
  }) async {
    final result = await dioEngine.requestNetResult(
      ApiConstants.apiProfileInfo,
      method: HttpMethod.GET,
      cancelToken: cancelToken,
    );

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

  /// 更新用户信息
  Future<HttpResult> updateProfile({
    required String? firstName,
    required String? lastName,
    required String? email,
    required String? avatarPath,
    CancelToken? cancelToken,
  }) async {
    Map<String, String> params = {};
    params['first_name'] = firstName!;
    params['last_name'] = lastName!;
    params['email'] = email!;

    Map<String, String> paths = {};

    //如果是链接通过params传参
    if (avatarPath != null && avatarPath.startsWith("http")) {
      params['avatar'] = avatarPath;
    } else {
      //如果是文件通过Path传参
      paths['avatar'] = avatarPath ?? "";
    }

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

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

  /// 获取用户的默认头像列表
  Future<HttpResult<String>> fetchDefaultAvatar({
    CancelToken? cancelToken,
  }) async {
    final result = await dioEngine.requestNetResult(
      ApiConstants.apiDefaultAvatar,
      method: HttpMethod.GET,
      cancelToken: cancelToken,
    );

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

      List<String> stringList = [];
      if (jsonList != null) {
        stringList = jsonList
            .map((value) {
              // 假设 value 是字符串类型，直接返回
              if (value is String) {
                return value;
              }
              return null;
            })
            .where((item) => item != null)
            .cast<String>()
            .toList();
      }

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

    return result.convert<String>();
  }

  /// 修改手机号码
  Future<HttpResult> changeMobilePhone({
    required String? smsCode,
    required String? countryCode,
    required String? phone,
    CancelToken? cancelToken,
  }) async {
    Map<String, String> params = {};

    params['sms_code'] = smsCode!;
    params['country_code'] = countryCode!;
    params['phone'] = phone!;

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

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

  /// 设置默认房产单元
  Future<HttpResult> setUnitAsDefault({
    required String? unitId,
    CancelToken? cancelToken,
  }) async {
    Map<String, String> params = {};
    params['unit_id'] = unitId!;

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

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

  /// 删除指定的房产单元
  Future<HttpResult> deleteEstateUnit({
    required String? unitId,
    CancelToken? cancelToken,
  }) async {
    Map<String, String> params = {};
    params['unit_id'] = unitId!;

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

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

  /// 搜索房产
  Future<HttpResult<IdNameEntity>> searchEstate({
    required String? keyword,
    CancelToken? cancelToken,
  }) async {
    Map<String, String> params = {};
    params['keyword'] = keyword ?? "";

    final result = await dioEngine.requestNetResult(
      ApiConstants.apiEstateSearch,
      params: params,
      method: HttpMethod.GET,
      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<IdAddressEntity>> searchEstateUnits({
    required String? estateId,
    CancelToken? cancelToken,
  }) async {
    Map<String, String> params = {};
    params['estate_id'] = estateId ?? "";

    final result = await dioEngine.requestNetResult(
      ApiConstants.apiEstateUnitSearch,
      params: params,
      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 IdAddressEntity.fromJson(value);
        } else {
          return null;
        }
      }).where((item) => item != null).cast<IdAddressEntity>().toList();

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

  /// 加入房产之前的单元验证
  Future<HttpResult> estateJoinCheck({
    required String? unitId,
    CancelToken? cancelToken,
  }) async {
    Map<String, String> params = {};
    params['unit_id'] = unitId!;

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

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

  /// 加入房产的单元
  Future<HttpResult<JoinEstateSuccessEntity>> joinEstateUnit({
    required String? unitId,
    required String? type,
    required List<String>? paths,
    CancelToken? cancelToken,
  }) async {
    Map<String, String> params = {};
    params['unit_id'] = unitId!;
    params['type'] = type!;

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

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

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