import 'dart:io';
import 'package:dio/dio.dart';
import 'package:mypoint_flutter_app/app/config/api_paths.dart';
import 'package:mypoint_flutter_app/shared/widgets/base_view/base_response_model.dart';
import 'package:mypoint_flutter_app/app/config/constants.dart';
import 'package:mypoint_flutter_app/core/utils/extensions/string_extension.dart';
import 'package:mypoint_flutter_app/core/network/restful_api_client.dart';
import 'package:mypoint_flutter_app/shared/preferences/data_preference.dart';
import 'package:mypoint_flutter_app/features/voucher/models/product_model.dart';
import '../../app/config/callbacks.dart';
import '../../features/personal/personal_edit_item_model.dart';
import '../services/device_info.dart';
import '../../shared/navigation/directional_screen.dart';
import '../../features/home/models/header_home_model.dart';
import '../../features/biometric/model/biometric_register_response_model.dart';
import '../../features/login/model/login_token_response_model.dart';
import '../../features/personal/model/profile_response_model.dart';
import '../services/package_info.dart';
import '../../features/health_book/health_book_model.dart';
import '../../features/history_point/models/history_point_models.dart';
import '../../features/history_point/models/transaction_summary_by_date_model.dart';
import '../../features/register_campaign/model/verify_register_model.dart';
import '../../features/splash/models/update_response_model.dart';
import '../../features/bank_account_manager/bank_account_info_model.dart';
import '../../features/campaign7day/models/campaign_7day_info_model.dart';
import '../../features/campaign7day/models/campaign_7day_mission_model.dart';
import '../../features/campaign7day/models/campaign_7day_reward_model.dart';
import '../../features/daily_checkin/daily_checkin_models.dart';
import '../../features/device_manager/device_manager_model.dart';
import '../../features/electric_payment/models/customer_contract_object_model.dart';
import '../../features/electric_payment/models/electric_payment_response_model.dart';
import '../../features/flash_sale/models/flash_sale_category_model.dart';
import '../../features/flash_sale/models/flash_sale_detail_response.dart';
import '../../features/history_point_cashback/models/history_point_cashback_model.dart';
import '../../features/achievement/model/achievement_model.dart';
import '../../features/home/models/hover_data_model.dart';
import '../../features/home/models/main_section_config_model.dart';
import '../../features/pipi/model/pipi_detail_model.dart';
import '../../features/interested_categories/models/interested_categories_model.dart';
import '../../features/invite_friend_campaign/models/invite_friend_campaign_model.dart';
import '../../features/membership/models/membership_info_response.dart';
import '../../features/onboarding/model/check_phone_response_model.dart';
import '../../features/onboarding/model/onboarding_info_model.dart';
import '../../features/otp/model/create_otp_response_model.dart';
import '../../features/otp/model/otp_verify_response_model.dart';
import '../../features/popup_manager/popup_manager_model.dart';
import '../../features/quiz_campaign/quiz_campaign_model.dart';
import '../../features/register_campaign/model/registration_form_package_model.dart';
import '../../features/traffic_service/traffic_service_model.dart';
import '../../features/transaction/history/transaction_category_model.dart';
import '../../features/transaction/history/transaction_history_model.dart';
import '../../features/transaction/history/transaction_history_response_model.dart';

extension RestfulAPIClientAllRequest on RestfulAPIClient {
  Future<BaseResponseModel<UpdateImageResponseModel>> uploadImage(String imagePath, String feedbackId) async {
    final token = DataPreference.instance.token ?? "";
    final formData = FormData.fromMap({
      "access_token": token,
      "feedback_id": feedbackId,
      "lang": "vi",
      "image_data": await MultipartFile.fromFile(
        imagePath,
        filename: imagePath.split('/').last,
      ),
    });
    return requestMultipart(APIPaths.updateImageRequest, formData, _parseUpdateImageResponse);
  }

  UpdateImageResponseModel _parseUpdateImageResponse(dynamic data) {
    if (data is Json) {
      if (data['image_id'] != null) {
        return UpdateImageResponseModel.fromJson(data);
      }
      final nested = data['data'];
      if (nested is Json) {
        return UpdateImageResponseModel.fromJson(nested);
      }
    }
    return UpdateImageResponseModel(imageId: null);
  }

