
import 'package:hmg_patient_app/config/config.dart';
import 'package:hmg_patient_app/config/shared_pref_kay.dart';
import 'package:hmg_patient_app/core/model/blooddonation/blood_groub_details.dart';
import 'package:hmg_patient_app/core/model/my_balance/AdvanceModel.dart';
import 'package:hmg_patient_app/core/model/my_balance/patient_advance_balance_amount.dart';
import 'package:hmg_patient_app/core/model/my_balance/patient_info.dart';
import 'package:hmg_patient_app/core/model/my_balance/patient_info_and_mobile_number.dart';
import 'package:hmg_patient_app/core/service/AuthenticatedUserObject.dart';
import 'package:hmg_patient_app/core/service/base_service.dart';
import 'package:hmg_patient_app/locator.dart';
import 'package:hmg_patient_app/models/FamilyFiles/GetAllSharedRecordByStatusResponse.dart';
import 'package:hmg_patient_app/models/FamilyFiles/GetAllSharedRecordsByStatusReq.dart';
import 'package:hmg_patient_app/services/family_files/family_files_provider.dart';
import 'package:hmg_patient_app/uitl/app_toast.dart';

class MyBalanceService extends BaseService {
  List<PatientAdvanceBalanceAmount> patientAdvanceBalanceAmountList =[];
  dynamic totalAdvanceBalanceAmount;
  List<PatientInfo> patientInfoList =[];
  GetAllSharedRecordsByStatusResponse getAllSharedRecordsByStatusResponse =
      GetAllSharedRecordsByStatusResponse();
   PatientInfoAndMobileNumber? patientInfoAndMobileNumber;
  String? logInTokenID;
  String? verificationCode;
  String updatedRegisterBloodMessage = "";
  AuthenticatedUserObject authenticatedUserObject =
      locator<AuthenticatedUserObject>();

  // MyBalanceService() {
  //   // getFamilyFiles();
  // }

  getPatientAdvanceBalanceAmount() async {
    hasError = false;
    super.error = "";
    await baseAppClient.post(GET_PATIENT_AdVANCE_BALANCE_AMOUNT,
        onSuccess: (response, statusCode) async {
      patientAdvanceBalanceAmountList.clear();
      response['List_PatientAdvanceBalanceAmount'].forEach((item) {
        patientAdvanceBalanceAmountList
            .add(PatientAdvanceBalanceAmount.fromJson(item));
      });
      totalAdvanceBalanceAmount = response['TotalAdvanceBalanceAmount'];
    }, onFailure: (String error, int statusCode) {
      hasError = true;
      super.error = error;
    }, body: Map());
  }

  getPatientInfoByPatientID({required String id}) async {
    hasError = false;
    super.error = "";
    Map<String, dynamic> body = Map();
    body['SearchPatientID'] = int.parse(id);
    body['isDentalAllowedBackend'] = false;
    await baseAppClient.post(GET_PATIENT_INFO_BY_ID,
        onSuccess: (response, statusCode) async {
      patientInfoList.clear();
      response['GetPatientInfoByPatientIDList'].forEach((item) {
        patientInfoList.add(PatientInfo.fromJson(item));
      });
    }, onFailure: (String error, int statusCode) {
      hasError = true;
      super.error = error;
    }, body: body);
  }

  getPatientInfoByPatientIDAndMobileNumber(AdvanceModel advanceModel) async {
    hasError = false;
    super.error = "";
    Map<String, dynamic> body = Map();
    body['isDentalAllowedBackend'] = false;
    body['MobileNo'] = advanceModel.mobileNumber;
    body['ProjectID'] = advanceModel.hospitalsModel!.iD;
    body['PatientID'] = advanceModel.fileNumber;

    await baseAppClient.post(GET_PATIENT_INFO_BY_ID_AND_MOBILE_NUMBER,
        onSuccess: (response, statusCode) async {
      response['List_PatientInfo'].forEach((item) {
        patientInfoAndMobileNumber = PatientInfoAndMobileNumber.fromJson(item);
      });
    }, onFailure: (String error, int statusCode) {
      hasError = true;
      super.error = error;
      super.error = error;
    }, body: body);
  }

