flutter-freaccess-hub/lib/pages/pets_page/pets_page_model.dart

391 lines
12 KiB
Dart

import 'dart:convert';
import 'dart:developer';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart';
import 'package:hub/backend/api_requests/api_calls.dart';
import 'package:hub/backend/api_requests/api_manager.dart';
import 'package:hub/custom_code/actions/convert_to_upload_file.dart';
import 'package:hub/flutter_flow/flutter_flow_util.dart';
import 'package:hub/flutter_flow/form_field_controller.dart';
import 'package:hub/pages/pets_page/pets_page_widget.dart';
import 'package:hub/shared/helpers/db_helper.dart';
import 'package:hub/shared/utils/dialog_util.dart';
import 'package:hub/shared/utils/log_util.dart';
import 'package:hub/shared/utils/validator_util.dart';
import '/custom_code/actions/index.dart' as actions;
class PetsPageModel extends FlutterFlowModel<PetsPageWidget> {
final DatabaseHelper db = DatabaseHelper();
late final String devUUID;
late final String userUUID;
late final String cliUUID;
late final String petAmountRegister;
dynamic item;
late final TabController tabBarController;
VoidCallback? onUpdatePet;
VoidCallback? onRegisterPet;
VoidCallback? safeSetState;
VoidCallback? updateImage;
final GlobalKey<FormState> registerFormKey = GlobalKey<FormState>();
final GlobalKey<FormState> updateFormKey = GlobalKey<FormState>();
ApiCallResponse? petsResponse;
int? petId;
BuildContext? buildContext;
bool isEditing = false;
bool isDataUploading = false;
FFUploadedFile? uploadedLocalFile;
FFUploadedFile? uploadedTempFile;
String? imgBase64;
String? dropDownValue1;
FormFieldController<String>? dropDownValueController1;
String? dropDownValue2;
FormFieldController<String>? dropDownValueController2;
FocusNode? textFieldFocusName;
TextEditingController? textControllerName;
String? textControllerNameValidator(BuildContext context, String? val) {
if (val == null || val.isEmpty) {
return FFLocalizations.of(context).getVariableText(
enText: 'This field is required',
ptText: 'Este campo é obrigatório',
);
}
return null;
}
FocusNode? textFieldFocusSpecies;
TextEditingController? textControllerSpecies;
String? textControllerSpeciesValidator(BuildContext context, String? val) {
if (val == null || val.isEmpty) {
return FFLocalizations.of(context).getVariableText(
enText: 'This field is required',
ptText: 'Este campo é obrigatório',
);
}
return null;
}
FocusNode? textFieldFocusRace;
TextEditingController? textControllerRace;
String? textControllerRaceValidator(BuildContext context, String? val) {
if (val == null || val.isEmpty) {
return FFLocalizations.of(context).getVariableText(
enText: 'This field is required',
ptText: 'Este campo é obrigatório',
);
}
return null;
}
FocusNode? textFieldFocusColor;
TextEditingController? textControllerColor;
String? Function(BuildContext, String?)? textControllerColorValidator;
DateTime? selectedDate;
FocusNode? textFieldFocusData;
TextEditingController? textControllerData;
String? textControllerDataValidator(BuildContext context, String? val) {
return null;
}
FocusNode? textFieldFocusObservation;
TextEditingController? textControllerObservation;
String? Function(BuildContext, String?)? textControllerObservationValidator;
Future<void> initAsync() async {
devUUID = await db.get(key: 'devUUID', field: 'value').then((value) {
return value.toString();
});
userUUID = await db.get(key: 'userUUID', field: 'value').then((value) {
return value.toString();
});
cliUUID = await db.get(key: 'cliUUID', field: 'value').then((value) {
return value.toString();
});
petAmountRegister = await db
.get(key: 'petAmountRegister', field: 'value')
.then((value) => value.toString());
safeSetState?.call();
}
@override
void initState(BuildContext context) {
tabBarController = TabController(
vsync: Navigator.of(context),
length: 2,
);
textFieldFocusName = FocusNode();
textControllerName = TextEditingController();
textFieldFocusSpecies = FocusNode();
textControllerSpecies = TextEditingController();
textFieldFocusRace = FocusNode();
textControllerRace = TextEditingController();
textFieldFocusColor = FocusNode();
textControllerColor = TextEditingController();
textFieldFocusData = FocusNode();
textControllerData = TextEditingController(
text: dateTimeFormat(
'dd/MM/yyyy',
DateTime.now(),
));
textFieldFocusObservation = FocusNode();
textControllerObservation = TextEditingController();
dropDownValueController1 =
FormFieldController<String>(dropDownValue1 ??= 'Selecione uma opção');
dropDownValueController2 =
FormFieldController<String>(dropDownValue2 ??= 'Selecione uma opção');
initAsync();
}
void setEditForm() {
log('item: $item');
if (item != null) petId = item['id'];
// updateImage!();
(() async {
Response response = await get(Uri.parse(
'https://freaccess.com.br/freaccess/getImage.php?devUUID=$devUUID&userUUID=$userUUID&cliID=$cliUUID&atividade=consultaFotoPet&petId=$petId'));
String base64 = base64Encode(response.bodyBytes);
uploadedTempFile = await convertToUploadFile(base64);
updateImage?.call();
})();
textControllerName =
TextEditingController(text: item != null ? item['name'] ?? '' : '');
textFieldFocusName = FocusNode();
textControllerSpecies =
TextEditingController(text: item != null ? item['species'] ?? '' : '');
textFieldFocusSpecies = FocusNode();
textControllerRace =
TextEditingController(text: item != null ? item['breed'] ?? '' : '');
textFieldFocusRace = FocusNode();
textControllerColor =
TextEditingController(text: item != null ? item['color'] ?? '' : '');
textFieldFocusColor = FocusNode();
textControllerData = TextEditingController(
text: item != null
? item['birthdayDate'] != null
? ValidatorUtil.formatDateTimePicker(item['birthdayDate'])
: dateTimeFormat(
'dd/MM/yyyy',
DateTime.now(),
)
: dateTimeFormat(
'dd/MM/yyyy',
DateTime.now(),
));
textFieldFocusData = FocusNode();
textControllerObservation =
TextEditingController(text: item != null ? item['notes'] ?? '' : '');
textFieldFocusObservation = FocusNode();
item != null ? dropDownValue1 = item['gender'] ?? '' : dropDownValue1 = '';
item != null ? dropDownValue2 = item['size'] ?? '' : dropDownValue2 = '';
dropDownValueController1 = FormFieldController<String>(dropDownValue1);
dropDownValueController2 = FormFieldController<String>(dropDownValue2);
}
@override
void dispose() {
tabBarController.dispose();
textFieldFocusName?.dispose();
textControllerName?.dispose();
textFieldFocusSpecies?.dispose();
textControllerSpecies?.dispose();
textFieldFocusRace?.dispose();
textControllerRace?.dispose();
textFieldFocusColor?.dispose();
textControllerColor?.dispose();
textFieldFocusData?.dispose();
textControllerData?.dispose();
textFieldFocusObservation?.dispose();
textControllerObservation?.dispose();
dropDownValueController1?.dispose();
dropDownValueController2?.dispose();
}
bool isFormValid(BuildContext context) {
if (uploadedLocalFile == null || uploadedLocalFile!.bytes!.isEmpty) {
return false;
}
if (textControllerName.text.isEmpty ||
textControllerName.text.length > 80 ||
textControllerName.text == '') {
return false;
}
if (textControllerSpecies.text.isEmpty ||
textControllerSpecies.text == '') {
return false;
}
if (textControllerRace.text.isEmpty || textControllerRace.text == '') {
return false;
}
if (dropDownValue1 == null ||
dropDownValue1!.isEmpty ||
dropDownValue1 == '') {
return false;
}
if (dropDownValue2 == null ||
dropDownValue2!.isEmpty ||
dropDownValue2 == '') {
return false;
}
return true;
}
Future<void> updatePet() async {
var img = await actions.convertImageFileToBase64(uploadedLocalFile!);
img = "base64;jpeg,$img";
await PhpGroup.updatePet.call(
petID: petId,
image: imgBase64,
birthdayDate: textControllerData!.text,
color: textControllerColor!.text,
breed: textControllerRace!.text,
species: textControllerSpecies!.text,
name: textControllerName!.text,
gender: dropDownValue1!,
notes: textControllerObservation!.text,
size: dropDownValue2!,
);
if (response.jsonBody['error'] == false) {
DialogUtil.success(
buildContext!,
FFLocalizations.of(buildContext!).getVariableText(
enText: 'Pet successfully updated',
ptText: 'Pet atualizado com sucesso',
),
);
CachedNetworkImage.evictFromCache(url);
onUpdatePet?.call();
switchTab(1);
} else {
String errorMessage;
try {
errorMessage =
jsonDecode(response.jsonBody['error_msg'])[0]['message'].toString();
} catch (e) {
errorMessage = FFLocalizations.of(buildContext!).getVariableText(
enText: 'Failed to update pet',
ptText: 'Falha ao atualizar o pet',
);
}
DialogUtil.error(buildContext!, errorMessage);
}
}
Future<void> registerPet() async {
var img = await actions.convertImageFileToBase64(uploadedLocalFile!);
img = "base64;jpeg,$img";
await PhpGroup.registerPet.call(
image: img,
birthdayDate: textControllerData!.text,
color: textControllerColor!.text,
breed: textControllerRace!.text,
species: textControllerSpecies!.text,
name: textControllerName!.text,
gender: dropDownValue1!,
size: dropDownValue2!,
notes: textControllerObservation!.text,
);
if (response.jsonBody['error'] == false) {
DialogUtil.success(
buildContext!,
FFLocalizations.of(buildContext!).getVariableText(
enText: 'Pet successfully registered',
ptText: 'Pet cadastrado com sucesso',
),
);
onRegisterPet?.call();
} else {
String errorMessage;
try {
errorMessage =
jsonDecode(response.jsonBody['error_msg'])[0]['message'].toString();
} catch (e) {
if (response.jsonBody['error_msg'] ==
"Limite de Cadastro de Pet Atingido.") {
errorMessage = FFLocalizations.of(buildContext!).getVariableText(
enText: 'Pet registration limit reached',
ptText: 'Limite de cadastro de pets atingido',
);
} else {
DialogUtil.errorDefault(buildContext!);
}
}
}
}
void switchTab(int index) {
tabBarController.animateTo(index);
if (index == 1) handleEditingChanged(false);
safeSetState?.call();
}
void handleUploadComplete(FFUploadedFile uploadedFile) {
uploadedLocalFile = uploadedFile;
safeSetState?.call();
}
void handleEditingChanged(bool editing) {
isEditing = editing;
clearFields();
}
void clearFields() {
uploadedLocalFile = null;
textControllerName?.clear();
textControllerName?.clear();
textControllerSpecies?.clear();
textControllerRace?.clear();
textControllerColor?.clear();
textControllerData?.clear();
textControllerObservation?.clear();
dropDownValue1 = null;
dropDownValue2 = null;
dropDownValueController1 = FormFieldController<String>(null);
dropDownValueController2 = FormFieldController<String>(null);
}
}