  Future<BaseResponseModel<UpdateResponseModel>> checkUpdateApp() async {
    final operatingSystem = Platform.operatingSystem;
    final version = await AppInfoHelper.version;
    final buildNumber = await AppInfoHelper.buildNumber;
    final body = {
      "operating_system": operatingSystem,
      "software_model": "MyPoint",
      "version": version,
      "build_number": buildNumber,
    };
    return requestNormal(APIPaths.checkUpdate, Method.POST, body, (data) => UpdateResponseModel.fromJson(data as Json));
  }

  Future<BaseResponseModel<OnboardingInfoModel>> getOnboardingInfo() async {
    return requestNormal(
      APIPaths.getOnboardingInfo,
      Method.GET,
      {},
      (data) => OnboardingInfoModel.fromJson(data as Json),
    );
  }

  Future<BaseResponseModel<CheckPhoneResponseModel>> checkPhoneNumber(String phone) async {
    var deviceKey = await DeviceInfo.getDeviceId();
    var key = "$phone+_=$deviceKey/*8854";
    final body = {"device_key": deviceKey, "phone_number": phone, "key": key.toSha256()};
    return requestNormal(
      APIPaths.checkPhoneNumber,
      Method.POST,
      body,
      (data) => CheckPhoneResponseModel.fromJson(data as Json),
    );
  }

  Future<BaseResponseModel<OTPVerifyResponseModel>> verifyOTP(String otp, String mfaToken) async {
    final body = {"otp": otp, "mfaToken": mfaToken};
    return requestNormal(
      APIPaths.verifyOtpWithAction,
      Method.POST,
      body,
      (data) => OTPVerifyResponseModel.fromJson(data as Json),
    );
  }

  Future<BaseResponseModel<OTPResendResponseModel>> resendOTP(String mfaToken) async {
    final body = {"mfaToken": mfaToken};
    return requestNormal(
      APIPaths.retryOtpWithAction,
      Method.POST,
      body,
      (data) => OTPResendResponseModel.fromJson(data as Json),
    );
  }

  Future<BaseResponseModel<CreateOTPResponseModel>> requestOtpDeleteAccount() async {
    return requestNormal(
      APIPaths.otpDeleteAccountRequest,
      Method.POST,
      {},
      (data) => CreateOTPResponseModel.fromJson(data as Json),
    );
  }

  Future<BaseResponseModel<OTPVerifyResponseModel>> verifyDeleteAccount(String otp) async {
    String? token = DataPreference.instance.token ?? "";
    return requestNormal(APIPaths.verifyDeleteAccount, Method.POST, {
      "otp": otp,
      "access_token": token,
      "lang": "vi",
    }, (data) => OTPVerifyResponseModel.fromJson(data as Json));
  }

  Future<BaseResponseModel<EmptyCodable>> signup(String phone, String password) async {
    var deviceKey = await DeviceInfo.getDeviceId();
    final body = {"username": phone, "password": password.toSha256(), "device_key": deviceKey};
    return requestNormal(APIPaths.signup, Method.POST, body, (data) => EmptyCodable.fromJson(data as Json));
  }

  Future<BaseResponseModel<LoginTokenResponseModel>> login(String phone, String password) async {
    var deviceKey = await DeviceInfo.getDeviceId();
    final body = {
      "username": phone,
      "password": password.toSha256(),
      "device_key": deviceKey,
      "workspace_code": "8854",
    };
    return requestNormal(APIPaths.login, Method.POST, body, (data) => LoginTokenResponseModel.fromJson(data as Json));
  }

  Future<BaseResponseModel<EmptyCodable>> logout() async {
    var deviceKey = await DeviceInfo.getDeviceId();
    var phone = DataPreference.instance.phone ?? "";
    final body = {"username": phone, "device_key": deviceKey, "lang": "vi"};
    return requestNormal(APIPaths.logout, Method.POST, body, (data) => EmptyCodable.fromJson(data as Json));
  }

