|
- import 'dart:convert';
-
- import 'package:farm_tpf/custom_model/Disease.dart';
- import 'package:farm_tpf/custom_model/RequestDisease.dart';
- import 'package:farm_tpf/data/api/app_exception.dart';
- import 'package:farm_tpf/data/repository/repository.dart';
- import 'package:farm_tpf/presentation/custom_widgets/bloc/media_helper_bloc.dart';
- import 'package:farm_tpf/presentation/custom_widgets/widget_loading.dart';
- import 'package:farm_tpf/presentation/custom_widgets/widget_media_picker.dart';
- import 'package:farm_tpf/presentation/custom_widgets/widget_text_form_field.dart';
- import 'package:farm_tpf/presentation/custom_widgets/widget_utils.dart';
- import 'package:farm_tpf/presentation/screens/actions/bloc/action_detail_bloc.dart';
- import 'package:farm_tpf/presentation/screens/actions/state_management_helper/change_file_controller.dart';
- import 'package:farm_tpf/utils/const_common.dart';
- import 'package:farm_tpf/utils/const_string.dart';
- import 'package:farm_tpf/utils/const_style.dart';
- import 'package:farm_tpf/utils/pref.dart';
- import 'package:farm_tpf/utils/validators.dart';
- import 'package:flutter/material.dart';
- import 'package:flutter_bloc/flutter_bloc.dart';
- import 'package:flutter_datetime_picker/flutter_datetime_picker.dart';
- import 'package:get/get.dart';
- import 'package:intl/intl.dart';
- import 'package:keyboard_dismisser/keyboard_dismisser.dart';
- import 'package:pattern_formatter/pattern_formatter.dart';
- import 'package:farm_tpf/utils/formatter.dart';
-
- import '../util_action.dart';
-
- class EditActionDiseaseScreen extends StatefulWidget {
- final int cropId;
- final bool isEdit;
- final int activityId;
- EditActionDiseaseScreen(
- {@required this.cropId, this.isEdit = false, this.activityId});
- @override
- _EditActionDiseaseScreenState createState() =>
- _EditActionDiseaseScreenState();
- }
-
- class _EditActionDiseaseScreenState extends State<EditActionDiseaseScreen> {
- final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();
- final _repository = Repository();
- GlobalKey<FormState> _formKey = GlobalKey();
- bool _autoValidate = false;
- Disease _disease = Disease();
- var pref = LocalPref();
- TextEditingController _typesOfPestController = TextEditingController();
- TextEditingController _numTreeController = TextEditingController();
- TextEditingController _harmLevelController = TextEditingController();
- TextEditingController _treePercentController = TextEditingController();
- TextEditingController _locationController = TextEditingController();
- TextEditingController _naturalEnemyController = TextEditingController();
- TextEditingController _treatmentMeasuresController = TextEditingController();
- TextEditingController _descriptionController = TextEditingController();
- final _executeByController = TextEditingController();
-
- String executeTimeView;
- DateTime executeTime = DateTime.now();
- List<String> filePaths = List<String>();
- var changeFileController = Get.put(ChangeFileController());
-
- Future<Null> getSharedPrefs() async {
- var currentFullName = await pref.getString(DATA_CONST.CURRENT_FULL_NAME);
- _executeByController.text = currentFullName ?? "";
- }
-
- @override
- void initState() {
- super.initState();
- getSharedPrefs();
- changeFileController.initValue();
- var parsedExecuteDate =
- DateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'").format(executeTime);
- _disease.executeDate = "$parsedExecuteDate";
- executeTimeView = DateFormat("dd/MM/yyyy HH:mm").format(executeTime);
- _disease.cropId = widget.cropId;
- }
-
- _validateInputs() async {
- if (_formKey.currentState.validate()) {
- _formKey.currentState.save();
- LoadingDialog.showLoadingDialog(context);
- filePaths = Get.find<ChangeFileController>().newFiles;
- //Create request general model
- try {
- RequestDisease requestDisease = RequestDisease()
- ..cropId = _disease.cropId
- ..activityId = _disease.activityId
- ..description = _disease.description
- ..executeDate = _disease.executeDate;
- var generalDetail = List<ObjectUpdateDetail>();
- generalDetail.add(ObjectUpdateDetail()
- ..name = "LOAI_DICH_HAI"
- ..index = _disease.typesOfPest);
- generalDetail.add(ObjectUpdateDetail()
- ..name = "MUC_DO_GAY_HAI"
- ..index = _disease.harmLevel);
- generalDetail.add(ObjectUpdateDetail()
- ..name = "PHAN_TRAM_CAY"
- ..index = _disease.treePercent);
- generalDetail.add(ObjectUpdateDetail()
- ..name = "VI_TRI"
- ..index = _disease.location);
- generalDetail.add(ObjectUpdateDetail()
- ..name = "THIEN_DICH"
- ..index = _disease.naturalEnemy);
- generalDetail.add(ObjectUpdateDetail()
- ..name = "BIEN_PHAP_XU_LY"
- ..index = _disease.treatmentMeasures);
- requestDisease.objectUpdateDetail = generalDetail;
- requestDisease.mediaDel = Get.find<ChangeFileController>().deleteFiles;
- var activityDisease = jsonEncode(requestDisease.toJson()).toString();
- //ADD NEW
- if (_disease.activityId == null) {
- _repository.createAction((value) {
- LoadingDialog.hideLoadingDialog(context);
- Get.back(result: value);
- Utils.showSnackBarSuccess(message: label_add_success);
- }, (error) {
- LoadingDialog.hideLoadingDialog(context);
- Utils.showSnackBarError(message: AppException.handleError(error));
- },
- apiAddAction: ConstCommon.apiAddDisease,
- paramActivity: ConstCommon.paramsActionDisease,
- activityAction: activityDisease,
- filePaths: filePaths);
- } else {
- //UPDATE
- _repository.updateAction((value) {
- LoadingDialog.hideLoadingDialog(context);
- Get.back(result: value);
- Utils.showSnackBarSuccess(message: label_update_success);
- }, (error) {
- LoadingDialog.hideLoadingDialog(context);
- Utils.showSnackBarError(message: AppException.handleError(error));
- },
- apiUpdateAction: ConstCommon.apiUpdateDisease,
- paramActivity: ConstCommon.paramsActionDisease,
- activityAction: activityDisease,
- filePaths: filePaths);
- }
- } catch (e) {
- LoadingDialog.hideLoadingDialog(context);
- print(e.toString());
- }
- } else {
- _autoValidate = true;
- }
- }
-
- Widget _btnExecuteTimePicker() {
- return FlatButton(
- padding: EdgeInsets.only(top: 0.0, right: 0.0, bottom: 0.0, left: 0.0),
- onPressed: () {
- DatePicker.showDateTimePicker(context,
- showTitleActions: true, onChanged: (date) {}, onConfirm: (date) {
- setState(() {
- var parsedDate =
- DateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'").format(date);
- _disease.executeDate = "$parsedDate";
- executeTimeView = DateFormat("dd/MM/yyyy HH:mm").format(date);
- });
- }, currentTime: executeTime, locale: LocaleType.vi);
- },
- child: Container(
- padding:
- EdgeInsets.only(top: 0.0, right: 0.0, bottom: 10.5, left: 0.0),
- decoration: BoxDecoration(
- border: kBorderTextField,
- ),
- child: Row(
- children: [
- Expanded(
- child: Text(
- //TODO: check condition
- executeTimeView == null ? "$executeTime" : executeTimeView,
- style: TextStyle(fontSize: 14.0, color: Colors.black87),
- )),
- Icon(
- Icons.date_range,
- color: Colors.blue,
- ),
- ],
- )));
- }
-
- Widget _typeOfPestField() {
- return TextFormField(
- keyboardType: TextInputType.text,
- decoration: InputDecoration(labelText: "Loại dịch hại *"),
- controller: _typesOfPestController,
- validator: (String value) {
- return Validators.validateNotNullOrEmpty(value, "Loại dịch hại");
- },
- onSaved: (newValue) {
- _disease.typesOfPest = newValue;
- },
- );
- }
-
- Widget _harmLevelField() {
- return TextFormField(
- keyboardType: TextInputType.text,
- decoration: InputDecoration(labelText: "Mức độ gây hại"),
- controller: _harmLevelController,
- onSaved: (newValue) {
- _disease.harmLevel = newValue;
- },
- );
- }
-
- Widget _treePercentField() {
- return WidgetTextFormFieldNumber(
- hintValue: "% cây",
- textController: _treePercentController,
- onSaved: (newValue) {
- _disease.treePercent = newValue;
- },
- );
- }
-
- Widget _locationField() {
- return TextFormField(
- keyboardType: TextInputType.text,
- decoration: InputDecoration(labelText: "Vị trí"),
- controller: _locationController,
- onSaved: (newValue) {
- _disease.location = newValue;
- },
- );
- }
-
- Widget _naturalEnemyField() {
- return TextFormField(
- keyboardType: TextInputType.text,
- decoration: InputDecoration(labelText: "Thiên địch"),
- controller: _naturalEnemyController,
- onSaved: (newValue) {
- _disease.naturalEnemy = newValue;
- },
- );
- }
-
- Widget _treatmentMeasuresField() {
- return TextFormField(
- keyboardType: TextInputType.text,
- decoration: InputDecoration(labelText: "Biện pháp xử lý"),
- controller: _treatmentMeasuresController,
- onSaved: (newValue) {
- _disease.treatmentMeasures = newValue;
- },
- );
- }
-
- Widget _descriptionField() {
- return TextFormField(
- keyboardType: TextInputType.text,
- decoration: InputDecoration(labelText: "Ghi chú"),
- controller: _descriptionController,
- onSaved: (newValue) {
- _disease.description = newValue;
- },
- );
- }
-
- Widget _executeByField() {
- return TextFormField(
- keyboardType: TextInputType.text,
- decoration: InputDecoration(labelText: "Người thực hiện"),
- enabled: false,
- controller: _executeByController,
- onSaved: (newValue) {},
- );
- }
-
- _actionAppBar() {
- IconButton iconButton;
- if (1 == 1) {
- iconButton = IconButton(
- icon: Icon(
- Icons.done,
- color: Colors.black,
- ),
- onPressed: () {
- FocusScopeNode currentFocus = FocusScope.of(context);
- if (!currentFocus.hasPrimaryFocus) {
- currentFocus.unfocus();
- }
- _validateInputs();
- },
- );
- return <Widget>[iconButton];
- }
- return <Widget>[Container()];
- }
-
- @override
- Widget build(BuildContext context) => KeyboardDismisser(
- gestures: [
- GestureType.onTap,
- GestureType.onPanUpdateDownDirection,
- ],
- child: Scaffold(
- key: _scaffoldKey,
- appBar: AppBar(
- centerTitle: true,
- title: Text(plot_action_disease),
- actions: _actionAppBar()),
- body: KeyboardDismisser(
- child: MultiBlocProvider(
- providers: [
- BlocProvider<ActionDetailBloc>(
- create: (context) =>
- ActionDetailBloc(repository: Repository())
- ..add(FetchData(
- isNeedFetchData: widget.isEdit,
- apiActivity: ConstCommon.apiDetailDisease,
- activityId: widget.activityId))),
- BlocProvider<MediaHelperBloc>(
- create: (context) =>
- MediaHelperBloc()..add(ChangeListMedia(items: [])),
- )
- ],
- child: Form(
- key: _formKey,
- autovalidate: _autoValidate,
- child: SingleChildScrollView(
- padding: EdgeInsets.all(8.0),
- child: BlocConsumer<ActionDetailBloc, ActionDetailState>(
- listener: (context, state) async {
- if (state is ActionDetailFailure) {
- LoadingDialog.hideLoadingDialog(context);
- } else if (state is ActionDetailSuccess) {
- LoadingDialog.hideLoadingDialog(context);
- print(state.item);
- _disease = Disease.fromJson(state.item);
- _disease.activityId = widget.activityId;
- _typesOfPestController.text =
- _disease.typesOfPest ?? "";
- _harmLevelController.text =
- _disease.harmLevel ?? "";
- _treePercentController.text = _disease.treePercent
- .formatStringToStringDecimal();
- _locationController.text =
- _disease.location.formatStringToStringDecimal();
- _naturalEnemyController.text =
- _disease.naturalEnemy ?? "";
- _treatmentMeasuresController.text =
- _disease.treatmentMeasures ?? "";
- _descriptionController.text =
- _disease.description ?? "";
- _executeByController.text = _disease.executeBy;
-
- try {
- executeTime =
- DateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'")
- .parse(_disease.executeDate);
- } catch (_) {}
- executeTimeView = DateFormat("dd/MM/yyyy HH:mm")
- .format(executeTime);
- //Show media
- if (_disease.media.isNotEmpty) {
- BlocProvider.of<MediaHelperBloc>(context).add(
- ChangeListMedia(
- items: UtilAction.convertFilePathToMedia(
- _disease.media)));
- }
- } else if (state is ActionDetailInitial) {
- } else if (state is ActionDetailLoading) {
- LoadingDialog.showLoadingDialog(context);
- }
- },
- builder: (context, state) {
- return Column(
- children: <Widget>[
- Container(
- width: double.infinity,
- child: Text(
- "Ngày thực hiện *",
- style: TextStyle(
- color: Colors.black54, fontSize: 13.0),
- ),
- ),
- _btnExecuteTimePicker(),
- SizedBox(
- height: 8.0,
- ),
- _typeOfPestField(),
- SizedBox(
- height: 8.0,
- ),
- _harmLevelField(),
- SizedBox(
- height: 8.0,
- ),
- _treePercentField(),
- SizedBox(
- height: 8.0,
- ),
- _locationField(),
- SizedBox(
- height: 8.0,
- ),
- _naturalEnemyField(),
- SizedBox(
- height: 8.0,
- ),
- _treatmentMeasuresField(),
- SizedBox(
- height: 8.0,
- ),
- _descriptionField(),
- SizedBox(
- height: 8.0,
- ),
- _executeByField(),
- SizedBox(
- height: 8.0,
- ),
- BlocBuilder<MediaHelperBloc, MediaHelperState>(
- builder: (context, state) {
- if (state is MediaHelperSuccess) {
- return WidgetMediaPicker(
- currentItems: state.items,
- onChangeFiles: (newPathFiles,
- deletePathFiles) async {
- Get.find<ChangeFileController>().change(
- newPathFiles, deletePathFiles);
- });
- } else {
- return Center(
- child: CircularProgressIndicator());
- }
- }),
- ],
- );
- },
- ),
- )),
- ))));
- @override
- void dispose() {
- _typesOfPestController.dispose();
- _harmLevelController.dispose();
- _treePercentController.dispose();
- _locationController.dispose();
- _naturalEnemyController.dispose();
- _treatmentMeasuresController.dispose();
- _descriptionController.dispose();
- _executeByController.dispose();
- super.dispose();
- }
- }
|