import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:rkm_educa_app/componentes/alert_default.dart';
import 'package:rkm_educa_app/componentes/appbar_custom.dart';
import 'package:rkm_educa_app/componentes/drawer_custom.dart';
import 'package:rkm_educa_app/componentes/snackBars.dart';
import 'package:rkm_educa_app/componentes/text_custom.dart';
import 'package:rkm_educa_app/modelos/estudante_modelo.dart';
import 'package:http/http.dart' as http;
import 'package:rkm_educa_app/utils/dimensoes.dart';
import '../componentes/buttom_custom.dart';
import '../controllers/main_controllers.dart';
import '../utils/cores.dart';

class TelaPasse extends StatefulWidget {
  EstudanteModelo estudanteModelo;

  TelaPasse({
    required this.estudanteModelo
});

  @override
  State<TelaPasse> createState() => _TelaPasseState();
}

class _TelaPasseState extends State<TelaPasse> {

  List dadosPasse=[];
  List dadosFrequncia = [];
  List dadosCarteira = [];
  bool carregando = true;
  String dataNasc = '';
  String dataEmissao = '';

  getPasse()async{
    String teste_passe = '4E275A169EA2432E949FF90DF8D2CF10';
    String passe = widget.estudanteModelo.dados[widget.estudanteModelo.nroAluno]['CD_ALUNO'];
    final url = '${widget.estudanteModelo.URL}/passe?CD_ALUNO=${teste_passe}&CIDADE=${widget.estudanteModelo.cidade}';
    print(url);
    final response = await http.get(Uri.parse(url));
    var map = json.decode(response.body);
    dadosPasse = map;
    print(dadosPasse);
    String dataBD = dadosPasse[0]['DT_NASCIMENTO']??'';
    if(dataBD!=''){
      dataNasc = '${dataBD.substring(6,8)} / ${dataBD.substring(4,6)} / ${dataBD.substring(0,4)}';
    }
    String dataDBEmissao = dadosPasse[0]['VALIDADE_CARTEIRINHA']??'';
    if(dataDBEmissao!=''){
      List list = dataDBEmissao.toString().split('-');
      dataEmissao = '${list[2]} / ${list[1]} / ${list[0]}';
    }

    if(dadosPasse.length==0){
      showSnackBar(context, 'Nenhum passe disponível', Colors.red);
      carregando = false;
      setState(() {});
    }else{
      getFrequencia(teste_passe);
    }
  }
  getFrequencia(String CD_ALUNO)async{
    dadosFrequncia.clear();
    final url = '${widget.estudanteModelo.URL}/frequencia?CD_ALUNO=${CD_ALUNO}&CIDADE=${widget.estudanteModelo.cidade}';
    print(url);
    final response = await http.get(Uri.parse(url));
    var map = json.decode(response.body);
    dadosFrequncia = map;
    print(dadosFrequncia);
    if(dadosPasse.length==0){
      showSnackBar(context, 'Nenhuma frequência registrada', Colors.red);
    }else{
      dadosFrequncia = [
        {'DIA':1,'PRESENTE':0},
        {'DIA':2,'PRESENTE':0},
        {'DIA':3,'PRESENTE':0},
        {'DIA':4,'PRESENTE':0},
        {'DIA':5,'PRESENTE':0},
        {'DIA':6,'PRESENTE':0},
        {'DIA':7,'PRESENTE':0},
        {'DIA':8,'PRESENTE':0},
        {'DIA':9,'PRESENTE':0},
        {'DIA':10,'PRESENTE':0},
        {'DIA':11,'PRESENTE':0},
        {'DIA':12,'PRESENTE':0},
        {'DIA':13,'PRESENTE':0},
        {'DIA':14,'PRESENTE':0},
        {'DIA':15,'PRESENTE':0},
        {'DIA':16,'PRESENTE':0},
        {'DIA':17,'PRESENTE':0},
        {'DIA':18,'PRESENTE':0},
        {'DIA':19,'PRESENTE':0},
        {'DIA':20,'PRESENTE':0},
        {'DIA':21,'PRESENTE':0},
        {'DIA':22,'PRESENTE':0},
        {'DIA':23,'PRESENTE':0},
        {'DIA':24,'PRESENTE':0},
        {'DIA':25,'PRESENTE':0},
        {'DIA':26,'PRESENTE':0},
        {'DIA':27,'PRESENTE':0},
        {'DIA':28,'PRESENTE':0},
        {'DIA':29,'PRESENTE':0},
        {'DIA':30,'PRESENTE':0},
        {'DIA':31,'PRESENTE':0},
      ];
    }
    carregando = false;
    setState(() {});
    // print(dadosFrequncia);
  }

