import 'package:diplomaticquarterapp/config/config.dart';
import 'package:diplomaticquarterapp/config/shared_pref_kay.dart';
import 'package:diplomaticquarterapp/core/model/pharmacies/Addresses.dart';
import 'package:diplomaticquarterapp/core/model/pharmacies/LacumAccountInformation.dart';
import 'package:diplomaticquarterapp/core/model/pharmacies/ShoppingCart.dart';
import 'package:diplomaticquarterapp/core/model/pharmacies/order_detail.dart';
import 'package:diplomaticquarterapp/core/model/pharmacies/payment-checkout-data.dart';
import 'package:diplomaticquarterapp/core/service/base_service.dart';
import 'package:diplomaticquarterapp/core/viewModels/pharmacyModule/OrderPreviewViewModel.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';

class OrderPreviewService extends BaseService {
  bool isFinished = true;
  bool hasError = false;
  String errorMsg = '';

  List<Addresses> addresses = List();
  LacumAccountInformation lacumInformation;
  LacumAccountInformation lacumGroupInformation;
  List<OrderDetailModel> orderList = List();

  Future getAddresses() async {
    var customerId = await sharedPref.getString(PHARMACY_CUSTOMER_ID);
    var customerGUID = await sharedPref.getString(PHARMACY_CUSTOMER_GUID);
    Map<String, String> queryParams = {'fields': 'addresses'};
    hasError = false;
    try {
      await baseAppClient.getPharmacy("$GET_CUSTOMERS_ADDRESSES$customerId/$customerGUID", onSuccess: (dynamic response, int statusCode) {
        addresses.clear();
        response['customers'][0]['addresses'].forEach((item) {
          addresses.add(Addresses.fromJson(item));
        });
      }, onFailure: (String error, int statusCode) {
        hasError = true;
        super.error = error;
      }, queryParams: queryParams);
    } catch (error) {
      throw error;
    }
  }

  Future<Map> getShippingOption(Addresses selectedAddress) async {
    var customerId = await sharedPref.getString(PHARMACY_CUSTOMER_ID);
    Map<String, String> queryParams = Map();
    dynamic localRes;
    hasError = false;
    try {
      await baseAppClient.getPharmacy("$GET_SHIPPING_OPTIONS$customerId/${selectedAddress.id}", onSuccess: (dynamic response, int statusCode) {
        localRes = response['shipping_option'][0];
      }, onFailure: (String error, int statusCode) {
        hasError = true;
        super.error = error;
      }, queryParams: queryParams);
    } catch (error) {
      throw error;
    }
    return Future.value(localRes);
  }

  Future<Map> getShoppingCart() async {
    var customerId = await sharedPref.getString(PHARMACY_CUSTOMER_ID);
    var customerGUID = await sharedPref.getObject(PHARMACY_CUSTOMER_GUID);

    if (customerId == null) return null;

    Map<String, String> queryParams = {'shopping_cart_type': '1'};
    dynamic localRes;
    hasError = false;
    try {
      await baseAppClient.getPharmacy("$GET_SHOPPING_CART$customerId/$customerGUID", onSuccess: (dynamic response, int statusCode) {
        localRes = response;
      }, onFailure: (String error, int statusCode) {
        hasError = true;
        super.error = error;
      }, queryParams: queryParams);
    } catch (error) {
      throw error;
    }
    return Future.value(localRes);
  }

  Future<Map> changeProductQuantity(String productId, ShoppingCart product) async {
    hasError = false;
    super.error = "";
    dynamic localRes;
    Map<String, dynamic> choppingCartObject = Map();
    choppingCartObject['id'] = product.id;
    choppingCartObject['quantity'] = product.quantity;
    choppingCartObject['shopping_cart_type'] = "1";
    choppingCartObject['product_id'] = product.productId;
    choppingCartObject['customer_id'] = product.customerId;

    Map<String, dynamic> body = Map();
    body["shopping_cart_item"] = choppingCartObject;

    await baseAppClient.pharmacyPost("$GET_SHOPPING_CART$productId", isExternal: false, onSuccess: (response, statusCode) async {
      localRes = response;
    }, onFailure: (String error, int statusCode) {
      hasError = true;
      super.error = error;
    }, body: body);

    return Future.value(localRes);
  }

  Future<Map> deleteProduct(String productId) async {
    hasError = false;
    super.error = "";
    dynamic localRes;

    Map<String, dynamic> body = Map();

    await baseAppClient.pharmacyPost("$DELETE_SHOPPING_CART$productId", isExternal: false, onSuccess: (response, statusCode) async {
      localRes = response;
    }, onFailure: (String error, int statusCode) {
      hasError = true;
      super.error = error;
    }, body: body);

    return Future.value(localRes);
  }

  Future<Map> deleteShoppingCart() async {
    var customerId = await sharedPref.getString(PHARMACY_CUSTOMER_ID);

    hasError = false;
    super.error = "";
    dynamic localRes;

    await baseAppClient.getPharmacy("$DELETE_SHOPPING_CART_ALL$customerId/ShoppingCart", onSuccess: (response, statusCode) async {
      localRes = response;
    }, onFailure: (String error, int statusCode) {
      hasError = true;
      super.error = error;
    });

    return Future.value(localRes);
  }

