import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:rkm/service/db/db_querys.dart';
import 'package:rkm/widgets/button_default.dart';
import '../../config/color_palette.dart';
import '../../service/api/api_data_post.dart';
import '../../service/db/db_sqlite_load.dart';
import '../../service/db/db_sqlite_sync.dart';
import '../../widgets/text_default.dart';

class SincDataScreen extends StatefulWidget {
  const SincDataScreen({Key? key}) : super(key: key);

  @override
  State<SincDataScreen> createState() => _SincDataScreenState();
}

class _SincDataScreenState extends State<SincDataScreen> {

  String mode ='';
  String urlAPI ='';
  String nameCityApi ='';
  var tableCIDADAOS;
  var tableCIDADAO_DOMICILIO;
  var tableDOMICILIOS_CIDADAOS;
  var tableINNERJOINCIDADAO_DOMICILIO;
  var tableCADASTROS_INDIVIDUAIS;
  var tableATENDS_INDIV_COMPL;
  var tableATENDS_INDIV_EXAMES;
  var tableATENDS_INDIV_PROC;
  var tableATENDS_INDIV_PROF;
  var tableATENDS_INDIVIDUAIS;
  var tablePROCEDIMENTOS_FICHAS;
  var tablePROCEDIMENTOS_INDIV;
  var tablePROCEDIMENTOS_INDIV_FICHA;
  var tablePROCEDIMENTOS_INDIV_SIGTAP;
  var tableVISITAS_DOMICILIARES;
  var tableVISITAS_DOMICILIARES_COMPL;
  var tableVISITAS_DOMICILIARES_PROC;
  var tableFICHAS_COMPLEMENTARES;
  var tableATENDIMENTOS_DOMICILIARES;
  var tableATENDS_DOM_COMPL;
  var tableATENDS_DOM_PROC;
  var tableATENDS_DOM_SIGTAP;
  var tableATENDS_ODONTOLOGICOS;
  var tableATENDS_ODONTO_PROF;
  var tableATENDS_ODONTO_PROC;
  var tableATENDS_ODONTO_SIGTAP;
  var tableATENDS_ODONTO_COMPL;
  var tableMARCADORES_CON_QUEST;
  var tableMARCADORES_CONSUMO;
  var tableAVAL_ELEG_COND_AVAL;
  var tableAVAL_ELEG_CONCL_INE;
  var tableAVALIACOES_ELEGIBILIDADE;
  String message = 'A Sincronização poderá demorar. Prosseguir?';
  bool upload = false;
  bool done = false;
  bool error = false;

