pharmacy_mobile/lib/pages/add_medicine_page.dart
2025-02-26 12:52:08 +08:00

356 lines
13 KiB
Dart

import 'dart:convert';
import 'dart:developer';
import 'dart:io';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:gap/gap.dart';
import 'package:image_picker/image_picker.dart';
import 'package:internet_connection_checker/internet_connection_checker.dart';
import 'package:pharmacy_mobile/functions/barcode_scan_function.dart';
import 'package:pharmacy_mobile/functions/checkresult_function.dart';
import 'package:pharmacy_mobile/tables/ref_categories.dart';
import 'package:pharmacy_mobile/tables/ref_generic_names.dart';
import 'package:pharmacy_mobile/tables/ref_manufactorers.dart';
import 'package:pharmacy_mobile/tables/ref_medicines.dart';
import 'package:pharmacy_mobile/tables/ref_types.dart';
import 'package:pharmacy_mobile/tables/storage.dart';
import 'package:pharmacy_mobile/widgets/button_widget.dart';
import 'package:pharmacy_mobile/widgets/dropdown_widget.dart';
import 'package:pharmacy_mobile/widgets/dropdown_wrappermulti_widget.dart';
import 'package:pharmacy_mobile/widgets/form_border_widget2.dart';
import 'package:pharmacy_mobile/widgets/input_widget.dart';
import 'package:pharmacy_mobile/widgets/page_background_widget.dart';
import 'package:pharmacy_mobile/widgets/scanbarcode_widget.dart';
import 'package:pharmacy_mobile/widgets/snackbar_widget.dart';
import 'package:pharmacy_mobile/widgets/text_widget.dart';
import 'package:pharmacy_mobile/widgets/title_widget.dart';
import 'package:go_router/go_router.dart';
import 'package:uuid/uuid.dart';
import 'package:flutter_image_compress/flutter_image_compress.dart';
class AddMedicinePage extends StatefulWidget {
const AddMedicinePage({super.key});
@override
State<AddMedicinePage> createState() => _AddMedicinePageState();
}
class _AddMedicinePageState extends State<AddMedicinePage> {
final _formKey = GlobalKey<FormState>();
final _refGenericNames = RefGenericNames();
final _refCategories = RefCategories();
final _refTypes = RefTypes();
final _refManufactorer = RefManufactorers();
final _refMedicines = RefMedicines();
final _storage = Storage();
final _nameController = TextEditingController();
final _barcodeController = TextEditingController();
bool _isLoading = false;
late List _genericNameList = [];
late String _selectedGeneric = '';
late String _selectedCategory = '';
late List _typeList = [];
late String _selectedType = '';
late List _manufactorerList = [];
late String _selectedManufactorer = '';
late String uuid = '';
late bool imageUploaded = false;
late String imageUrl = '';
// void _checkResult(List list, String name) {
// if (list.isEmpty) {
// if (mounted) {
// showNotification(context, 'Error: No $name Found', false);
// WidgetsBinding.instance.addPostFrameCallback((_) {
// if (mounted) {
// context.push('/main');
// }
// });
// }
// } else {
// setState(() => {});
// }
// }
// Future<Uint8List> compressFile(XFile file) async {
// var result = await FlutterImageCompress.compressWithFile(
// file.path,
// minWidth: 1020,
// minHeight: 765,
// quality: 90,
// format: CompressFormat.webp,
// );
// return result;
// }
Future<void> _getGenerics() async {
_genericNameList = await _refGenericNames.getList();
setState(() {
checkResult(context, _genericNameList, 'Generics');
});
}
Future<void> _getTypes() async {
_typeList = await _refTypes.getList();
setState(() {
checkResult(context, _typeList, 'Types');
});
}
Future<void> _getManufactorer() async {
_manufactorerList = await _refManufactorer.getList();
setState(() {
checkResult(context, _manufactorerList, 'Manufactorer');
});
}
void autoRun() async {
if (await InternetConnectionChecker.instance.hasConnection) {
await _getGenerics();
await _getTypes();
await _getManufactorer();
// final sample = await _refMedicines.getList2();
} else {
if (mounted) {
showNotification(context, 'Error: No Internet Connection', false);
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted) {
context.push('/main');
}
});
}
}
}
void _updateGeneric(dynamic generic) async {
_selectedGeneric = generic;
final catuuid = await _refGenericNames.getCategoryUUID(_selectedGeneric);
final catname = await _refCategories.getName(catuuid);
setState(() => _selectedCategory = catname);
}
void _updateType(dynamic type) {
_selectedType = type;
}
void _updateManufactorer(dynamic manufactorer) {
_selectedManufactorer = manufactorer;
}
Future<void> _scanBarcode() async {
// String? barcode = await SimpleBarcodeScanner.scanBarcode(
// context,
// // barcodeAppBar: const BarcodeAppBar(
// // // appBarTitle: 'Test',
// // // centerTitle: false,
// // // enableBackButton: false,
// // // backButtonIcon: Icon(Icons.arrow_back_ios),
// // ),
// // isShowFlashIcon: true,
// delayMillis: 2000,
// scanType: ScanType.barcode,
// cameraFace: CameraFace.back,
// );
_barcodeController.text = await barcodeScan(context);
}
void _saveMedicine() async {
setState(() => _isLoading = true);
try {
// final String encrpytedBarcode = await encrypt(_barcodeController.text);
final String encrpytedBarcode = _barcodeController.text;
if (await InternetConnectionChecker.instance.hasConnection) {
final medName = _nameController.text;
final medGenericUUID = await _refGenericNames.getUUID(_selectedGeneric);
final medTypeUUID = await _refTypes.getUUID(_selectedType);
final medManufactorerUUID = await _refManufactorer.getUUID(_selectedManufactorer);
await _refMedicines.postMedicine(
uuid, medName, medManufactorerUUID, medGenericUUID, medTypeUUID, encrpytedBarcode);
} else {
if (mounted) {
showNotification(context, 'Error: No Internet Connection', false);
}
}
} catch (e) {
if (mounted) {
showNotification(context, 'Error: $e', false);
}
} finally {
setState(() => _isLoading = false);
}
}
void _addImage() async {
final imageName = Uuid().v4();
final ImagePicker picker = ImagePicker();
final XFile? image = await picker.pickImage(source: ImageSource.gallery, imageQuality: 100);
const storageName = 'ref_medicines_images';
final imageBytes = await image!.readAsBytes();
final webpImage = await _webpConvert(imageBytes);
uuid = imageName;
if (mounted) {
imageUrl = await _storage.uploadImage(context, storageName, webpImage, '$imageName.webp');
}
setState(() {
if (imageUrl.isEmpty) {
if (mounted) {
showNotification(context, 'Image Upload failed, try again.', false);
}
}
});
}
Future<Uint8List> _webpConvert(Uint8List file) async {
final result = await FlutterImageCompress.compressWithList(
file,
// minHeight: 1080,
// minWidth: 1080,
quality: 75,
rotate: 0,
keepExif: false,
format: CompressFormat.webp,
);
return result;
}
@override
void initState() {
autoRun();
super.initState();
}
@override
void dispose() {
_nameController.dispose();
_barcodeController.dispose();
_genericNameList = [];
_selectedGeneric = '';
_selectedCategory = '';
_typeList = [];
_selectedType = '';
_manufactorerList = [];
_selectedManufactorer = '';
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: PageBackgroundWidget(
height: MediaQuery.of(context).size.height + 600,
child: Center(
child: Column(children: [
const Gap(96),
const TitleWidget(
firstTextSize: 14,
secondTextSize: 24,
logoSize: 90,
),
const Gap(32),
const TextWidget(text: 'Add Medicine'),
const Gap(16),
FormBorderWidget2(
color: 'green',
child: Form(
key: _formKey,
child: Center(
child: Column(
children: [
InputWidget(label: 'Name', controller: _nameController),
const Gap(16),
DropdownWrapperMultiWidget(list: _genericNameList, text: 'Data', children: [
Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
DropDownWidget(
label: 'Generic Name',
list: _genericNameList,
listTitle: 'generic_name',
onChanged: _updateGeneric),
const Gap(8),
Padding(
padding: const EdgeInsets.only(left: 12),
child: TextWidget(text: _selectedCategory, size: 18),
),
const Gap(16),
DropDownWidget(
label: 'Type', list: _typeList, listTitle: 'type_name', onChanged: _updateType),
const Gap(16),
DropDownWidget(
label: 'Manufactorer',
list: _manufactorerList,
listTitle: 'manufactorer_name',
onChanged: _updateManufactorer),
const Gap(16),
InputWidget(label: 'Barcode', controller: _barcodeController),
ScanbarcodeWidget(onTap: _scanBarcode),
const Gap(16),
if (imageUrl.isNotEmpty)
Center(
child: ClipRRect(
borderRadius: BorderRadius.circular(12), // Add your desired border radius here
child: Image.network(imageUrl, fit: BoxFit.cover, width: 250, height: 250)),
)
else
ButtonWidget(
text: 'Add Image',
onPressed: _addImage,
outline: true,
),
const Gap(32),
if (_isLoading)
const Center(child: CircularProgressIndicator(color: Colors.white))
else
ButtonWidget(text: 'Save Medicine', onPressed: _saveMedicine)
])
]),
// DropdownWrapperWidget(
// list: _genericNameList,
// text: 'Generics',
// widget: Column(
// crossAxisAlignment: CrossAxisAlignment.start,
// children: [
// DropDownWidget(
// label: 'Generic Name',
// list: _genericNameList,
// listTitle: 'generic_name',
// onChanged: _updateGeneric),
// const Gap(8),
// TextWidget(text: _selectedCategory, size: 18),
// ],
// )),
// const Gap(16),
// DropdownWrapperWidget(
// list: _typeList,
// text: 'Types',
// widget: DropDownWidget(
// label: 'Type', list: _typeList, listTitle: 'type_name', onChanged: _updateType)),
// const Gap(16),
// DropdownWrapperWidget(
// list: _manufactorerList,
// text: 'Manufactorers',
// widget: DropDownWidget(
// label: 'Manufactorer',
// list: _manufactorerList,
// listTitle: 'manufactorer_name',
// onChanged: _updateManufactorer)),
// const Gap(32),
],
),
)))
]))));
}
}