  Future<BaseResponseModel<LoginTokenResponseModel>> loginWithBiometric(String phone) async {
    var deviceKey = await DeviceInfo.getDeviceId();
    var bioToken = await DataPreference.instance.getBioToken(phone) ?? "";
    final body = {"username": phone, "bioToken": bioToken, "deviceKey": deviceKey, "workspaceCode": "8854"};
    return requestNormal(
      APIPaths.loginWithBiometric,
      Method.POST,
      body,
      (data) => LoginTokenResponseModel.fromJson(data as Json),
    );
  }

  Future<BaseResponseModel<ProfileResponseModel>> getUserProfile() async {
    return requestNormal(APIPaths.getUserInfo, Method.GET, {}, (data) => ProfileResponseModel.fromJson(data as Json));
  }

  Future<BaseResponseModel<TokenRefreshResponseModel>> refreshToken() async {
    String? token = DataPreference.instance.token ?? "";
    String? refreshToken = DataPreference.instance.refreshToken ?? "";
    final body = {"access_token_old": token, "refresh_token": refreshToken, 'lang': 'vi'};
    return requestNormal(
      APIPaths.refreshToken,
      Method.POST,
      body,
      (data) => TokenRefreshResponseModel.fromJson(data as Json),
    );
  }

  Future<BaseResponseModel<CreateOTPResponseModel>> otpCreateNew(String ownerId) async {
    final body = {"owner_id": ownerId, "ttl": Constants.otpTtl, "resend_after_second": Constants.otpTtl, 'lang': 'vi'};
    return requestNormal(
      APIPaths.otpCreateNew,
      Method.POST,
      body,
      (data) => CreateOTPResponseModel.fromJson(data as Json),
    );
  }

  Future<BaseResponseModel<CreateOTPResponseModel>> otpVerifyForDoingNextEvent(
    String ownerId,
    String otp,
    String nextEventName,
  ) async {
    final body = {
      "owner_id": ownerId,
      "otp": otp,
      "next_event_name": nextEventName,
      "ttdne": 180,
      "ttl": Constants.otpTtl, "resend_after_second": Constants.otpTtl,
    };
    return requestNormal(
      APIPaths.otpVerifyForDoingNextEvent,
      Method.POST,
      body,
      (data) => CreateOTPResponseModel.fromJson(data as Json),
    );
  }

  Future<BaseResponseModel<EmptyCodable>> accountPasswordReset(String phone, String password) async {
    final body = {"login_name": phone, "password": password.toSha256()};
    return requestNormal(
      APIPaths.accountPasswordReset,
      Method.POST,
      body,
      (data) => EmptyCodable.fromJson(data as Json),
    );
  }

  Future<BaseResponseModel<EmptyCodable>> accountPasswordChange(String phone, String password) async {
    String? token = DataPreference.instance.token ?? "";
    final body = {"login_name": phone, "password": password.toSha256(), "access_token": token};
    return requestNormal(
      APIPaths.accountPasswordChange,
      Method.POST,
      body,
      (data) => EmptyCodable.fromJson(data as Json),
    );
  }

  Future<BaseResponseModel<EmptyCodable>> accountLoginForPasswordChange(String phone, String password) async {
    String? token = DataPreference.instance.token ?? "";
    final body = {"login_name": phone, "password": password.toSha256(), "access_token": token};
    return requestNormal(
      APIPaths.accountLoginForPasswordChange,
      Method.POST,
      body,
      (data) => EmptyCodable.fromJson(data as Json),
    );
  }

  Future<BaseResponseModel<BiometricRegisterResponseModel>> accountBioCredential() async {
    var deviceKey = await DeviceInfo.getDeviceId();
    final body = {"deviceKey": deviceKey};
    return requestNormal(
      APIPaths.bioCredential,
      Method.POST,
      body,
      (data) => BiometricRegisterResponseModel.fromJson(data as Json),
    );
  }

  Future<BaseResponseModel<BiometricRegisterResponseModel>> registerBiometric() async {
    var deviceKey = await DeviceInfo.getDeviceId();
    final body = {"deviceKey": deviceKey};
    return requestNormal(
      APIPaths.registerBiometric,
      Method.POST,
      body,
      (data) => BiometricRegisterResponseModel.fromJson(data as Json),
    );
  }

