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.

490 lines
18KB

  1. import 'dart:convert';
  2. import 'package:farm_tpf/custom_model/Harvest.dart';
  3. import 'package:farm_tpf/custom_model/Sell.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/state_management_helper/change_file_controller.dart';
  12. import 'package:farm_tpf/utils/const_common.dart';
  13. import 'package:farm_tpf/utils/const_string.dart';
  14. import 'package:farm_tpf/utils/const_style.dart';
  15. import 'package:farm_tpf/utils/pref.dart';
  16. import 'package:farm_tpf/utils/validators.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 '../bloc_get_harvest.dart';
  26. import '../util_action.dart';
  27. class EditActionSellScreen extends StatefulWidget {
  28. final int cropId;
  29. final bool isEdit;
  30. final int activityId;
  31. final int harvestId;
  32. EditActionSellScreen(
  33. {@required this.cropId,
  34. this.isEdit = false,
  35. this.activityId,
  36. this.harvestId});
  37. @override
  38. _EditActionSellScreenState createState() => _EditActionSellScreenState();
  39. }
  40. class _EditActionSellScreenState extends State<EditActionSellScreen> {
  41. final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();
  42. final _repository = Repository();
  43. GlobalKey<FormState> _formKey = GlobalKey();
  44. bool _autoValidate = false;
  45. Sell _sell = Sell();
  46. TextEditingController _l1Controller = TextEditingController();
  47. TextEditingController _l2Controller = TextEditingController();
  48. TextEditingController _l3Controller = TextEditingController();
  49. TextEditingController _removedQuantityController = TextEditingController();
  50. TextEditingController _descriptionController = TextEditingController();
  51. final _buyerController = TextEditingController();
  52. final _executeByController = TextEditingController();
  53. var pref = LocalPref();
  54. List<Harvest> _harvests = List<Harvest>();
  55. Harvest harvestValue;
  56. String executeTimeView;
  57. DateTime executeTime = DateTime.now();
  58. List<String> filePaths = List<String>();
  59. var changeFileController = Get.put(ChangeFileController());
  60. Future<Null> getSharedPrefs() async {
  61. var currentFullName = await pref.getString(DATA_CONST.CURRENT_FULL_NAME);
  62. _executeByController.text = currentFullName ?? "";
  63. }
  64. @override
  65. void initState() {
  66. super.initState();
  67. getSharedPrefs();
  68. changeFileController.initValue();
  69. var parsedExecuteDate =
  70. DateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'").format(executeTime);
  71. _sell.executeDate = "$parsedExecuteDate";
  72. executeTimeView = DateFormat("dd/MM/yyyy HH:mm").format(executeTime);
  73. _sell.cropId = widget.cropId;
  74. if (!widget.isEdit) {
  75. getHarvestBloc.getHarvests((data) {
  76. _harvests = data;
  77. for (var item in _harvests) {
  78. if (item.id == widget.harvestId) {
  79. harvestValue = item;
  80. break;
  81. }
  82. }
  83. }, (err) {});
  84. }
  85. }
  86. _validateInputs() async {
  87. if (_formKey.currentState.validate()) {
  88. _formKey.currentState.save();
  89. LoadingDialog.showLoadingDialog(context);
  90. filePaths = Get.find<ChangeFileController>().files;
  91. try {
  92. var activitySell = jsonEncode(_sell.toJson()).toString();
  93. //ADD NEW
  94. if (_sell.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.apiAddSell,
  104. paramActivity: ConstCommon.paramsActionSell,
  105. activityAction: activitySell,
  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.apiUpdateSell,
  118. paramActivity: ConstCommon.paramsActionSell,
  119. activityAction: activitySell,
  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. _sell.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. _sell.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. _sell.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. _sell.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. _sell.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. _sell.removedQuantity = newValue.parseDoubleThousand();
  250. },
  251. );
  252. }
  253. Widget _buyerField() {
  254. return TextFormField(
  255. keyboardType: TextInputType.text,
  256. decoration: InputDecoration(labelText: "Khách hàng"),
  257. controller: _buyerController,
  258. onSaved: (newValue) {
  259. _sell.buyer = newValue;
  260. },
  261. );
  262. }
  263. Widget _descriptionField() {
  264. return TextFormField(
  265. keyboardType: TextInputType.text,
  266. decoration: InputDecoration(labelText: "Ghi chú"),
  267. controller: _descriptionController,
  268. onSaved: (newValue) {
  269. _sell.description = newValue;
  270. },
  271. );
  272. }
  273. Widget _executeByField() {
  274. return TextFormField(
  275. keyboardType: TextInputType.text,
  276. decoration: InputDecoration(labelText: "Người thực hiện"),
  277. enabled: false,
  278. controller: _executeByController,
  279. onSaved: (newValue) {},
  280. );
  281. }
  282. _actionAppBar() {
  283. IconButton iconButton;
  284. if (1 == 1) {
  285. iconButton = IconButton(
  286. icon: Icon(
  287. Icons.done,
  288. color: Colors.black,
  289. ),
  290. onPressed: () {
  291. FocusScopeNode currentFocus = FocusScope.of(context);
  292. if (!currentFocus.hasPrimaryFocus) {
  293. currentFocus.unfocus();
  294. }
  295. _validateInputs();
  296. },
  297. );
  298. return <Widget>[iconButton];
  299. }
  300. return <Widget>[Container()];
  301. }
  302. @override
  303. Widget build(BuildContext context) => KeyboardDismisser(
  304. gestures: [
  305. GestureType.onTap,
  306. GestureType.onPanUpdateDownDirection,
  307. ],
  308. child: Scaffold(
  309. key: _scaffoldKey,
  310. appBar: AppBar(
  311. centerTitle: true,
  312. title: Text(plot_action_sell),
  313. actions: _actionAppBar()),
  314. body: KeyboardDismisser(
  315. child: MultiBlocProvider(
  316. providers: [
  317. BlocProvider<ActionDetailBloc>(
  318. create: (context) =>
  319. ActionDetailBloc(repository: Repository())
  320. ..add(FetchData(
  321. isNeedFetchData: widget.isEdit,
  322. apiActivity: ConstCommon.apiDetailSell,
  323. activityId: widget.activityId))),
  324. BlocProvider<MediaHelperBloc>(
  325. create: (context) =>
  326. MediaHelperBloc()..add(ChangeListMedia(items: [])),
  327. )
  328. ],
  329. child: Form(
  330. key: _formKey,
  331. autovalidate: _autoValidate,
  332. child: SingleChildScrollView(
  333. padding: EdgeInsets.all(8.0),
  334. child: BlocConsumer<ActionDetailBloc, ActionDetailState>(
  335. listener: (context, state) async {
  336. if (state is ActionDetailFailure) {
  337. LoadingDialog.hideLoadingDialog(context);
  338. } else if (state is ActionDetailSuccess) {
  339. LoadingDialog.hideLoadingDialog(context);
  340. print(state.item);
  341. _sell = Sell.fromJson(state.item);
  342. _sell.activityId = widget.activityId;
  343. _l1Controller.text =
  344. _sell.quantityLv1.formatNumtoStringDecimal();
  345. _l2Controller.text =
  346. _sell.quantityLv2.formatNumtoStringDecimal();
  347. _l3Controller.text =
  348. _sell.quantityLv3.formatNumtoStringDecimal();
  349. _removedQuantityController.text = _sell
  350. .removedQuantity
  351. .formatNumtoStringDecimal();
  352. _buyerController.text = _sell.buyer ?? "";
  353. _descriptionController.text =
  354. _sell.description ?? "";
  355. _executeByController.text = _sell.executeBy;
  356. //select harvest
  357. getHarvestBloc.getHarvests((data) {
  358. _harvests = data;
  359. for (var item in _harvests) {
  360. if (item.id == _sell.harvestId) {
  361. harvestValue = item;
  362. break;
  363. }
  364. }
  365. }, (err) {});
  366. try {
  367. executeTime =
  368. DateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'")
  369. .parse(_sell.executeDate);
  370. executeTimeView = DateFormat("dd/MM/yyyy HH:mm")
  371. .format(executeTime);
  372. } catch (_) {}
  373. //Show media
  374. if (_sell.media != null) {
  375. await UtilAction.cacheFiles(_sell.media)
  376. .then((value) {
  377. BlocProvider.of<MediaHelperBloc>(context)
  378. .add(ChangeListMedia(items: value));
  379. }).whenComplete(() {
  380. print("completed");
  381. });
  382. }
  383. } else if (state is ActionDetailInitial) {
  384. } else if (state is ActionDetailLoading) {
  385. LoadingDialog.showLoadingDialog(context);
  386. }
  387. },
  388. builder: (context, state) {
  389. return Column(
  390. children: <Widget>[
  391. Container(
  392. width: double.infinity,
  393. child: Text(
  394. "Ngày thực hiện *",
  395. style: TextStyle(
  396. color: Colors.black54, fontSize: 13.0),
  397. ),
  398. ),
  399. _btnExecuteTimePicker(),
  400. SizedBox(
  401. height: 8.0,
  402. ),
  403. _dropdownHarvest(),
  404. SizedBox(
  405. height: 8.0,
  406. ),
  407. _l1Field(),
  408. SizedBox(
  409. height: 8.0,
  410. ),
  411. _l2Field(),
  412. SizedBox(
  413. height: 8.0,
  414. ),
  415. _l3Field(),
  416. SizedBox(
  417. height: 8.0,
  418. ),
  419. _removedQuantityField(),
  420. SizedBox(
  421. height: 8.0,
  422. ),
  423. _buyerField(),
  424. SizedBox(
  425. height: 8.0,
  426. ),
  427. _descriptionField(),
  428. SizedBox(
  429. height: 8.0,
  430. ),
  431. _executeByField(),
  432. SizedBox(
  433. height: 8.0,
  434. ),
  435. BlocBuilder<MediaHelperBloc, MediaHelperState>(
  436. builder: (context, state) {
  437. if (state is MediaHelperSuccess) {
  438. return WidgetMediaPicker(
  439. currentItems: state.items,
  440. onChangeFiles: (filePaths) async {
  441. Get.find<ChangeFileController>()
  442. .addAllFile(filePaths);
  443. });
  444. } else {
  445. return Center(
  446. child: CircularProgressIndicator());
  447. }
  448. }),
  449. ],
  450. );
  451. },
  452. ),
  453. )),
  454. ))));
  455. @override
  456. void dispose() {
  457. _l1Controller.dispose();
  458. _l2Controller.dispose();
  459. _l3Controller.dispose();
  460. _removedQuantityController.dispose();
  461. _descriptionController.dispose();
  462. _buyerController.dispose();
  463. _executeByController.dispose();
  464. super.dispose();
  465. }
  466. }