import 'dart:convert'; import 'dart:io'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:geolocator/geolocator.dart'; import 'package:healthcare_user/common/settings.dart'; import 'package:healthcare_user/common/zoom_image.dart'; import 'package:healthcare_user/models/pharmacies_model.dart'; import 'package:healthcare_user/prescriptions/add_prescriptions.dart'; import 'package:healthcare_user/prescriptions/oreder_medicines.dart'; import 'package:image_picker/image_picker.dart'; import 'package:photo_view/photo_view.dart'; import 'package:healthcare_user/models/prescriptions_model.dart'; class Prescriptions extends StatefulWidget { const Prescriptions({Key? key}) : super(key: key); @override State createState() => _PrescriptionsState(); } class _PrescriptionsState extends State { final ImagePicker _picker = ImagePicker(); String Url = ''; List pharmaciesList = []; List prescriptionsList = []; List prescriptionsListOriginal = []; List FilteredList = []; bool isPharmacyDataLoading = false; bool isPrescriptionsDataLoading = false; bool isSereverIssue = false; double lat = 0; double lng = 0; String userAddress = ''; String dropdownArea = '2'; //String dropdownType = 'Tank'; var AreaItems = ['2', '5', '10', '25', '50', '100']; List pharmaciesCheckboxes = []; bool isLoading=false; Future getAllPharmaciesData(var distance) async { isPharmacyDataLoading=true; try { var pharmacyResponse = await AppSettings.getAllpharmacies(); setState(() { pharmaciesList = ((jsonDecode(pharmacyResponse)['data']) as List) .map((dynamic model) { return PharmaciesModel.fromJson(model); }).toList(); FilteredList = []; pharmaciesList.forEach((element) async { var distanceInM; if (distance == '2') { distanceInM = 2000; } else if (distance == '5') { distanceInM = 5000; } else if (distance == '10') { distanceInM = 10000; } else if (distance == '25') { distanceInM = 25000; } else if (distance == '50') { distanceInM = 50000; } else if (distance == '100') { distanceInM = 100000; } double distanceInMeters = await Geolocator.distanceBetween( element.lat, element.lng, lat, lng); if (distanceInMeters <= distanceInM) { FilteredList.add(element); } }); isPharmacyDataLoading = false; }); } catch (e) { setState(() { isPharmacyDataLoading = false; isSereverIssue = true; }); } } Future getAllPrescriptions() async { isPrescriptionsDataLoading=true; try { var response = await AppSettings.getAllPrescriptions(); setState(() { prescriptionsListOriginal = ((jsonDecode(response)) as List) .map((dynamic model) { return PrescriptionsModel.fromJson(model); }).toList(); prescriptionsList=prescriptionsListOriginal.reversed.toList(); isPrescriptionsDataLoading = false; }); } catch (e) { setState(() { isPrescriptionsDataLoading = false; isSereverIssue = true; }); } } @override void initState() { lat = AppSettings.userLatitude; lng = AppSettings.userLongitude; userAddress = AppSettings.userAddress; getAllPrescriptions(); //getAllPharmaciesData(dropdownArea); super.initState(); } Future pickImageFromGallery() async { try { final image = await _picker.pickImage(source: ImageSource.gallery); if (image == null) return; final imageTemp = File(image.path); AppSettings.preLoaderDialog(context); var res = await AppSettings.uploadImageHTTPForPrescriptions(image); print(jsonDecode(res)); Navigator.of(context, rootNavigator: true).pop(); setState(() { Url = jsonDecode(res)['pictures'][0]; }); } on PlatformException catch (e) { print('Failed to pick image: $e'); } } Future takeImageFromCamera() async { try { final image = await _picker.pickImage(source: ImageSource.camera); if (image == null) return; final imageTemp = File(image.path); AppSettings.preLoaderDialog(context); var res = await AppSettings.uploadImageHTTPForPrescriptions(image); print(jsonDecode(res)); Navigator.of(context, rootNavigator: true).pop(); setState(() { Url = jsonDecode(res)['pictures'][0]; }); } on PlatformException catch (e) { print('Failed to pick image: $e'); } } Widget _pharamciesData() { if (FilteredList.length != 0) { return Column( children: [ GridView.builder( shrinkWrap: true, physics: NeverScrollableScrollPhysics(), itemCount: FilteredList.length, itemBuilder: (context, index) { return Card( elevation: 2.0, child: CheckboxListTile( title: Padding( padding: EdgeInsets.fromLTRB(10, 10, 0, 0), child: Row( mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start, children: [ Container( width: MediaQuery.of(context).size.width * .18, height: MediaQuery.of(context).size.height * .10, decoration: BoxDecoration( shape: BoxShape.rectangle, image: DecorationImage( image: FilteredList[index].picture == '' ? AssetImage("images/logo.png") : NetworkImage( FilteredList[index].picture) as ImageProvider, // picked file fit: BoxFit.contain)), ), SizedBox( width: 5, ), Expanded( child: Container( width: MediaQuery.of(context).size.width * .70, child: Column( mainAxisAlignment: MainAxisAlignment.spaceBetween, crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( FilteredList[index] .pharmacy_name .toUpperCase(), style: wrapTextStyleBlack()), SizedBox( height: 10, ), Text( FilteredList[index] .contact_number .toUpperCase(), style: wrapTextStyleBlack()), /*Visibility( visible: FilteredList[index].supplier_alternate_phone_number!='', child: Text( FilteredList[index] .supplier_alternate_phone_number .toUpperCase(), style: wrapTextStyleBlack()),),*/ SizedBox( height: 10, ), Text( FilteredList[index] .pharmacy_address .toUpperCase(), style: wrapTextStyleBlack()), Visibility( visible: FilteredList[index].description != '', child: SizedBox( height: 10, ), ), Visibility( visible: FilteredList[index].description != '', child: Text( FilteredList[index] .description .toUpperCase(), style: wrapTextStyleBlack()), ), SizedBox( height: 10, ), /*Text( FilteredList[index] .starting_price .toUpperCase(), style: wrapTextStyleBlack()), SizedBox(height: 10,),*/ ], )), ), ], ) ), checkColor: Colors.white, activeColor: primaryColor, value: FilteredList[index].isChecked, onChanged: (val) { setState( () { FilteredList[index].isChecked = val!; }, ); if (FilteredList[index].isChecked) { pharmaciesCheckboxes.add({ 'pharmacyId': FilteredList[index] .pharmacy_id, }); } else { pharmaciesCheckboxes.removeWhere((e) => e['pharmacyId'] .toString() .toUpperCase() == FilteredList[index] .pharmacy_id .toString() .toUpperCase()); } }, ), ); }, gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 1,//.size.width * .33, childAspectRatio: MediaQuery.of(context).size.width / (MediaQuery.of(context).size.height /7)), ), ElevatedButton( style: ElevatedButton.styleFrom( primary: primaryColor, // background onPrimary: Colors.white, // foreground ), onPressed: () async { if(Url!=''&&pharmaciesCheckboxes.isNotEmpty){ AppSettings.preLoaderDialog(context); var payload = new Map(); payload["picture"] = Url.toString(); payload["pharmacies"] = pharmaciesCheckboxes; bool status = await AppSettings.getQuotation(payload); try { if (status) { Navigator.of(context, rootNavigator: true).pop(); Url=''; pharmaciesCheckboxes = []; AppSettings.longSuccessToast( "Prescription uploaded Successfully"); // Navigator.pop(context); getAllPharmaciesData(dropdownArea); /* Navigator.push( context, MaterialPageRoute( builder: (context) => ConnectionsView()), );*/ } else { Navigator.of(context, rootNavigator: true).pop(); AppSettings.longFailedToast( "Failed to upload prescription"); } } catch (exception) { AppSettings.longFailedToast("Failed to upload prescription"); print(exception); } } else{ AppSettings.longFailedToast('Please select image and pharmacies' ); } }, child: const Text('Upload'), ) ], ); } else { return Center( child: Padding( padding: EdgeInsets.fromLTRB(0, 40, 0, 0), child: isSereverIssue ? Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Image( image: AssetImage('images/serverissue.png'), // height: MediaQuery.of(context).size.height * .10, ), SizedBox( height: 20, ), Text( 'There is an issue at server please try after some time', style: serverIssueTextStyle(), ), ], ) : userAddress == '' ? Column( mainAxisAlignment: MainAxisAlignment.center, children: [ /*Image( image: AssetImage('images/resourceblue.pngs'), // height: MediaQuery.of(context).size.height * .10, ),*/ Icon( Icons.location_on_outlined, color: primaryColor, size: 40, ), SizedBox( height: 20, ), Text( 'Please select location to see near by pharmacies', style: TextStyle( color: primaryColor, fontWeight: FontWeight.bold, ), ), ], ) : Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Image( image: AssetImage('images/no_data.png'), // height: MediaQuery.of(context).size.height * .10, ), SizedBox( height: 20, ), Text( 'No Pharmacies', style: serverIssueTextStyle(), ), ], ), )); } } showPicDialog(var imageUrl){ return showDialog( context: context, barrierDismissible: false, builder: (BuildContext context) { return StatefulBuilder( builder: (BuildContext context, StateSetter setState) { return AlertDialog( title: const Text(''), content: SingleChildScrollView( child: ListBody( children: [ Container( width: MediaQuery.of(context).size.width * .10, height: MediaQuery.of(context).size.height * .50, child: PhotoView( imageProvider: NetworkImage(imageUrl) as ImageProvider, maxScale: PhotoViewComputedScale.contained * 4.0, minScale: PhotoViewComputedScale.contained, initialScale: PhotoViewComputedScale.contained, basePosition: Alignment.center, ) ) ], ), ), actions: [ TextButton( child: Text('Close', style: textButtonStyle()), onPressed: () { Navigator.of(context).pop(); }, ), ], ); }); }, ); } Widget prescriptions(var obj){ return Container( width: double.infinity, height: MediaQuery.of(context).size.height * .20, child: ListView.builder( scrollDirection: Axis.horizontal, itemCount: obj.prescriptionUrls.length, itemBuilder: (context, index) { return Column( children: [ Card( child: GestureDetector( onTap: (){ //showPicDialog(obj.prescriptionImages[index]['url']); Navigator.push( context, new MaterialPageRoute( builder: (__) => new ImageZoomPage(imageName:'Prescriptions',imageDetails:obj.prescriptionUrls[index]['url']))); }, child: Container( width: MediaQuery.of(context).size.width * .30, height: MediaQuery.of(context).size.height * .15, decoration: BoxDecoration( shape: BoxShape.rectangle, image: DecorationImage( image: NetworkImage( obj.prescriptionUrls[index] ['url']) as ImageProvider, // picked file fit: BoxFit.fill)), ), ), ), /*Expanded(child:IconButton( icon: const Icon(Icons.remove,color: Colors.red,), onPressed: () async{ }, ),)*/ ], ); }), ); } Widget _allPrescriptions(){ if (prescriptionsList.length != 0) { return Column( crossAxisAlignment: CrossAxisAlignment.end, children: [ Expanded(child:ListView.builder( padding: EdgeInsets.all(0), itemCount: prescriptionsList.length, itemBuilder: (BuildContext context, int index) { return Card( //color: prescriptionsList[index].cardColor, child: Padding( padding:EdgeInsets.all(8) , child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ prescriptions(prescriptionsList[index]), TextButton( child: const Text( 'Order Medicines', style: TextStyle(color: primaryColor), ), onPressed: () { Navigator.push( context, new MaterialPageRoute( builder: (__) => new OrderMedicines(prescriptionDetails:prescriptionsList[index]))); //signup screen }, ) ], ), ), ); }) ), Padding( padding: EdgeInsets.fromLTRB(8, 8, 8, 8), child: CircleAvatar( backgroundColor: primaryColor, radius: 40, child: Column( mainAxisSize: MainAxisSize.min, children: [ IconButton( iconSize: 40, icon: const Icon( Icons.add, color: Colors.white, ), onPressed: () async{ /*await Navigator.push( context, MaterialPageRoute( builder: (context) => AddPrescription()), );*/ Navigator.push(context, MaterialPageRoute(builder: (context) => AddPrescription())).then((value) { getAllPrescriptions(); }); //showBoreAddingDialog(); }, ), /* Padding( padding: EdgeInsets.fromLTRB(5, 0, 5, 5), child: Text( 'Add Tanks ', style: TextStyle(color: Colors.white), ), )*/ ], ), ), ), ]); } else{ return Center( child: Padding( padding: EdgeInsets.fromLTRB(0, 40, 0, 0), child: Column( crossAxisAlignment: CrossAxisAlignment.center, children: [ SizedBox(height: MediaQuery.of(context).size.height * .25,), Text('Click below icon to add new prescription'), SizedBox( height: 20, ), CircleAvatar( backgroundColor: primaryColor, radius: 40, child: IconButton( iconSize: 40, icon: const Icon( Icons.add, color: Colors.white, ), onPressed: () async { Navigator.push(context, MaterialPageRoute(builder: (context) => AddPrescription())).then((value) { getAllPrescriptions(); }); }, ), ) ], ), ) ); } } /**/ @override Widget build(BuildContext context) { return Scaffold( appBar: AppSettings.appBar('Prescriptions'), body: isPrescriptionsDataLoading?Center( child: CircularProgressIndicator( color: primaryColor, strokeWidth: 5.0, ), ): _allPrescriptions(), ); } }