  Future<BaseResponseModel<EmptyCodable>> unRegisterBiometric() async {
    var deviceKey = await DeviceInfo.getDeviceId();
    final path = "${APIPaths.unRegisterBiometric}/$deviceKey";
    final body = {"deviceKey": deviceKey};
    return requestNormal(path, Method.POST, body, (data) => EmptyCodable.fromJson(data as Json));
  }

  Future<BaseResponseModel<HeaderHomeModel>> getHomeHeaderData() async {
    return requestNormal(APIPaths.headerHome, Method.GET, {}, (data) => HeaderHomeModel.fromJson(data as Json));
  }

  Future<BaseResponseModel<RegistrationFormPackageModel>> getRegistrationForm(String id) async {
    final path = APIPaths.getRegistrationForm.replaceAll("%@", id);
    return requestNormal(path, Method.GET, {}, (data) {
      return RegistrationFormPackageModel.fromJson(data as Json);
    });
  }

  Future<BaseResponseModel<TransactionHistoryModel>> getTransactionHistoryDetail(String id) async {
    final path = APIPaths.getTransactionHistoryDetail.replaceAll("%@", id);
    return requestNormal(path, Method.GET, {}, (data) {
      return TransactionHistoryModel.fromJson(data as Json);
    });
  }

  Future<BaseResponseModel<PipiDetailResponseModel>> getPipiDetail() async {
    String? token = DataPreference.instance.token ?? "";
    final body = {"access_token": token};
    return requestNormal(APIPaths.getPipiDetail, Method.POST, body, (data) {
      return PipiDetailResponseModel.fromJson(data as Json);
    });
  }

  Future<BaseResponseModel<List<MainSectionConfigModel>>> getSectionLayoutHome() async {
    return requestNormal(APIPaths.getSectionLayoutHome, Method.GET, {}, (data) {
      final list = data as List<dynamic>;
      return list.map((e) => MainSectionConfigModel.fromJson(e)).toList();
    });
  }

  Future<BaseResponseModel<AchievementListResponse>> getAchievementList(Json body) async {
    return requestNormal(APIPaths.achievementGetList, Method.POST, body, (data) {
      return AchievementListResponse.fromJson(data as Json);
    });
  }

  Future<BaseResponseModel<HoverDataModel>> getDataPiPiHome() async {
    return requestNormal(APIPaths.getIconPiPiHome, Method.GET, {}, (data) {
      return HoverDataModel.fromJson(data as Json);
    });
  }

  Future<BaseResponseModel<HeaderHomeModel>> getDynamicHeaderHome() async {
    return requestNormal(APIPaths.getDynamicHeaderHome, Method.GET, {}, (data) {
      return HeaderHomeModel.fromJson(data as Json);
    });
  }

  Future<BaseResponseModel<EmptyCodable>> updateWorkerSiteProfile(Json body) async {
    String? token = DataPreference.instance.token ?? "";
    body["access_token"] = token;
    return requestNormal(APIPaths.updateWorkerSiteProfile, Method.POST, body, (data) {
      return EmptyCodable.fromJson(data as Json);
    });
  }

  Future<BaseResponseModel<MembershipInfoResponse>> getMembershipLevelInfo() async {
    String? token = DataPreference.instance.token ?? "";
    final body = {"access_token": token, "lang": "vi"};
    return requestNormal(APIPaths.getMembershipLevelInfo, Method.POST, body, (data) {
      return MembershipInfoResponse.fromJson(data as Json);
    });
  }

  Future<BaseResponseModel<HistoryPointCashBackResponse>> historyPointCashBackRequest(Json body) async {
    String? token = DataPreference.instance.token ?? "";
    body["access_token"] = token;
    return requestNormal(APIPaths.historyCashBackPoint, Method.GET, body, (data) {
      return HistoryPointCashBackResponse.fromJson(data as Json);
    });
  }

  Future<BaseResponseModel<InviteFriendDetailModel>> getCampaignInviteFriend() async {
    String? token = DataPreference.instance.token ?? "";
    final body = {"access_token": token};
    return requestNormal(APIPaths.campaignInviteFriend, Method.GET, body, (data) {
      return InviteFriendDetailModel.fromJson(data as Json);
    });
  }

