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.

375 lines
16KB

  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. print("plant: ${_plant.mediaDel[0]}");
  83. var activityPlant = jsonEncode(_plant.toJson()).toString();
  84. //ADD NEW
  85. if (_plant.activityId == null) {
  86. _repository.createAction((value) {
  87. LoadingDialog.hideLoadingDialog(context);
  88. Get.back(result: value);
  89. Utils.showSnackBarSuccess(message: label_add_success);
  90. }, (error) {
  91. LoadingDialog.hideLoadingDialog(context);
  92. Utils.showSnackBarError(message: AppException.handleError(error));
  93. },
  94. apiAddAction: ConstCommon.apiAddPlant,
  95. paramActivity: ConstCommon.paramsActionPlant,
  96. activityAction: activityPlant,
  97. filePaths: filePaths);
  98. } else {
  99. //UPDATE
  100. _repository.updateAction((value) {
  101. LoadingDialog.hideLoadingDialog(context);
  102. Get.back(result: value);
  103. Utils.showSnackBarSuccess(message: label_update_success);
  104. }, (error) {
  105. LoadingDialog.hideLoadingDialog(context);
  106. Utils.showSnackBarError(message: AppException.handleError(error));
  107. },
  108. apiUpdateAction: ConstCommon.apiUpdatePlant,
  109. paramActivity: ConstCommon.paramsActionPlant,
  110. activityAction: activityPlant,
  111. filePaths: filePaths);
  112. }
  113. } else {
  114. _autoValidate = true;
  115. }
  116. }
  117. Widget _btnExecuteTimePicker() {
  118. return FlatButton(
  119. padding: EdgeInsets.only(top: 0.0, right: 0.0, bottom: 0.0, left: 0.0),
  120. onPressed: () {
  121. DatePicker.showDateTimePicker(context,
  122. showTitleActions: true, onChanged: (date) {}, onConfirm: (date) {
  123. setState(() {
  124. var parsedDate =
  125. DateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'").format(date);
  126. _plant.executeDate = "$parsedDate";
  127. executeTimeView = DateFormat("dd/MM/yyyy HH:mm").format(date);
  128. });
  129. }, currentTime: executeTime, locale: LocaleType.vi);
  130. },
  131. child: Container(
  132. padding:
  133. EdgeInsets.only(top: 0.0, right: 0.0, bottom: 10.5, left: 0.0),
  134. decoration: BoxDecoration(
  135. border: kBorderTextField,
  136. ),
  137. child: Row(
  138. children: [
  139. Expanded(
  140. child: Text(
  141. //TODO: check condition
  142. executeTimeView == null ? "$executeTime" : executeTimeView,
  143. style: TextStyle(fontSize: 14.0, color: Colors.black87),
  144. )),
  145. Icon(
  146. Icons.date_range,
  147. color: Colors.blue,
  148. ),
  149. ],
  150. )));
  151. }
  152. Widget _quantityField() {
  153. return TextFormField(
  154. keyboardType: TextInputType.numberWithOptions(decimal: true),
  155. inputFormatters: [
  156. ThousandsFormatter(
  157. formatter: NumberFormat("#,###.##", "es"), allowFraction: true)
  158. ],
  159. decoration: InputDecoration(labelText: "Số lượng cây trồng"),
  160. controller: _quantityController,
  161. onSaved: (newValue) {
  162. _plant.quantity = newValue.parseDoubleThousand();
  163. },
  164. );
  165. }
  166. Widget _densityField() {
  167. return TextFormField(
  168. keyboardType: TextInputType.text,
  169. decoration: InputDecoration(labelText: "Mật độ"),
  170. controller: _densityController,
  171. onSaved: (newValue) {
  172. _plant.density = newValue;
  173. },
  174. );
  175. }
  176. Widget _desciptionField() {
  177. return TextFormField(
  178. keyboardType: TextInputType.text,
  179. decoration: InputDecoration(labelText: "Ghi chú"),
  180. controller: _descriptionController,
  181. onSaved: (newValue) {
  182. _plant.description = newValue;
  183. },
  184. );
  185. }
  186. Widget _executeByField() {
  187. return TextFormField(
  188. keyboardType: TextInputType.text,
  189. decoration: InputDecoration(labelText: "Người thực hiện"),
  190. enabled: false,
  191. controller: _executeByController,
  192. onSaved: (newValue) {},
  193. );
  194. }
  195. _actionAppBar() {
  196. IconButton iconButton;
  197. if (1 == 1) {
  198. iconButton = IconButton(
  199. icon: Icon(
  200. Icons.done,
  201. color: Colors.black,
  202. ),
  203. onPressed: () {
  204. FocusScopeNode currentFocus = FocusScope.of(context);
  205. if (!currentFocus.hasPrimaryFocus) {
  206. currentFocus.unfocus();
  207. }
  208. _validateInputs();
  209. },
  210. );
  211. return <Widget>[iconButton];
  212. }
  213. return <Widget>[Container()];
  214. }
  215. @override
  216. Widget build(BuildContext context) => KeyboardDismisser(
  217. gestures: [
  218. GestureType.onTap,
  219. GestureType.onPanUpdateDownDirection,
  220. ],
  221. child: Scaffold(
  222. key: _scaffoldKey,
  223. appBar: AppBar(
  224. centerTitle: true,
  225. title: Text(plot_action_plant),
  226. actions: _actionAppBar()),
  227. body: KeyboardDismisser(
  228. child: MultiBlocProvider(
  229. providers: [
  230. BlocProvider<ActionDetailBloc>(
  231. create: (context) =>
  232. ActionDetailBloc(repository: Repository())
  233. ..add(FetchData(
  234. isNeedFetchData: widget.isEdit,
  235. apiActivity: ConstCommon.apiDetailPlant,
  236. activityId: widget.activityId))),
  237. BlocProvider<MediaHelperBloc>(
  238. create: (context) =>
  239. MediaHelperBloc()..add(ChangeListMedia(items: [])),
  240. )
  241. ],
  242. child: Form(
  243. key: _formKey,
  244. autovalidate: _autoValidate,
  245. child: SingleChildScrollView(
  246. padding: EdgeInsets.all(8.0),
  247. child: BlocConsumer<ActionDetailBloc,
  248. ActionDetailState>(
  249. listener: (context, state) async {
  250. if (state is ActionDetailFailure) {
  251. LoadingDialog.hideLoadingDialog(context);
  252. } else if (state is ActionDetailSuccess) {
  253. LoadingDialog.hideLoadingDialog(context);
  254. _plant = Plant.fromJson(state.item);
  255. _plant.activityId = widget.activityId;
  256. _quantityController.text = _plant.quantity
  257. .formatNumtoStringDecimal();
  258. _densityController.text = _plant.density;
  259. _descriptionController.text =
  260. _plant.description;
  261. _executeByController.text = _plant.executeBy;
  262. try {
  263. executeTime =
  264. DateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'")
  265. .parse(_plant.executeDate);
  266. } catch (_) {}
  267. executeTimeView =
  268. DateFormat("dd/MM/yyyy HH:mm")
  269. .format(executeTime);
  270. //Show media
  271. if (_plant.media != null) {
  272. BlocProvider.of<MediaHelperBloc>(context)
  273. .add(ChangeListMedia(
  274. items: UtilAction
  275. .convertFilePathToMedia(
  276. _plant.media)));
  277. }
  278. //list supply
  279. suppliesUsing = _plant.suppliesUsing;
  280. Get.find<ChangeSupplyUsing>()
  281. .changeInitList(suppliesUsing);
  282. } else if (state is ActionDetailInitial) {
  283. print("init");
  284. } else if (state is ActionDetailLoading) {
  285. print("loading");
  286. LoadingDialog.showLoadingDialog(context);
  287. }
  288. },
  289. builder: (context, state) {
  290. return Column(
  291. children: <Widget>[
  292. Container(
  293. width: double.infinity,
  294. child: Text(
  295. "Ngày thực hiện *",
  296. style: TextStyle(
  297. color: Colors.black54,
  298. fontSize: 13.0),
  299. ),
  300. ),
  301. _btnExecuteTimePicker(),
  302. SizedBox(
  303. height: 8.0,
  304. ),
  305. _quantityField(),
  306. SizedBox(
  307. height: 8.0,
  308. ),
  309. _densityField(),
  310. SizedBox(
  311. height: 8.0,
  312. ),
  313. _desciptionField(),
  314. SizedBox(
  315. height: 8.0,
  316. ),
  317. _executeByField(),
  318. SizedBox(
  319. height: 8.0,
  320. ),
  321. WidgetPlantSupply(
  322. currentItems: [],
  323. onChangeSupplies: (value) {
  324. suppliesUsing = value;
  325. }),
  326. SizedBox(
  327. height: 8.0,
  328. ),
  329. BlocBuilder<MediaHelperBloc,
  330. MediaHelperState>(
  331. builder: (context, state) {
  332. if (state is MediaHelperSuccess) {
  333. return WidgetMediaPicker(
  334. currentItems: state.items,
  335. onChangeFiles: (newPathFiles,
  336. deletePathFiles) async {
  337. Get.find<ChangeFileController>()
  338. .change(newPathFiles,
  339. deletePathFiles);
  340. });
  341. } else {
  342. return Center(
  343. child: CircularProgressIndicator());
  344. }
  345. }),
  346. ],
  347. );
  348. },
  349. ),
  350. ))))));
  351. @override
  352. void dispose() {
  353. _quantityController.dispose();
  354. _densityController.dispose();
  355. _descriptionController.dispose();
  356. _executeByController.dispose();
  357. super.dispose();
  358. }
  359. }