
import 'dart:async';
import 'dart:convert';

import 'package:diplomaticquarterapp/config/config.dart';
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/prescriptions/prescriptions_order.dart';
import 'package:diplomaticquarterapp/core/service/base_service.dart';
import 'package:diplomaticquarterapp/core/service/parmacyModule/parmacy_module_service.dart';
import 'package:diplomaticquarterapp/locator.dart';
import 'package:diplomaticquarterapp/models/rrt/service_price.dart';
import 'package:diplomaticquarterapp/services/pharmacy_services/pharmacyAddress_service.dart';
import 'package:diplomaticquarterapp/uitl/app_toast.dart';
import 'package:flutter/cupertino.dart';

import '../base_view_model.dart';


class RRTService extends BaseService{

}
class _RRTServiceData{
  List<PrescriptionsOrder> pendingOrders = [];
  List<PrescriptionsOrder> completedOrders = [];
  ServicePrice servicePrice;
}

class  RRTViewModel extends BaseViewModel{
  var _service = RRTService();
  var _pharmacy_service = locator<PharmacyModuleService>();
  var _pharmacy_address_service = locator<PharmacyAddressService>();
  
  _RRTServiceData rrtServiceData = _RRTServiceData();

  Future<_RRTServiceData> loadRequiredData() async{
    await getServicePrice();
    await getAllOrders();
    return rrtServiceData;
  }

  Future<int> createOrder(Map<String, dynamic> body) async{
    body['IdentificationNo'] = user.patientIdentificationNo;
    body['NationalityID'] = user.nationalityID;
    body['CreatedBy'] = user.patientIdentificationType;
    body['OrderServiceID'] = 5;

    int requestNo;
    await _service.baseAppClient.post(PATIENT_ER_INSERT_PRES_ORDER, body: body, onSuccess: (response, statusCode){
        requestNo = response['RequestNo'];
    }, onFailure: (error, statusCode){
      AppToast.showErrorToast(message: error);
    });
    return requestNo;
  }

  // Service ID: 4 ==  RRT
  Future<_RRTServiceData> getAllOrders() async{
    await _service.baseAppClient.post(GET_PRESCRIPTIONS_ALL_ORDERS, body: {}, onSuccess: (response, statusCode){
      var data = response["PatientER_GetPatientAllPresOrdersList"];
      if(data != null && data is List){
        data.forEach((json){
          if(json["ServiceID"] == 5){
            if(json["Status"] == 1){ // Pending
              rrtServiceData.pendingOrders.clear();
              rrtServiceData.pendingOrders.add(PrescriptionsOrder.fromJson(json));
            }else if (json["Status"] == 3){ //  Completed
              rrtServiceData.completedOrders.clear();
              rrtServiceData.completedOrders.add(PrescriptionsOrder.fromJson(json));
            }
          }
          return Future.error("404");
        });
      }
    }, onFailure: (error, statusCode){
      AppToast.showErrorToast(message: error);
    });
    return rrtServiceData;
  }


  Future getOrderDetails() async{
    return null;
  }


  Future getAllQuestions() async{
    dynamic  response_;
    await _service.baseAppClient.post(GET_ALL_RRT_QUESTIONS, body: {}, onSuccess: (response, statusCode){
      response_ = response;
    }, onFailure: (error, statusCode){
      AppToast.showErrorToast(message: error);
    });
    return response_;
  }


  Future<ServicePrice> getServicePrice() async{
    Map<String,dynamic> body = {"IdentificationNo":user.patientIdentificationNo};
    ServicePrice  servicePrice;
    await _service.baseAppClient.post(GET_RRT_SERVICE_PRICE, body: body, onSuccess: (response, statusCode){
      var data = response['PatientE_RealRRT_GetServicePriceList'];
      if(data != null && data is List){
        var priceData = data.first;
        if(priceData != null){
          servicePrice = ServicePrice.fromJson(priceData);
          rrtServiceData.servicePrice = servicePrice;
        }
      }
    }, onFailure: (error, statusCode){
      AppToast.showErrorToast(message: error);
    });
    return servicePrice;
  }

  Future<bool> cancelOrder(PrescriptionsOrder order, {String reason = ""}) async{
    var body = {"PresOrderID":order.iD, "PresOrderStatus":4,"EditedBy":3,"RejectionReason":reason};
    var success = false;
    await _service.baseAppClient.post(PATIENT_ER_UPDATE_PRES_ORDER, body: body, onSuccess: (response, statusCode){
      success = true;
    }, onFailure: (error, statusCode){
      AppToast.showErrorToast(message: error);
      success = false;
    });
    return Future.value(success);
  }

  Future getCancelReasons(){
  }

  Future<List<Addresses>> getAddresses() async{
    Object error;
    try{
      var token = await sharedPref.getString(PHARMACY_AUTORZIE_TOKEN);
      if(token == null)
        await _pharmacy_service.generatePharmacyToken();

      await _pharmacy_service.makeVerifyCustomer({'PatientID': user.patientID.toString()});
      await _pharmacy_address_service.getAddresses();
      return _pharmacy_address_service.addresses;
    }catch(e){
      error = e;
    }
    Future.error(error);
  }
}