  Future<BaseResponseModel<CampaignInviteFriendDetail>> getDetailCampaignInviteFriend() async {
    String? token = DataPreference.instance.token ?? "";
    final body = {"access_token": token};
    return requestNormal(APIPaths.inviteFriendCampaigns, Method.GET, body, (data) {
      return CampaignInviteFriendDetail.fromJson(data as Json);
    });
  }

  Future<BaseResponseModel<InviteFriendResponse>> phoneInviteFriend(String phone) async {
    String? token = DataPreference.instance.token ?? "";
    final body = {"access_token": token, 'username': phone};
    return requestNormal(APIPaths.phoneInviteFriend, Method.POST, body, (data) {
      return InviteFriendResponse.fromJson(data as Json);
    });
  }

  Future<BaseResponseModel<CampaignInviteFriendDetail>> getReferralCampaigns(String code) async {
    final path = APIPaths.referralCampaignsInviteFriend.replaceAll("%@", code);
    return requestNormal(path, Method.GET, {}, (data) {
      return CampaignInviteFriendDetail.fromJson(data as Json);
    });
  }

  Future<BaseResponseModel<InviteFriendAcceptResponse>> referralCampaignAccept(String id, Json body) async {
    String? token = DataPreference.instance.token ?? "";
    body["access_token"] = token;
    final path = APIPaths.referralCampaignAccept.replaceAll("%@", id);
    return requestNormal(path, Method.POST, body, (data) {
      return InviteFriendAcceptResponse.fromJson(data as Json);
    });
  }

  Future<BaseResponseModel<CampaignInviteFriendItemModel>> getInviteFriendCampaignDetail(String id, Json body) async {
    String? token = DataPreference.instance.token ?? "";
    body["access_token"] = token;
    final path = APIPaths.inviteFriendCampaignDetail.replaceAll("%@", id);
    return requestNormal(path, Method.GET, body, (data) {
      return CampaignInviteFriendItemModel.fromJson(data as Json);
    });
  }

  // inviteFriendCampaignDetail
  Future<BaseResponseModel<CheckInDataModel>> rewardOpportunityGetList() async {
    String? token = DataPreference.instance.token ?? "";
    final body = {"access_token": token, 'number_day': '7'};
    return requestNormal(APIPaths.rewardOpportunityGetList, Method.POST, body, (data) {
      return CheckInDataModel.fromJson(data as Json);
    });
  }

  Future<BaseResponseModel<SubmitCheckInData>> submitCheckIn() async {
    String? token = DataPreference.instance.token ?? "";
    final body = {"access_token": token};
    return requestNormal(APIPaths.rewardOpportunityOpenRequest, Method.POST, body, (data) {
      return SubmitCheckInData.fromJson(data as Json);
    });
  }

  Future<BaseResponseModel<TransactionHistoryResponse>> getTransactionHistoryResponse(Json body) async {
    return requestNormal(APIPaths.getTransactionOrderHistory, Method.GET, body, (data) {
      return TransactionHistoryResponse.fromJson(data as Json);
    });
  }

  Future<BaseResponseModel<List<TransactionCategoryModel>>> getTransactionHistoryCategories() async {
    return requestNormal(APIPaths.orderHistoryCategories, Method.GET, {}, (data) {
      final list = data as List<dynamic>;
      return list.map((e) => TransactionCategoryModel.fromJson(e)).toList();
    });
  }

  Future<BaseResponseModel<CustomerContractModel>> customerContractRequestSearch(String maKH) async {
    String? token = DataPreference.instance.token ?? "";
    final body = {"access_token": token, 'ma_khang': maKH};
    return requestNormal(APIPaths.customerContractRequestSearch, Method.POST, body, (data) {
      return CustomerContractModel.fromJson(data as Json);
    });
  }

  Future<BaseResponseModel<List<CustomerContractModel>>> customerContractSearchHistoryGetList() async {
    String? token = DataPreference.instance.token ?? "";
    final body = {"access_token": token};
    return requestNormal(APIPaths.customerContractSearchHistoryGetList, Method.POST, body, (data) {
      final list = data as List<dynamic>;
      return list.map((e) => CustomerContractModel.fromJson(e)).toList();
    });
  }