  Future getLacumAccountInformation(String identificationNo) async {
    hasError = false;
    super.error = "";

    Map<String, dynamic> body = Map();
    body['IdentificationNo'] = identificationNo;

    try {
      await baseAppClient.post(GET_LACUM_ACCOUNT_INFORMATION, onSuccess: (response, statusCode) async {
        lacumInformation = LacumAccountInformation.fromJson(response);
      }, onFailure: (String error, int statusCode) {
        hasError = true;
        super.error = error;
      }, body: body);
    } catch (error) {
      throw error;
    }
  }

  Future getLacumGroupInformation(String identificationNo) async {
    hasError = false;
    super.error = "";

    Map<String, dynamic> body = Map();
    body['IdentificationNo'] = identificationNo;
    body['AccountNumber'] = "${lacumInformation.yahalaAccountNo}";

    try {
      await baseAppClient.post(GET_LACUM_GROUP_INFORMATION, onSuccess: (response, statusCode) async {
        lacumGroupInformation = LacumAccountInformation.fromJson(response);
      }, onFailure: (String error, int statusCode) {
        hasError = true;
        super.error = error;
      }, body: body);
    } catch (error) {
      throw error;
    }
  }

  Future makeOrder(PaymentCheckoutData paymentCheckoutData, List<ShoppingCart> shoppingCarts, bool isLakumEnabled) async {
    paymentCheckoutData.address.isChecked = true;
    hasError = false;
    super.error = "";

    var languageID = await sharedPref.getStringWithDefaultValue(APP_LANGUAGE, 'en');
    var customerId = await sharedPref.getString(PHARMACY_CUSTOMER_ID);

    Map<String, dynamic> orderBody = Map();
    orderBody['rx_attachments'] = "";
    orderBody['customer_language_id'] = languageID == 'ar' ? 2 : 1;
    orderBody['billing_address'] = paymentCheckoutData.address;
    orderBody['pick_up_in_store'] = false;
    orderBody['payment_method_system_name'] = "Payments.PayFort";

    if (paymentCheckoutData.shippingOption.shippingRateComputationMethodSystemName == "Shipping.Aramex")
      orderBody['shipping_method'] = "Aramex Domestic";
    else
      orderBody['shipping_method'] = "Fixed Price";

    orderBody['shipping_rate_computation_method_system_name'] = paymentCheckoutData.shippingOption.shippingRateComputationMethodSystemName;
    orderBody['customer_id'] = int.parse(customerId);
    orderBody['custom_values_xml'] = "PaymentOption:${getPaymentOptionName(paymentCheckoutData.paymentOption)}";
    orderBody['shippingOption'] = paymentCheckoutData.shippingOption;
    orderBody['shipping_address'] = paymentCheckoutData.address;
    orderBody['lakum_amount'] = isLakumEnabled ? paymentCheckoutData.usedLakumPoints : 0;

    List<Map<String, dynamic>> itemsList = List();
    shoppingCarts.forEach((item) {
      Map<String, dynamic> orderItemsBody = Map();
      orderItemsBody['product_id'] = item.product.id;
      orderItemsBody['quantity'] = item.quantity;
      itemsList.add(orderItemsBody);
    });
    orderBody['order_items'] = itemsList;

    Map<String, dynamic> body = Map();
    body['order'] = orderBody;

    try {
      await baseAppClient.pharmacyPost(ORDER_SHOPPING_CART, isExternal: false, isAllowAny: true, onSuccess: (response, statusCode) async {
        orderList.clear();
        response['orders'].forEach((item) {
          orderList.add(OrderDetailModel.fromJson(item));
          print(response);
        });
      }, onFailure: (String error, int statusCode) {
        hasError = true;
        super.error = error;
      }, body: body);
    } catch (error) {
      throw error;
    }
  }

  String getPaymentOptionName(PaymentOption paymentOption) {
    switch (paymentOption.index) {
      case 0:
        return "MADA";
        break;
      case 1:
        return "SADAD";
        break;
      case 2:
        return "VISA";
        break;
      case 3:
        return "MASTERCARD";
        break;
      case 4:
        return "INSTALLMENT";
        break;
      case 5:
        return "ApplePay";
        break;
      default:
        return "";
    }
  }

  Future<LatLng> getDriverLocation(dynamic driverId) async {
    Map<String, dynamic> jsonBody = Map();
    jsonBody['DriverID'] = driverId;

    LatLng coordinates;
    await baseAppClient.post(DRIVER_LOCATION, onSuccess: (response, statusCode) async {
      if (statusCode == 200) {
        dynamic locationObject = response['PatientER_GetDriverLocationList'][0];
        double lat = locationObject['Latitude'];
        double lon = locationObject['Longitude'];
        if (lat != null && lon != null) {
          coordinates = LatLng(lat, lon);
        }
      }
    }, onFailure: (String error, int statusCode) {}, body: jsonBody);

    return coordinates;
  }
}
