Advertisement
Guest User

lifecycle

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