  Future<BaseResponseModel<bool>> customerContractDelete(String maKHs) async {
    String? token = DataPreference.instance.token ?? "";
    final body = {"access_token": token, 'ma_khang': maKHs};
    return requestNormal(APIPaths.customerContractDelete, Method.POST, body, (data) {
      return data == true;
    });
  }

  Future<BaseResponseModel<HealthBookResponseModel>> getHealthBookCards(Json body) async {
    return requestNormal(APIPaths.getHealthBookCards, Method.GET, body, (data) {
      return HealthBookResponseModel.fromJson(data as Json);
    });
  }

  Future<BaseResponseModel<HealthBookCardItemModel>> getDetailHealthBookCard(String id) async {
    final path = APIPaths.detailHealthBookCardDetail.replaceAll("%@", id);
    return requestNormal(path, Method.GET, {}, (data) {
      return HealthBookCardItemModel.fromJson(data as Json);
    });
  }

  Future<BaseResponseModel<TrafficServiceDetailModel>> getDetailMyPackageVnTra(String id) async {
    final path = APIPaths.detailMyPackageVnTra.replaceAll("%@", id);
    return requestNormal(path, Method.GET, {}, (data) {
      return TrafficServiceDetailModel.fromJson(data as Json);
    });
  }

  Future<BaseResponseModel<EmptyCodable>> submitPerformMission(Campaign7DayMissionModel mission, String id) async {
    final path = APIPaths.submitCampaignMission.replaceFirst('%@', id).replaceFirst('%@', mission.id.toString());

    return requestNormal(path, Method.POST, {}, (data) {
      return EmptyCodable.fromJson(data as Json);
    });
  }

  Future<BaseResponseModel<List<Campaign7DayRewardModel>>> getCampaignRewards(String id) async {
    final path = APIPaths.getCampaignReward.replaceFirst('%@', id);
    return requestNormal(path, Method.GET, {}, (data) {
      final list = data as List<dynamic>;
      return list.map((e) => Campaign7DayRewardModel.fromJson(e)).toList();
    });
  }

  Future<BaseResponseModel<List<String>>> getCampaignLiveTransactions(String id) async {
    final path = APIPaths.getCampaignLiveTransactions.replaceFirst('%@', id);
    return requestNormal(path, Method.GET, {}, (data) {
      if (data is List) {
        return data.map((e) => e.toString()).toList();
      }
      return <String>[];
    });
  }

  Future<BaseResponseModel<Campaign7DayInfoModel>> getCampaignMissions(String id) async {
    final path = APIPaths.getCampaignMissions.replaceFirst('%@', id);
    return requestNormal(path, Method.GET, {}, (data) {
      return Campaign7DayInfoModel.fromJson(data as Json);
    });
  }

  Future<BaseResponseModel<SurveyCampaignInfoModel>> getCampaignQuizSurvey(String id) async {
    final path = APIPaths.getQuizCampaign.replaceFirst('%@', id);
    return requestNormal(path, Method.GET, {}, (data) {
      return SurveyCampaignInfoModel.fromJson(data as Json);
    });
  }

  Future<BaseResponseModel<QuizCampaignSubmitResponseModel>> quizSubmitCampaign(String id, Json body) async {
    final path = APIPaths.quizSubmitCampaign.replaceFirst('%@', id);
    return requestNormal(path, Method.POST, body, (data) {
      return QuizCampaignSubmitResponseModel.fromJson(data as Json);
    });
  }

  Future<BaseResponseModel<List<FlashSaleCategoryModel>>> getFlashSaleCategories(String groupId) async {
    final path = APIPaths.getFlashSaleGroup.replaceFirst('%@', groupId);
    return requestNormal(path, Method.GET, const {}, (data) {
      if (data is List) {
        return data.whereType<Map<String, dynamic>>().map(FlashSaleCategoryModel.fromJson).toList();
      }
      if (data is Map<String, dynamic>) {
        final categories = data['categories'] ?? data['data'] ?? data['items'];
        if (categories is List) {
          return categories.whereType<Map<String, dynamic>>().map(FlashSaleCategoryModel.fromJson).toList();
        }
        if (data.containsKey('_id')) {
          return [FlashSaleCategoryModel.fromJson(Map<String, dynamic>.from(data))];
        }
      }
      return <FlashSaleCategoryModel>[];
    });
  }

