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.

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