  updateTable()async{
    setState(() {
      upload = true;
      message = 'Aguarde enquanto os dados são Sincronizados.';
    });
    await DBQuerys().cadCidadaos().then((response)async{
      tableCIDADAOS = response;
      await DBQuerys().cadDomiciliares().then((response)async{
        tableCIDADAO_DOMICILIO = response;
        // print(tableCIDADAO_DOMICILIO);
        await DBQuerys().domCidadaos().then((response)async{
          tableDOMICILIOS_CIDADAOS = response;
          // print(tableDOMICILIOS_CIDADAOS);
          await DBQuerys().logrDomicilios().then((response)async{
            tableINNERJOINCIDADAO_DOMICILIO = response;
            // print(tableINNERJOINCIDADAO_DOMICILIO);
            await DBQuerys().cadIndividuais().then((response)async{
              tableCADASTROS_INDIVIDUAIS = response;
              // print(tableCADASTROS_INDIVIDUAIS);
              await DBQuerys().atendsIndivCompl().then((response)async{
                tableATENDS_INDIV_COMPL = response;
                // print(tableATENDS_INDIV_COMPL);
                await DBQuerys().atendsIndivExames().then((response)async{
                  tableATENDS_INDIV_EXAMES  =response;
                  // print(tableATENDS_INDIV_EXAMES);
                  await DBQuerys().atendsIndivProc().then((response)async{
                    tableATENDS_INDIV_PROC = response;
                    // print(tableATENDS_INDIV_PROC);
                    await DBQuerys().atendsIndivProf().then((response)async{
                      tableATENDS_INDIV_PROF = response;
                      // print(tableATENDS_INDIV_PROF);
                      await DBQuerys().atendsIndividuais().then((response)async{
                        tableATENDS_INDIVIDUAIS = response;
                        // print(tableATENDS_INDIVIDUAIS);
                        await DBQuerys().procedimentosFichas().then((response)async{
                          tablePROCEDIMENTOS_FICHAS = response;
                          // print(tablePROCEDIMENTOS_FICHAS);
                          await DBQuerys().procedimentosIndiv().then((response)async{
                            tablePROCEDIMENTOS_INDIV = response;
                            // print(tablePROCEDIMENTOS_INDIV);
                            await DBQuerys().procedimentosIndivFicha().then((response)async{
                              tablePROCEDIMENTOS_INDIV_FICHA = response;
                              // print(tablePROCEDIMENTOS_INDIV_FICHA);
                              await DBQuerys().procedimentosIndivSigtap().then((response)async{
                                tablePROCEDIMENTOS_INDIV_SIGTAP = response;
                                // print(tablePROCEDIMENTOS_INDIV_SIGTAP);
                                await DBQuerys().visitasDomiciliares().then((response)async{
                                  tableVISITAS_DOMICILIARES = response;
                                  // print(tableVISITAS_DOMICILIARES);
                                  await DBQuerys().visitasDomiciliaresCompl().then((response)async{
                                    tableVISITAS_DOMICILIARES_COMPL = response;
                                    // print(tableVISITAS_DOMICILIARES_COMPL);
                                    await DBQuerys().visitasDomiciliaresProc().then((response)async{
                                      tableVISITAS_DOMICILIARES_PROC = response;
                                      // print(tableVISITAS_DOMICILIARES_PROC);
                                      await DBQuerys().fichasComplementares().then((response)async{
                                        tableFICHAS_COMPLEMENTARES = response;
                                        // print(tableFICHAS_COMPLEMENTARES);
                                        await DBQuerys().atendimentosDomiciliares().then((response)async{
                                          tableATENDIMENTOS_DOMICILIARES = response;
                                          // print(tableATENDIMENTOS_DOMICILIARES);
                                          await DBQuerys().atendDomCompl().then((response)async{
                                            tableATENDS_DOM_COMPL = response;
                                            // print(tableATENDS_DOM_COMPL);
                                            await DBQuerys().atendDomProcsFicha().then((response)async{
                                              tableATENDS_DOM_PROC = response;
                                              // print(tableATENDS_DOM_PROC);
                                              await DBQuerys().atendDomProcsSigtap().then((response)async{
                                                tableATENDS_DOM_SIGTAP = response;
                                                // print(tableATENDS_DOM_SIGTAP);
                                                await DBQuerys().atendsOdontologicos().then((response)async{
                                                  tableATENDS_ODONTOLOGICOS = response;
                                                  // print(tableATENDS_ODONTOLOGICOS);
                                                  await DBQuerys().atendsOdontoProf().then((response)async{
                                                    tableATENDS_ODONTO_PROF = response;
                                                    // print(tableATENDS_ODONTO_PROF);
                                                    await DBQuerys().atendsOdontoProc().then((response)async{
                                                      tableATENDS_ODONTO_PROC = response;
                                                      // print(tableATENDS_ODONTO_PROC);
                                                      await DBQuerys().atendsOdontoSigtap().then((response)async{
                                                        tableATENDS_ODONTO_SIGTAP = response;
                                                        // print(tableATENDS_ODONTO_SIGTAP);
                                                        await DBQuerys().atendsOdontoCompl().then((response)async{
                                                          tableATENDS_ODONTO_COMPL = response;
                                                          // print(tableATENDS_ODONTO_COMPL);
                                                          await DBQuerys().marcadoresConQuest().then((response)async{
                                                            tableMARCADORES_CON_QUEST = response;
                                                            // print(tableMARCADORES_CON_QUEST);
                                                            await DBQuerys().marcadoresConsumo().then((response)async{
                                                              tableMARCADORES_CONSUMO = response;
                                                              // print(tableMARCADORES_CONSUMO);
                                                              await DBQuerys().avalElegCondAval().then((response)async{
                                                                tableAVAL_ELEG_COND_AVAL = response;
                                                                // print(tableAVAL_ELEG_COND_AVAL);
                                                                await DBQuerys().avalElegConclIne().then((response)async{
                                                                  tableAVAL_ELEG_CONCL_INE = response;
                                                                  // print(tableAVAL_ELEG_CONCL_INE);
                                                                  await DBQuerys().avaliacoesElegibilidade().then((response)async{
                                                                    tableAVALIACOES_ELEGIBILIDADE = response;
                                                                    // print(tableAVALIACOES_ELEGIBILIDADE);
                                                                    // print('aqui2');
                                                                    syncData();
                                                                  });
                                                                });
                                                              });
                                                            });
                                                          });
                                                        });
                                                      });
                                                    });
                                                  });
                                                });
                                              });
                                            });
                                          });
                                        });
                                      });
                                    });
                                  });
                                });
                              });
                            });
                          });
                        });
                      });
                    });
                  });
                });
              });
            });
          });
        });
      });
    });
  }
  syncData()async{
      Map map ={
        'cidadaos' : tableCIDADAOS,
        'cad_domiciliares': tableCIDADAO_DOMICILIO,
        'dom_cidadaos': tableDOMICILIOS_CIDADAOS,
        'logr_domicilios': tableINNERJOINCIDADAO_DOMICILIO,
        'cad_individuais': tableCADASTROS_INDIVIDUAIS,
        'atends_indiv_compl': tableATENDS_INDIV_COMPL,
        'atends_indiv_exames': tableATENDS_INDIV_EXAMES,
        'atends_indiv_proc': tableATENDS_INDIV_PROC,
        'atends_indiv_prof': tableATENDS_INDIV_PROF,
        'atends_individuais': tableATENDS_INDIVIDUAIS,
        'procedimentos_fichas': tablePROCEDIMENTOS_FICHAS,
        'procedimentos_indiv': tablePROCEDIMENTOS_INDIV,
        'procedimentos_indiv_ficha': tablePROCEDIMENTOS_INDIV_FICHA,
        'procedimentos_indiv_sigtap': tablePROCEDIMENTOS_INDIV_SIGTAP,
        'visitas_domiciliares': tableVISITAS_DOMICILIARES,
        'visitas_domiciliares_compl': tableVISITAS_DOMICILIARES_COMPL,
        'visitas_domiciliares_proc': tableVISITAS_DOMICILIARES_PROC,
        'fichas_complementares': tableFICHAS_COMPLEMENTARES,
        'atendimentos_domiciliares': tableATENDIMENTOS_DOMICILIARES,
        'atend_dom_compl': tableATENDS_DOM_COMPL,
        'atend_dom_procs_ficha': tableATENDS_DOM_PROC,
        'atend_dom_procs_sigtap': tableATENDS_DOM_SIGTAP,
        'atends_odontologicos': tableATENDS_ODONTOLOGICOS,
        'atends_odonto_prof': tableATENDS_ODONTO_PROF,
        'atends_odonto_proc': tableATENDS_ODONTO_PROC,
        'atends_odonto_sigtap': tableATENDS_ODONTO_SIGTAP,
        'atends_odonto_compl': tableATENDS_ODONTO_COMPL,
        'marcadores_con_quest': tableMARCADORES_CON_QUEST,
        'marcadores_consumo': tableMARCADORES_CONSUMO,
        'aval_eleg_cond_aval': tableAVAL_ELEG_COND_AVAL,
        'aval_eleg_concl_ine': tableAVAL_ELEG_CONCL_INE,
        'avaliacao_elegibilidade': tableAVALIACOES_ELEGIBILIDADE,
      };
      await ApiDataPost().sincronizacao(urlAPI, mode, nameCityApi,map).then((response)async{
        if(response['status']!=1){
          setState(() {
            error = true;
            message = 'error';
          });
        }else{
          setState(() {
            upload = false;
            done = true;
            message = '';
          });
        }
      });
  }