  getCarteira()async{
    dadosCarteira.clear();
    carregando = true;
    setState(() {});
    String teste_passe = '4E275A169EA2432E949FF90DF8D2CF10';
    String CD_ALUNO = widget.estudanteModelo.dados[widget.estudanteModelo.nroAluno]['CD_ALUNO'];
    final url = '${widget.estudanteModelo.URL}/carteira?CD_ALUNO=${teste_passe}&CIDADE=${widget.estudanteModelo.cidade}';
    print(url);
    final response = await http.get(Uri.parse(url));
    var map = json.decode(response.body);
    dadosCarteira = map;
    print(dadosCarteira);
    carregando = false;
    setState(() {});
    AlertDefault().alert(
      context, Dimensoes.height*0.8,
      SafeArea(
        child: Center(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Container(
                alignment: Alignment.topCenter,
                width: 378,
                height: 270,
                decoration: BoxDecoration(
                  border: Border.all(width: 2.0)
                ),
                child: Column(
                  children: [
                    Row(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Container(
                          width: 124,
                          height: 159,
                          alignment: Alignment.center,
                          decoration: BoxDecoration(
                              border: Border.all(width: 2.0)
                          ),
                          child: TextCustom(text: '3x4',size: 12.0,fontWeight: FontWeight.bold,color: Colors.black,),
                        ),
                        Column(
                          children: [
                            Container(
                              width: 235,
                              height: 65,
                              alignment: Alignment.center,
                              decoration: BoxDecoration(
                                  border: Border.all(width: 2.0)
                              ),
                              child: Row(
                                children: [
                                  Container(
                                    width: 53,
                                    height: 49,
                                    child: Image.asset('assets/images/logo_carteirinha_${widget.estudanteModelo.cidade.toLowerCase()}.png'),
                                  ),
                                  TextCustom(text: widget.estudanteModelo.cidade,size: 16.0,fontWeight: FontWeight.bold,color: Colors.black,),
                                ],
                              ),
                            ),
                            Container(
                              width: 235,
                              height: 20,
                              decoration: BoxDecoration(
                                  border: Border.all(width: 2.0)
                              ),
                              child: TextCustom(text: '1ª Via - Transporte Escolar',size: 12.0,fontWeight: FontWeight.bold,color: Colors.black,),
                            ),
                            Container(
                              width: 235,
                              height: 20,
                              decoration: BoxDecoration(
                                  border: Border.all(width: 2.0)
                              ),
                              child: TextCustom(text: 'RA: ${dadosCarteira[0]['NR_RA']}',size: 12.0,fontWeight: FontWeight.bold,color: Colors.black,),
                            ),
                            Container(
                              width: 235,
                              height: 54,
                              decoration: BoxDecoration(
                                  border: Border.all(width: 2.0)
                              ),
                              child: TextCustom(text: 'Nome: ${dadosCarteira[0]['NO_ALUNO']}',size: 12.0,fontWeight: FontWeight.bold,color: Colors.black),
                            ),
                          ],
                        ),
                      ],
                    ),
                    Container(
                      width: 373,
                      height: 27.5,
                      decoration: BoxDecoration(
                          border: Border.all(width: 2.0)
                      ),
                      child: TextCustom(text: ' Endereço: ${dadosCarteira[0]['NO_LOGRADOURO']}, ${dadosCarteira[0]['NR_LOGRADOURO']}, ${dadosCarteira[0]['DESC_BAIRRO']}',size: 12.0,fontWeight: FontWeight.bold,color: Colors.black,),
                    ),
                    Container(
                      width: 373,
                      height: 26.5,
                      decoration: BoxDecoration(
                          border: Border.all(width: 2.0)
                      ),
                      child: TextCustom(
                        text: ' Fone: (${dadosCarteira[0]['NR_DDD_TELEFONE']}) ${dadosCarteira[0]['NR_TELEFONE']}  Escola: ${dadosCarteira[0]['NO_FANTASIA']}',
                        size: 12.0,fontWeight: FontWeight.bold,color: Colors.black,),
                    ),
                    Container(
                      width: 373,
                      height: 26.5,
                      decoration: BoxDecoration(
                          border: Border.all(width: 2.0)
                      ),
                      child: TextCustom(
                        text: ' Celular: (${dadosCarteira[0]['NR_DDD_CELULAR']}) ${dadosCarteira[0]['NR_CELULAR']}  Validade: ${dadosCarteira[0]['VALIDADE_CARTEIRINHA']} CEAC: ${dadosCarteira[0]['CEAC'].toString().trim()=='N'?'NÃO':'SIM'}',
                        size: 12.0,fontWeight: FontWeight.bold,color: Colors.black,),
                    ),
                    Container(
                      width: 373,
                      height: 26.5,
                      decoration: BoxDecoration(
                          border: Border.all(width: 2.0)
                      ),
                      child: TextCustom(text: ' Tipo Transp.: ${dadosCarteira[0]['FL_TIPO_TRANSPORTE'].toString().trim()=='R'?'TRANSPORTE MUNICIPAL':'TRANSPORTE INTERMUNICIPAL'}',size: 12.0,fontWeight: FontWeight.bold,color: Colors.black,),
                    ),
                  ],
                ),
              ),
              Container(
                width: 378,
                height: 270,
                decoration: BoxDecoration(
                    border: Border.all(width: 4.0)
                ),
                child: Row(
                  children: [
                    Column(
                      children: [
                        SizedBox(height: 14,),
                        Container(
                          width: 212,
                          height: 60,
                          child: TextCustom(
                            text:'Respeite a orientação do condutor do veículo, pois ele é seu amigo. Obrigatória apresentação desta identificação, diariamente.',
                            maxLines: 4,
                            size: 12.0,
                            textAlign: TextAlign.justify,
                            fontWeight: FontWeight.bold,
                            color: Colors.black,
                          ),
                        ),
                        SizedBox(height: 12,),
                        Container(
                          width: 211,
                          height: 45,
                          child: TextCustom(
                            text:'Casos de insubordinação serão comunicados aos pais e estarão sujeitos a advertência.',
                            maxLines: 3,
                            size: 12.0,
                            textAlign: TextAlign.justify,
                            fontWeight: FontWeight.bold,
                            color: Colors.black,
                          ),
                        ),
                        SizedBox(height: 70,),
                        Container(
                          margin: EdgeInsets.symmetric(horizontal: 5),
                          width: 211,
                          height: 2,
                          color: Colors.black,
                        ),
                        Container(
                          width: 211,
                          height: 45,
                          child: TextCustom(
                            text:'Coordenadoria de Educação',
                            maxLines: 3,
                            size: 12.0,
                            textAlign: TextAlign.center,
                            fontWeight: FontWeight.bold,
                            color: Colors.black,
                          ),
                        ),
                      ],
                    ),
                    Column(
                      children: [
                        SizedBox(height: 14,),
                        Container(
                          width: 132,
                          height: 112,
                          decoration: BoxDecoration(
                              border: Border.all(width: 2.0)
                          ),
                          child: TextCustom(text: 'Ano:', size: 12.0,color: Colors.black,fontWeight: FontWeight.bold),
                        ),
                        SizedBox(height: 14,),
                        Container(
                          width: 132,
                          height: 112,
                          decoration: BoxDecoration(
                              border: Border.all(width: 2.0)
                          ),
                          child: TextCustom(text: 'Ano:', size: 12.0,color: Colors.black,fontWeight: FontWeight.bold),
                        )
                      ],
                    ),
                  ],
                ),
              ),
              Spacer(),
              ButtonCustom(
                text: 'Voltar',
                fontsize: 14.0,
                colorBorder: PaletaCores.cinzaClaro,
                colorButton: PaletaCores.cinzaClaro,
                colorText: Colors.white,
                widthCustom: 0.25,
                heightCustom: 0.05,
                onPressed: ()=>Navigator.of(context).pop(),
              ),
            ],
          ),
        ),
      )
    );
  }

  @override
  void initState() {
    super.initState();
    MainControllers().salvarLog(widget.estudanteModelo, 'PASSE');
    getPasse();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBarCustom().appbar(context, 'PASSE ESCOLAR'),
      drawer: DrawerCustom(estudanteModelo: widget.estudanteModelo),
      bottomSheet: carregando?SizedBox(width: 0,height: 0,): Container(
        width: Dimensoes.width,
        height: 70,
        alignment: Alignment.center,
        child: ButtonCustom(
          text: 'Exibir Carteira',
          fontsize: 14.0,
          colorBorder: PaletaCores.cinzaClaro,
          colorButton: PaletaCores.cinzaClaro,
          colorText: Colors.white,
          widthCustom: 0.8,
          heightCustom: 0.05,
          onPressed: ()=>getCarteira(),
        ),
      ),
      body: carregando?Center(
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            CircularProgressIndicator(color: PaletaCores.cinzaClaro,),
            SizedBox(width: 20,),
            TextCustom(text: 'Buscando dados ...')
          ],
        ),
      ):Container(
          alignment: Alignment.center,
          margin: EdgeInsets.all(10),
          height: Dimensoes.height,
          child: ListView(
            children: [
              Container(
                color: Colors.black,
                child: TextCustom(text: widget.estudanteModelo.NO_ALUNO,fontWeight: FontWeight.bold,color: Colors.white,textAlign: TextAlign.center),
              ),
              Row(
                children: [
                  Column(
                    children: [
                      Container(
                          width: Dimensoes.width*0.55,
                          child: TextCustom(text: 'RA: ${dadosPasse[0]['NR_RA']}',size: 14.0, fontWeight: FontWeight.bold)
                      ),
                      Container(
                          width: Dimensoes.width*0.55,
                          child: TextCustom(text: 'DATA NASC: $dataNasc',size: 14.0, fontWeight: FontWeight.bold,)
                      ),
                    ],
                  ),
                  Container(
                    width: Dimensoes.width*0.4,
                    alignment: Alignment.center,
                    child: TextCustom(text: 'CARTEIRA N°: ${dadosPasse[0]['NR_CARTEIRA']}',size: 16.0, fontWeight: FontWeight.bold,)
                  ),
                ],
              ),
              TextCustom(text: 'DATA EMISSÃO: $dataEmissao',size: 14.0, fontWeight: FontWeight.bold,),
              TextCustom(text: 'LINHA: ${dadosPasse[0]['NR_TRANSPORTE']}',size: 14.0, fontWeight: FontWeight.bold,),
              TextCustom(text: 'SÉRIE: ${dadosPasse[0]['DESC_SERIE']} - ${dadosPasse[0]['GRAU']}'
                  '  TURNO: ${dadosPasse[0]['TURNO'].toString().trim()=='1'?'MANHÃ':dadosPasse[0]['GRAU'].toString().trim()=='2'?'TARDE':''}',size: 14.0, fontWeight: FontWeight.bold,),
              TextCustom(text: 'ESCOLA: ${widget.estudanteModelo.ESCOLA}',size: 14.0, fontWeight: FontWeight.bold,),
              Container(
                margin: EdgeInsets.symmetric(vertical: 20),
                color: Colors.black,
                alignment: Alignment.center,
                child: TextCustom(text: 'FREQUÊNCIA USO DO PASSE MÊS ${DateTime.now().month}',fontWeight: FontWeight.bold,color: Colors.white,),
              ),
              Container(
                width: Dimensoes.width*0.9,
                height: Dimensoes.height*0.5,
                child: GridView.builder(
                  physics: NeverScrollableScrollPhysics(),
                    gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                        crossAxisCount: 7,
                        mainAxisSpacing: 25,
                        crossAxisSpacing: 0
                    ),
                    itemCount: dadosFrequncia.length,
                    itemBuilder: (context,index){
                      return Container(
                        height: 40,
                        width: 40,
                        child: Column(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            Container(
                                alignment: Alignment.center,
                                width: 20,
                                height: 15,
                                child: TextCustom(text: dadosFrequncia[index]['DIA'].toString(),size: 15.0,)),
                            Container(
                              width: 30,
                              height: 30,
                              child: Checkbox(
                                value: dadosFrequncia[index]['PRESENTE'].toString()=='1'?true:false,
                                onChanged: (v){},
                                activeColor: PaletaCores.cinzaClaro,
                              ),
                            )
                          ],
                        ),
                      );
                    }
                ),
              ),
            ],
          )
      ),
    );
  }
}
