Advertisement
danielbrito1987

home_page

Nov 16th, 2018
153
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Dart 41.68 KB | None | 0 0
  1. import 'dart:async';
  2. import 'dart:convert';
  3. import 'dart:io';
  4. import 'dart:isolate';
  5. import 'dart:typed_data';
  6.  
  7. import 'package:coocafe_tecnico_app/helpers/cultura_helper.dart';
  8. import 'package:coocafe_tecnico_app/helpers/notificacao_propriedade_helper.dart';
  9. import 'package:coocafe_tecnico_app/helpers/notificacoes_helper.dart';
  10. import 'package:coocafe_tecnico_app/helpers/produtor_helper.dart';
  11. import 'package:coocafe_tecnico_app/helpers/filial_helper.dart';
  12. import 'package:coocafe_tecnico_app/helpers/propriedade_helper.dart';
  13. import 'package:coocafe_tecnico_app/helpers/safra_helper.dart';
  14. import 'package:coocafe_tecnico_app/helpers/talhao_helper.dart';
  15. import 'package:coocafe_tecnico_app/helpers/tipo_titulo_helper.dart';
  16. import 'package:coocafe_tecnico_app/helpers/notificacoes_cooperado_helper.dart';
  17. import 'package:coocafe_tecnico_app/helpers/titulos_cp_helper.dart';
  18. import 'package:coocafe_tecnico_app/helpers/titulos_cr_helper.dart';
  19. import 'package:coocafe_tecnico_app/widgets/customShowDialog.dart';
  20. import 'package:coocafe_tecnico_app/widgets/drawer.dart';
  21. import 'package:coocafe_tecnico_app/pages/lista-produtor-page.dart';
  22. import 'package:coocafe_tecnico_app/pages/login_page.dart';
  23. import 'package:coocafe_tecnico_app/pages/notificacoes-page.dart';
  24. import 'package:coocafe_tecnico_app/pages/produtor_page.dart';
  25. import 'package:flutter/material.dart';
  26. import 'package:flutter/services.dart';
  27. import 'package:flutter_string_encryption/flutter_string_encryption.dart';
  28. import 'package:shared_preferences/shared_preferences.dart';
  29. import 'package:url_launcher/url_launcher.dart';
  30. import 'package:http/http.dart' as http;
  31. import 'package:date_format/date_format.dart';
  32. //import 'package:html/parser.dart' show parse;
  33. import 'package:connectivity/connectivity.dart';
  34. import 'package:screen/screen.dart';
  35. import 'package:modal_progress_hud/modal_progress_hud.dart';
  36.  
  37. class HomePage extends StatefulWidget {
  38.   static String tag = "home-page";
  39.   final bool refreshDrawer;
  40.  
  41.   HomePage({this.refreshDrawer});
  42.  
  43.   @override
  44.   _HomePageState createState() => _HomePageState();
  45. }
  46.  
  47. class _HomePageState extends State<HomePage> {
  48.   final String url = 'http://coocafe.com.br/vSite/views/soap/app_tecnico/hom/';
  49.   //final String url = 'http://coocafe.com.br/vSite/views/soap/app_tecnico/prod/';
  50.   PageController _pageCtrl = new PageController();
  51.   ProdutorHelper prodHelper = ProdutorHelper();
  52.   FilialHelper filialHelper = FilialHelper();
  53.   TipoTituloHelper tipoTituloHelper = TipoTituloHelper();
  54.   PropriedadeHelper propriedadeHelper = PropriedadeHelper();
  55.   TalhaoHelper talhaoHelper = TalhaoHelper();
  56.   SafraHelper safraHelper = SafraHelper();
  57.   CulturaHelper culturaHelper = CulturaHelper();
  58.   NotificacoesCoopHelper notProdutorHelper = NotificacoesCoopHelper();
  59.   TitulosCRHelper titCRHelper = TitulosCRHelper();
  60.   TitulosCPHelper titCPHelper = TitulosCPHelper();
  61.   NotificacoesHelper notificacoesHelper = NotificacoesHelper();
  62.   NotificacoesPropHelper notPropriedadeHelper = NotificacoesPropHelper();
  63.   List<Produtor> _listaProdutor = List();
  64.   ScrollController _scrollCtrl = ScrollController();
  65.   String _dataRefresh = "";
  66.   static int _qtdNot;
  67.   static int progresso;
  68.   static String textProgress = "Requisitando dados...";
  69.   static bool _refresh = false;
  70.   bool _refreshDrawer = false;
  71.   static Future<List<Produtor>> tempList;
  72.   String _connectionStatus = "Unknown";
  73.   final Connectivity _connectivity = Connectivity();
  74.   StreamSubscription<ConnectivityResult> _connectivitySubscription;
  75.   ListaProdutorPage pageListaProdutor;
  76.   NotificacoesPage pageNotificacoes = NotificacoesPage();
  77.   bool _isRefreshing;
  78.  
  79.   @override
  80.   void initState() {
  81.     _isRefreshing = false;
  82.  
  83.     //WidgetsBinding.instance.addObserver(this);
  84.  
  85.     initConnectivity();
  86.     _connectivitySubscription =
  87.         _connectivity.onConnectivityChanged.listen((ConnectivityResult result) {
  88.           setState(() => _connectionStatus = result.toString());
  89.         });
  90.  
  91.     _refresh = false;
  92.     progresso = 0;
  93.  
  94.     SharedPreferences.getInstance().then((data) {
  95.       if(data.getString("TextoAtualizacao") != null) {
  96.         _dataRefresh = data.getString("TextoAtualizacao");
  97.       }
  98.     });
  99.  
  100.     filialHelper.getAll().then((list) {
  101.       if (list.length <= 0) _getListaFilial().then((filiais) {});
  102.     });
  103.  
  104.     safraHelper.getAll().then((list) {
  105.       if (list.length <= 0) _getListaSafra().then((safras) {});
  106.     });
  107.  
  108.     culturaHelper.getAll().then((list) {
  109.       if (list.length <= 0) _getListaCultura().then((culturas) {});
  110.     });
  111.  
  112.     tipoTituloHelper.getAll().then((list) {
  113.       if (list.length <= 0) _getListaTipoTitulo().then((tipos) {});
  114.     });
  115.  
  116.     notificacoesHelper.getAll().then((list) {
  117.       if (list.length <= 0) _getListaNotificacoesTecnico().then((notificacoes) {});
  118.     });
  119.  
  120.     tempList = _getListaProdutorLocal();
  121.  
  122.     _refreshDrawer = widget.refreshDrawer != null ? widget.refreshDrawer : false;
  123.     if(_refreshDrawer) {
  124.       setState(() {
  125.         _isRefreshing = true;
  126.         progresso = 0;
  127.         textProgress = "Requisitando dados...";
  128.  
  129.         _atualizarTalhoes();
  130.       });
  131.     }
  132.  
  133.     notificacoesHelper.getCountNotificacaoTec().then((value) {
  134.       setState(() {
  135.         _qtdNot = value;
  136.         pageListaProdutor = ListaProdutorPage(controller: _pageCtrl, qtdNot: _qtdNot,);
  137.       });
  138.     });
  139.  
  140.     super.initState();
  141.   }
  142.  
  143.   @override
  144.   void dispose() {
  145.     _connectivitySubscription.cancel();
  146.  
  147.     super.dispose();
  148.   }
  149.  
  150.   @override
  151.   Widget build(BuildContext context) {
  152.     //print('Estado do app: $_lastLifecycleState.');
  153.     return WillPopScope(
  154.       child: PageView(
  155.         controller: _pageCtrl,
  156.         physics: NeverScrollableScrollPhysics(),
  157.         children: <Widget>[
  158.           Scaffold(
  159.                 backgroundColor: Colors.white,
  160.                 drawer: DrawerPage(pageCtrl: _pageCtrl, qtdNot: _qtdNot,),
  161.                 appBar: AppBar(
  162.                   title: Text("App Técnico"),
  163.                   centerTitle: true,
  164.                   actions: <Widget>[
  165.                     ButtonTheme(
  166.                       minWidth: 44.0,
  167.                       padding: EdgeInsets.all(0.0),
  168.                       child: ButtonBar(
  169.                         children: <Widget>[
  170.                           FlatButton(
  171.                             child: IconTheme(
  172.                               data: IconThemeData(color: Colors.white),
  173.                               child: Icon(Icons.refresh),
  174.                             ),
  175.                             onPressed: () async {
  176.                               if(_connectionStatus == "ConnectivityResult.none") {
  177.                                 showDialog(
  178.                                     context: context,
  179.                                     barrierDismissible: false,
  180.                                     builder: (BuildContext context) {
  181.                                       return CustomAlertDialog(
  182.                                         title: Text("Atenção!"),
  183.                                         content: Text("Sem conexão no momento. Tente novamente com o dispositivo conectado à internet."),
  184.                                         actions: <Widget>[
  185.                                           FlatButton(
  186.                                             child: Text("OK"),
  187.                                             onPressed: () {
  188.                                               Navigator.of(context).pop();
  189.                                             },
  190.                                           )
  191.                                         ],
  192.                                       );
  193.                                     }
  194.                                 );
  195.                               } else if(!_isRefreshing) {
  196.                                 showDialog(
  197.                                     context: context,
  198.                                     barrierDismissible: false,
  199.                                     builder: (BuildContext context) {
  200.                                       return CustomAlertDialog(
  201.                                         title: Text("Sincronizar Dados"),
  202.                                         content: Text("Deseja sincronizar os dados com o servidor?"),
  203.                                         actions: <Widget>[
  204.                                           FlatButton(
  205.                                             child: Text("Sim"),
  206.                                             onPressed: () async {
  207.                                               Navigator.of(context).pop();
  208.  
  209.                                               try {
  210.                                                 Screen.keepOn(true);
  211.  
  212.                                                 setState(() async {
  213.                                                   _isRefreshing = true;
  214.                                                   progresso = 0;
  215.                                                   textProgress = "Requisitando dados...";
  216.  
  217.                                                   await _atualizarTalhoes();
  218.                                                 });
  219.  
  220.                                                 Screen.keepOn(false);
  221.                                               } catch (e) {
  222.                                                 _showDialog(context, e);
  223.                                               }
  224.                                             },
  225.                                           ),
  226.                                           FlatButton(
  227.                                             child: Text("Não"),
  228.                                             onPressed: () {
  229.                                               Navigator.of(context).pop();
  230.                                             },
  231.                                           ),
  232.                                         ],
  233.                                       );
  234.                                     }
  235.                                 );
  236.                               }
  237.                             },
  238.                           ),
  239.                         ],
  240.                       ),
  241.                     )
  242.                   ],
  243.                 ),
  244.                 body: FutureBuilder(
  245.                     future: tempList,
  246.                     builder: (context, snapshot) {
  247.                       switch(snapshot.connectionState) {
  248.                         case ConnectionState.none:
  249.                         case ConnectionState.waiting:
  250.                           return Column(
  251.                             mainAxisAlignment: MainAxisAlignment.center,
  252.                             crossAxisAlignment: CrossAxisAlignment.stretch,
  253.                             children: <Widget>[
  254.                               Container(
  255.                                   width: 200.00,
  256.                                   height: 200.00,
  257.                                   alignment: Alignment.center,
  258.                                   child: Column(
  259.                                     children: <Widget>[
  260.                                       CircularProgressIndicator(
  261.                                         valueColor: AlwaysStoppedAnimation<Color>(Colors.green),
  262.                                         strokeWidth: 5.0,
  263.                                       ),
  264.                                       Text(textProgress, style: TextStyle(fontSize: 15.0, color: Colors.black),),
  265.                                     ],
  266.                                   )
  267.                               )
  268.                             ],
  269.                           );
  270.                           break;
  271.                         default:
  272.                           if(_connectionStatus == "ConnectivityResult.none") {
  273.                             return Container(
  274.                               child: Column(
  275.                                 crossAxisAlignment: CrossAxisAlignment.stretch,
  276.                                 mainAxisAlignment: MainAxisAlignment.center,
  277.                                 children: <Widget>[
  278.                                   Icon(Icons.signal_wifi_off, size: 40.0, color: Colors.red,),
  279.                                   Center(
  280.                                     child: Text(
  281.                                       "Dispositivo Off-line",
  282.                                       style: TextStyle(fontSize: 20.0),
  283.                                     ),
  284.                                   ),
  285.                                 ],
  286.                               ),
  287.                             );
  288.                           } else
  289.                           if(snapshot.hasData) {
  290.                             return Container(
  291.                               padding: EdgeInsets.only(top: 10.0),
  292.                               child: Column(
  293.                                 children: <Widget>[
  294.                                   Center(
  295.                                     child: Text(_dataRefresh),
  296.                                   ),
  297.                                 ],
  298.                               ),
  299.                             );
  300.                           } else if(snapshot.hasError) {
  301.                             _isRefreshing = false;
  302.  
  303.                             Screen.keepOn(false);
  304.                             return Container(
  305.                               child: Column(
  306.                                 crossAxisAlignment: CrossAxisAlignment.stretch,
  307.                                 mainAxisAlignment: MainAxisAlignment.center,
  308.                                 children: <Widget>[
  309.                                   Icon(
  310.                                     Icons.error_outline,
  311.                                     size: 40.0,
  312.                                     color: Colors.red,
  313.                                   ),
  314.                                   Center(
  315.                                     child: Text(
  316.                                       "Erro ao atualizar os dados!",
  317.                                       style: TextStyle(fontSize: 20.0),
  318.                                     ),
  319.                                   ),
  320.                                   Center(
  321.                                     child: Text(snapshot.error.toString()),
  322.                                   ),
  323.                                 ],
  324.                               ),
  325.                             );
  326.                           } else {
  327.                             _isRefreshing = false;
  328.                             return Container();
  329.                           }
  330.                           break;
  331.                       }
  332.                     }
  333.                 ),
  334.             ),
  335.           Scaffold(
  336.             backgroundColor: Colors.white,
  337.             body: pageListaProdutor,
  338.           ),
  339.           Scaffold(
  340.             backgroundColor: Colors.white,
  341.             drawer: DrawerPage(pageCtrl: _pageCtrl, qtdNot: _qtdNot,),
  342.             appBar: AppBar(
  343.               title: Text("Notificações"),
  344.               centerTitle: true,
  345.             ),
  346.             body: pageNotificacoes,
  347.           )
  348.         ],
  349.       ),
  350.       onWillPop: () {
  351.         Future(() => false);
  352.       },
  353.     );
  354.   }
  355.  
  356.   Widget buildHomePage(BuildContext context) {
  357.     return Container();
  358.   }
  359.  
  360.   Future<List> _getListaFilial() async {
  361.     FilialHelper filialHelper = FilialHelper();
  362.     print('--> Atualizando Filiais');
  363.     Map<String, dynamic> myMap = Map();
  364.     SharedPreferences prefs = await SharedPreferences.getInstance();
  365.     List<Filial> lista = List();
  366.  
  367.     String usuario = prefs.get("user");
  368.     String senha = prefs.get("pass");
  369.     String key = prefs.get("key");
  370.  
  371.     final cryptor = new PlatformStringCryptor();
  372.     final String encrypted = await cryptor.decrypt(senha, key);
  373.  
  374.     Map dados = {"user": usuario, "password": encrypted};
  375.     String ldados = json.encode(dados);
  376.  
  377.     http.Response response = await http.post(
  378.         url + "filial.php",
  379.         body: ldados).catchError((error) {
  380.           _showDialog(context, error);
  381.         });
  382.  
  383.     Map<String, dynamic> retorno = json.decode(response.body);
  384.  
  385.     if (retorno["status"] != "" && retorno["status"] != null) {
  386.       _showDialog(context, "Erro ao processar a requisição.");
  387.     } else {
  388.       var listaFilial = retorno['lista'];
  389.  
  390.       await filialHelper.deleteAll();
  391.  
  392.       for (Map itens in listaFilial) {
  393.  
  394.  
  395.         Filial filialIns = await filialHelper.saveFilial(Filial.fromMap(itens));
  396.         lista.add(filialIns);
  397.       }
  398.     }
  399.  
  400.     return lista;
  401.   }
  402.  
  403.   Future<List> _getListaSafra() async {
  404.     SafraHelper safraHelper = SafraHelper();
  405.     print('--> Atualizando Safras');
  406.     Map<String, dynamic> myMap = Map();
  407.     SharedPreferences prefs = await SharedPreferences.getInstance();
  408.     List<Safra> lista = List();
  409.  
  410.     String usuario = prefs.get("user");
  411.     String senha = prefs.get("pass");
  412.     String key = prefs.get("key");
  413.  
  414.     final cryptor = new PlatformStringCryptor();
  415.     final String encrypted = await cryptor.decrypt(senha, key);
  416.  
  417.     Map dados = {"user": usuario, "password": encrypted};
  418.     String ldados = json.encode(dados);
  419.  
  420.     http.Response response = await http.post(
  421.         url + "safra.php",
  422.         body: ldados).catchError((error) {
  423.           _showDialog(context, error);
  424.         });
  425.     Map<String, dynamic> retorno = json.decode(response.body);
  426.  
  427.     if (retorno["status"] != "" && retorno["status"] != null) {
  428.       _showDialog(context, "Erro ao processar a requisição.");
  429.     } else {
  430.       var listaSafra = retorno['lista'];
  431.  
  432.       await safraHelper.deleteAll();
  433.  
  434.       for (Map itens in listaSafra) {
  435.         Safra safraIns = await safraHelper.saveSafra(Safra.fromMap(itens));
  436.         lista.add(safraIns);
  437.       }
  438.     }
  439.  
  440.     return lista;
  441.   }
  442.  
  443.   Future<List> _getListaCultura() async {
  444.     CulturaHelper culturaHelper = CulturaHelper();
  445.     print('--> Atualizando Culturas');
  446.     Map<String, dynamic> myMap = Map();
  447.     SharedPreferences prefs = await SharedPreferences.getInstance();
  448.     List<Cultura> lista = List();
  449.  
  450.     String usuario = prefs.get("user");
  451.     String senha = prefs.get("pass");
  452.     String key = prefs.get("key");
  453.  
  454.     final cryptor = new PlatformStringCryptor();
  455.     final String encrypted = await cryptor.decrypt(senha, key);
  456.  
  457.     Map dados = {"user": usuario, "password": encrypted};
  458.     String ldados = json.encode(dados);
  459.  
  460.     http.Response response = await http.post(
  461.         url + "cultura.php",
  462.         body: ldados).catchError((error) {
  463.           _showDialog(context, error);
  464.         });
  465.     Map<String, dynamic> retorno = json.decode(response.body);
  466.  
  467.     if (retorno["status"] != "" && retorno["status"] != null) {
  468.       _showDialog(context, "Erro ao processar a requisição.");
  469.     } else {
  470.       var listaCultura = retorno['lista'];
  471.  
  472.       await culturaHelper.deleteAll();
  473.  
  474.       for (Map itens in listaCultura) {
  475.         Cultura culturaIns = await culturaHelper.saveCultura(Cultura.fromMap(itens));
  476.         lista.add(culturaIns);
  477.       }
  478.     }
  479.  
  480.     return lista;
  481.   }
  482.  
  483.   Future<List> _getListaTipoTitulo() async {
  484.     TipoTituloHelper tipoTituloHelper = TipoTituloHelper();
  485.     print('--> Atualizando Tipos de Título');
  486.     Map<String, dynamic> myMap = Map();
  487.     SharedPreferences prefs = await SharedPreferences.getInstance();
  488.     List<TipoTitulo> lista = List();
  489.     List<TipoTitulo> tiposTitulo = List();
  490.  
  491.     String usuario = prefs.get("user");
  492.     String senha = prefs.get("pass");
  493.     String key = prefs.get("key");
  494.  
  495.     final cryptor = new PlatformStringCryptor();
  496.     final String encrypted = await cryptor.decrypt(senha, key);
  497.  
  498.     Map dados = {"user": usuario, "password": encrypted};
  499.     String ldados = json.encode(dados);
  500.  
  501.     http.Response response = await http.post(
  502.         url + "tipoTitulo.php",
  503.         body: ldados).catchError((error) {
  504.           _showDialog(context, error);
  505.         });
  506.  
  507.     Map<String, dynamic> retorno = json.decode(response.body);
  508.  
  509.     if (retorno["status"] != "" && retorno["status"] != null) {
  510.       _showDialog(context, "Erro ao processar a requisição.");
  511.     } else {
  512.       var listaTipoTitulo = retorno['lista'];
  513.  
  514.       await tipoTituloHelper.deleteAll();
  515.  
  516.       for (Map itens in listaTipoTitulo) {
  517.         TipoTitulo tipoTituloIns = TipoTitulo();
  518.  
  519.         tipoTituloIns = await tipoTituloHelper.saveTipoTitulo(TipoTitulo.fromMap(itens));
  520.         tiposTitulo.add(tipoTituloIns);
  521.       }
  522.     }
  523.  
  524.     return tiposTitulo;
  525.   }
  526.  
  527.   Future<List> _getListaNotificacoesTecnico() async {
  528.     NotificacoesHelper notificacoesHelper = NotificacoesHelper();
  529.     print('--> Atualizando Notificações do Técnico');
  530.     Map<String, dynamic> myMap = Map();
  531.     SharedPreferences prefs = await SharedPreferences.getInstance();
  532.     List<Notificacoes> lista = List();
  533.  
  534.     String usuario = prefs.get("user");
  535.     String senha = prefs.get("pass");
  536.     String key = prefs.get("key");
  537.  
  538.     final cryptor = new PlatformStringCryptor();
  539.     final String encrypted = await cryptor.decrypt(senha, key);
  540.  
  541.     Map dados = {"user": usuario, "password": encrypted};
  542.     String ldados = json.encode(dados);
  543.  
  544.     http.Response response = await http.post(
  545.         url + "notificacoes.php",
  546.         body: ldados).catchError((error) {
  547.           _showDialog(context, error);
  548.         });
  549.     Map<String, dynamic> retorno = json.decode(response.body);
  550.  
  551.     if (retorno["status"] != "" && retorno["status"] != null) {
  552.       _showDialog(context, "Erro ao processar a requisição.");
  553.     } else {
  554.       var listaNotificacoes = retorno['lista'];
  555.  
  556.       //await notificacoesHelper.deleteAll();
  557.  
  558.       if(listaNotificacoes != null) {
  559.         for (Map itens in listaNotificacoes) {
  560.           Notificacoes not = Notificacoes.fromMap(itens);
  561.  
  562.           Notificacoes notificacao = await notificacoesHelper.saveNotificacao(not);
  563.           lista.add(notificacao);
  564.         }
  565.       }
  566.     }
  567.     return lista;
  568.   }
  569.  
  570.   Future<List<Produtor>> _getListaProdutorLocal() async {
  571.     List<Produtor> lista = List();
  572.  
  573.     lista = await prodHelper.getAll();
  574.  
  575.     return lista;
  576.   }
  577.  
  578.   Future<List<Produtor>> _atualizarTalhoes() async {
  579.       Screen.keepOn(true);
  580.       try {
  581.         print('--> Atualizando Talhões');
  582.         Map<String, dynamic> myMap = Map();
  583.         SharedPreferences prefs = await SharedPreferences.getInstance();
  584.         List<Produtor> lista = List();
  585.         List<Propriedade> propriedades = List();
  586.         List listaTalhao;
  587.  
  588.         String usuario = prefs.get("user");
  589.         String senha = prefs.get("pass");
  590.         String key = prefs.get("key");
  591.  
  592.         final cryptor = new PlatformStringCryptor();
  593.         final String encrypted = await cryptor.decrypt(senha, key);
  594.  
  595.         listaTalhao = await talhaoHelper.getListaTalhaoParaAtualizar().catchError((error) {
  596.           _showDialog(context, error.toString());
  597.         });;
  598.  
  599.         if (listaTalhao.length > 0) {
  600.           print('--> Existe talhão para atualizar');
  601.           Map dados = {
  602.             "user": usuario,
  603.             "password": encrypted,
  604.             "talhao": listaTalhao,
  605.             "opeExe": "A"
  606.           };
  607.  
  608.           String ldados = json.encode(dados);
  609.  
  610.           http.Response response = await http.post(
  611.               url + 'produtor.php',
  612.               body: ldados).catchError((error) {
  613.                 _showDialog(context, error);
  614.               });
  615.  
  616.           Map<String, dynamic> retorno = json.decode(response.body);
  617.  
  618.           if (retorno["status"] != null && retorno["status"] != "") {
  619.             _showDialog(context, retorno["status"]);
  620.           } else {
  621.             var result = retorno["lista"];
  622.  
  623.             if(result != null) {
  624.               var resultPropriedade = result["propriedade"];
  625.  
  626.               if(resultPropriedade["talhao"].toString().startsWith("[")) {
  627.                 for (Map m in resultPropriedade["talhao"]) {
  628.                   if (m["retorno"] != null) {
  629.                     Notificacoes not = Notificacoes();
  630.                     not.Descricao = m["retorno"];
  631.                     not.Data = formatDate(DateTime.now(), [dd, '/', mm, '/', yyyy]);
  632.                     not.Situacao = "Não Lida";
  633.  
  634.                     print('--> Salvando notificação');
  635.                     notificacoesHelper.saveNotificacao(not).then((notificacao) {}).catchError((error) {
  636.                       _showDialog(context, error.toString());
  637.                     });
  638.                   }
  639.                 }
  640.               } else {
  641.                 String retorno = resultPropriedade["talhao"]["retorno"];
  642.  
  643.                 if(retorno != null) {
  644.                   Notificacoes not = Notificacoes();
  645.                   not.Descricao = retorno;
  646.                   not.Data = formatDate(DateTime.now(), [dd, '/', mm, '/', yyyy]);
  647.                   not.Situacao = "Não Lida";
  648.  
  649.                   notificacoesHelper.saveNotificacao(not).then((notificacao) {}).catchError((error) {
  650.                     _showDialog(context, error.toString());
  651.                   });
  652.                 }
  653.               }
  654.             }
  655.  
  656.             _getListaSafra();
  657.             _getListaCultura();
  658.             _getListaFilial();
  659.             _getListaTipoTitulo();
  660.             _getListaNotificacoesTecnico();
  661.             tempList = _getListaProdutor();
  662.             _dataRefresh = "Atualizado em " + formatDate(DateTime.now(), [dd, '/', mm, '/', yyyy ]) + " às " + formatDate(DateTime.now(), [HH, ':', nn, ':', ss ]);
  663.             _isRefreshing = false;
  664.             prefs.setString("TextoAtualizacao", _dataRefresh);
  665.           }
  666.         } else {
  667.           print('--> Não existe talhão para atualizar');
  668.  
  669.           setState(() {
  670.             _getListaSafra();
  671.             _getListaCultura();
  672.             _getListaFilial();
  673.             _getListaTipoTitulo();
  674.             _getListaNotificacoesTecnico();
  675.             tempList = _getListaProdutor();
  676.             _dataRefresh = "Atualizado em " + formatDate(DateTime.now(), [dd, '/', mm, '/', yyyy ]) + " às " + formatDate(DateTime.now(), [HH, ':', nn, ':', ss ]);
  677.             _isRefreshing = false;
  678.             prefs.setString("TextoAtualizacao", _dataRefresh);
  679.           });
  680.  
  681.           Screen.keepOn(false);
  682.  
  683.           return lista;
  684.         }
  685.       } catch(e) {
  686.         _showDialog(context, e);
  687.       }
  688.  
  689.     Screen.keepOn(false);
  690.   }
  691.  
  692.   Future<List<Produtor>> _getListaProdutor() async {
  693.     Screen.isKeptOn.then((value) {
  694.       if(!value) {
  695.         Screen.keepOn(true);
  696.       }
  697.     });
  698.  
  699.     try {
  700.       ProdutorHelper prodHelper = ProdutorHelper();
  701.       PropriedadeHelper propriedadeHelper = PropriedadeHelper();
  702.       TalhaoHelper talhaoHelper = TalhaoHelper();
  703.       NotificacoesCoopHelper notProdutorHelper = NotificacoesCoopHelper();
  704.       TitulosCRHelper titCRHelper = TitulosCRHelper();
  705.       NotificacoesPropHelper notPropriedadeHelper = NotificacoesPropHelper();
  706.       print('--> Atualizando dados');
  707.       int totalRegistros = 0;
  708.  
  709.       Map<String, dynamic> myMap = Map();
  710.       SharedPreferences prefs = await SharedPreferences.getInstance();
  711.       List<Produtor> lista = List();
  712.       List<Propriedade> propriedades = List();
  713.       //String listaTalhao;
  714.  
  715.       String usuario = prefs.get("user");
  716.       String senha = prefs.get("pass");
  717.       String key = prefs.get("key");
  718.  
  719.       final cryptor = new PlatformStringCryptor();
  720.       final String encrypted = await cryptor.decrypt(senha, key);
  721.  
  722.       //listaTalhao = await talhaoHelper.getListaTalhaoParaAtualizar();
  723.  
  724.       //print(listaTalhao.toString());
  725.  
  726.       Map dados = {
  727.         "user": usuario,
  728.         "password": encrypted,
  729.         "talhao": "",
  730.         "opeExe": ""
  731.       };
  732.  
  733.       String ldados = json.encode(dados);
  734.  
  735.       http.Response response = await http.post(url + 'produtor.php', body: ldados)
  736.           .catchError((error) {
  737.             _showDialog(context, error);
  738.             throw error;
  739.           });
  740.  
  741.       Map<String, dynamic> retorno = json.decode(response.body);
  742.  
  743.       if (retorno["status"] != null && retorno["status"] != "") {
  744.         _showDialog(context, retorno["status"]);
  745.       } else {
  746.         var listaProdutor = retorno['lista'];
  747.         totalRegistros = retorno['qtdReg'];
  748.  
  749.         await notProdutorHelper.deleteAll();
  750.         await notPropriedadeHelper.deleteAll();
  751.         await talhaoHelper.deleteAll();
  752.         await propriedadeHelper.deleteAll();
  753.         await titCRHelper.deleteAll();
  754.         await titCPHelper.deleteAll();
  755.         await prodHelper.deleteAll();
  756.  
  757.         for (Map itens in listaProdutor) {
  758.           Produtor prod = Produtor();
  759.  
  760.           if (itens["codigo"] != 0 && itens["codigo"] != null) {
  761.             Produtor prod = Produtor.fromMap(itens);
  762.  
  763.             prodHelper.saveProdutor(prod).then((prodInsert) {
  764.               prod = prodInsert;
  765.  
  766.               print('--> Atualizando Produtor ${prod.id}');
  767.  
  768.               setState(() {
  769.                 progresso = progresso + 1;
  770.                 textProgress = "Atualizando $progresso de $totalRegistros registros";
  771.               });
  772.             });
  773.  
  774.             lista.add(prod);
  775.  
  776.             if(itens['notificacoesProdutor'].toString().startsWith("[")) {
  777.               var listaNotificacoes = itens['notificacoesProdutor'];
  778.  
  779.               if(listaNotificacoes != null) {
  780.                 for (Map m in listaNotificacoes) {
  781.                   NotificacoesCoop notificacao = await notProdutorHelper.saveNotificacaoCoop(NotificacoesCoop.fromMap(m));
  782.  
  783.                   print('--> Atualizando Notificações do Produtor ${notificacao.codProdutor}');
  784.  
  785.                   setState(() {
  786.                     progresso = progresso + 1;
  787.                     textProgress = "Atualizando $progresso de $totalRegistros registros";
  788.                   });
  789.                 }
  790.               }
  791.             } else {
  792.               if(itens['notificacoesProdutor'] != null) {
  793.                 var notProd = NotificacoesCoop.fromMap(itens['notificacoesProdutor']);
  794.  
  795.                 await notProdutorHelper.saveNotificacaoCoop(notProd);
  796.  
  797.                 setState(() {
  798.                   progresso = progresso + 1;
  799.                   textProgress = "Atualizando $progresso de $totalRegistros registros";
  800.                 });
  801.               }
  802.             }
  803.  
  804.             var listaPropriedades = itens['propriedade'];
  805.             var listaTitulosCR = itens['titulosCR'];
  806.  
  807.             print('--> Atualizando Títulos a Receber');
  808.             if (itens['titulosCR'].toString().startsWith("[")) {
  809.               //É uma lista
  810.               var titulosCR = itens['titulosCR'];
  811.  
  812.               if(titulosCR != null) {
  813.                 for (Map titCR in titulosCR) {
  814.                   TitulosCR tituloCR = await titCRHelper.saveTituloCR(TitulosCR.fromMap(titCR));
  815.  
  816.                   setState(() {
  817.                     progresso = progresso + 1;
  818.                     textProgress = "Atualizando $progresso de $totalRegistros registros";
  819.                   });
  820.                 }
  821.               }
  822.             } else {
  823.               //É um objeto
  824.               if (itens['titulosCR'] != null) {
  825.                 var titulosCR = TitulosCR.fromMap(itens['titulosCR']);
  826.  
  827.                 TitulosCR titCR = await titCRHelper.saveTituloCR(titulosCR);
  828.  
  829.                 setState(() {
  830.                   progresso = progresso + 1;
  831.                   textProgress = "Atualizando $progresso de $totalRegistros registros";
  832.                 });
  833.               }
  834.             }
  835.  
  836.             print('--> Atualizando Títulos a Pagar');
  837.             if (itens['titulosCP'].toString().startsWith("[")) {
  838.               //É uma lista
  839.               var titulosCP = itens['titulosCP'];
  840.  
  841.               if(titulosCP != null) {
  842.                 for (Map titCP in titulosCP) {
  843.                   TitulosCP tituloCP = await titCPHelper.saveTituloCP(TitulosCP.fromMap(titCP));
  844.  
  845.                   setState(() {
  846.                     progresso = progresso + 1;
  847.                     textProgress = "Atualizando $progresso de $totalRegistros registros";
  848.                   });
  849.                 }
  850.               }
  851.             } else {
  852.               //É um objeto
  853.               if (itens['titulosCP'] != null) {
  854.                 var titulosCP = TitulosCP.fromMap(itens['titulosCP']);
  855.  
  856.                 TitulosCP titCR = await titCPHelper.saveTituloCP(titulosCP);
  857.  
  858.                 setState(() {
  859.                   progresso = progresso + 1;
  860.                   textProgress = "Atualizando $progresso de $totalRegistros registros";
  861.                 });
  862.               }
  863.             }
  864.  
  865.             print('--> Atualizando Propriedades');
  866.             if (itens['propriedade'].toString().startsWith("[")) {
  867.               //É uma lista
  868.               var listaProp = itens['propriedade'];
  869.  
  870.               if(listaProp != null) {
  871.                 for (Map prop in listaProp) {
  872.                   Propriedade propi = await propriedadeHelper.savePropriedade(Propriedade.fromMap(prop));
  873.  
  874.                   setState(() {
  875.                     progresso = progresso + 1;
  876.                     textProgress = "Atualizando $progresso de $totalRegistros registros";
  877.                   });
  878.  
  879.                   print('--> Atualizando Notificações da Propriedade');
  880.                   if(prop['notificacoesPropriedade'].toString().startsWith("[")) {
  881.                     var listaNotificacoes = prop['notificacoesPropriedade'];
  882.  
  883.                     if(listaNotificacoes != null) {
  884.                       for (Map m in listaNotificacoes) {
  885.                         NotificacoesProp notificacao = await notPropriedadeHelper.saveNotificacaoProp(NotificacoesProp.fromMap(m));
  886.  
  887.                         setState(() {
  888.                           progresso = progresso + 1;
  889.                           textProgress = "Atualizando $progresso de $totalRegistros registros";
  890.                         });
  891.                       }
  892.                     }
  893.                   } else {
  894.                     if(prop['notificacoesPropriedade'] != null) {
  895.                       var notProp = NotificacoesProp.fromMap(prop['notificacoesPropriedade']);
  896.  
  897.                       await notPropriedadeHelper.saveNotificacaoProp(notProp);
  898.  
  899.                       setState(() {
  900.                         progresso = progresso + 1;
  901.                         textProgress = "Atualizando $progresso de $totalRegistros registros";
  902.                       });
  903.                     }
  904.                   }
  905.  
  906.                   if (prop['talhao'].toString().startsWith('[')) {
  907.                     //Lista de Talhões
  908.                     if(prop['talhao'] != null) {
  909.                       for (Map talhao in prop['talhao']) {
  910.                         if (talhao != null) {
  911.                           Talhao tal = await talhaoHelper.saveTalhao(Talhao.fromMap(talhao));
  912.                         }
  913.  
  914.                         setState(() {
  915.                           progresso = progresso + 1;
  916.                           textProgress = "Atualizando $progresso de $totalRegistros registros";
  917.                         });
  918.                       }
  919.                     }
  920.                   } else {
  921.                     //Objeto Talhão
  922.                     if (prop['talhao'] != null) {
  923.                       Talhao tal = await talhaoHelper.saveTalhao(Talhao.fromMap(prop['talhao']));
  924.  
  925.                       setState(() {
  926.                         progresso = progresso + 1;
  927.                         textProgress = "Atualizando $progresso de $totalRegistros registros";
  928.                       });
  929.                     }
  930.                   }
  931.                 }
  932.               }
  933.             } else {
  934.               //É um objeto
  935.               if (itens['propriedade'] != null) {
  936.                 var propriedades = Propriedade.fromMap(itens['propriedade']);
  937.                 //var talhao = Talhao.fromMap(listaPropriedades['talhao']);
  938.                 Propriedade prop = await propriedadeHelper.savePropriedade(propriedades);
  939.  
  940.                 setState(() {
  941.                   progresso = progresso + 1;
  942.                   textProgress = "Atualizando $progresso de $totalRegistros registros";
  943.                 });
  944.  
  945.                 print('--> Atualizando Notificações da Propriedade');
  946.                 if(itens['propriedade']['notificacoesPropriedade'].toString().startsWith("[")) {
  947.                   var listaNotificacoes = itens['propriedade']['notificacoesPropriedade'];
  948.  
  949.                   if(listaNotificacoes != null) {
  950.                     for (Map m in listaNotificacoes) {
  951.                       NotificacoesProp notificacao = await notPropriedadeHelper.saveNotificacaoProp(NotificacoesProp.fromMap(m));
  952.  
  953.                       setState(() {
  954.                         progresso = progresso + 1;
  955.                         textProgress = "Atualizando $progresso de $totalRegistros registros";
  956.                       });
  957.                     }
  958.                   }
  959.                 } else {
  960.                   if(itens['propriedade']['notificacoesPropriedade'] != null) {
  961.                     var notProp = NotificacoesProp.fromMap(itens['propriedade']['notificacoesPropriedade']);
  962.  
  963.                     await notPropriedadeHelper.saveNotificacaoProp(notProp);
  964.  
  965.                     setState(() {
  966.                       progresso = progresso + 1;
  967.                       textProgress = "Atualizando $progresso de $totalRegistros registros";
  968.                     });
  969.                   }
  970.                 }
  971.  
  972.                 print('--> Atualizando Talhões produtor: ${propriedades.idProdutor}');
  973.                 if (itens['propriedade']['talhao'].toString().startsWith('[')) {
  974.                   //Lista de Talhões
  975.                   if(itens['propriedade']['talhao'] != null) {
  976.                     for (Map talhao in itens['propriedade']['talhao']) {
  977.                       if (talhao != null) {
  978.                         Talhao tal = await talhaoHelper.saveTalhao(Talhao.fromMap(talhao));
  979.                       }
  980.  
  981.                       setState(() {
  982.                         progresso = progresso + 1;
  983.                         textProgress = "Atualizando $progresso de $totalRegistros registros";
  984.                       });
  985.                     }
  986.                   }
  987.                 } else {
  988.                   //Objeto Talhão
  989.                   if (itens['propriedade']['talhao'] != null) {
  990.                     Talhao tal = await talhaoHelper.saveTalhao(Talhao.fromMap(itens['propriedade']['talhao']));
  991.  
  992.                     setState(() {
  993.                       progresso = progresso + 1;
  994.                       textProgress = "Atualizando $progresso de $totalRegistros registros";
  995.                     });
  996.                   }
  997.                 }
  998.               }
  999.             }
  1000.           }
  1001.         }
  1002.       }
  1003.  
  1004.       /*getCountNotProp();
  1005.       getCountNotTec();
  1006.       getCountTitCP();
  1007.       getCountTitCR();
  1008.       getCountNotProd();
  1009.       getCountTalhao();
  1010.       getCountProdutor();
  1011.       getCountPropriedade();*/
  1012.  
  1013.       setState(() {
  1014.         _isRefreshing = false;
  1015.         _refresh = false;
  1016.         progresso = 0;
  1017.         _dataRefresh = "Atualizado em " + formatDate(
  1018.             DateTime.now(), [dd, '/', mm, '/', yyyy]) + " às " +
  1019.             formatDate(DateTime.now(), [HH, ':', nn, ':', ss]);
  1020.       });
  1021.  
  1022.       Screen.keepOn(false);
  1023.  
  1024.       return lista;
  1025.     } catch(e) {
  1026.       _showDialog(context, e);
  1027.     }
  1028.   }
  1029.  
  1030.   Future<Null> initConnectivity() async {
  1031.     String connectionStatus;
  1032.     // Platform messages may fail, so we use a try/catch PlatformException.
  1033.     try {
  1034.       connectionStatus = (await _connectivity.checkConnectivity()).toString();
  1035.     } catch (e) {
  1036.       print(e.toString());
  1037.       connectionStatus = 'Failed to get connectivity.';
  1038.     }
  1039.  
  1040.     // If the widget was removed from the tree while the asynchronous platform
  1041.     // message was in flight, we want to discard the reply rather than calling
  1042.     // setState to update our non-existent appearance.
  1043.     if (!mounted) {
  1044.       return;
  1045.     }
  1046.  
  1047.     setState(() {
  1048.       _connectionStatus = connectionStatus;
  1049.     });
  1050.   }
  1051.  
  1052.   void getCountNotProp() {
  1053.     notPropriedadeHelper.getCount().then((value) {
  1054.       print('Not. Propriedade: ' + value.toString());
  1055.     });
  1056.   }
  1057.  
  1058.   void getCountNotTec() {
  1059.     notificacoesHelper.getCount().then((value) {
  1060.       print('Not. Tecnico: ' + value.toString());
  1061.     });
  1062.   }
  1063.  
  1064.   void getCountTitCP() {
  1065.     titCPHelper.getCount().then((value) {
  1066.       print('Titulos CP: ' + value.toString());
  1067.     });
  1068.   }
  1069.  
  1070.   void getCountTitCR() {
  1071.     titCRHelper.getCount().then((value) {
  1072.       print('Titulos CR: ' + value.toString());
  1073.     });
  1074.   }
  1075.  
  1076.   void getCountNotProd() {
  1077.     notProdutorHelper.getCount().then((value) {
  1078.       print('Not. Produtor: ' + value.toString());
  1079.     });
  1080.   }
  1081.  
  1082.   void getCountCultura() {
  1083.     culturaHelper.getCount().then((value) {
  1084.       print('Culturas: ' + value.toString());
  1085.     });
  1086.   }
  1087.  
  1088.   void getCountSafra() {
  1089.     safraHelper.getCount().then((value) {
  1090.       print('Safras: ' + value.toString());
  1091.     });
  1092.   }
  1093.  
  1094.   void getCountProdutor() {
  1095.     prodHelper.getCount().then((value) {
  1096.       print('Produtores: ' + value.toString());
  1097.     });
  1098.   }
  1099.  
  1100.   void getCountFilial() {
  1101.     filialHelper.getCount().then((value) {
  1102.       print('Filiais: ' + value.toString());
  1103.     });
  1104.   }
  1105.  
  1106.   void getCountTipoTitulo() {
  1107.     tipoTituloHelper.getCount().then((value) {
  1108.       print('Tipos de Título: ' + value.toString());
  1109.     });
  1110.   }
  1111.  
  1112.   void getCountPropriedade() {
  1113.     propriedadeHelper.getCount().then((value) {
  1114.       print('Propriedades: ' + value.toString());
  1115.     });
  1116.   }
  1117.  
  1118.   void _showDialog(BuildContext context, String texto) {
  1119.     // flutter defined function
  1120.     showDialog(
  1121.       barrierDismissible: false,
  1122.       context: context,
  1123.       builder: (BuildContext context) {
  1124.         // return object of type Dialog
  1125.         return CustomAlertDialog(
  1126.           title: new Text("Atenção"),
  1127.           content: new Text(texto),
  1128.           actions: <Widget>[
  1129.             // usually buttons at the bottom of the dialog
  1130.             new FlatButton(
  1131.               child: new Text("OK"),
  1132.               onPressed: () {
  1133.                 Navigator.of(context).pop();
  1134.               },
  1135.             ),
  1136.           ],
  1137.         );
  1138.       },
  1139.     );
  1140.   }
  1141. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement