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/PharmacyProduct.dart';
import 'package:hmg_patient_app/core/model/pharmacy/categorise_parent_model.dart';
import 'package:hmg_patient_app/core/model/pharmacy/final_products_model.dart';
import 'package:hmg_patient_app/core/model/pharmacy/pharmacy_categorise.dart';
import 'package:hmg_patient_app/core/model/pharmacy/scan_qr_model.dart';
import 'package:hmg_patient_app/models/LiveCare/validators.dart';

import 'base_service.dart';

class PharmacyCategoriseService extends BaseService {
  //service one
  List<PharmacyCategorise> _categoriseList =[];
  List<PharmacyCategorise> get categoriseList => _categoriseList;

  //service two
  List<CategoriseParentModel> _parentCategoriseList =[];
  List<CategoriseParentModel> get parentCategoriseList => _parentCategoriseList;

  //service three
  List<PharmacyProduct> _parentProductsList =[];
  List<PharmacyProduct> get parentProductsList => _parentProductsList;

  //service four
  List<CategoriseParentModel> _subCategoriseList =[];
  List<CategoriseParentModel> get subCategoriseList => _subCategoriseList;

  //service five
  List<PharmacyProduct> _subProductsList =[];
  List<PharmacyProduct> get subProductsList => _subProductsList;

  //service six
  List<PharmacyProduct> _finalProducts =[];
  List<PharmacyProduct> get finalProducts => _finalProducts;

  //service 7

  List<CategoriseParentModel> _brandsList =[];
  List<CategoriseParentModel> get brandsList => _brandsList;

  // service 8

  List<PharmacyProduct> _searchList =[];
  List<PharmacyProduct> get searchList => _searchList;

  List<ScanQrModel> _scanList =[];
  List<ScanQrModel> get scanList => _scanList;

  List<FinalProductsModel> manufacturerProducts =[];

  clearSearchList() {
    _searchList.clear();
  }

  Future getCategorise() async {
    hasError = false;
    _categoriseList.clear();
    await baseAppClient.getPharmacy(
      GET_PHARMACY_CATEGORISE,
      onSuccess: (dynamic response, int statusCode) {
        response['categories'].forEach((item) {
          _categoriseList.add(PharmacyCategorise.fromJson(item));
        });
      },
      onFailure: (String error, int statusCode) {
        hasError = true;
        super.error = error;
      },
    );
  }

  Future scanQr({required String id}) async {
    hasError = false;
    _scanList.clear();
    String endPoint = id != null ? SCAN_QR_CODE + "$id" : SCAN_QR_CODE + "";
    await baseAppClient.getPharmacy(
      endPoint,
      onSuccess: (dynamic response, int statusCode) {
        response['products'].forEach((item) {
          _scanList.add(ScanQrModel.fromJson(item));
        });
      },
      onFailure: (String error, int statusCode) {
        hasError = true;
        super.error = error;
      },
    );
  }

  Future searchProducts({required String productName}) async {
    hasError = false;
    _searchList.clear();
    // the language ID in pharmacy is different not same in patient app, en == 1 , ar == 2
    var languageID = await sharedPref.getStringWithDefaultValue(APP_LANGUAGE, 'ar');
    var languageId = languageID == 'ar' ? 2 : 1;
    String endPoint = productName != null
        ? GET_SEARCH_PRODUCTS + "$productName" + '&language_id=' + "$languageId"
        : GET_SEARCH_PRODUCTS + "";
    await baseAppClient.getPharmacy(
      endPoint,
      onSuccess: (dynamic response, int statusCode) {
        response['products'].forEach((item) {
          _searchList.add(PharmacyProduct.fromJson(item));
        });
      },
      onFailure: (String error, int statusCode) {
        hasError = true;
        super.error = error;
      },
    );
  }

  Future getBrands({required String id}) async {
    hasError = false;
    _brandsList.clear();
    await baseAppClient.getPharmacy(
      GET_BRANDS_LIST + "$id" + "&fields=id,name,image,namen",
      onSuccess: (dynamic response, int statusCode) {
        response['manufacturer'].forEach((item) {
          _brandsList.add(CategoriseParentModel.fromJson(item));
        });
      },
      onFailure: (String error, int statusCode) {
        hasError = true;
        super.error = error;
      },
    );
  }

  Future getCategoriseParent({required String id}) async {
    hasError = false;
    _parentCategoriseList.clear();
    String endPoint =
        id != null ? GET_CATEGORISE_PARENT + "$id" : GET_CATEGORISE_PARENT + "";
    await baseAppClient.getPharmacy(
      endPoint,
      onSuccess: (dynamic response, int statusCode) {
        response['categories'].forEach((item) {
          _parentCategoriseList.add(CategoriseParentModel.fromJson(item));
        });
      },
      onFailure: (String error, int statusCode) {
        hasError = true;
        super.error = error;
      },
    );
  }

  Future getParentProducts(
      {String? id, int? pageNumber, bool isLoading = false}) async {
    hasError = false;
    if (isLoading == false) {
      _parentProductsList.clear();
    }
    String endPoint = id != null
        ? GET_PARENT_PRODUCTS + "$id" + '&page=' + '$pageNumber' + '&limit=24'
        : GET_PARENT_PRODUCTS + "";
    await baseAppClient.getPharmacy(
      endPoint,
      onSuccess: (dynamic response, int statusCode) {
        response['products'].forEach((item) {
          _parentProductsList.add(PharmacyProduct.fromJson(item));
        });
        //pageNumber++;
      },
      onFailure: (String error, int statusCode) {
        hasError = true;
        super.error = error;
      },
    );
  }

