import 'dart:convert';
import 'package:echo_app/enums/global-errors.dart';
import 'package:echo_app/global/global.dart';
import 'package:echo_app/models/constant-storage.dart';
import 'package:echo_app/models/shared-filter.dart';
import 'package:echo_app/screens/tap_page/tap.page.dart';
import 'package:echo_app/shared/core.session.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:http/http.dart' as http;


class ItemService {
  String _url = "";
  static var items = [];
  static double netTotal = 0;
  int languageId = 1;
 
  //static int cartCount = 0;
  ItemService() {
    this._url = CoreSession.api + "API/EchoItem/";
  }

  Future<dynamic> getItems(GeneralFilter filter) async {
    final String urlValue = this._url + "GetItems";
    var body = jsonEncode({
      'divisionId': filter.divisionId,
      'itemCategoryId': filter.itemCategoryId,
      'brandId': filter.brandId,
      'packId': filter.packId,
      'searchText': filter.searchText,
      'typeId': filter.typeId,
      'subTypeId': filter.subTypeId,
    });
    try {
      final response = await http.post(
        Uri.parse(urlValue),
        headers: Global.httpOptions,
        body: body,
      );
      return json.decode(response.body);
    } catch (error) {
      print(error);
    }
  }

  Future<void> fillHomePageSectionsAndItems() async {
    final String urlValue = this._url + "GetEchoHomePageData";
    SharedPreferences prefs = await SharedPreferences.getInstance();
    try {
      final res = await http.post(
        Uri.parse(urlValue),
        headers: Global.httpOptions,
      );
      var response = json.decode(res.body);

      if (response['status'] == GlobalErrors.Success.index) {
        var data = response['data'];
        ItemService.items = data['items'];
        CoreSession.homePageData = data['homePagesections'];
        CoreSession.newNotificationCount = data['notificationCount'];
        TapPage.enteredValue.value = CoreSession.newNotificationCount;

        String? favBasket = prefs.getString(ConstantStorage.favBasket);
        if (favBasket != '' &&
            favBasket != null &&
            favBasket != '[]') {
          CoreSession.favBasket = json.decode(favBasket);
        }


        var itemsOffer = [];
        itemsOffer = CoreSession.currentOperator['itemOffers'] != null
            ? CoreSession.currentOperator['itemOffers']
            : [];
            
        ItemService.items.forEach(
          (i) => {
            i['hasOffer'] = itemsOffer
                        .where((item) => item['itemId'] == i['itemId'])
                        .length >
                    0
                ? true
                : false,
          },
        );
      }
      await CoreSession.getCustomerBasket();
    } catch (error) {
      print(error);
      ItemService.items = [];
    }
  }

  updateBasket(itemList, orderNetTotal) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    // CoreSession.currentBasket['items'] = itemList;
    // CoreSession.currentBasket['netTotal'] = orderNetTotal;
    var basket = {
      'customerId': CoreSession.currentOperator['customerId'],
      'outletId': CoreSession.currentOperator['outletId'],
      'items': itemList,
      'netTotal': orderNetTotal
    };

    int index = CoreSession.ordersBasket.indexWhere((o) =>
        o['customerId'] == CoreSession.currentOperator['customerId'] &&
        o['outletId'] == CoreSession.currentOperator['outletId']);
    if (index > -1) {
      CoreSession.ordersBasket.remove(CoreSession.ordersBasket[index]);
    }

    var savedBasket = [];
    String? orderBasketJson = prefs.getString(ConstantStorage.orderBasket);
    if (orderBasketJson != '' &&
        orderBasketJson != null &&
        orderBasketJson != '[]') {
      savedBasket = json.decode(orderBasketJson);
    }
    int index2 = savedBasket.indexWhere((o) =>
        o['customerId'] == CoreSession.currentOperator['customerId'] &&
        o['outletId'] == CoreSession.currentOperator['outletId']);
    if (index2 > -1) {
      savedBasket.remove(savedBasket[index2]);
    }
    CoreSession.currentBasket = basket;
    CoreSession.ordersBasket.add(basket);
    savedBasket.add(basket);

    prefs.setString(ConstantStorage.orderBasket, json.encode(savedBasket));
    //ItemService.cartCount = itemList.length;
    TapPage.cartValue.value = itemList.length;

  }

  saveCustomerBasket(items) async {
    var body = jsonEncode({
      'packs': items,
      'token': CoreSession.deviceToken,
    });
    final String urlValue = this._url + 'SaveCustomerBasket';
    try {
      final response = await http.post(
        Uri.parse(urlValue),
        headers: Global.httpOptions,
        body: body,
      );
      return json.decode(response.body);
    } catch (error) {
      print(error);
    }
  }

  Future<dynamic> getItemDocuments(int itemId) async {
    final String urlValue =
        this._url + "GetItemDocuments" + "?itemId=" + itemId.toString();
    try {
      final response = await http.get(
        Uri.parse(urlValue),
        headers: Global.httpOptions,
      );
      return json.decode(response.body);
    } catch (error) {
      print(error);
    }
  }
}
