You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

374 lines
15KB

  1. import 'dart:convert';
  2. import 'package:farm_tpf/custom_model/Plant.dart';
  3. import 'package:farm_tpf/custom_model/SuppliesUsing.dart';
  4. import 'package:farm_tpf/data/api/app_exception.dart';
  5. import 'package:farm_tpf/data/repository/repository.dart';
  6. import 'package:farm_tpf/presentation/custom_widgets/bloc/media_helper_bloc.dart';
  7. import 'package:farm_tpf/presentation/custom_widgets/widget_loading.dart';
  8. import 'package:farm_tpf/presentation/custom_widgets/widget_media_picker.dart';
  9. import 'package:farm_tpf/presentation/custom_widgets/widget_utils.dart';
  10. import 'package:farm_tpf/presentation/screens/actions/bloc/action_detail_bloc.dart';
  11. import 'package:farm_tpf/presentation/screens/actions/controller/ChangeSupplyUsing.dart';
  12. import 'package:farm_tpf/presentation/screens/actions/plant/widget_plant_supply.dart';
  13. import 'package:farm_tpf/presentation/screens/actions/state_management_helper/change_file_controller.dart';
  14. import 'package:farm_tpf/utils/const_common.dart';
  15. import 'package:farm_tpf/utils/const_string.dart';
  16. import 'package:farm_tpf/utils/const_style.dart';
  17. import 'package:farm_tpf/utils/pref.dart';
  18. import 'package:farm_tpf/utils/validators.dart';
  19. import 'package:flutter/material.dart';
  20. import 'package:flutter_bloc/flutter_bloc.dart';
  21. import 'package:flutter_datetime_picker/flutter_datetime_picker.dart';
  22. import 'package:get/get.dart';
  23. import 'package:intl/intl.dart';
  24. import 'package:keyboard_dismisser/keyboard_dismisser.dart';
  25. import 'package:pattern_formatter/pattern_formatter.dart';
  26. import 'package:farm_tpf/utils/formatter.dart';
  27. import '../util_action.dart';
  28. class EditActionPlantScreen extends StatefulWidget {
  29. final int cropId;
  30. final bool isEdit;
  31. final int activityId;
  32. EditActionPlantScreen(
  33. {@required this.cropId, this.isEdit = false, this.activityId});
  34. @override
  35. _EditActionPlantScreenState createState() => _EditActionPlantScreenState();
  36. }
  37. class _EditActionPlantScreenState extends State<EditActionPlantScreen> {
  38. final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();
  39. final _repository = Repository();
  40. GlobalKey<FormState> _formKey = GlobalKey();
  41. bool _autoValidate = false;
  42. Plant _plant = Plant();
  43. var pref = LocalPref();
  44. final _descriptionController = TextEditingController();
  45. final _quantityController = TextEditingController();
  46. final _densityController = TextEditingController();
  47. final _executeByController = TextEditingController();
  48. List<SuppliesUsing> suppliesUsing = new List<SuppliesUsing>();
  49. String executeTimeView;
  50. DateTime executeTime = DateTime.now();
  51. List<String> filePaths = List<String>();
  52. var changeFileController = Get.put(ChangeFileController());
  53. Future<Null> getSharedPrefs() async {
  54. var currentFullName = await pref.getString(DATA_CONST.CURRENT_FULL_NAME);
  55. _executeByController.text = currentFullName ?? "";
  56. }
  57. @override
  58. void initState() {
  59. super.initState();
  60. getSharedPrefs();
  61. changeFileController.initValue();
  62. _plant.suppliesUsing = new List<SuppliesUsing>();
  63. var parsedExecuteDate =
  64. DateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'").format(executeTime);
  65. _plant.executeDate = "$parsedExecuteDate";
  66. executeTimeView = DateFormat("dd/MM/yyyy HH:mm").format(executeTime);
  67. _plant.cropId = widget.cropId;
  68. }
  69. _validateInputs() async {
  70. if (_formKey.currentState.validate()) {
  71. _formKey.currentState.save();
  72. LoadingDialog.showLoadingDialog(context);
  73. filePaths = Get.find<ChangeFileController>().newFiles;
  74. List<SuppliesUsing> newSups = [];
  75. suppliesUsing.forEach((sup) {
  76. var newSup = sup;
  77. newSup.suppliesInWarehouseId = sup.tbSuppliesInWarehouseId;
  78. newSups.add(newSup);
  79. });
  80. _plant.suppliesUsing = newSups;
  81. _plant.mediaDel = Get.find<ChangeFileController>().deleteFiles;
  82. var activityPlant = jsonEncode(_plant.toJson()).toString();
  83. //ADD NEW
  84. if (_plant.activityId == null) {
  85. _repository.createAction((value) {
  86. LoadingDialog.hideLoadingDialog(context);
  87. Get.back(result: value);
  88. Utils.showSnackBarSuccess(message: label_add_success);
  89. }, (error) {
  90. LoadingDialog.hideLoadingDialog(context);
  91. Utils.showSnackBarError(message: AppException.handleError(error));
  92. },
  93. apiAddAction: ConstCommon.apiAddPlant,
  94. paramActivity: ConstCommon.paramsActionPlant,
  95. activityAction: activityPlant,
  96. filePaths: filePaths);
  97. } else {
  98. //UPDATE
  99. _repository.updateAction((value) {
  100. LoadingDialog.hideLoadingDialog(context);
  101. Get.back(result: value);
  102. Utils.showSnackBarSuccess(message: label_update_success);
  103. }, (error) {
  104. LoadingDialog.hideLoadingDialog(context);
  105. Utils.showSnackBarError(message: AppException.handleError(error));
  106. },
  107. apiUpdateAction: ConstCommon.apiUpdatePlant,
  108. paramActivity: ConstCommon.paramsActionPlant,
  109. activityAction: activityPlant,
  110. filePaths: filePaths);
  111. }
  112. } else {
  113. _autoValidate = true;
  114. }
  115. }
  116. Widget _btnExecuteTimePicker() {
  117. return FlatButton(
  118. padding: EdgeInsets.only(top: 0.0, right: 0.0, bottom: 0.0, left: 0.0),
  119. onPressed: () {
  120. DatePicker.showDateTimePicker(context,
  121. showTitleActions: true, onChanged: (date) {}, onConfirm: (date) {
  122. setState(() {
  123. var parsedDate =
  124. DateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'").format(date);
  125. _plant.executeDate = "$parsedDate";
  126. executeTimeView = DateFormat("dd/MM/yyyy HH:mm").format(date);
  127. });
  128. }, currentTime: executeTime, locale: LocaleType.vi);
  129. },
  130. child: Container(
  131. padding:
  132. EdgeInsets.only(top: 0.0, right: 0.0, bottom: 10.5, left: 0.0),
  133. decoration: BoxDecoration(
  134. border: kBorderTextField,
  135. ),
  136. child: Row(
  137. children: [
  138. Expanded(
  139. child: Text(
  140. //TODO: check condition
  141. executeTimeView == null ? "$executeTime" : executeTimeView,
  142. style: TextStyle(fontSize: 14.0, color: Colors.black87),
  143. )),
  144. Icon(
  145. Icons.date_range,
  146. color: Colors.blue,
  147. ),
  148. ],
  149. )));
  150. }
  151. Widget _quantityField() {
  152. return TextFormField(
  153. keyboardType: TextInputType.numberWithOptions(decimal: true),
  154. inputFormatters: [
  155. ThousandsFormatter(
  156. formatter: NumberFormat("#,###.##", "es"), allowFraction: true)
  157. ],
  158. decoration: InputDecoration(labelText: "Số lượng cây trồng"),
  159. controller: _quantityController,
  160. onSaved: (newValue) {
  161. _plant.quantity = newValue.parseDoubleThousand();
  162. },
  163. );
  164. }
  165. Widget _densityField() {
  166. return TextFormField(
  167. keyboardType: TextInputType.text,
  168. decoration: InputDecoration(labelText: "Mật độ"),
  169. controller: _densityController,
  170. onSaved: (newValue) {
  171. _plant.density = newValue;
  172. },
  173. );
  174. }
  175. Widget _desciptionField() {
  176. return TextFormField(
  177. keyboardType: TextInputType.text,
  178. decoration: InputDecoration(labelText: "Ghi chú"),
  179. controller: _descriptionController,
  180. onSaved: (newValue) {
  181. _plant.description = newValue;
  182. },
  183. );
  184. }
  185. Widget _executeByField() {
  186. return TextFormField(
  187. keyboardType: TextInputType.text,
  188. decoration: InputDecoration(labelText: "Người thực hiện"),
  189. enabled: false,
  190. controller: _executeByController,
  191. onSaved: (newValue) {},
  192. );
  193. }
  194. _actionAppBar() {
  195. IconButton iconButton;
  196. if (1 == 1) {
  197. iconButton = IconButton(
  198. icon: Icon(
  199. Icons.done,
  200. color: Colors.black,
  201. ),
  202. onPressed: () {
  203. FocusScopeNode currentFocus = FocusScope.of(context);
  204. if (!currentFocus.hasPrimaryFocus) {
  205. currentFocus.unfocus();
  206. }
  207. _validateInputs();
  208. },
  209. );
  210. return <Widget>[iconButton];
  211. }
  212. return <Widget>[Container()];
  213. }
  214. @override
  215. Widget build(BuildContext context) => KeyboardDismisser(
  216. gestures: [
  217. GestureType.onTap,
  218. GestureType.onPanUpdateDownDirection,
  219. ],
  220. child: Scaffold(
  221. key: _scaffoldKey,
  222. appBar: AppBar(
  223. centerTitle: true,
  224. title: Text(plot_action_plant),
  225. actions: _actionAppBar()),
  226. body: KeyboardDismisser(
  227. child: MultiBlocProvider(
  228. providers: [
  229. BlocProvider<ActionDetailBloc>(
  230. create: (context) =>
  231. ActionDetailBloc(repository: Repository())
  232. ..add(FetchData(
  233. isNeedFetchData: widget.isEdit,
  234. apiActivity: ConstCommon.apiDetailPlant,
  235. activityId: widget.activityId))),
  236. BlocProvider<MediaHelperBloc>(
  237. create: (context) =>
  238. MediaHelperBloc()..add(ChangeListMedia(items: [])),
  239. )
  240. ],
  241. child: Form(
  242. key: _formKey,
  243. autovalidate: _autoValidate,
  244. child: SingleChildScrollView(
  245. padding: EdgeInsets.all(8.0),
  246. child: BlocConsumer<ActionDetailBloc,
  247. ActionDetailState>(
  248. listener: (context, state) async {
  249. if (state is ActionDetailFailure) {
  250. LoadingDialog.hideLoadingDialog(context);
  251. } else if (state is ActionDetailSuccess) {
  252. LoadingDialog.hideLoadingDialog(context);
  253. _plant = Plant.fromJson(state.item);
  254. _plant.activityId = widget.activityId;
  255. _quantityController.text = _plant.quantity
  256. .formatNumtoStringDecimal();
  257. _densityController.text = _plant.density;
  258. _descriptionController.text =
  259. _plant.description;
  260. _executeByController.text = _plant.executeBy;
  261. try {
  262. executeTime =
  263. DateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'")
  264. .parse(_plant.executeDate);
  265. } catch (_) {}
  266. executeTimeView =
  267. DateFormat("dd/MM/yyyy HH:mm")
  268. .format(executeTime);
  269. //Show media
  270. if (_plant.media != null) {
  271. BlocProvider.of<MediaHelperBloc>(context)
  272. .add(ChangeListMedia(
  273. items: UtilAction
  274. .convertFilePathToMedia(
  275. _plant.media)));
  276. }
  277. //list supply
  278. suppliesUsing = _plant.suppliesUsing;
  279. Get.find<ChangeSupplyUsing>()
  280. .changeInitList(suppliesUsing);
  281. } else if (state is ActionDetailInitial) {
  282. print("init");
  283. } else if (state is ActionDetailLoading) {
  284. print("loading");
  285. LoadingDialog.showLoadingDialog(context);
  286. }
  287. },
  288. builder: (context, state) {
  289. return Column(
  290. children: <Widget>[
  291. Container(
  292. width: double.infinity,
  293. child: Text(
  294. "Ngày thực hiện *",
  295. style: TextStyle(
  296. color: Colors.black54,
  297. fontSize: 13.0),
  298. ),
  299. ),
  300. _btnExecuteTimePicker(),
  301. SizedBox(
  302. height: 8.0,
  303. ),
  304. _quantityField(),
  305. SizedBox(
  306. height: 8.0,
  307. ),
  308. _densityField(),
  309. SizedBox(
  310. height: 8.0,
  311. ),
  312. _desciptionField(),
  313. SizedBox(
  314. height: 8.0,
  315. ),
  316. _executeByField(),
  317. SizedBox(
  318. height: 8.0,
  319. ),
  320. WidgetPlantSupply(
  321. currentItems: [],
  322. onChangeSupplies: (value) {
  323. suppliesUsing = value;
  324. }),
  325. SizedBox(
  326. height: 8.0,
  327. ),
  328. BlocBuilder<MediaHelperBloc,
  329. MediaHelperState>(
  330. builder: (context, state) {
  331. if (state is MediaHelperSuccess) {
  332. return WidgetMediaPicker(
  333. currentItems: state.items,
  334. onChangeFiles: (newPathFiles,
  335. deletePathFiles) async {
  336. Get.find<ChangeFileController>()
  337. .change(newPathFiles,
  338. deletePathFiles);
  339. });
  340. } else {
  341. return Center(
  342. child: CircularProgressIndicator());
  343. }
  344. }),
  345. ],
  346. );
  347. },
  348. ),
  349. ))))));
  350. @override
  351. void dispose() {
  352. _quantityController.dispose();
  353. _densityController.dispose();
  354. _descriptionController.dispose();
  355. _executeByController.dispose();
  356. super.dispose();
  357. }
  358. }