import 'package:hmg_patient_app/config/config.dart';
import 'package:hmg_patient_app/config/shared_pref_kay.dart';
import 'package:hmg_patient_app/core/model/pharmacies/Manufacturer.dart';
import 'package:hmg_patient_app/core/model/pharmacies/PharmacyImageObject.dart';
import 'package:hmg_patient_app/core/model/pharmacies/PharmacyProduct.dart';
import 'package:hmg_patient_app/core/service/AlHabibMedicalService/customer_addresses_service.dart';
import 'package:hmg_patient_app/core/service/base_service.dart';
import 'package:hmg_patient_app/uitl/app_shared_preferences.dart';
import 'package:hmg_patient_app/uitl/utils.dart';

class PharmacyModuleService extends BaseService {
  final AppSharedPreferences sharedPref = AppSharedPreferences();
  bool isFinished = true;
  String errorMsg = '';
  String url = "";
  CustomerInfo? customerInfo;

  List<PharmacyImageObject> bannerItems =[];
  List<Manufacturer> manufacturerList =[];
  List<PharmacyProduct> bestSellerProducts =[];
  List<PharmacyProduct> lastVisitedProducts =[];
  List<PharmacyProduct> mostViewedProducts =[];

  Future makeVerifyCustomer(dynamic data) async {
    Map<String, String> queryParams = {'FileNumber': data['PatientID'].toString()};
    hasError = false;
    try {
      await baseAppClient.getPharmacy(PHARMACY_VERIFY_CUSTOMER, onSuccess: (dynamic response, int statusCode) async {
        if (response['UserName'] != null) {
          sharedPref.setString(PHARMACY_CUSTOMER_ID, response['CustomerId'].toString());
        } else {
          await createUser();
        }
      }, onFailure: (String error, int statusCode) {
        hasError = true;
        super.error = error;
      }, queryParams: queryParams);
    } catch (error) {
      throw error;
    }
  }

  Future<int> createUser() async {
    var data = await sharedPref.getObject(USER_PROFILE);
    var languageID = await sharedPref.getString(APP_LANGUAGE);
    Map<String, String> queryParams = {
      'Phone': Utils.getPhoneNumberWithoutZero(data['MobileNumber']),
      'FileNumber': data['PatientID'].toString(),
      'Language': languageID.toString() == 'en' ? '2' : '1',
      'Iqama': data['PatientIdentificationNo'],
      'CountryCode': data['ZipCode'] ?? '966',
    };
    hasError = false;
    try {
      await baseAppClient.getPharmacy(PHARMACY_CREATE_CUSTOMER, onSuccess: (dynamic response, int statusCode) async {
        if (!response['IsRegistered']) {
        } else {
          customerInfo = CustomerInfo.fromJson(response);
          await sharedPref.setObject(PHARMACY_CUSTOMER_ID, customerInfo!.customerId);
          await sharedPref.setObject(PHARMACY_CUSTOMER_GUID, response['customerDto']['customerGuid']);
        }
      }, onFailure: (String error, int statusCode) {
        hasError = true;
        super.error = error;
      }, queryParams: queryParams);
    } catch (error) {
      throw error;
    }
    return Future.value(1);
  }

  Future generatePharmacyToken() async {
    await getUser();
    Map<String, String> queryParams = {
      'Filenumber': user.patientID.toString(),
      'MobileNumber': Utils.getPhoneNumberWithoutZero(user.mobileNumber!),
    };
    hasError = false;
    try {
      await baseAppClient.getPharmacy(PHARMACY_AUTORZIE_CUSTOMER, onSuccess: (dynamic response, int statusCode) async {
        if (response['Status'] == 200) {
          await sharedPref.setString(PHARMACY_AUTORZIE_TOKEN, response['token'].toString());
        }
      }, onFailure: (String error, int statusCode) {
        hasError = true;
        super.error = error;
      }, queryParams: queryParams);
    } catch (error) {
      throw error;
    }
  }

  Future getBannerListList() async {
    hasError = false;
    try {
      await baseAppClient.getPharmacy(GET_PHARMACY_BANNER, onSuccess: (dynamic response, int statusCode) {
        bannerItems.clear();
        response['images'].forEach((item) {
          bannerItems.add(PharmacyImageObject.fromJson(item));
        });
      }, onFailure: (String error, int statusCode) {
        hasError = true;
        super.error = error;
      });
    } catch (error) {
      throw error;
    }
  }