  Future getSubCategorise({required String id}) async {
    hasError = false;
    _subCategoriseList.clear();

    String endPoint =
        id != null ? GET_SUB_CATEGORISE + "$id" : GET_SUB_CATEGORISE + "";
    await baseAppClient.getPharmacy(
      endPoint,
      onSuccess: (dynamic response, int statusCode) {
        response['categories'].forEach((item) {
          _subCategoriseList.add(CategoriseParentModel.fromJson(item));
        });
      },
      onFailure: (String error, int statusCode) {
        hasError = true;
        super.error = error;
      },
    );
  }

  Future getSubProducts(
      {String? id, int? pageIndex, bool isLoading = false}) async {
    hasError = false;
    if (isLoading == false) {
      _subProductsList.clear();
    }
    String endPoint = id != null
        ? GET_SUB_PRODUCTS + "$id" + '&page=' + '$pageIndex' + '&limit=24'
        : GET_SUB_PRODUCTS + "";
    await baseAppClient.getPharmacy(
      endPoint,
      onSuccess: (dynamic response, int statusCode) {
        response['products'].forEach((item) {
          _subProductsList.add(PharmacyProduct.fromJson(item));
        });
      },
      onFailure: (String error, int statusCode) {
        hasError = true;
        super.error = error;
      },
    );
  }

  Future getFinalProducts({required String id}) async {
    hasError = false;
    _finalProducts.clear();
    String endPoint =
        id != null ? GET_FINAL_PRODUCTS + "$id" : GET_FINAL_PRODUCTS + "";
    await baseAppClient.getPharmacy(
      endPoint,
      onSuccess: (dynamic response, int statusCode) {
        response['products'].forEach((item) {
          _finalProducts.add(PharmacyProduct.fromJson(item));
        });
      },
      onFailure: (String error, int statusCode) {
        hasError = true;
        super.error = error;
      },
    );
  }

  Future getManufacturerProducts(String id) async {
    hasError = false;
    Map<String, String> queryParams = {'ManufacturerId': id};

    _finalProducts.clear();
    await baseAppClient.getPharmacy(
      GET_BRAND_ITEMS,
      onSuccess: (dynamic response, int statusCode) {
        response['products'].forEach((item) {
          _finalProducts.add(PharmacyProduct.fromJson(item));
        });
      },
      onFailure: (String error, int statusCode) {
        hasError = true;
        super.error = error;
      },
      queryParams: queryParams,
    );
  }

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

  Future getBestSellerProducts() async {
    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) {
        _finalProducts.clear();
        response['products'].forEach((item) {
          _finalProducts.add(PharmacyProduct.fromJson(item));
        });
      }, onFailure: (String error, int statusCode) {
        hasError = true;
        super.error = error;
      }, queryParams: queryParams);
    } catch (error) {
      throw error;
    }
  }

  Future getFilteredProducts(
      {String? categoryId, String? brandId, String? min, String? max}) async {
    hasError = false;
    String endPoint;

    _parentProductsList.clear();
    endPoint = FILTERED_PRODUCTS +
        "$categoryId" +
        "$brandId" +
        "$min" +
        "$max&page=1&limit=50";
    await baseAppClient.getPharmacy(
      endPoint,
      onSuccess: (dynamic response, int statusCode) {
        response['products'].forEach((item) {
          _parentProductsList.add(PharmacyProduct.fromJson(item));
        });
      },
      onFailure: (String error, int statusCode) {
        hasError = true;
        super.error = error;
      },
    );
  }

  Future getFilteredSubProducts(
      {String? categoryId, String? brandId, String? min, String? max}) async {
    hasError = false;
    String endPoint;

    _subProductsList.clear();
    endPoint = FILTERED_PRODUCTS +
        "$categoryId" +
        "$brandId" +
        "$min" +
        "$max&page=1&limit=50";
    await baseAppClient.getPharmacy(
      endPoint,
      onSuccess: (dynamic response, int statusCode) {
        response['products'].forEach((item) {
          _subProductsList.add(PharmacyProduct.fromJson(item));
        });
      },
      onFailure: (String error, int statusCode) {
        hasError = true;
        super.error = error;
      },
    );
  }

  Future getMostViewedProducts() async {
    hasError = false;
    Map<String, String> queryParams = {
      'fields':
          'mostview?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) {
        _finalProducts.clear();
        response['products'].forEach((item) {
          _finalProducts.add(PharmacyProduct.fromJson(item));
        });
        print("most viewed products ---------");
        print(response);
      }, onFailure: (String error, int statusCode) {
        hasError = true;
        super.error = error;
      }, queryParams: queryParams);
    } catch (error) {
      hasError = true;
      super.error = error.toString();
      // throw error;
    }
  }

  Future getNewProducts() async {
    Map<String, String> queryParams = {
      'fields':
          'Id,name,namen,localized_names,price,images,sku,stock_availability,published',
    };
    try {
      await baseAppClient.getPharmacy(GET_NEW_PRODUCTS,
          onSuccess: (dynamic response, int statusCode) {
        _finalProducts.clear();
        response['products'].forEach((item) {
          _finalProducts.add(PharmacyProduct.fromJson(item));
        });
        print("new products ---------");
        print(response);
      }, onFailure: (String error, int statusCode) {
        hasError = true;
        super.error = error;
      }, queryParams: queryParams);
    } catch (error) {
      throw error;
    }
  }
}