  Future<BaseResponseModel<FlashSaleDetailResponse>> getFlashSaleDetail({
    required String groupId,
    int index = 0,
    int size = 10,
    int? categoryId,
  }) async {
    final path = APIPaths.getFlashSaleDetail.replaceFirst('%@', groupId);
    final params = <String, dynamic>{'index': index, 'size': size, if (categoryId != null) 'category_id': categoryId};
    return requestNormal(path, Method.GET, params, (data) {
      if (data is Map<String, dynamic>) {
        return FlashSaleDetailResponse.fromJson(data);
      }
      if (data is List && data.isNotEmpty) {
        final first = data.first;
        if (first is Map<String, dynamic>) {
          return FlashSaleDetailResponse.fromJson(first);
        }
      }
      return FlashSaleDetailResponse(products: <ProductModel>[]);
    });
  }

  Future<BaseResponseModel<DeviceItemModel>> getCurrentDevice() async {
    return requestNormal(APIPaths.getCurrentDevice, Method.GET, {}, (data) {
      return DeviceItemModel.fromJson(data as Json);
    });
  }

  Future<BaseResponseModel<DevicesLogoutListResponse>> getLogoutDevices(Json body) async {
    return requestNormal(APIPaths.getLogoutDevices, Method.GET, body, (data) {
      return DevicesLogoutListResponse.fromJson(data as Json);
    });
  }

  Future<BaseResponseModel<String>> deleteDevice(String deviceKey) async {
    final path = APIPaths.deleteDevice.replaceFirst('%@', deviceKey);
    return requestNormal(path, Method.DELETE, {}, (data) => data as String);
  }

  Future<BaseResponseModel<InterestedCategoriesResponse>> categoryTopLevelGetList() async {
    String? token = DataPreference.instance.token ?? "";
    final body = {"access_token": token, "lang": "vi"};
    return requestNormal(APIPaths.categoryTopLevelGetList, Method.POST, body, (data) {
      return InterestedCategoriesResponse.fromJson(data as Json);
    });
  }

  Future<BaseResponseModel<EmptyCodable>> submitCategorySubscribe(String code) async {
    String? token = DataPreference.instance.token ?? "";
    final body = {"access_token": token, 'category_codes': code};
    return requestNormal(APIPaths.categorySubscribeList, Method.POST, body, (data) {
      return EmptyCodable.fromJson(data as Json);
    });
  }

  Future<BaseResponseModel<EmptyCodable>> submitCategoryUnsubscribeList(String code) async {
    String? token = DataPreference.instance.token ?? "";
    final body = {"access_token": token, 'category_codes': code};
    return requestNormal(APIPaths.categoryUnsubscribeList, Method.POST, body, (data) {
      return EmptyCodable.fromJson(data as Json);
    });
  }

  Future<BaseResponseModel<ElectricPaymentResponseModel>> customerEvnPaymentGatewayRequest(
    CustomerContractModel contract,
    String paymentMethod,
  ) async {
    String? token = DataPreference.instance.token ?? "";
    final body = {
      "access_token": token,
      'ma_khang': contract.maKH ?? '',
      'evn_bill_id': contract.idHoaHon ?? '',
      'amount': contract.amount ?? 0,
      'payment_method': paymentMethod,
    };
    return requestNormal(APIPaths.customerEvnPaymentGatewayRequest, Method.POST, body, (data) {
      return ElectricPaymentResponseModel.fromJson(data as Json);
    });
  }

  Future<BaseResponseModel<List<PopupManagerModel>>> getPopupManagerCommonScreen() async {
    String? token = DataPreference.instance.token ?? "";
    final body = {"access_token": token, "lang": "vi"};
    return requestNormal(APIPaths.getPopup, Method.POST, body, (data) {
      final list = data as List<dynamic>;
      return list.map((e) => PopupManagerModel.fromJson(e)).toList();
    });
  }

