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.

474 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>().files;
  90. try {
  91. var activityPacking = jsonEncode(_packing.toJson()).toString();
  92. //ADD NEW
  93. if (_packing.activityId == null) {
  94. _repository.createAction((value) {
  95. LoadingDialog.hideLoadingDialog(context);
  96. Get.back(result: value);
  97. Utils.showSnackBarSuccess(message: label_add_success);
  98. }, (error) {
  99. LoadingDialog.hideLoadingDialog(context);
  100. Utils.showSnackBarError(message: AppException.handleError(error));
  101. },
  102. apiAddAction: ConstCommon.apiAddPacking,
  103. paramActivity: ConstCommon.paramsActionPacking,
  104. activityAction: activityPacking,
  105. filePaths: filePaths);
  106. } else {
  107. //UPDATE
  108. _repository.updateAction((value) {
  109. LoadingDialog.hideLoadingDialog(context);
  110. Get.back(result: value);
  111. Utils.showSnackBarSuccess(message: label_update_success);
  112. }, (error) {
  113. LoadingDialog.hideLoadingDialog(context);
  114. Utils.showSnackBarError(message: AppException.handleError(error));
  115. },
  116. apiUpdateAction: ConstCommon.apiUpdatePacking,
  117. paramActivity: ConstCommon.paramsActionPacking,
  118. activityAction: activityPacking,
  119. filePaths: filePaths);
  120. }
  121. } catch (e) {
  122. LoadingDialog.hideLoadingDialog(context);
  123. print(e.toString());
  124. }
  125. } else {
  126. _autoValidate = true;
  127. }
  128. }
  129. List<DropdownMenuItem<Harvest>> _buildDropMenu(List<Harvest> actions) {
  130. return actions
  131. .map((action) => DropdownMenuItem<Harvest>(
  132. child: Text("Mã thu hoạch " + action.id.toString()),
  133. value: action,
  134. ))
  135. .toList();
  136. }
  137. Widget _dropdownHarvest() {
  138. return StreamBuilder(
  139. stream: getHarvestBloc.actions,
  140. builder: (context, AsyncSnapshot<dynamic> snapshot) {
  141. if (snapshot.hasData) {
  142. return DropdownButtonFormField<Harvest>(
  143. value: harvestValue,
  144. hint: Text("Mã thu hoạch *"),
  145. onChanged: (Harvest newValue) {
  146. setState(() {
  147. harvestValue = newValue;
  148. _packing.harvestId = newValue.id;
  149. });
  150. },
  151. validator: (value) => value == null ? "Mã thu hoạch" : null,
  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. await UtilAction.cacheFiles(_packing.media)
  365. .then((value) {
  366. BlocProvider.of<MediaHelperBloc>(context)
  367. .add(ChangeListMedia(items: value));
  368. }).whenComplete(() {
  369. print("completed");
  370. });
  371. }
  372. } else if (state is ActionDetailInitial) {
  373. } else if (state is ActionDetailLoading) {
  374. LoadingDialog.showLoadingDialog(context);
  375. }
  376. },
  377. builder: (context, state) {
  378. return Column(
  379. children: <Widget>[
  380. Container(
  381. width: double.infinity,
  382. child: Text(
  383. "Ngày thực hiện *",
  384. style: TextStyle(
  385. color: Colors.black54, fontSize: 13.0),
  386. ),
  387. ),
  388. _btnExecuteTimePicker(),
  389. SizedBox(
  390. height: 8.0,
  391. ),
  392. _dropdownHarvest(),
  393. SizedBox(
  394. height: 8.0,
  395. ),
  396. _l1Field(),
  397. SizedBox(
  398. height: 8.0,
  399. ),
  400. _l2Field(),
  401. SizedBox(
  402. height: 8.0,
  403. ),
  404. _l3Field(),
  405. SizedBox(
  406. height: 8.0,
  407. ),
  408. _removedQuantityField(),
  409. SizedBox(
  410. height: 8.0,
  411. ),
  412. _descriptionField(),
  413. SizedBox(
  414. height: 8.0,
  415. ),
  416. _executeByField(),
  417. SizedBox(
  418. height: 8.0,
  419. ),
  420. BlocBuilder<MediaHelperBloc, MediaHelperState>(
  421. builder: (context, state) {
  422. if (state is MediaHelperSuccess) {
  423. return WidgetMediaPicker(
  424. currentItems: state.items,
  425. onChangeFiles: (filePaths) async {
  426. Get.find<ChangeFileController>()
  427. .addAllFile(filePaths);
  428. });
  429. } else {
  430. return Center(
  431. child: CircularProgressIndicator());
  432. }
  433. }),
  434. ],
  435. );
  436. },
  437. ),
  438. )),
  439. ))));
  440. @override
  441. void dispose() {
  442. _l1Controller.dispose();
  443. _l2Controller.dispose();
  444. _l3Controller.dispose();
  445. _removedQuantityController.dispose();
  446. _descriptionController.dispose();
  447. _executeByController.dispose();
  448. super.dispose();
  449. }
  450. }