import 'package:diplomaticquarterapp/config/shared_pref_kay.dart';
import 'package:diplomaticquarterapp/core/enum/viewstate.dart';
import 'package:diplomaticquarterapp/core/model/pharmacies/Addresses.dart';
import 'package:diplomaticquarterapp/core/model/pharmacies/LacumAccountInformation.dart';
import 'package:diplomaticquarterapp/core/model/pharmacies/ShippingOption.dart';
import 'package:diplomaticquarterapp/core/model/pharmacies/ShoppingCart.dart';
import 'package:diplomaticquarterapp/core/model/pharmacies/ShoppingCartResponse.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/parmacyModule/order-preview-service.dart';
import 'package:diplomaticquarterapp/core/viewModels/pharmacyModule/pharmacy_module_view_model.dart';

import '../../../locator.dart';
import '../base_view_model.dart';

class OrderPreviewViewModel extends BaseViewModel {
  OrderPreviewService _orderService = locator<OrderPreviewService>();

  List<Addresses> get addresses => _orderService.addresses;
  LacumAccountInformation get lacumInformation =>
      _orderService.lacumInformation;
  List<OrderDetailModel> get orderListModel => _orderService.orderList;

  PharmacyModuleViewModel pharmacyModuleViewModel =
  locator<PharmacyModuleViewModel>();

  ShoppingCartResponse cartResponse = ShoppingCartResponse();
  PaymentCheckoutData paymentCheckoutData = PaymentCheckoutData();
  double totalAdditionalShippingCharge = 0;

  Future getOrderPreviewData() async {
    setState(ViewState.Busy);
    await _orderService.getAddresses();
    if (_orderService.hasError) {
      error = _orderService.error;
      setState(ViewState.Error);
    } else {
      getShoppingCart();
    }
  }

  Future getShoppingCart() async {
    setState(ViewState.Busy);
    await _orderService.getShoppingCart().then((res) {
      _handleGetShoppingCartResponse(res);
    });
    if (_orderService.hasError) {
      error = _orderService.error;
      setState(ViewState.Error);
    } else {
      if (paymentCheckoutData != null) {
        paymentCheckoutData.cartDataVisible = true;
      }
      setState(ViewState.Idle);
    }
  }

  Future <ShoppingCartResponse> changeProductQuantity(ShoppingCart product) async {
    setState(ViewState.Busy);
    var resp = await _orderService.changeProductQuantity(product.id, product);
    var object = _handleGetShoppingCartResponse(resp);
    if (_orderService.hasError) {
      error = _orderService.error;
      setState(ViewState.ErrorLocal);
    } else {
      setState(ViewState.Idle);
    }
    return object;
  }

  Future<ShoppingCartResponse> deleteProduct(ShoppingCart product) async {
    setState(ViewState.Busy);
    var resp = await _orderService.deleteProduct(product.id);
    var object = _handleGetShoppingCartResponse(resp);
    if (_orderService.hasError) {
      error = _orderService.error;
      setState(ViewState.Error);
    } else {
      setState(ViewState.Idle);
    }
    return object;
  }

  Future deleteShoppingCart() async {
    setState(ViewState.Busy);
    await _orderService.deleteShoppingCart().then((res) {
      _handleGetShoppingCartResponse(res);
    });
    if (_orderService.hasError) {
      error = _orderService.error;
      setState(ViewState.Error);
    } else {
      setState(ViewState.Idle);
    }
  }

  ShoppingCartResponse _handleGetShoppingCartResponse(Map res) {
    totalAdditionalShippingCharge = 0;
    if (res == null) {
      error = "response is null";
      setState(ViewState.Error);
      return null;
    }
    print(res);
    cartResponse.itemCount = res["item_count"];
    cartResponse.quantityCount = res["quantity_count"];
    cartResponse.subtotal = res["subtotal"];
    cartResponse.subtotalWithVat = res["subtotal_with_vat"];
    cartResponse.subtotalVatAmount = res["subtotal_vat_amount"];
    cartResponse.subtotalVatRate = res["subtotal_vat_rate"];
    cartResponse.shoppingCarts = List();
    res["shopping_carts"].forEach((item) {
      ShoppingCart shoppingCart = ShoppingCart.fromJson(item);
      cartResponse.shoppingCarts.add(shoppingCart);
      totalAdditionalShippingCharge += shoppingCart.product.additionalShippingCharge;
    });
    cartResponse.updateShoppingCard();
    return cartResponse;
  }

  String getPaymentOptionImage(PaymentOption paymentOption) {
    String assetFile = "assets/images/pharmacy_module/payment/";
    switch (paymentOption.index) {
      case 0:
        return "${assetFile}mada.png";
        break;
      case 1:
        return "${assetFile}sadad.png";
        break;
      case 2:
        return "${assetFile}visa.png";
        break;
      case 3:
        return "${assetFile}mastercard.png";
        break;
      case 4:
        return "${assetFile}installment.png";
        break;
      default:
        return "";
    }
  }

  String getPaymentOptionName(PaymentOption paymentOption) {
    return _orderService.getPaymentOptionName(paymentOption);
  }

  getInformationsByAddress() async {
    await getLacumAccountInformation();
    await getShippingOption();
  }

  getLacumAccountInformation() async {
    setState(ViewState.Busy);
    await _orderService.getLacumAccountInformation();
    if (_orderService.hasError) {
      error = _orderService.error;
      setState(ViewState.Error);
    } else {
      getLacumGroupData();
    }
  }

  Future getLacumGroupData() async {
    setState(ViewState.Busy);
    await _orderService.getLacumGroupInformation();
    paymentCheckoutData.lacumInformation = _orderService.lacumGroupInformation;
    paymentCheckoutData.usedLakumPoints = paymentCheckoutData.lacumInformation.lakumInquiryInformationObjVersion.pointsBalanceAmount;
    if (_orderService.hasError) {
      error = _orderService.error;
      setState(ViewState.Error);
    } else {
      setState(ViewState.Idle);
    }
  }

  getShippingOption() async {
    setState(ViewState.Busy);
    await _orderService.getShippingOption(paymentCheckoutData.address).then((res) {
      paymentCheckoutData.shippingOption =  ShippingOption.fromJson(res);
      paymentCheckoutData.updateData();
    });
    if (_orderService.hasError) {
      error = _orderService.error;
      setState(ViewState.Error);
    } else {
      setState(ViewState.Idle);
    }
  }

  Future makeOrder() async {
    setState(ViewState.Busy);
    await pharmacyModuleViewModel.generatePharmacyToken();

    await _orderService.makeOrder(paymentCheckoutData, cartResponse.shoppingCarts);
    if (_orderService.hasError) {
      error = _orderService.error;
      setState(ViewState.ErrorLocal);
    } else {
      setState(ViewState.Idle);
    }
  }
}

enum PaymentOption { meda, sadad, visa, mastercard, installments }
