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.

472 lines
18KB

  1. import 'dart:convert';
  2. import 'package:farm_tpf/custom_model/Harvest.dart';
  3. import 'package:farm_tpf/custom_model/Packing.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/bloc_get_harvest.dart';
  12. import 'package:farm_tpf/presentation/screens/actions/state_management_helper/change_file_controller.dart';
  13. import 'package:farm_tpf/utils/const_common.dart';
  14. import 'package:farm_tpf/utils/const_string.dart';
  15. import 'package:farm_tpf/utils/const_style.dart';
  16. import 'package:farm_tpf/utils/pref.dart';
  17. import 'package:flutter/material.dart';
  18. import 'package:flutter_bloc/flutter_bloc.dart';
  19. import 'package:flutter_datetime_picker/flutter_datetime_picker.dart';
  20. import 'package:get/get.dart';
  21. import 'package:intl/intl.dart';
  22. import 'package:keyboard_dismisser/keyboard_dismisser.dart';
  23. import 'package:pattern_formatter/pattern_formatter.dart';
  24. import 'package:farm_tpf/utils/formatter.dart';
  25. import '../util_action.dart';
  26. class EditActionPackingScreen extends StatefulWidget {
  27. final int cropId;
  28. final bool isEdit;
  29. final int activityId;
  30. final int harvestId;
  31. EditActionPackingScreen(
  32. {@required this.cropId,
  33. this.isEdit = false,
  34. this.activityId,
  35. this.harvestId});
  36. @override
  37. _EditActionPackingScreenState createState() =>
  38. _EditActionPackingScreenState();
  39. }
  40. class _EditActionPackingScreenState extends State<EditActionPackingScreen> {
  41. final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();
  42. final _repository = Repository();
  43. GlobalKey<FormState> _formKey = GlobalKey();
  44. bool _autoValidate = false;
  45. Packing _packing = Packing();
  46. TextEditingController _l1Controller = TextEditingController();
  47. TextEditingController _l2Controller = TextEditingController();
  48. TextEditingController _l3Controller = TextEditingController();
  49. TextEditingController _removedQuantityController = TextEditingController();
  50. TextEditingController _descriptionController = TextEditingController();
  51. final _executeByController = TextEditingController();
  52. var pref = LocalPref();
  53. List<Harvest> _harvests = List<Harvest>();
  54. Harvest harvestValue;
  55. String executeTimeView;
  56. DateTime executeTime = DateTime.now();
  57. List<String> filePaths = List<String>();
  58. var changeFileController = Get.put(ChangeFileController());
  59. Future<Null> getSharedPrefs() async {
  60. var currentFullName = await pref.getString(DATA_CONST.CURRENT_FULL_NAME);
  61. _executeByController.text = currentFullName ?? "";
  62. }
  63. @override
  64. void initState() {
  65. super.initState();
  66. getSharedPrefs();
  67. changeFileController.initValue();
  68. var parsedExecuteDate =
  69. DateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'").format(executeTime);
  70. _packing.executeDate = "$parsedExecuteDate";
  71. executeTimeView = DateFormat("dd/MM/yyyy HH:mm").format(executeTime);
  72. _packing.cropId = widget.cropId;
  73. if (!widget.isEdit) {
  74. getHarvestBloc.getHarvests((data) {
  75. _harvests = data;
  76. for (var item in _harvests) {
  77. if (item.id == widget.harvestId) {
  78. harvestValue = item;
  79. break;
  80. }
  81. }
  82. }, (err) {});
  83. }
  84. }
  85. _validateInputs() async {
  86. if (_formKey.currentState.validate()) {
  87. _formKey.currentState.save();
  88. LoadingDialog.showLoadingDialog(context);
  89. filePaths = Get.find<ChangeFileController>().newFiles;
  90. try {
  91. _packing.mediaDel = Get.find<ChangeFileController>().deleteFiles;
  92. var activityPacking = jsonEncode(_packing.toJson()).toString();
  93. //ADD NEW
  94. if (_packing.activityId == null) {
  95. _repository.createAction((value) {
  96. LoadingDialog.hideLoadingDialog(context);
  97. Get.back(result: value);
  98. Utils.showSnackBarSuccess(message: label_add_success);
  99. }, (error) {
  100. LoadingDialog.hideLoadingDialog(context);
  101. Utils.showSnackBarError(message: AppException.handleError(error));
  102. },
  103. apiAddAction: ConstCommon.apiAddPacking,
  104. paramActivity: ConstCommon.paramsActionPacking,
  105. activityAction: activityPacking,
  106. filePaths: filePaths);
  107. } else {
  108. //UPDATE
  109. _repository.updateAction((value) {
  110. LoadingDialog.hideLoadingDialog(context);
  111. Get.back(result: value);
  112. Utils.showSnackBarSuccess(message: label_update_success);
  113. }, (error) {
  114. LoadingDialog.hideLoadingDialog(context);
  115. Utils.showSnackBarError(message: AppException.handleError(error));
  116. },
  117. apiUpdateAction: ConstCommon.apiUpdatePacking,
  118. paramActivity: ConstCommon.paramsActionPacking,
  119. activityAction: activityPacking,
  120. filePaths: filePaths);
  121. }
  122. } catch (e) {
  123. LoadingDialog.hideLoadingDialog(context);
  124. print(e.toString());
  125. }
  126. } else {
  127. _autoValidate = true;
  128. }
  129. }
  130. List<DropdownMenuItem<Harvest>> _buildDropMenu(List<Harvest> actions) {
  131. return actions
  132. .map((action) => DropdownMenuItem<Harvest>(
  133. child: Text("Mã thu hoạch " + action.id.toString()),
  134. value: action,
  135. ))
  136. .toList();
  137. }
  138. Widget _dropdownHarvest() {
  139. return StreamBuilder(
  140. stream: getHarvestBloc.actions,
  141. builder: (context, AsyncSnapshot<dynamic> snapshot) {
  142. if (snapshot.hasData) {
  143. return DropdownButtonFormField<Harvest>(
  144. value: harvestValue,
  145. hint: Text("Mã thu hoạch *"),
  146. onChanged: (Harvest newValue) {
  147. setState(() {
  148. harvestValue = newValue;
  149. _packing.harvestId = newValue.id;
  150. });
  151. },
  152. isExpanded: true,
  153. items: _buildDropMenu(_harvests));
  154. } else {
  155. return Center(
  156. child: CircularProgressIndicator(),
  157. );
  158. }
  159. },
  160. );
  161. }
  162. Widget _btnExecuteTimePicker() {
  163. return FlatButton(
  164. padding: EdgeInsets.only(top: 0.0, right: 0.0, bottom: 0.0, left: 0.0),
  165. onPressed: () {
  166. DatePicker.showDateTimePicker(context,
  167. showTitleActions: true, onChanged: (date) {}, onConfirm: (date) {
  168. setState(() {
  169. var parsedDate =
  170. DateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'").format(date);
  171. _packing.executeDate = "$parsedDate";
  172. executeTimeView = DateFormat("dd/MM/yyyy HH:mm").format(date);
  173. });
  174. }, currentTime: executeTime, locale: LocaleType.vi);
  175. },
  176. child: Container(
  177. padding:
  178. EdgeInsets.only(top: 0.0, right: 0.0, bottom: 10.5, left: 0.0),
  179. decoration: BoxDecoration(
  180. border: kBorderTextField,
  181. ),
  182. child: Row(
  183. children: [
  184. Expanded(
  185. child: Text(
  186. //TODO: check condition
  187. executeTimeView == null ? "$executeTime" : executeTimeView,
  188. style: TextStyle(fontSize: 14.0, color: Colors.black87),
  189. )),
  190. Icon(
  191. Icons.date_range,
  192. color: Colors.blue,
  193. ),
  194. ],
  195. )));
  196. }
  197. Widget _l1Field() {
  198. return TextFormField(
  199. keyboardType: TextInputType.numberWithOptions(decimal: true),
  200. inputFormatters: [
  201. ThousandsFormatter(
  202. formatter: NumberFormat("#,###.##", "es"), allowFraction: true)
  203. ],
  204. decoration: InputDecoration(labelText: "Số lượng/khối lượng loại 1"),
  205. controller: _l1Controller,
  206. onSaved: (newValue) {
  207. _packing.quantityLv1 = newValue.parseDoubleThousand();
  208. },
  209. );
  210. }
  211. Widget _l2Field() {
  212. return TextFormField(
  213. keyboardType: TextInputType.numberWithOptions(decimal: true),
  214. inputFormatters: [
  215. ThousandsFormatter(
  216. formatter: NumberFormat("#,###.##", "es"), allowFraction: true)
  217. ],
  218. decoration: InputDecoration(labelText: "Số lượng/khối lượng loại 2"),
  219. controller: _l2Controller,
  220. onSaved: (newValue) {
  221. _packing.quantityLv2 = newValue.parseDoubleThousand();
  222. },
  223. );
  224. }
  225. Widget _l3Field() {
  226. return TextFormField(
  227. keyboardType: TextInputType.numberWithOptions(decimal: true),
  228. inputFormatters: [
  229. ThousandsFormatter(
  230. formatter: NumberFormat("#,###.##", "es"), allowFraction: true)
  231. ],
  232. decoration: InputDecoration(labelText: "Số lượng/khối lượng loại 3"),
  233. controller: _l3Controller,
  234. onSaved: (newValue) {
  235. _packing.quantityLv3 = newValue.parseDoubleThousand();
  236. },
  237. );
  238. }
  239. Widget _removedQuantityField() {
  240. return TextFormField(
  241. keyboardType: TextInputType.numberWithOptions(decimal: true),
  242. inputFormatters: [
  243. ThousandsFormatter(
  244. formatter: NumberFormat("#,###.##", "es"), allowFraction: true)
  245. ],
  246. decoration: InputDecoration(labelText: "Số lượng/khối lượng loại bỏ"),
  247. controller: _removedQuantityController,
  248. onSaved: (newValue) {
  249. _packing.removedQuantity = newValue.parseDoubleThousand();
  250. },
  251. );
  252. }
  253. Widget _descriptionField() {
  254. return TextFormField(
  255. keyboardType: TextInputType.text,
  256. decoration: InputDecoration(labelText: "Ghi chú"),
  257. controller: _descriptionController,
  258. onSaved: (newValue) {
  259. _packing.description = newValue;
  260. },
  261. );
  262. }
  263. Widget _executeByField() {
  264. return TextFormField(
  265. keyboardType: TextInputType.text,
  266. decoration: InputDecoration(labelText: "Người thực hiện"),
  267. enabled: false,
  268. controller: _executeByController,
  269. onSaved: (newValue) {},
  270. );
  271. }
  272. _actionAppBar() {
  273. IconButton iconButton;
  274. if (1 == 1) {
  275. iconButton = IconButton(
  276. icon: Icon(
  277. Icons.done,
  278. color: Colors.black,
  279. ),
  280. onPressed: () {
  281. FocusScopeNode currentFocus = FocusScope.of(context);
  282. if (!currentFocus.hasPrimaryFocus) {
  283. currentFocus.unfocus();
  284. }
  285. _validateInputs();
  286. },
  287. );
  288. return <Widget>[iconButton];
  289. }
  290. return <Widget>[Container()];
  291. }
  292. @override
  293. Widget build(BuildContext context) => KeyboardDismisser(
  294. gestures: [
  295. GestureType.onTap,
  296. GestureType.onPanUpdateDownDirection,
  297. ],
  298. child: Scaffold(
  299. key: _scaffoldKey,
  300. appBar: AppBar(
  301. centerTitle: true,
  302. title: Text(plot_action_packing),
  303. actions: _actionAppBar()),
  304. body: KeyboardDismisser(
  305. child: MultiBlocProvider(
  306. providers: [
  307. BlocProvider<ActionDetailBloc>(
  308. create: (context) =>
  309. ActionDetailBloc(repository: Repository())
  310. ..add(FetchData(
  311. isNeedFetchData: widget.isEdit,
  312. apiActivity: ConstCommon.apiDetailPacking,
  313. activityId: widget.activityId))),
  314. BlocProvider<MediaHelperBloc>(
  315. create: (context) =>
  316. MediaHelperBloc()..add(ChangeListMedia(items: [])),
  317. )
  318. ],
  319. child: Form(
  320. key: _formKey,
  321. autovalidate: _autoValidate,
  322. child: SingleChildScrollView(
  323. padding: EdgeInsets.all(8.0),
  324. child: BlocConsumer<ActionDetailBloc, ActionDetailState>(
  325. listener: (context, state) async {
  326. if (state is ActionDetailFailure) {
  327. LoadingDialog.hideLoadingDialog(context);
  328. } else if (state is ActionDetailSuccess) {
  329. LoadingDialog.hideLoadingDialog(context);
  330. print(state.item);
  331. _packing = Packing.fromJson(state.item);
  332. _packing.activityId = widget.activityId;
  333. _l1Controller.text =
  334. _packing.quantityLv1.formatNumtoStringDecimal();
  335. _l2Controller.text =
  336. _packing.quantityLv2.formatNumtoStringDecimal();
  337. _l3Controller.text =
  338. _packing.quantityLv3.formatNumtoStringDecimal();
  339. _removedQuantityController.text = _packing
  340. .removedQuantity
  341. .formatNumtoStringDecimal();
  342. _descriptionController.text =
  343. _packing.description ?? "";
  344. _executeByController.text = _packing.executeBy;
  345. //select harvest
  346. getHarvestBloc.getHarvests((data) {
  347. _harvests = data;
  348. for (var item in _harvests) {
  349. if (item.id == _packing.harvestId) {
  350. harvestValue = item;
  351. break;
  352. }
  353. }
  354. }, (err) {});
  355. try {
  356. executeTime =
  357. DateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'")
  358. .parse(_packing.executeDate);
  359. executeTimeView = DateFormat("dd/MM/yyyy HH:mm")
  360. .format(executeTime);
  361. } catch (_) {}
  362. //Show media
  363. if (_packing.media != null) {
  364. BlocProvider.of<MediaHelperBloc>(context).add(
  365. ChangeListMedia(
  366. items: UtilAction.convertFilePathToMedia(
  367. _packing.media)));
  368. }
  369. } else if (state is ActionDetailInitial) {
  370. } else if (state is ActionDetailLoading) {
  371. LoadingDialog.showLoadingDialog(context);
  372. }
  373. },
  374. builder: (context, state) {
  375. return Column(
  376. children: <Widget>[
  377. Container(
  378. width: double.infinity,
  379. child: Text(
  380. "Ngày thực hiện *",
  381. style: TextStyle(
  382. color: Colors.black54, fontSize: 13.0),
  383. ),
  384. ),
  385. _btnExecuteTimePicker(),
  386. SizedBox(
  387. height: 8.0,
  388. ),
  389. _dropdownHarvest(),
  390. SizedBox(
  391. height: 8.0,
  392. ),
  393. _l1Field(),
  394. SizedBox(
  395. height: 8.0,
  396. ),
  397. _l2Field(),
  398. SizedBox(
  399. height: 8.0,
  400. ),
  401. _l3Field(),
  402. SizedBox(
  403. height: 8.0,
  404. ),
  405. _removedQuantityField(),
  406. SizedBox(
  407. height: 8.0,
  408. ),
  409. _descriptionField(),
  410. SizedBox(
  411. height: 8.0,
  412. ),
  413. _executeByField(),
  414. SizedBox(
  415. height: 8.0,
  416. ),
  417. BlocBuilder<MediaHelperBloc, MediaHelperState>(
  418. builder: (context, state) {
  419. if (state is MediaHelperSuccess) {
  420. return WidgetMediaPicker(
  421. currentItems: state.items,
  422. onChangeFiles: (newPathFiles,
  423. deletePathFiles) async {
  424. Get.find<ChangeFileController>().change(
  425. newPathFiles, deletePathFiles);
  426. });
  427. } else {
  428. return Center(
  429. child: CircularProgressIndicator());
  430. }
  431. }),
  432. ],
  433. );
  434. },
  435. ),
  436. )),
  437. ))));
  438. @override
  439. void dispose() {
  440. _l1Controller.dispose();
  441. _l2Controller.dispose();
  442. _l3Controller.dispose();
  443. _removedQuantityController.dispose();
  444. _descriptionController.dispose();
  445. _executeByController.dispose();
  446. super.dispose();
  447. }
  448. }