import 'dart:convert'; import 'package:farm_tpf/custom_model/Other.dart'; import 'package:farm_tpf/data/api/app_exception.dart'; import 'package:farm_tpf/data/repository/repository.dart'; import 'package:farm_tpf/models/index.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_utils.dart'; import 'package:farm_tpf/presentation/screens/actions/bloc/action_detail_bloc.dart'; import 'package:farm_tpf/presentation/screens/actions/other/bloc_get_action_type.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: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 '../util_action.dart'; class EditActionOtherScreen extends StatefulWidget { final int cropId; final bool isEdit; final int activityId; EditActionOtherScreen( {@required this.cropId, this.isEdit = false, this.activityId}); @override _EditActionOtherScreenState createState() => _EditActionOtherScreenState(); } class _EditActionOtherScreenState extends State { final GlobalKey _scaffoldKey = new GlobalKey(); final _repository = Repository(); GlobalKey _formKey = GlobalKey(); bool _autoValidate = false; var pref = LocalPref(); Other _other = Other(); final _descriptionController = TextEditingController(); final _executeByController = TextEditingController(); List _actionTypes = List(); ActionType _actionType; String executeTimeView; DateTime executeTime = DateTime.now(); List filePaths = List(); var changeFileController = Get.put(ChangeFileController()); Future 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); _other.executeDate = "$parsedExecuteDate"; executeTimeView = DateFormat("dd/MM/yyyy HH:mm").format(executeTime); _other.cropId = widget.cropId; if (!widget.isEdit) { getActionTypeBloc.getActionTypes((data) { _actionTypes = data; }, (err) {}); } } _validateInputs() async { if (_formKey.currentState.validate()) { _formKey.currentState.save(); LoadingDialog.showLoadingDialog(context); filePaths = Get.find().files; try { var activityOther = jsonEncode(_other.toJson()).toString(); //ADD NEW if (_other.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.apiAddOther, paramActivity: ConstCommon.paramsActionOther, activityAction: activityOther, 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.apiUpdateOther, paramActivity: ConstCommon.paramsActionOther, activityAction: activityOther, 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); _other.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, ), ], ))); } List> _buildDropMenu(List actions) { return actions .map((action) => DropdownMenuItem( child: Text(action.description.toString()), value: action, )) .toList(); } Widget _dropdownAcionTypes() { return StreamBuilder( stream: getActionTypeBloc.actions, builder: (context, AsyncSnapshot snapshot) { if (snapshot.hasData) { return DropdownButtonFormField( value: _actionType, hint: Text("Hoạt động *"), onChanged: (ActionType newValue) { setState(() { _actionType = newValue; _other.activityTypeName = newValue.name; }); }, validator: (value) => value == null ? "Hoạt động" : null, isExpanded: true, items: _buildDropMenu(_actionTypes)); } else if (snapshot.hasError) { return Container(); } else { return Center( child: CircularProgressIndicator(), ); } }, ); } Widget _desciptionField() { return TextFormField( keyboardType: TextInputType.text, decoration: InputDecoration(labelText: "Ghi chú"), controller: _descriptionController, onSaved: (newValue) { _other.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 [iconButton]; } return [Container()]; } @override Widget build(BuildContext context) => KeyboardDismisser( gestures: [ GestureType.onTap, GestureType.onPanUpdateDownDirection, ], child: Scaffold( key: _scaffoldKey, appBar: AppBar( centerTitle: true, title: Text(plot_action_other), actions: _actionAppBar()), body: KeyboardDismisser( child: MultiBlocProvider( providers: [ BlocProvider( create: (context) => ActionDetailBloc(repository: Repository()) ..add(FetchData( isNeedFetchData: widget.isEdit, apiActivity: ConstCommon.apiDetailOther, activityId: widget.activityId))), BlocProvider( create: (context) => MediaHelperBloc()..add(ChangeListMedia(items: [])), ) ], child: Form( key: _formKey, autovalidate: _autoValidate, child: SingleChildScrollView( padding: EdgeInsets.all(8.0), child: BlocConsumer( listener: (context, state) async { if (state is ActionDetailFailure) { LoadingDialog.hideLoadingDialog(context); } else if (state is ActionDetailSuccess) { LoadingDialog.hideLoadingDialog(context); _other = Other.fromJson(state.item); _other.activityId = widget.activityId; _descriptionController.text = _other.description ?? ""; _executeByController.text = _other.createdByName; //select harvest getActionTypeBloc.getActionTypes((data) { _actionTypes = data; for (var item in _actionTypes) { if (item.name == _other.activityTypeName) { _actionType = item; break; } } }, (err) {}); try { executeTime = DateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'") .parse(_other.executeDate); executeTimeView = DateFormat("dd/MM/yyyy HH:mm") .format(executeTime); } catch (_) {} //Show media if (_other.media != null) { await UtilAction.cacheFiles(_other.media) .then((value) { BlocProvider.of(context) .add(ChangeListMedia(items: value)); }).whenComplete(() { print("completed"); }); } } else if (state is ActionDetailInitial) { } else if (state is ActionDetailLoading) { LoadingDialog.showLoadingDialog(context); } }, builder: (context, state) { return Column( children: [ 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, ), _dropdownAcionTypes(), SizedBox( height: 8.0, ), _desciptionField(), SizedBox( height: 8.0, ), _executeByField(), SizedBox( height: 8.0, ), BlocBuilder( builder: (context, state) { if (state is MediaHelperSuccess) { return WidgetMediaPicker( currentItems: state.items, onChangeFiles: (filePaths) async { Get.find() .addAllFile(filePaths); }); } else { return Center( child: CircularProgressIndicator()); } }), ], ); }, ), )), )))); @override void dispose() { _descriptionController.dispose(); _executeByController.dispose(); super.dispose(); } }