· 4 years ago · Sep 12, 2021, 04:42 PM
1
2
3import 'dart:convert';
4// import 'dart:html';
5import 'package:date_time_picker/date_time_picker.dart';
6import 'package:flutter/cupertino.dart';
7import 'package:flutter/material.dart';
8import 'package:http/http.dart' as http;
9import 'package:medbo/Animation/showupAnimation.dart';
10import 'package:medbo/Booking/PathologicalMultipleBooking/testModel.dart';
11import 'package:shared_preferences/shared_preferences.dart';
12import 'AllPathLabTestModel.dart';
13import 'GetTestFeeModel.dart';
14
15
16class GetTestFeeMap {
17String? encPartnerId;
18String? encTestId;
19int? fee;
20int? discountedFee;
21int? bookingFee;
22
23GetTestFeeMap(
24 {this.encPartnerId,
25 this.encTestId,
26 this.fee,
27 this.discountedFee,
28 this.bookingFee});
29
30GetTestFeeMap.fromJson(Map<String, dynamic> json) {
31 encPartnerId = json['EncPartnerId'];
32 encTestId = json['EncTestId'];
33 //fee = json['Fee'];
34 fee = int.parse(json['Fee']);
35 // discountedFee = json['DiscountedFee'];
36 discountedFee = int.parse(json['DiscountedFee']);
37 //bookingFee = json['BookingFee'];
38 bookingFee = int.parse(json['BookingFee']);
39}
40
41Map<String, dynamic> toJson() {
42 final Map<String, dynamic> data = new Map<String, dynamic>();
43 data['EncPartnerId'] = this.encPartnerId;
44 data['EncTestId'] = this.encTestId;
45 data['Fee'] = this.fee;
46 data['DiscountedFee'] = this.discountedFee;
47 data['BookingFee'] = this.bookingFee;
48 return data;
49 }
50}
51
52
53
54class MultipleTestBooking extends StatefulWidget {
55 //const MultipleTestBooking({required Key key}) : super(key: key);
56
57 @override
58 _MultipleTestBookingState createState() => _MultipleTestBookingState();
59}
60
61class _MultipleTestBookingState extends State<MultipleTestBooking> {
62
63
64
65
66//========================================S H O W USER DETIALS IN APP DRAWER WITH SHARED PREFERENCES==================
67
68String Name="";
69String EncUserId="";
70
71// void initState(){
72// super.initState();
73// getCred();
74// }
75
76void getCred() async{
77 //HERE WE FETCH OUR CREDENTIALS FROM SHARED PREF
78 SharedPreferences pref = await SharedPreferences.getInstance();
79 setState(() {
80 Name = pref.getString("userEmail");
81 EncUserId= pref.getString("encId");
82 });
83
84}
85//========================================S H O W USER DETIALS IN APP DRAWER WITH SHARED PREFERENCES====================
86
87
88
89
90
91
92
93
94
95
96
97
98
99 int delayAmount = 500;
100
101
102 List<GetTestFeeMap> reponseArray =[]; // Storing API response || later showing test fee in table format
103 int feeSum =0;
104 int discountSum =0;
105 int bookingSum =0 ;
106
107 String eNcTestIdInList='';
108
109 // String actualFee ='';
110 // String actualDiscountFee='';
111 // String actualBookingFee='';
112
113 GetTestFeeMap? getTestFeeObj;
114
115 Partner? _selectedLab;
116 Datum? _selectedTest;
117 Future? getAllPathLabResults;
118 Future? getTestByLabResult;
119
120 String encLabId = '';
121 String encTestId = '';
122 String testName ='';
123
124 void initState() {
125 getCred();
126 super.initState();
127 getAllPathLabResults = allPathLab();
128 getTestByLabResult = getTestByLab();
129 }
130
131 String _selectedDate = DateTime.now().toString();
132
133
134
135//==================================================== BUILD =============================================================
136 @override
137 Widget build(BuildContext context) {
138 var screenWidth = MediaQuery.of(context).size.width;
139 var screenHeight = MediaQuery.of(context).size.height;
140 var blockSizeHorizontal = (screenWidth / 100);
141 var blockSizeVertical = (screenHeight / 100);
142
143 return Scaffold(
144 body: SafeArea(
145 child: SingleChildScrollView(
146 child: Container(
147 child: Column(
148 children: [
149 Padding(
150 padding: const EdgeInsets.all(8.0),
151 child: ShowUp(
152 delay: delayAmount,
153 child: ListTile(
154 title: Text("Booking Information",
155 style: TextStyle(
156 fontWeight: FontWeight.bold,
157 fontSize: blockSizeHorizontal * 5,
158 fontFamily: 'Poppins',
159 color: Theme.of(context).primaryColor,
160 )),
161 subtitle: Text("Preferred Visit Date"),
162 ),
163 ),
164 ),
165 ShowUp(
166 delay: delayAmount+450,
167 child: Container(
168 margin: EdgeInsets.only(left: 20),
169 padding: EdgeInsets.only(left: 0, right: 150),
170 decoration: BoxDecoration(
171 color: Colors.lightBlue[50],
172 borderRadius: BorderRadius.all(Radius.circular(12)),
173 ),
174 child: Padding(
175 padding: const EdgeInsets.all(8.0),
176 child: DateTimePicker(
177 initialValue: DateTime.now().toString(),
178 //initialValue:'', // initialValue or controller.text can be null, empty or a DateTime string otherwise it will throw an error.
179 type: DateTimePickerType.date,
180 dateLabelText: 'Select Date',
181 style: TextStyle(
182 fontWeight: FontWeight.bold,
183 fontSize: blockSizeHorizontal * 3.5,
184 fontFamily: 'Poppins',
185 color: Colors.green,
186 letterSpacing: 2.0,
187 ),
188 firstDate: DateTime.now(),
189 lastDate: DateTime.now().add(Duration(days: 30)),
190 // This will add one year from current date
191 validator: (value) {
192 return null;
193 },
194 onChanged: (value) {
195 if (value.isNotEmpty) {
196 setState(() {
197 _selectedDate = value;
198 });
199 }
200 },
201 onSaved: (value) {
202 if (value.isNotEmpty) {
203 _selectedDate = value;
204 }
205 },
206 ),
207 ),
208 ),
209 ),
210
211 //=========================================================== INITIAL drop down===============
212
213 ShowUp(
214 delay: delayAmount+500,
215 child: ListTile(
216 title: Text(
217 "Select Pathological Lab",
218 style: TextStyle(
219 fontWeight: FontWeight.bold,
220 fontSize: blockSizeHorizontal * 4.0,
221 fontFamily: 'Poppins',
222 color: Theme.of(context).primaryColor,
223 ),
224 ),
225 ),
226 ),
227
228 ShowUp(
229 delay: 0,
230 child: Container(
231 child: FutureBuilder<List<Partner>>(
232 future: getAllPathLabResults as Future<List<Partner>>,
233 builder: (BuildContext context, AsyncSnapshot snapshot) {
234 if (snapshot.connectionState != ConnectionState.done) {
235 return CircularProgressIndicator();
236 }
237 if (snapshot.hasError) {
238 return Text("Somthing went wrong");
239 }
240
241 if (snapshot.hasData) {
242 List<Partner> data =
243 snapshot.hasData ? snapshot.data : [];
244 return Padding(
245 padding: const EdgeInsets.only(left:20.0, right: 150),
246 child: DropdownButton<Partner>(
247 value: _selectedLab,//USER SELECTED DROPDOWN ITEM VALUE
248 hint: Text("Select Lab"),
249 //underline: SizedBox(),
250 isExpanded: true,
251 items: data.map((Partner data) => DropdownMenuItem<Partner>(
252 child: Text("${data.partnerName}"),
253 value: data,
254 )).toList().cast<DropdownMenuItem<Partner>>(),
255 onChanged: (val) {
256 setState(() {
257 _selectedLab = val!;
258
259 encLabId = val.encPartnerId; //===== Passing encLabId to my next API function
260 getTestByLabResult = getTestByLab();
261 });
262 //GetTestByLab(value!.encPartnerId); // passing encid to my next API function
263 // GetTestByLab();
264 },
265 ),
266 );
267 }
268 return Text("Waiting for Internet Connection");
269 },
270 ),
271 ),
272 ),
273
274 //=========================================================== Dependent drop down=============================
275
276 ShowUp(
277 delay: delayAmount+600,
278 child: ListTile(
279 title: Text(
280 "Test Name",
281 style: TextStyle(
282 fontWeight: FontWeight.bold,
283 fontSize: blockSizeHorizontal * 4.0,
284 fontFamily: 'Poppins',
285 color: Theme.of(context).primaryColor,
286 ),
287 ),
288 ),
289 ),
290
291 ShowUp(
292 delay: 0,
293 child: Container(
294 child: FutureBuilder<List<Datum>>(
295 future: getTestByLabResult as Future<List<Datum>>,
296 builder: (BuildContext context, AsyncSnapshot snapshot) {
297 if (snapshot.connectionState != ConnectionState.done) {
298 return CircularProgressIndicator();
299 }
300 if (snapshot.hasError) {
301 return Text("Something wrong");
302 }
303
304 if (snapshot.hasData) {
305 List<Datum> data = snapshot.hasData ? snapshot.data : [];
306
307 return Padding(
308 padding: const EdgeInsets.only(left:20.0, right: 150),
309 child: DropdownButton<Datum>(
310 value: _selectedTest,
311 hint: Text(""),
312 //underline: SizedBox(),
313 isExpanded: true,
314 items: data
315 .map((Datum data) => DropdownMenuItem<Datum>(
316 child: Text("${data.testName}"),
317 value: data,
318 ))
319 .toList()
320 .cast<DropdownMenuItem<Datum>>(),
321 onChanged: (value) {
322 print("This is the TestName : ${value!.testName}");
323 print("This is the EncTestId which is need to get Test Fee : ${value.testId}");
324 setState(() {
325 encTestId = value.testId; // == SELCTED TEST from drop down 'encTestId' needed for to get Test Fee
326 testName = value.testName;
327 _selectedTest = value;
328
329 }),
330 );
331 }
332 return Text("Waiting for Internet Connection");
333 },
334 ),
335 ),
336 ),
337 SizedBox(height: 50,),
338 ShowUp(
339 delay: delayAmount+900,
340 child: OutlinedButton(
341 onPressed: (){
342 setState(() {
343 });
344 GetTestFee();
345 },
346 child:Text("Add")),
347 ),
348
349
350 ShowUp(
351 delay: delayAmount+1000,
352 child: DataTable(
353 columnSpacing: 13.0,
354 columns: <DataColumn>[
355 //DataColumn(label: Text("encPartnerId")),
356 //DataColumn(label: Text("encTestId")),
357 DataColumn(label: Text("TestName")),
358 DataColumn(label: Text("Fee")),
359 DataColumn(label: Text("Discounted Fee")),
360 DataColumn(label: Text("Booking Fee")),
361 ],
362
363 rows:reponseArray.map((testRowData){
364 return DataRow(
365 cells: [
366 DataCell(Text(testName)),
367 DataCell(Text (testRowData.fee!.toString() )),
368 DataCell(Text(testRowData.discountedFee !.toString() )),
369 DataCell(Text(testRowData.bookingFee!.toString() ))
370 ]
371 );
372 }).toList()
373 ),
374 ),
375
376
377
378 ShowUp(
379 delay: delayAmount+ 1050,
380 child: ListTile(
381 title: Text("Total Fee: ${feeSum}\nTotal Discounted Fee: ${discountSum}\nTotal Booking Fee: ${bookingSum}" ),
382 ),
383 ),
384
385
386
387
388
389
390 ShowUp(
391 delay: delayAmount+ 1100,
392 child: OutlinedButton(onPressed: (){
393 SaveMultipleTestBooking();
394 },
395 child: Text("Save Mutiple bookking")),
396 )
397
398
399 ],
400 ),
401 ),
402 ),
403 ),
404 );
405 }
406
407
408
409
410
411
412//============================================================================All Lab list API===============================
413 Future<List<Partner>> allPathLab() async {
414 var jsonResponse;
415 var response = await http.post(Uri.parse("http://medbo.digitalicon.in/api/medboapi/AllPathLab"),
416 body: ({ }));
417 if (response.statusCode == 200) {
418 print("Correct");
419 jsonResponse = json.decode(response.body.toString());
420 print(jsonResponse);
421
422 AllPathLabTestModel dataModel = allPathLabTestModelFromJson(response.body);
423 print(dataModel.partner.length);
424 for (final item in dataModel.partner) {
425 print("This are the hte LAB name :${item.partnerName}");
426 }
427
428 List<Partner> arrData = dataModel.partner; // this "partner" is actual json array of data[]
429 return arrData;
430 } else {
431 print("Wrong URL");
432 throw Exception("Faild to fetch");
433 }
434 }
435//============================================================== Dependent Test dropdown list Api ==========================
436
437 Future<List<Datum>> getTestByLab() async {
438 print("This is the LabId :$encLabId");
439 print("This is the EncTestId :$encTestId");
440 _selectedTest = null as Datum;
441 var response = await http.post(Uri.parse("http://medbo.digitalicon.in/api/medboapi/GetTestByLab"),
442 body: ({
443 "EncId": encLabId
444 }));
445
446 if (response.statusCode == 200) {
447 final dataModel = dataModelFromJson(response.body);
448 print(dataModel.data.length);
449 for (final item in dataModel.data) {
450 print("This are hte test names :${item.testName}");
451 print("This are hte test EncTestId :${item.encTestId}");
452 }
453
454
455 List<Datum> arrData = dataModel.data;
456 return arrData;
457 }
458
459 return [];
460 }
461//=====================================================================Get Test Fee Api=========================================
462 Future<void> GetTestFee() async {
463 var jsonResponse;
464 if (encTestId.isNotEmpty) {
465 var response = await http.post(
466 Uri.parse("http://medbo.digitalicon.in/api/medboapi/GetTestFee"),
467 body: ({
468 'EncPartnerId': encLabId,
469 'EncTestId': encTestId,
470
471 }));
472 if (response.statusCode == 200) {
473 print("Correct");
474 print(response.body);
475 jsonResponse = json.decode(response.body.toString());
476 print(jsonResponse);
477 getTestFeeObj=GetTestFeeMap.fromJson(jsonResponse);
478 setState(() {
479 reponseArray.add(getTestFeeObj!); // Adding data to my Arraylist
480 feeSum=0;
481 discountSum=0;
482 bookingSum=0;
483
484 for(GetTestFeeMap elem in reponseArray){
485
486 feeSum += elem.fee! ;
487 discountSum += elem.discountedFee! ; // Doing calculation here
488 bookingSum += elem.bookingFee! ;
489
490 eNcTestIdInList =elem.encTestId!;
491//===============================================================================================================
492 print("Storing Test Id in list: ${elem.encTestId}"); //Test id stroring in list after hiting ADD button
493//===============================================================================================================
494
495 }
496 print(feeSum);
497 print(discountSum);
498 print(bookingSum);
499 });
500
501 } else {
502 throw Exception("Faild to fetch");
503 }
504 } else {
505 throw Exception("Faild to fetch");
506 }
507 }
508
509//================================================================== SaveMultipleTestBooking ==========================
510
511
512 Future<void> SaveMultipleTestBooking() async {
513 var jsonResponse;
514 if (encTestId.isNotEmpty) {
515 var response = await http.post(
516 Uri.parse("http://medbo.digitalicon.in/api/medboapi/SaveMultipleTestBooking"),
517 body: ({
518 "EncDoctorId": "I3uXyzcuDZf21SSe5fHnSQ==,7Ch2aVnhokZtRWyJtuDA/A==", //test id
519 //'EncPartnerId':encLabId,
520 //'EncDoctorId': eNcTestIdInList,
521 //'VisitDate': _selectedDate,
522 // 'Fee': getTestFeeObj!.fee.toString(),
523 // 'DiscountedFee': getTestFeeObj!.discountedFee,
524 // 'BookingFee': getTestFeeObj!.bookingFee.toString(),
525 //================================
526 // 'TotalFee': feeSum .toString(),
527 // 'TotalDiscountedFee' : discountSum .toString(),
528 // 'TotalBookingFee' : bookingSum .toString(),
529 //'EncUserId' : EncUserId,
530
531 //"EncDoctorId": "I3uXyzcuDZf21SSe5fHnSQ==,7Ch2aVnhokZtRWyJtuDA/A==", //test id
532 // "EncPartnerId": "0aruO0FbYOu5IerRBxdT8w==",
533 // "EncUserId": "bbA/HajfPdswT0fhhiMvEg==",
534 // "VisitDate": "09/12/2021",
535 // "Fee": "500,300",
536 // "DiscountedFee" : "450,200",
537 // "BookingFee" : "200,150",
538 // "TotalFee" :"800",
539 // "TotalDiscountedFee": "650",
540 // "TotalBookingFee" : "350"
541 }));
542 if (response.statusCode == 200) {
543 print("Correct");
544 print(response.body);
545 jsonResponse = json.decode(response.body.toString());
546 print(jsonResponse);
547 } else {
548 ScaffoldMessenger.of(context)
549 .showSnackBar(SnackBar(content: Text("Please select from available dates")));
550 throw Exception("Faild to fetch");
551 }
552 } else {
553 throw Exception("Faild to fetch");
554 }
555 }
556
557}