  Future<BaseResponseModel<List<BankAccountInfoModel>>> getOrderPaymentMyAccounts() async {
    return requestNormal(APIPaths.orderPaymentMyAccounts, Method.GET, {}, (data) {
      final list = data as List<dynamic>;
      return list.map((e) => BankAccountInfoModel.fromJson(e)).toList();
    });
  }

  Future<BaseResponseModel<String>> setDefaultBankAccount(String id, bool isDefault) async {
    final path = APIPaths.bankAccountSetDefault.replaceFirst('%@', id);
    final body = {"is_default": isDefault ? 1 : 0};
    return requestNormal(path, Method.POST, body, (data) => data as String);
  }

  Future<BaseResponseModel<String>> deleteBankAccount(String id) async {
    final path = APIPaths.bankAccountDelete.replaceFirst('%@', id);
    return requestNormal(path, Method.DELETE, {}, (data) => data as String);
  }

  Future<BaseResponseModel<TransactionSummaryByDateModel>> transactionGetSummaryByDate(Json body) async {
    String? token = DataPreference.instance.token ?? "";
    body["access_token"] = token;
    return requestNormal(APIPaths.transactionGetSummaryByDate, Method.POST, body, (data) {
      return TransactionSummaryByDateModel.fromJson(data as Json);
    });
  }

  Future<BaseResponseModel<ListHistoryResponseModel>> transactionHistoryGetList(Json body) async {
    String? token = DataPreference.instance.token ?? "";
    body["access_token"] = token;
    return requestNormal(APIPaths.transactionHistoryGetList, Method.POST, body, (data) {
      return ListHistoryResponseModel.fromJson(data as Json);
    });
  }

  Future<BaseResponseModel<DirectionalScreen>> getDirectionOfflineBrand(String id) async {
    final body = {"bank_account": id};
    return requestNormal(APIPaths.getOfflineBrand, Method.GET, body, (data) {
      return DirectionalScreen.fromJson(data as Json);
    });
  }

  Future<BaseResponseModel<EmptyCodable>> pushNotificationDeviceUpdateToken(String token) async {
    var deviceKey = await DeviceInfo.getDeviceId();
    final details = await DeviceInfo.getDetails();
    String? accessToken = DataPreference.instance.token ?? "";
    var body = details.toMap();
    body["access_token"] = accessToken;
    body["push_notification_token"] = token;
    body["device_key"] = deviceKey;
    body["lang"] = 'vi';
    body["software_type"] = "Application";
    body["software_model"] = "MyPoint";
    return requestNormal(APIPaths.pushNotificationDeviceUpdateToken, Method.POST, body, (data) {
      return EmptyCodable.fromJson(data as Json);
    });
  }

  Future<BaseResponseModel<DirectionalScreen>> getDirectionScreen(String path) async {
    var path_ = path.startsWith('/') ? path : '/$path';
    return requestNormal(path_, Method.GET, {}, (data) {
      return DirectionalScreen.fromJson(data as Json);
    });
  }

  Future<BaseResponseModel<EmptyCodable>> submitShareContent(String path) async {
    var path_ = path.startsWith('/') ? path : '/$path';
    return requestNormal(path_, Method.GET, {}, (data) {
      return EmptyCodable.fromJson(data as Json);
    });
  }

  Future<BaseResponseModel<VerifyRegisterCampaignModel>> verifyRegisterForm(String path, Json body) async {
    var path_ = path.startsWith('/') ? path : '/$path';
    return requestNormal(path_, Method.POST, body, (data) {
      return VerifyRegisterCampaignModel.fromJson(data as Json);
    });
  }

  Future<BaseResponseModel<SubmitViewVoucherCompletedResponse>> submitCampaignViewVoucherComplete() async {
    return requestNormal(APIPaths.submitCampaignViewVoucherComplete, Method.POST, {}, (data) {
      return SubmitViewVoucherCompletedResponse.fromJson(data as Json);
    });
  }

  Future<BaseResponseModel<EmptyCodable>> webUpdateProfile(Json body) async {
    return requestNormal(APIPaths.webUpdateProfile, Method.POST, body, (data) {
      return EmptyCodable.fromJson(data as Json);
    });
  }
}