  Future getTopManufacturerList() async {
    if (manufacturerList.isNotEmpty) return;
    Map<String, String> queryParams = {'page': '1', 'limit': '8'};
    try {
      await baseAppClient.getPharmacy(GET_PHARMACY_TOP_MANUFACTURER, onSuccess: (dynamic response, int statusCode) {
        manufacturerList.clear();
        response['manufacturer'].forEach((item) {
          Manufacturer manufacturer = Manufacturer.fromJson(item);
          // if (manufacturer.image != null) {
          manufacturerList.add(Manufacturer.fromJson(item));
          // }
        });
        hasError = false;
      }, onFailure: (String error, int statusCode) {
        hasError = true;
        super.error = error;
      }, queryParams: queryParams);
    } catch (error) {
      throw error;
    }
  }

  Future getBestSellerProducts() async {
    if (bestSellerProducts.isNotEmpty) return;

    Map<String, String> queryParams = {
      'fields':
          'id,discount_ids,name,namen,localized_names,display_order,short_description,full_description,full_descriptionn,sku,order_minimum_quantity,order_maximum_quantity,price,old_price,images,is_rx,rx_message,rx_messagen,discount_name,discount_namen,approved_rating_sum,approved_total_reviews,allow_back_in_stock_subscriptions,stock_quantity,stock_availability,stock_availabilityn,discount_percentage,reviews,specifications',
    };
    try {
      await baseAppClient.getPharmacy(GET_PHARMACY_BEST_SELLER_PRODUCT, onSuccess: (dynamic response, int statusCode) {
        bestSellerProducts.clear();
        response['products'].forEach((item) {
          bestSellerProducts.add(PharmacyProduct.fromJson(item));
        });
        hasError = false;
      }, onFailure: (String error, int statusCode) {
        hasError = true;
        super.error = error;
      }, queryParams: queryParams);
    } catch (error) {
      throw error;
    }
  }

  Future getLastVisitedProducts() async {
    String lastVisited = "";
    if (await this.sharedPref.getString(PHARMACY_LAST_VISITED_PRODUCTS) != null) {
      lastVisited = await this.sharedPref.getString(PHARMACY_LAST_VISITED_PRODUCTS);
      // lastVisited = "2458,4561";
      try {
        await baseAppClient.getPharmacy("$GET_PHARMACY_PRODUCTs_BY_IDS$lastVisited", onSuccess: (dynamic response, int statusCode) {
          lastVisitedProducts.clear();
          response['products'].forEach((item) {
            lastVisitedProducts.add(PharmacyProduct.fromJson(item));
          });
          hasError = false;
        }, onFailure: (String error, int statusCode) {
          hasError = true; //   sharedPref.setString(PHARMACY_LAST_VISITED_PRODUCTS, "");
          super.error = error;
        });
      } catch (error) {
        throw error;
      }
    }
  }

  Future getMostViewedProducts() async {
    hasError = false;
    Map<String, String> queryParams = {
      'fields':
          'id,discount_ids,name,reviews,namen,localized_names,display_order,short_description,full_description,full_descriptionn,sku,order_minimum_quantity,order_maximum_quantity,price,old_price,images,is_rx,rx_message,rx_messagen,discount_name,discount_namen,approved_rating_sum,approved_total_reviews,allow_back_in_stock_subscriptions,stock_quantity,stock_availability,stock_availabilityn,discount_percentage,specifications',
    };
    try {
      await baseAppClient.getPharmacy(GET_MOST_VIEWED_PRODUCTS, onSuccess: (dynamic response, int statusCode) {
        mostViewedProducts.clear();
        response['products'].forEach((item) {
          mostViewedProducts.add(PharmacyProduct.fromJson(item));
        });
      }, onFailure: (String error, int statusCode) {
        hasError = true;
        super.error = error;
      }, queryParams: queryParams);
    } catch (error) {
      hasError = true;
      super.error = error.toString();
      // throw error;
    }
  }
}
