import 'dart:async';

import 'package:hmg_patient_app/config/config.dart';
import 'package:hmg_patient_app/config/shared_pref_kay.dart';
import 'package:hmg_patient_app/core/enum/viewstate.dart';
import 'package:hmg_patient_app/core/model/AlHabibMedicalService/ComprehensiveMedicalCheckup/GetCMCAllOrdersResponseModel.dart';
import 'package:hmg_patient_app/core/model/prescriptions/prescriptions_order.dart';
import 'package:hmg_patient_app/core/service/AlHabibMedicalService/customer_addresses_service.dart';
import 'package:hmg_patient_app/core/service/base_service.dart';
import 'package:hmg_patient_app/core/service/parmacyModule/parmacy_module_service.dart';
import 'package:hmg_patient_app/locator.dart';
import 'package:hmg_patient_app/models/rrt/RRTProcedureList.dart';
import 'package:hmg_patient_app/models/rrt/service_price.dart';
import 'package:hmg_patient_app/services/appointment_services/GetDoctorsList.dart';
import 'package:hmg_patient_app/services/pharmacy_services/pharmacyAddress_service.dart';
import 'package:hmg_patient_app/uitl/app_toast.dart';

import '../base_view_model.dart';

class RRTService extends BaseService {}

class _RRTServiceData {
  List<GetCMCAllOrdersResponseModel> pendingOrders = [];
  List<GetCMCAllOrdersResponseModel> completedOrders = [];
  ServicePrice servicePrice =  ServicePrice();

// RRTProcedureList rrtProcedureList;
}

class RRTViewModel extends BaseViewModel {
  var _service = RRTService();
  late int createdRequestNo;
  var _pharmacy_service = locator<PharmacyModuleService>();
  var _pharmacy_address_service = locator<PharmacyAddressService>();
  CustomerAddressesService _customerAddressesService = locator<CustomerAddressesService>();
  List<VidaProcedureList> rrtProcedureList = [];

  List<AddressInfo> get addressesList => _customerAddressesService.addressesList;

  _RRTServiceData rrtServiceData = _RRTServiceData();

  Future<_RRTServiceData> loadRequiredData(int languageID) async {
    // await getServicePrice();
    // await getAllOrders();
    await getProcedureDetails(languageID);
    await getAllOrdersRC();
    // getProcedureDetails();
    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;
    var localRes;
    int requestNo;
    await _service.baseAppClient.post(PATIENT_ER_INSERT_PRES_ORDER, body: body, onSuccess: (response, statusCode) {
      requestNo = response['RequestNo'];
      return requestNo;
    }, onFailure: (error, statusCode) {
      AppToast.showErrorToast(message: error);
      return error;
    });
  }

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

    await _service.baseAppClient.post(ADD_RRT_ORDER_RC, isRCService: true, body: body, onSuccess: (response, statusCode) {
      createdRequestNo = response['response'];
      Future.value(createdRequestNo);
    }, onFailure: (error, statusCode) {
      AppToast.showErrorToast(message: error);
      return error;
    });
  }

  // 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"];
      rrtServiceData.completedOrders.clear();
      rrtServiceData.pendingOrders.clear();
      if (data != null && data is List) {
        data.forEach((json) {
          if (json["ServiceID"] == 5) {
            if (json["Status"] == 1 || json["Status"] == 2) {
              // Pending
              rrtServiceData.pendingOrders.add(GetCMCAllOrdersResponseModel.fromJson(json));
            }
            rrtServiceData.completedOrders.add(GetCMCAllOrdersResponseModel.fromJson(json));
          }
        });
      }
    }, onFailure: (error, statusCode) {
      AppToast.showErrorToast(message: error);
    });
    return rrtServiceData;
  }

  Future<_RRTServiceData> getAllOrdersRC() async {
    await _service.baseAppClient.post(GET_ALL_RRT_ORDERS_RC, isRCService: true, body: {}, onSuccess: (response, statusCode) {
      var data = response["response"];
      rrtServiceData.completedOrders.clear();
      rrtServiceData.pendingOrders.clear();
      if (data != null && data is List) {
        data.forEach((json) {
          if (json["StatusId"] == 1 || json["StatusId"] == 2) {
            // Pending
            rrtServiceData.pendingOrders.add(GetCMCAllOrdersResponseModel.fromJson(json));
          }
          rrtServiceData.completedOrders.add(GetCMCAllOrdersResponseModel.fromJson(json));
        });
      }
    }, onFailure: (error, statusCode) {
      AppToast.showErrorToast(message: error);
    });
    return rrtServiceData;
  }

  Future<_RRTServiceData> getProcedureDetails(int languageID) async {
    DoctorsListService service = new DoctorsListService();
    await service.getRRTProcedures(15, languageID).then((res) {
      rrtProcedureList.clear();
      var data = res["Vida_ProcedureList"];
      data.forEach((json) {
        rrtProcedureList.add(VidaProcedureList.fromJson(json));
      });
      print(rrtProcedureList.length);
    }).catchError((err) {
      AppToast.showErrorToast(message: err);
      print(err);
    });
    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;
          return servicePrice;
        }
      }
      
    }, onFailure: (error, statusCode) {
      AppToast.showErrorToast(message: error);
      return error;
    });
  }

  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;
      rrtServiceData.pendingOrders.remove(order);
    }, onFailure: (error, statusCode) {
      AppToast.showErrorToast(message: error);
      success = false;
    });
    return Future.value(success);
  }

  Future<bool> cancelOrderRC(GetCMCAllOrdersResponseModel order, {String reason = ""}) async {
    Map<String, dynamic> body = {"Id": order.iD, "ClickButton": 14};
    var success = false;
    await _service.baseAppClient.post(UPDATE_RRT_ORDER_RC, isRCService: true, body: body, onSuccess: (response, statusCode) {
      success = true;
      rrtServiceData.pendingOrders.remove(order);
    }, onFailure: (error, statusCode) {
      AppToast.showErrorToast(message: error);
      success = false;
    });
    return Future.value(success);
  }

  Future<List<AddressInfo>?> 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);
  }

  Future getCustomerAddresses() async {
    setState(ViewState.Busy);
    await _customerAddressesService.getCustomerAddresses();
    if (_customerAddressesService.hasError) {
      error = _customerAddressesService.error!;
      setState(ViewState.ErrorLocal);
    } else {
      setState(ViewState.Idle);
    }
  }

  Future getCustomerInfo() async {
    setState(ViewState.Busy);
    await _pharmacy_service.generatePharmacyToken();

    if (_customerAddressesService.hasError) {
      error = _customerAddressesService.error!;
      await _pharmacy_service.createUser();
      setState(ViewState.ErrorLocal);
    } else {
      await _pharmacy_service.createUser();
      if (!_pharmacy_service.hasError) await getCustomerAddresses();
    }

    // setState(ViewState.Busy);
    // await _pharmacy_service.generatePharmacyToken();
    // if (_customerAddressesService.hasError) {
    //   error = _customerAddressesService.error;
    //   await _pharmacy_service.createUser();
    //   await getCustomerAddresses();
    //   setState(ViewState.ErrorLocal);
    // } else {
    //   await _customerAddressesService.getCustomerInfo();
    //   await getCustomerAddresses();
    // }
  }
}