  dataSQLite()async{
    await DbSqliteLoad().intialDB().then((db)async {
      List list = await db.query('ARGS');
      urlAPI = list[0]['URLAPI'];
      mode = list[0]['MODE'];
      nameCityApi = list[0]['NAME_CITY_API'];
    });
    setState(() {});
  }


  deleteDB()async{
    await DbSqliteLoad().deleteLoad().then((_)async{
      await DbSqliteSync().deleteSync().then((_){
        Navigator.pushReplacementNamed(context, '/splash');
      });
    });
  }

  @override
  void initState() {
    super.initState();
    dataSQLite();
  }

  @override
  Widget build(BuildContext context) {
    double width = MediaQuery.of(context).size.width;
    double height = MediaQuery.of(context).size.height;
    return Scaffold(
      bottomSheet: Container(
        color: ColorPalette.appBar,
        child: Row(
          children: [
            Spacer(),
            ButtonDefault(
              title: 'Voltar',
              width: width*0.2,
              textColor: ColorPalette.white,
              background: ColorPalette.appBar,
              borderColor: ColorPalette.appBar,
              onPressed: ()=>Navigator.pushNamedAndRemoveUntil(context, '/home', (Route<dynamic> route) => false),
            )
          ],
        ),
      ),
      body: Container(
        padding: EdgeInsets.only(top: 100),
        decoration: BoxDecoration(
            color: ColorPalette.grayBackground,
            image: DecorationImage(
              fit: BoxFit.fitHeight,
              image: AssetImage('assets/images/load_image.png'),
            )
        ),
        width: double.infinity,
        height: double.infinity,
        child: Column(
          children: [
            Image.asset('assets/images/logo.PNG',width: width*0.5,),
            mode == 'homologacao'?Image.asset('assets/images/homologacao.png',width: width*0.4):Container(),
            mode == 'desenvolvimento'?Image.asset('assets/images/desenvolvimento.png',width: width*0.4):Container(),
            message == 'error'?Container():Padding(
              padding: const EdgeInsets.symmetric(vertical: 5.0),
              child: TextDefault(
                text: message,
                color: ColorPalette.black54,
                fontSize: 22,
                fontWeigth: FontWeight.bold,
              ),
            ),
            message!='error'&&upload?Image.asset('assets/images/loading.gif',width: width*0.4):Container(),
            message==''&&done?Image.asset('assets/images/send-done.png',width: width*0.9):Container(),
            error?Image.asset('assets/images/error.png',width: width*0.9):Container(),
            !upload && !done?ButtonDefault(
             title: 'Enviar informações',
             width: width*0.9,
             textColor: ColorPalette.white,
             background: ColorPalette.appBar,
             borderColor: ColorPalette.appBar,
             onPressed: ()=>updateTable(),
           ):Container(),
            SizedBox(height: 20,),
            message==''&&done?Container(
              color: ColorPalette.white,
                width: width,
                height: height*0.3,
                child: ListView(
                  children: [
                    TextDefault(
                      text: 'Atendimentos Domiciliares: ${tableATENDIMENTOS_DOMICILIARES==null?'0':tableATENDIMENTOS_DOMICILIARES.length}',
                      textAlign: TextAlign.center,
                      fontWeigth: FontWeight.bold,
                      color: ColorPalette.black54,
                      fontSize: 18,
                    ),
                    TextDefault(
                      text: 'Atendimento Individuais: ${tableATENDS_INDIVIDUAIS==null?'0':tableATENDS_INDIVIDUAIS.length}',
                      textAlign: TextAlign.center,
                      fontWeigth: FontWeight.bold,
                      color: ColorPalette.black54,
                      fontSize: 18,
                    ),
                    TextDefault(
                      textAlign: TextAlign.center,
                      text: 'Atendimentos Odontológicos: ${tableATENDS_ODONTOLOGICOS==null?'0':tableATENDS_ODONTOLOGICOS.length}',
                      fontWeigth: FontWeight.bold,
                      color: ColorPalette.black54,
                      fontSize: 18,
                    ),
                    TextDefault(
                      textAlign: TextAlign.center,
                      text: 'Avaliação Elegibilidade: ${tableAVALIACOES_ELEGIBILIDADE==null?'0':tableAVALIACOES_ELEGIBILIDADE.length}',
                      fontWeigth: FontWeight.bold,
                      color: ColorPalette.black54,
                      fontSize: 18,
                    ),
                    TextDefault(
                      textAlign: TextAlign.center,
                      text: 'Cadastros Cidadãos Realizados / Atualizados : ${tableCIDADAOS==null?'0':tableCIDADAOS.length}',
                      fontWeigth: FontWeight.bold,
                      color: ColorPalette.black54,
                      fontSize: 18,
                    ),
                    TextDefault(
                      textAlign: TextAlign.center,
                      text: 'Fichas Complementares: ${tableFICHAS_COMPLEMENTARES==null?'0':tableFICHAS_COMPLEMENTARES.length}',
                      fontWeigth: FontWeight.bold,
                      color: ColorPalette.black54,
                      fontSize: 18,
                    ),
                    TextDefault(
                      textAlign: TextAlign.center,
                      text: 'Marcadores de Consumo : ${tableMARCADORES_CONSUMO==null?'0':tableMARCADORES_CONSUMO.length}',
                      fontWeigth: FontWeight.bold,
                      color: ColorPalette.black54,
                      fontSize: 18,
                    ),
                    TextDefault(
                      textAlign: TextAlign.center,
                      //aqui verificar de qual tela seria esses dados
                      text: 'Procedimentos Consolidados: 0',
                      fontWeigth: FontWeight.bold,
                      color: ColorPalette.black54,
                      fontSize: 18,
                    ),
                    TextDefault(
                      textAlign: TextAlign.center,
                      text: 'Procedimentos Individuais : ${tablePROCEDIMENTOS_INDIV==null?'0':tablePROCEDIMENTOS_INDIV.length}',
                      fontWeigth: FontWeight.bold,
                      color: ColorPalette.black54,
                      fontSize: 18,
                    ),
                    TextDefault(
                      textAlign: TextAlign.center,
                      text: 'Visitas Domiciliares: ${tableVISITAS_DOMICILIARES==null?'0':tableVISITAS_DOMICILIARES.length}',
                      fontWeigth: FontWeight.bold,
                      color: ColorPalette.black54,
                      fontSize: 18,
                    ),
                  ],
                )
            ):Container(),
            SizedBox(height: 30,),
            done?Padding(
              padding: const EdgeInsets.symmetric(horizontal: 30.0),
              child: ButtonDefault(
                title: 'Continuar (Mantendo os Dados)',
                width: width*0.9,
                textColor: ColorPalette.white,
                background: ColorPalette.appBar,
                borderColor: ColorPalette.appBar,
                onPressed: ()=>Navigator.pushNamedAndRemoveUntil(context, '/home', (Route<dynamic> route) => false),
              ),
            ):Container(),
            done?Padding(
              padding: const EdgeInsets.symmetric(horizontal: 30.0),
              child: ButtonDefault(
                title: 'Continuar (Limpando os Dados)',
                width: width*0.9,
                textColor: ColorPalette.white,
                background: ColorPalette.red,
                borderColor: ColorPalette.red,
                onPressed: ()=>deleteDB(),
              ),
            ):Container(),
          ],
        ),
      ),
    );
  }
}
