import 'package:driverapp/core/enum/viewstate.dart';
import 'package:driverapp/core/model/StatusModel.dart';
import 'package:driverapp/core/model/orders/deliverd_order_res_model.dart';
import 'package:driverapp/core/model/orders/next_order_request_model.dart';
import 'package:driverapp/core/model/orders/pending_orders_res_model.dart';
import 'package:driverapp/core/model/orders/update_order_status_request_model.dart';
import 'package:driverapp/core/model/scan_qr/scan_qr_request_model.dart';
import 'package:driverapp/core/service/delivery_tracking_services.dart';
import 'package:driverapp/core/service/orders_service.dart';
import 'package:flutter/cupertino.dart';

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

class OrdersViewModel extends BaseViewModel {
  OrdersService _ordersService = locator<OrdersService>();
  DeliveryTrackingServices deliveryService = locator<DeliveryTrackingServices>();

  List<PendingOrdersRes> get orders => _ordersService.orders;

  List<DeliverdOrderResModel> get deliverdOrders =>
      _ordersService.deliveredOrderList;

  List<PendingOrdersRes> get nextOrdersList => _ordersService.nextOrdersList;
  bool isBottomSheetAppear = false;

  int get listCountDelivered => _ordersService.listCountDelivered;

  int get listCountUnDelivered => _ordersService.listCountUnDelivered;

  Future getPendingOrders(int driverAppPageID) async {
    setState(ViewState.Busy);
    await _ordersService.getPendingOrders(driverAppPageID);
    if (_ordersService.hasError) {
      error = _ordersService.error;
      setState(ViewState.Error);
    } else
      setState(ViewState.Idle);
  }

  Future getOrdersStatus() async {
    setState(ViewState.Busy);
    await _ordersService.getOrdersStatus();
    if (_ordersService.hasError) {
      error = _ordersService.error;
      setState(ViewState.Error);
    } else
      setState(ViewState.Idle);
  }

  Future getDeliveredOrders() async {
    setState(ViewState.Busy);
    await _ordersService.getDeliveredList();
    if (_ordersService.hasError) {
      error = _ordersService.error;
      setState(ViewState.Error);
    } else
      setState(ViewState.Idle);
  }

  Future insertOrder(ScanQrRequestModel _scanQrRequestModel) async {
    setState(ViewState.ErrorLocal);
    await _ordersService.insertOrder(_scanQrRequestModel);
    if (_ordersService.hasError) {
      error = _ordersService.error;
      setState(ViewState.ErrorLocal);
    } else
      setState(ViewState.Idle);
  }

  Future<ResponseModel> updateOrderStatus({@required int orderNo, @required int status, String rejectionReason}) async {
    var updateOrderStatusRequestModel
    = UpdateOrderStatusRequestModel(
        deliveryOrderID: orderNo,
        deliveryOrderStatus: status,
        rejectionReason: rejectionReason,
        cancleReason: rejectionReason);

    setState(ViewState.BusyLocal);
    await _ordersService.updateOrderStatus(updateOrderStatusRequestModel);
    if (_ordersService.hasError) {
      error = _ordersService.error;
      setState(ViewState.ErrorLocal);
      return ResponseModel(isSuccessful: false, message: error);
    } else {
      setState(ViewState.Idle);
      if(status == 2)
        moveOrderFromPendingToDelivered(orderNo);
      return ResponseModel(isSuccessful: true, message: "Successful");
    }
  }


  moveOrderFromPendingToDelivered(int orderNo) async{
    var idx = orders.indexWhere((element) => element.ePharmacyOrderNo == orderNo);
    var order = orders[idx];
    orders.removeAt(idx);
    var order_delivered = DeliverdOrderResModel.fromJson(order.toJson());
    order_delivered.description = "Delivered";
    order_delivered.descriptionN = "Delivered";
    deliverdOrders.add(order_delivered);
  }

  Future nextOrder(NextOrderRequestModel nextOrderRequestModel) async {
    setState(ViewState.BusyLocal);
    await _ordersService.nextOrder(nextOrderRequestModel);
    if (_ordersService.hasError) {
      error = _ordersService.error;
      setState(ViewState.ErrorLocal);
    } else
      setState(ViewState.Idle);
  }

  Future initDelivery(PendingOrdersRes order, {Function(@required ResponseModel response) completion}) async{
    var response = await deliveryService.initiateOrderDelivery(order);
    completion(response ?? ResponseModel(isSuccessful: false,message: "Something went wrong, Please try again later."));

    return response;
    // (true, response['ErrorEndUserMessage'] ?? response['ErrorMessage'] ?? "Successfully, Please start navigation.")
  }

  Future<ResponseModel> validateDelivery(PendingOrdersRes order, String pinCode) async{
    return await deliveryService.validateDelivery(order, pinCode);
  }

  Future<ResponseModel> resendOtpToReceiver(PendingOrdersRes order) async{
    // return await _deliveryService.validateDelivery(order, pinCode);
  }

  bool isActiveDeliveringOrder(int index){
    return deliveryService.isActiveDeliveringOrder(orders[index].ePharmacyOrderNo);
  }

  Future<List<String>> getActiveDeliveringOrders() async{
    return deliveryService.getActiveDeliveringOrders();
  }


  showBottomSheet() {
    isBottomSheetAppear = true;
    setState(ViewState.Idle);
  }

  hideBottomSheet() {
    isBottomSheetAppear = false;
    setState(ViewState.Idle);
  }
}
