import 'package:flutter/material.dart';
import 'package:rkm/screens/login/sync_login_screen.dart';
import 'package:rkm/config/color_palette.dart';
import 'package:rkm/widgets/alert_dialog_default.dart';
import 'package:rkm/widgets/button_default.dart';
import 'package:rkm/widgets/text_default.dart';
import '../service/api/api_data_load.dart';
import '../service/db/db_sqlite_load.dart';
import '../service/shared_preferences/shared_preferences_service.dart';

class LoadInitScreen extends StatefulWidget {

  @override
  State<LoadInitScreen> createState() => _LoadInitScreenState();
}

class _LoadInitScreenState extends State<LoadInitScreen> {

  final PrefService _prefService = PrefService();
  String messageSteps = 'Aguarde ...';
  bool finish = false;
  String idUsuario = '';
  String mode = '';
  String urlAPI = '';
  bool loading = false;
  String nameCityApi = '';
  String user = '';
  @override
  void initState() {
    super.initState();
    recupDB();
  }

  recupDB()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'];
      user = list[0]['USER'];
      if(urlAPI!=''){
        initLoading();
      }
    });
  }

  initLoading()async{
      await ApiDataLoad().loadPerm(urlAPI,mode,nameCityApi,user).then((response)async{
        if(response['status'] == 0){
          AlertDialogDefault().alert(context, 'Erro', 'Permissão negada', 'Voltar');
        } else if(response['status'] == 1 && response['load_perm'] == "S") {
          idUsuario = response['idUsuario'].toString();
          print('idUsuario $idUsuario');
          _prefService.createCacheidUsuario(idUsuario).then((value)async{
            await ApiDataLoad().loadUnidades(urlAPI,mode,nameCityApi,user).then((value)async{
              if(value.length !=0){
                setState(() {
                  messageSteps = "Etapa 1 de 7 - Gravando as Unidades no Aplicativo";
                });
                await DbSqliteLoad().saveUnidadesDB(value).then((value)async{
                  await ApiDataLoad().loadProcedimentos(urlAPI,mode,nameCityApi,user).then((value)async{
                    setState(() {
                      messageSteps = "Etapa 2 de 7 - Gravando os Procedimentos no Aplicativo";
                    });
                    await DbSqliteLoad().saveProceduresDB(value).then((value)async{
                      print('finalizou save Procedures');
                      await ApiDataLoad().loadProcedimentosRegistros(urlAPI,mode,nameCityApi,user).then((value)async{
                        await DbSqliteLoad().saveProceduresRegisterDB(value).then((value)async{
                          print('finalizou saveProceduresRegisterDB');
                          await ApiDataLoad().loadCID(urlAPI,mode,nameCityApi,user).then((value)async{
                            print('loadCID');
                            setState(() {
                              messageSteps = "Etapa 3 de 7 - Gravando os CIDs no Aplicativo";
                            });
                            await DbSqliteLoad().saveCID(value).then((value)async{
                              print('finalizou saveCID');
                              await ApiDataLoad().loadProcedimentosCID(urlAPI,mode,nameCityApi,user).then((value)async{
                                print('loadProcedimentosCID');
                                await DbSqliteLoad().saveProceduresCID(value).then((value)async{
                                  print('finalizou saveProceduresCID');
                                  await ApiDataLoad().loadCBO(urlAPI,mode,nameCityApi,user).then((value)async{
                                    print('loadCBO');
                                    setState(() {
                                      messageSteps = "Etapa 4 de 7 - Gravando os CBOs no Aplicativo";
                                    });
                                    await DbSqliteLoad().saveCBO(value).then((value)async{
                                      print('finalizou saveCBO');
                                      await ApiDataLoad().loadProcedimentosCBO(urlAPI,mode,nameCityApi,user).then((value)async{
                                        print('loadProcedimentosCBO');
                                        await DbSqliteLoad().saveProceduresCBO(value).then((value)async{
                                          print('finalizou saveProceduresCBO');
                                          await ApiDataLoad().loadCIAP(urlAPI,mode,nameCityApi,user).then((value)async{
                                            print('loadCIAP');
                                            setState(() {
                                              messageSteps =  "Etapa 5 de 7 - Gravando os CIAPs no Aplicativo";
                                            });
                                            await DbSqliteLoad().saveCIAP(value).then((value)async{
                                              print('finalizou saveCIAP');
                                              await ApiDataLoad().loadMunicipios(urlAPI,mode,nameCityApi,user).then((value)async{
                                                print('loadMunicipios');
                                                setState(() {
                                                  messageSteps =  "Etapa 6 de 7 - Gravando os Municípios no Aplicativo";
                                                });
                                                await DbSqliteLoad().saveCity(value).then((value)async{
                                                  print('finalizou saveCity');
                                                  await ApiDataLoad().loadEquipes(urlAPI,mode,nameCityApi,user).then((value)async{
                                                    print('loadEquipes');
                                                    setState(() {
                                                      messageSteps =  "Etapa 7 de 7 - Gravando as Equipes no Aplicativo";
                                                    });
                                                    await DbSqliteLoad().saveTeam(value).then((value)async{
                                                      print('finalizou saveTeam');
                                                      await ApiDataLoad().loadEquipeComponentes(urlAPI,mode,nameCityApi,user).then((value)async{
                                                        print('loadEquipeComponentes');
                                                        await DbSqliteLoad().saveTeamComponents(value).then((value)async{
                                                          print('finalizou saveTeamComponents');
                                                          setState(() {
                                                            finish = true;
                                                          });
                                                        });
                                                      });
                                                    });
                                                  });
                                                });
                                              });
                                            });
                                          });
                                        });
                                      });
                                    });
                                  });
                                });
                              });
                            });
                          });
                        });
                      });
                    });
                  });
                });
              }else{
                AlertDialogDefault().alert(context, 'Error', 'Unidades não carregada, tente novamente!', 'Voltar');
              }
            });
          });
        }
      });
  }

  @override
  Widget build(BuildContext context) {
    
    double width = MediaQuery.of(context).size.width;
    double height = MediaQuery.of(context).size.height;
    
    return Scaffold(
      bottomSheet: Container(
        width: width,
        height: height*0.05,
        color: ColorPalette.appBar,
        child: finish
          ?Row(
            children: [
              Spacer(),
              ButtonDefault(
                onPressed: (){
                  Navigator.pushReplacement(
                    context,
                    MaterialPageRoute(builder: (context) => SyncLoginScreen()),
                  );
                },
                title: 'Continuar',
                width: width*0.3,
                height: height*0.1,
                textColor: ColorPalette.white,
                background: ColorPalette.appBar,
                borderColor: ColorPalette.appBar,
              ),
            ],
          )
          :Padding(
            padding: const EdgeInsets.all(10.0),
            child: TextDefault(
              fontSize: 15,
              text: messageSteps,
              color: ColorPalette.white,
              maxLines: 2,
            ),
          ),
      ),
      body: Container(
        padding: EdgeInsets.all(50),
        width: width,
        height: height,
        decoration: BoxDecoration(
            color: ColorPalette.grayBackground,
            image: DecorationImage(
              fit: BoxFit.fitHeight,
              image: AssetImage('assets/images/load_image.png'),
            )
        ),
        child: finish?ListView(
          children: [
            Image.asset('assets/images/logo.PNG',width: width*0.3,height: height*0.2,),
            Image.asset('assets/images/load-done.png',width: width*0.9,height: height*0.2,),
          ],
        ):ListView(
          children: [
            Image.asset('assets/images/logo.PNG',width: width*0.2,height: height*0.1,),
            SizedBox(height: height*0.1),
            Image.asset('assets/images/loading.gif',width: width*0.2,height: height*0.1,),
            SizedBox(height: height*0.1),
            TextDefault(
              text: 'Aguarde enquanto a Carga Inicial é realizada.\n',
              textAlign: TextAlign.center,
              maxLines: 2,
              color: Colors.black,
              fontWeigth: FontWeight.bold,
            ),
            TextDefault(
              text: 'Esse processo pode levar vários minutos dependendo da sua conexão!',
              color: Colors.black,
              fontWeigth: FontWeight.bold,
              textAlign: TextAlign.center,
              maxLines: 3,
            )
          ],
        ),
      ),
    );
  }
}