  sendActivationCodeForAdvancePayment({required int patientID, required int projectID}) async {
    hasError = false;
    super.error = "";
    Map<String, dynamic> body = Map();
    body['PatientID'] = patientID;
    body['ProjectID'] = projectID;
    body['isDentalAllowedBackend'] = false;

    await baseAppClient.post(SEND_ACTIVATION_CODE_FOR_ADVANCE_PAYMENT,
        onSuccess: (response, statusCode) async {
      logInTokenID = response['LogInTokenID'];
      verificationCode = response['VerificationCode'];
    }, onFailure: (String error, int statusCode) {
      hasError = true;
      super.error = error;
      super.error = error;
    }, body: body);
  }

  checkActivationCodeForAdvancePayment({required String activationCode}) async {
    hasError = false;
    super.error = "";
    Map<String, dynamic> body = Map();
    body['activationCode'] = activationCode;
    body['PatientMobileNumber'] = 'XXXXXXXXXX';
    body['isDentalAllowedBackend'] = false;
    body['LogInTokenID'] = logInTokenID;

    await baseAppClient.post(CHECK_ACTIVATION_CODE_FOR_ADVANCE_PAYMENT,
        onSuccess: (response, statusCode) async {},
        onFailure: (String error, int statusCode) {
      hasError = true;
      super.error = error;
      super.error = error;
    }, body: body);
  }

  getSharedRecordByStatus() async {
    try {
      var request = GetAllSharedRecordsByStatusReq();
      request.status = 0;
      await baseAppClient.post(GET_SHARED_RECORD_BY_STATUS,
          onSuccess: (dynamic response, int statusCode) {
        sharedPref.setObject(FAMILY_FILE, response);
        getAllSharedRecordsByStatusResponse =
            GetAllSharedRecordsByStatusResponse.fromJson(response);
      }, onFailure: (String error, int statusCode) {
        AppToast.showErrorToast(message: error);
        hasError = true;
        super.error = error;
      }, body: request.toJson());
    } catch (error) {
      print(error);
      hasError = true;
      super.error = error.toString();
    }
  }

  getFamilyFiles() async {
    if (await sharedPref.getObject(FAMILY_FILE) != null) {
      getAllSharedRecordsByStatusResponse =
          GetAllSharedRecordsByStatusResponse.fromJson(
              await sharedPref.getObject(FAMILY_FILE));
      return getAllSharedRecordsByStatusResponse;
    } else {
      return await getSharedRecordByStatus();
    }
  }

  Future updateBloodGroup(List_BloodGroupDetailsModel detailsModel) async {
    hasError = false;
    await getUser();
    var languageID =
        await sharedPref.getStringWithDefaultValue(APP_LANGUAGE, 'ar');
    Map<String, dynamic> body = Map();
    body['City'] = detailsModel.city;
    body['cityCode'] = detailsModel.cityCode;
    body['Gender'] = detailsModel.gender;
    body['BloodGroup'] = detailsModel.bloodGroup;
    body['CellNumber'] = user.mobileNumber;
    body['LanguageID'] = languageID;
    body['NationalID'] = user.nationalityID;
    body['ZipCode'] = user.zipCode ?? "+966";
    body['isDentalAllowedBackend'] = false;

    await baseAppClient.post(BLOOD_DONATION_REGISTER_BLOOD_TYPE,
        onSuccess: (dynamic response, int statusCode) {
      updatedRegisterBloodMessage = response['ErrorEndUserMessage'];
    }, onFailure: (String error, int statusCode) {
      hasError = true;
      super.error = error;
      if(error == null){
        super.error = "Something went wrong";
      }
    }, body: body);
  }

  Future addUserAgreementForBloodDonation() async {
    hasError = false;
    var languageID =
    await sharedPref.getStringWithDefaultValue(APP_LANGUAGE, 'ar');
    Map<String, dynamic> body = Map();
    body['IsAgreed'] = true;
    body['LanguageID'] = languageID;
    body['isDentalAllowedBackend'] = false;

    await baseAppClient.post(ADD_USER_AGREEMENT_FOR_BLOOD_DONATION,
        onSuccess: (dynamic response, int statusCode) {
        }, onFailure: (String error, int statusCode) {
          hasError = true;
          super.error = error;
        }, body: body);
  }
}
