import 'package:brasil_fields/brasil_fields.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:intl/intl.dart';
import 'package:rkm/config/color_palette.dart';
import 'package:rkm/config/const_variable.dart';
import 'package:rkm/widgets/alert_dialog_default.dart';
import 'package:rkm/widgets/button_default.dart';
import 'package:rkm/widgets/title_containers.dart';
import 'package:sqflite/sqflite.dart';
import '../../controllers/main_controllers.dart';
import '../../service/db/db_querys.dart';
import '../../service/db/db_sqlite_load.dart';
import '../../service/db/db_sqlite_sync.dart';
import '../../service/shared_preferences/shared_preferences_service.dart';
import '../../widgets/appbar_default.dart';
import '../../widgets/dropdown_with_subtitle.dart';
import '../../widgets/error_default.dart';
import '../../widgets/input_search_text.dart';
import '../../widgets/input_with_subtitle.dart';
import '../../widgets/onbackbutton.dart';
import '../../widgets/subtitle_appbar_citizen.dart';
import '../../widgets/switch_with_subtitle.dart';
import '../../widgets/text_default.dart';
class RegisterCitizenScreen extends StatefulWidget {
  List listData;
  RegisterCitizenScreen({required this.listData});
  @override
  State<RegisterCitizenScreen> createState() => _RegisterCitizenScreenState();
}

class _RegisterCitizenScreenState extends State<RegisterCitizenScreen> {

  var nameController = TextEditingController();
  var nameSocialController = TextEditingController();
  var spouseController = TextEditingController();
  var cityBirthController = TextEditingController();
  var cityController = TextEditingController();
  var searchCityBirthController = TextEditingController();
  var searchCityController = TextEditingController();
  var nameMotherController = TextEditingController();
  var nameFatherController = TextEditingController();
  var codIBGEController = TextEditingController();
  var unitController = TextEditingController();
  var medicalRecordController = TextEditingController();
  var medicalRecordProvController = TextEditingController();
  var classificationProvController = TextEditingController();
  var numberFamilyController = TextEditingController();
  var cepController = TextEditingController();
  var numberController = TextEditingController();
  var complementController = TextEditingController();
  var referencePointController = TextEditingController();
  var foneDDDController = TextEditingController();
  var foneController = TextEditingController();
  var mobileDDDController = TextEditingController();
  var mobileController = TextEditingController();
  var messageDDDController = TextEditingController();
  var messageController = TextEditingController();
  var emailController = TextEditingController();
  var observationController = TextEditingController();
  var CPFController = TextEditingController();
  var CNSController = TextEditingController();
  var voterController = TextEditingController();
  var RGController = TextEditingController();
  var RGComplementController = TextEditingController();
  var RGOrganController = TextEditingController();
  var RGDateController = TextEditingController();
  String RGDateDB = '';
  var numberCertificateController = TextEditingController();
  var nameCertificateController = TextEditingController();
  var bookCertificateController = TextEditingController();
  var sheetCertificateController = TextEditingController();
  var termCertificateController = TextEditingController();
  var dateCertificateController = TextEditingController();
  String dateCertificateDB='';
  var CTPSController = TextEditingController();
  var numberCTPSController = TextEditingController();
  var PISController = TextEditingController();
  var NISController = TextEditingController();
  var incomeController = TextEditingController();
  var professionalController = TextEditingController();
  var dateDeathController = TextEditingController();
  String checkCNS = '';
  String checkCPF = '';
  String? selectTypeCertificate;
  int? selectTypeCertificateCod;
  String? selectCTPSUF;
  String? selectRGUF;
  String? selectTypeStreet;
  String? selectStreet;
  String? selectSubdivision;
  int? selectSubdivisionCOD;
  String? selectZone;
  int? selectZoneCod;
  String? selectVillage;
  String? selectCountry;
  String? selectClassification;
  int? selectClassificationCOD;
  String? selectGender;
  String? selectMaritalStatus;
  int? selectMaritalStatusCod;
  String? selectBreed;
  int? selectBreedCod;
  String? selectScooling;
  int? selectScoolingCod;
  String? selectDeficiency;
  int? selectDeficiencyCod;
  String? selectNaturality;
  int? selectNaturalityCod;
  int? cityBirthCod;
  bool enableSpouse = false;
  bool enableMother = false;
  bool enableFather = false;
  bool enableCityCard = false;
  bool enableBlocked = false;
  bool checkBoxNumber = false;
  String date = 'Data de Nascimento';
  String dateDB = '';
  String dateDeathDB = '';
  List cityDB = [];
  List ibgeDB = [];
  List<String> streetDB = [];
  List<String> subdivisionDB = [];
  List<String> villageDB = [];
  List<String> typeStreetDB = [];
  List showResultSearchCity = [];
  List showResultSearchIbge = [];
  List listVillageDB =[];
  List resultListNasc =[];
  List resultListResid =[];
  String idBairro='';
  int idTipo=0;
  bool showCheckError = false;
  bool showTab = false;
  String errorTopo = 'Existem campos obrigatórios não preenchidos.';
  List<String> typeCertificate = [];
  List<String> listDeficiency = [];
  List<String> listScooling = [];
  List<String> listBreed = [];
  List<String> listMaritalStatus = [];
  String idUnidade = '';
  String codSus = '';
  bool edit = false;
  bool editing = false;
  int idCidadao = 0;

  escolherprazoInicio(BuildContext context,String type) async {

    var pickDate = await showDatePicker(
        context: context,
        initialDate: DateTime.now(),
        firstDate: DateTime(1900),
        lastDate: DateTime(2024));
    if (pickDate != null) {
      setState(() {
        if(type == 'birth'){
          dateDB = '${pickDate.year}-${pickDate.month<10?'0':''}${pickDate.month}-${pickDate.day<10?'0':''}${pickDate.day}';
          date = formatData(year: pickDate.year, month: pickDate.month, day: pickDate.day);
        }
        if(type == 'rg'){
          RGDateController.text = formatData(year: pickDate.year, month: pickDate.month, day: pickDate.day);
          RGDateDB = '${pickDate.year}-${pickDate.month<10?'0':''}${pickDate.month}-${pickDate.day<10?'0':''}${pickDate.day}';
        }
        if(type == 'cert'){
          dateCertificateController.text = formatData(year: pickDate.year, month: pickDate.month, day: pickDate.day);
          dateCertificateDB = '${pickDate.year}-${pickDate.month<10?'0':''}${pickDate.month}-${pickDate.day<10?'0':''}${pickDate.day}';
        }
        if(type == 'death'){
          dateDeathController.text = formatData(year: pickDate.year, month: pickDate.month, day: pickDate.day);
          dateDeathDB = '${pickDate.year}-${pickDate.month<10?'0':''}${pickDate.month}-${pickDate.day<10?'0':''}${pickDate.day}';
        }
      });
    }
  }

  String formatData({int? year, int? month, int? day}) {
    DateTime data = DateTime(year!, month!, day!);
    String formattedDate = DateFormat('dd/MM/yyyy').format(data);
    return formattedDate;
  }

  getUnit()async{
      Database db = await DbSqliteLoad().intialDB();
      var queryControl = "SELECT * FROM CONTROLE_INTERNO";
      List listControl = await db.rawQuery(queryControl);
      final PrefService _prefService = PrefService();
      _prefService.readCacheUnidade('idUnidade').then((listUnidade)async{
        idUnidade =listUnidade[0];
      });
      setState(() {
        unitController.text = listControl[0]['NOME_UNIDADE'];
      });
  }

  changedCity()async{
    Database db = await DbSqliteLoad().intialDB();
    var queryCity = "SELECT * FROM ARGS";
    List listCity = await db.rawQuery(queryCity);
    // print(listCity);
    setState(() {
      cityController.text = '${listCity[0]['NAME_CITY_FRONT']} - ${listCity[0]['COD_STATE']}'.toUpperCase();
      codIBGEController.text = listCity[0]['COD_IBGE'].toString();
    });
    String city = MainControllers().replaceDefaul(listCity[0]['NAME_CITY_FRONT']);
    print(city);
    resultListResid = await DBQuerys().buscaMunicipioporNome(city);
  }

  loadVillgeDB()async{
    Database db = await DbSqliteLoad().intialDB();
    var query = "SELECT * FROM BAIRROS ORDER BY NO_BAIRRO";
    listVillageDB = await db.rawQuery(query);
    for(int i=0; listVillageDB.length > i;i++){
      villageDB.add('${listVillageDB[i]['NO_BAIRRO']}');
    }
    setState(() {});
  }

  loadTypeStreetDB()async{
    Database db = await DbSqliteLoad().intialDB();
    var query = "SELECT * FROM LOGRADOUROS_TIPOS ORDER BY NO_LOGR_TIPO";
    List list = await db.rawQuery(query);
    for(int i=0; list.length > i;i++){
      typeStreetDB.add('${list[i]['NO_LOGR_TIPO']}');
    }
    // print('oque');
    // print(typeStreetDB);
    setState(() {});
  }

  loadStreetDB()async{
    streetDB=[];
    Database db = await DbSqliteLoad().intialDB();
    // var query = "SELECT * FROM EQUIPES JOIN PROFISSIONAIS_EQUIPE ON PROFISSIONAIS_EQUIPE.ID_EQUIPE = EQUIPES.ID_EQUIPE WHERE ID_UNIDADE = $idUnidade AND ID_PROFISSIONAL = $idUsuario";
    //     {ID_LOGR_ENDERECO: 14, ID_LOGR_TIPO: 27, DESC_LOGR_ENDERECO: NICOLAU MAROTTI, ID_BAIRRO: 135},
    var query = "SELECT * FROM LOGRADOUROS_ENDERECOS WHERE ID_BAIRRO = $idBairro AND ID_LOGR_TIPO = $idTipo ORDER BY DESC_LOGR_ENDERECO";
    List list = await db.rawQuery(query);

    for(int i=0; list.length > i;i++){
      streetDB.add('${list[i]['DESC_LOGR_ENDERECO']}');
    }
    // print(streetDB);
    setState(() {});
  }

  loadSubdivisionsDB()async{
    Database db = await DbSqliteLoad().intialDB();
    List list = await db.rawQuery("SELECT * FROM LOGRADOUROS_LOTEAMENTOS ORDER BY DESC_LOGR_LOTEAMENTO");

    for(int i=0; list.length > i;i++){
      subdivisionDB.add('${list[i]['DESC_LOGR_LOTEAMENTO']}');
    }
    // print(list);
    setState(() {});
  }

  _searchCity(){
    searchCity('city');
  }

  _searchCityBirth(){
    searchCity('birth');
  }

  getCity()async{
    List list = await DBQuerys().buscaTodosMunicipios();
    for(int i=0; list.length > i;i++){
      cityDB.add('${list[i]['NO_MUNICIPIO']} - ${list[i]['UF_ESTADO']}');
      ibgeDB.add('${list[i]['CODIGO_IBGE']}');
    }
    searchCity('init');
    return 'complete';
  }

  searchCity(String search)async{
    if(search=='city'?searchCityController.text.isNotEmpty:searchCityBirthController.text.isNotEmpty){
      showResultSearchCity =[];
      showResultSearchIbge =[];
      for (int i =0;cityDB.length>i;i++) {
        String CIDADE = '${cityDB[i]}';

        if(CIDADE.contains(search=='city'?searchCityController.text.toUpperCase():searchCityBirthController.text.toUpperCase())){
          if(showResultSearchCity.length<10){
            showResultSearchCity.add(cityDB[i]);
            showResultSearchIbge.add(ibgeDB[i]);
          }
        }
      }
      setState(() {
        // print(showResultSearchCity);
      });
    }else{
      setState(() {
        for(int i = 0;i<10;i++){
          showResultSearchCity.add(cityDB[i]);
          showResultSearchIbge.add(ibgeDB[i]);
        }
      });
    }
  }

  checkSave()async{
    bool checkMother = false;
    bool checkFather = false;
    bool checkClassification = false;
    if(!enableMother && nameMotherController.text.isEmpty){
      checkMother = true;
      print('colocar nome mãe');
    }
    if(!enableFather && nameFatherController.text.isEmpty){
      checkFather = true;
      print('colocar nome pai');
    }
    if(CPFController.text.isNotEmpty){
      checkCPF = await MainControllers().validaCPF(CPFController.text,editing);
    }else{
      checkCPF = 'ok';
    }
    if(CNSController.text.isNotEmpty){
      checkCNS = await MainControllers().validaCNS(CNSController.text,editing);
    }else{
      checkCNS = 'ok';
    }
    if((selectClassification!='OUTRO MUNICIPIO' && selectCountry == 'BRASIL' && selectStreet == null) ||
        (selectStreet!=null && (cepController.text.isEmpty || cepController.text.length!=8)) ||
        (selectStreet!=null && numberController.text.isEmpty) ||
        (selectTypeStreet == null && selectClassification!='OUTRO MUNICIPIO') ||
        (selectVillage == null && (selectCountry == 'BRASIL' && selectClassification!='OUTRO MUNICIPIO')) ||
        (cityController.text.isEmpty && selectCountry!='OUTRO') ||
        selectCountry == null
    ){
      checkClassification = true;
      print('erro no end');
    }

    //ok
    if(nameController.text.isEmpty ||
        selectGender==null ||
        selectNaturality==null ||
        selectBreed==null ||
        selectDeficiency==null ||
        selectClassification==null ||
        selectCountry==null ||
        date == 'Data de Nascimento'||
        cityBirthController.text.isEmpty ||
        messageDDDController.text.isEmpty ||
        messageController.text.isEmpty ||
        checkMother ||
        checkFather ||
        checkClassification||
        (selectMaritalStatus == 'CASADO(A)' && spouseController.text.isEmpty)
    ){
      print('erro');
      setState(() {
        showCheckError = true;
      });
    }else{
      print('passou');
      if(widget.listData.length==0){
        codSus = MainControllers().gerarCDUsuarioSus();
      }else{
        codSus = widget.listData[0]['CD_USUARIO_SUS'];
      }
      if(codSus!=''){
        saveCitizen();
      }
    }
  }

  saveCitizen()async{
    Map<String, dynamic> row = {
      'ID_CIDADAO'          : idCidadao,
      'CD_USUARIO_SUS'      : codSus,
      'NOME_CIDADAO'        : nameController.text,
      'NOME_SOCIAL'         : nameSocialController.text,
      'SEXO'                : selectGender=='MASCULINO'?'M':'F',
      'DT_NASCIMENTO'       : dateDB,
      'ID_ESTADO_CIVIL'     : selectMaritalStatusCod,
      'NOME_CONJUGE'        : spouseController.text,
      'NACIONALIDADE'       : selectNaturalityCod,
      'ID_MUNICIPIO_NASC'   : resultListNasc[0]['ID_MUNICIPIO'],
      'NO_MUNICIPIO_NASC'   : resultListNasc[0]['NO_MUNICIPIO'],
      'ESTADO_UF_NASC'      : resultListNasc[0]['UF_ESTADO'],
      'ID_ETNIA'            : selectBreedCod,
      'ID_ESCOLARIDADE'     : selectScoolingCod,
      'ID_DEFICIENCIA'      : selectDeficiencyCod,
      'NOME_MAE'            : nameMotherController.text,
      'DESCONHECE_MAE'      : enableMother?1:0,
      'NOME_PAI'            : nameFatherController.text,
      'DESCONHECE_PAI'      : enableFather?1:0,
      'ID_UNIDADE'          : idUnidade,
      'NUM_PRONTUARIO'      : medicalRecordController.text,
      'NUM_PRONTUARIO_PROV' : medicalRecordProvController.text,
      'CLASSIFICACAO'       : selectClassificationCOD,
      'CLASSIFICACAO_SUB'   : selectSubdivisionCOD,
      'NUM_FAMILIA'         : numberFamilyController.text,
      'ID_PAIS_RESID'       : selectCountry=='BRASIL'?33:0,
      'ID_MUNICIPIO_RESID'  : resultListResid[0]['ID_MUNICIPIO'],
      'NO_MUNICIPIO_RESID'  : resultListResid[0]['NO_MUNICIPIO'],
      'ESTADO_UF_RESID'     : resultListResid[0]['UF_ESTADO'],
      'CODIGO_IBGE_RESID'   : codIBGEController.text,
      'NO_BAIRRO_LOGR'      : selectVillage,
      'ID_LOGR_TIPO'        : idTipo,
      'NOME_LOGR'           : selectStreet,
      'CEP_LOGR'            : cepController.text.isNotEmpty?int.parse(cepController.text):0,
      'NUMERO_LOGR'         : numberController.text.isNotEmpty?int.parse(numberController.text):0,
      'LOTEAMENTO_LOGR'     : selectSubdivision,
      'COMPL_LOGR'          : complementController.text,
      'PONTO_REFERENCIA'    : referencePointController.text,
      'ZONA_LOGR'           : selectZoneCod,
      'DDD_CELULAR'         : mobileDDDController.text.isNotEmpty?int.parse(mobileDDDController.text):0,
      'NUM_CELULAR'         : mobileController.text.isNotEmpty?int.parse(mobileController.text):0,
      'DDD_TELEFONE'        : foneDDDController.text.isNotEmpty?int.parse(foneDDDController.text):0,
      'NUM_TELEFONE'        : foneController.text.isNotEmpty?int.parse(foneController.text):0,
      'DDD_RECADO'          : messageDDDController.text.isNotEmpty?int.parse(messageDDDController.text):0,
      'NUM_RECADO'          : messageController.text.isNotEmpty?int.parse(messageController.text):0,
      'EMAIL'               : emailController.text,
      'OBSERVACOES'         : observationController.text,
      'CPF'                 : CPFController.text.isNotEmpty?int.parse(CPFController.text):0,
      'CNS'                 : checkCNS == 'ok'&& CNSController.text.isNotEmpty?int.parse(CNSController.text):999999999999999,
      'TITULO_ELEITOR'      : voterController.text,
      'RG_NUMERO'           : RGController.text.isNotEmpty?int.parse(RGController.text):0,
      'RG_COMPLEMENTO'      : RGComplementController.text,
      'RG_UF'               : selectRGUF,
      'RG_ORGAO'            : RGOrganController.text,
      'RG_DATA_EMISSAO'     : RGDateDB,
      'TIPO_CERTIDAO'       : selectTypeCertificateCod,
      'NUM_CERTIDAO'        : numberCertificateController.text,
      'CARTORIO_CERTIDAO'   : nameCertificateController.text,
      'LIVRO_CERTIDAO'      : bookCertificateController.text,
      'FOLHA_CERTIDAO'      : sheetCertificateController.text,
      'TERMO_CERTIDAO'      : termCertificateController.text,
      'DT_EMISSAO_CERTIDAO' : dateCertificateDB,
      'NUM_CTPS'            : CTPSController.text.isNotEmpty?int.parse(CTPSController.text):0,
      'NUM_SERIE_CTPS'      : numberCTPSController.text.isNotEmpty?int.parse(numberCTPSController.text):0,
      'ESTADO_UF_CTPS'      : selectCTPSUF,
      'NUM_PIS_PASEP'       : PISController.text.isNotEmpty?int.parse(PISController.text):0,
      'FL_RETIROU_CARTAO'   : enableCityCard?'S':'N',
      'NUM_NIS'             : NISController.text.isNotEmpty?int.parse(NISController.text):0,
      //aqui
      'NUM_PROT_CROSS'      : '',
      'RENDA_MENSAL'        : incomeController.text.isNotEmpty?double.parse(incomeController.text.replaceAll('R\$ ', '').replaceAll('.', '').replaceAll(',', '.')):0,
      'PROFISSAO'           : professionalController.text,
      'DT_OBITO'            : dateDeathDB,
      'DECLARACAO_OBITO'    : '',
      'BLOQUEIO'            : enableBlocked?1:0,
      'ORIGEM'              : 'A',
      'DT_HORA_CADASTRO'    : DateTime.now().toString(),
      // 'ID_USUARIO_CADASTRO' : '',
      //só quando for feito o atendimento domicíliar
      'ID_DOMICILIO'        : '',
      //só quando for feito um atendimento
      'ATENDIMENTOS'        : '',
      'SINCRONIZADO'        : 'N',
    };
    await DbSqliteSync().insertCidadaos(row,editing?'update':'new',codSus).then((value){
      if(checkCNS != 'ok' || CNSController.text.isEmpty){
        AlertDialogDefault().alert(
            context,
            'Aviso',
            'CNS Inválido!',
            'OK'
        );
        setState(() {
          errorTopo = 'O usuário foi cadastrado sem um CNS válido!';
        });
      }else{
        setState(() {
          showCheckError = false;
        });
      }
      AlertDialogDefault().alert(
          context,
          'Aviso',
          editing?
          'Cidadão alterado com sucesso!':
          'Cidadão cadastrado com sucesso!',
          'OK'
      );
      setState(() {
        showTab = true;
      });
      // print(value);
    });
  }

  loadLists(){
    for(int i = 0; ConstVariable().itensCertificate.length > i; i++){
      typeCertificate.add(ConstVariable().itensCertificate[i].title);
    }
    for(int i = 0; ConstVariable().itensDeficiency.length > i; i++){
      listDeficiency.add(ConstVariable().itensDeficiency[i].title);
    }
    for(int i = 0; ConstVariable().listScooling.length > i; i++){
      listScooling.add(ConstVariable().listScooling[i].title);
    }
    for(int i = 0; ConstVariable().listBreed.length > i; i++){
      listBreed.add(ConstVariable().listBreed[i].title);
    }
    for(int i = 0; ConstVariable().listMaritalStatus.length > i; i++){
      listMaritalStatus.add(ConstVariable().listMaritalStatus[i].title);
    }
  }

  getData()async{
    // print('passou');
    // print(widget.listData);
    idCidadao = widget.listData[0]['ID_CIDADAO'];
    codSus = widget.listData[0]['CD_USUARIO_SUS'];
    nameController.text = widget.listData[0]['NOME_CIDADAO'];
    nameSocialController.text = widget.listData[0]['NOME_SOCIAL'];
    selectGender = widget.listData[0]['SEXO']=='M'?'MASCULINO':'FEMININO';
    dateDB = widget.listData[0]['DT_NASCIMENTO'];
    List splittedDate = dateDB.split('-');
    date = '${splittedDate[2]}/${splittedDate[1]}/${splittedDate[0]}';
    for(int i = 0;ConstVariable().listMaritalStatus.length >i;i++){
      if(ConstVariable().listMaritalStatus[i].cod == widget.listData[0]['ID_ESTADO_CIVIL']){
        selectMaritalStatusCod = ConstVariable().listMaritalStatus[i].cod;
        selectMaritalStatus = ConstVariable().listMaritalStatus[i].title;
      }
    }
    spouseController.text = widget.listData[0]['NOME_CONJUGE'];
    selectNaturalityCod = widget.listData[0]['NACIONALIDADE'];
    if(selectNaturalityCod==1){
      selectNaturality = 'BRASILEIRO';
    }
    if(selectNaturalityCod==2){
      selectNaturality = 'ESTRANGEIRO';
    }
    if(selectNaturalityCod==3){
      selectNaturality = 'NATURALIZADO';
    }
    int codCityBirth = widget.listData[0]['ID_MUNICIPIO_NASC'];
    List listCityBirth = await DBQuerys().buscaMunicipioporId(codCityBirth);
    cityBirthController.text = listCityBirth[0]['NO_MUNICIPIO'];
    resultListNasc = listCityBirth;
    for(int i = 0;ConstVariable().listBreed.length >i;i++){
      if(ConstVariable().listBreed[i].cod == widget.listData[0]['ID_ETNIA']){
        selectBreedCod = ConstVariable().listBreed[i].cod;
        selectBreed = ConstVariable().listBreed[i].title;
      }
    }
    for(int i = 0;ConstVariable().listScooling.length >i;i++){
      if(ConstVariable().listScooling[i].cod == widget.listData[0]['ID_ESCOLARIDADE']){
        selectScoolingCod = ConstVariable().listScooling[i].cod;
        selectScooling = ConstVariable().listScooling[i].title;
      }
    }
    for(int i = 0;ConstVariable().itensDeficiency.length >i;i++){
      if(ConstVariable().itensDeficiency[i].cod == widget.listData[0]['ID_DEFICIENCIA']){
        selectDeficiencyCod = ConstVariable().itensDeficiency[i].cod;
        selectDeficiency = ConstVariable().itensDeficiency[i].title;
      }else{
        selectDeficiencyCod = 3;
        selectDeficiency = 'NENHUMA';
      }
    }
    nameMotherController.text = widget.listData[0]['NOME_MAE'];
    enableMother = widget.listData[0]['DESCONHECE_MAE']==0?false:true;
    nameFatherController.text = widget.listData[0]['NOME_PAI'];
    enableFather = widget.listData[0]['DESCONHECE_PAI']==0?false:true;
    idUnidade = widget.listData[0]['ID_UNIDADE'].toString();
    medicalRecordController.text = widget.listData[0]['NUM_PRONTUARIO'];
    medicalRecordProvController.text = widget.listData[0]['NUM_PRONTUARIO_PROV'].toString()=='null'?'':widget.listData[0]['NUM_PRONTUARIO_PROV'].toString();
    selectClassificationCOD = widget.listData[0]['CLASSIFICACAO'];
    if(selectClassificationCOD==1){
      selectClassification = 'MUNICIPE';
    }
    if(selectClassificationCOD==2){
      selectClassification = 'PROVISORIO';
    }
    if(selectClassificationCOD==3){
      selectClassification = 'OUTRO MUNICIPIO';
    }
    changedCity();
    if(widget.listData[0]['CLASSIFICACAO_SUB']!=null && widget.listData[0]['CLASSIFICACAO_SUB']!=''){
      selectSubdivisionCOD = widget.listData[0]['CLASSIFICACAO_SUB']=='null'?0:widget.listData[0]['CLASSIFICACAO_SUB'];
    }
    numberFamilyController.text = widget.listData[0]['NUM_FAMILIA'].toString();
    selectCountry = widget.listData[0]['ID_PAIS_RESID']==33?'BRASIL':'OUTRO';
    int codCity = widget.listData[0]['ID_MUNICIPIO_RESID'];
    List listCity = await DBQuerys().buscaMunicipioporId(codCity);
    cityController.text = listCity[0]['NO_MUNICIPIO'];
    resultListResid = listCity;
    codIBGEController.text = listCity[0]['CODIGO_IBGE'];
    selectVillage = widget.listData[0]['NO_BAIRRO_LOGR'];
    idTipo = widget.listData[0]['ID_LOGR_TIPO'];
    streetDB.add(widget.listData[0]['NOME_LOGR']);
    selectStreet = widget.listData[0]['NOME_LOGR'];
    List listTypeStreet = await DBQuerys().buscaTipoLogradouroPorId(idTipo);
    selectTypeStreet = listTypeStreet[0]['NO_LOGR_TIPO'];
    cepController.text =  widget.listData[0]['CEP_LOGR'].toString()=='null'?'': widget.listData[0]['CEP_LOGR'].toString();
    numberController.text =  widget.listData[0]['NUMERO_LOGR'].toString()??'';
    print('numberController');
    print(numberController.text);
    selectSubdivision = listTypeStreet[0]['LOTEAMENTO_LOGR']??null;
    if(selectSubdivision!=null){
      subdivisionDB.add(selectSubdivision!);
    }
    complementController.text = listTypeStreet[0]['COMPL_LOGR']??'';
    referencePointController.text = listTypeStreet[0]['PONTO_REFERENCIA']??'';
    selectZoneCod = widget.listData[0]['ZONA_LOGR'];
    print(selectZoneCod);
    if(selectZoneCod==1){
      selectZone = 'URBANA';
    }else if(selectZoneCod==2){
      selectZone = 'RURAL';
    }
    mobileDDDController.text = widget.listData[0]['DDD_CELULAR'].toString()=='null'?'':widget.listData[0]['DDD_CELULAR'].toString();
    mobileController.text = widget.listData[0]['NUM_CELULAR'].toString()=='null'?'':widget.listData[0]['NUM_CELULAR'].toString();
    foneDDDController.text = widget.listData[0]['DDD_TELEFONE'].toString()=='null'?'':widget.listData[0]['DDD_TELEFONE'].toString();
    foneController.text = widget.listData[0]['NUM_TELEFONE'].toString()=='null'?'':widget.listData[0]['NUM_TELEFONE'].toString();
    messageDDDController.text = widget.listData[0]['DDD_RECADO'].toString()=='null'?'':widget.listData[0]['DDD_RECADO'].toString();
    messageController.text = widget.listData[0]['NUM_RECADO'].toString()=='null'?'':widget.listData[0]['NUM_RECADO'].toString();
    emailController.text = widget.listData[0]['EMAIL'];
    observationController.text = widget.listData[0]['OBSERVACOES'];
    CPFController.text = widget.listData[0]['CPF'].toString();
    CNSController.text = widget.listData[0]['CNS'];
    voterController.text = widget.listData[0]['TITULO_ELEITOR'].toString()??'';
    RGController.text = widget.listData[0]['RG_NUMERO'].toString()=='null'?'':widget.listData[0]['RG_NUMERO'].toString();
    RGComplementController.text = widget.listData[0]['RG_COMPLEMENTO'].toString();
    selectRGUF = widget.listData[0]['RG_UF']??'';
    RGOrganController.text = widget.listData[0]['RG_ORGAO']==null?'':widget.listData[0]['RG_ORGAO'];
    RGDateController.text = widget.listData[0]['RG_DATA_EMISSAO']==null?'':widget.listData[0]['RG_DATA_EMISSAO'];
    RGDateDB = RGDateController.text;
    selectTypeCertificateCod = widget.listData[0]['TIPO_CERTIDAO']??0;
    for(int i = 0;ConstVariable().itensCertificate.length >i;i++){
      if(ConstVariable().itensCertificate[i].cod == selectTypeCertificateCod){
        selectTypeCertificate = ConstVariable().itensCertificate[i].title;
      }
      break;
    }
    numberCertificateController.text =  widget.listData[0]['NUM_CERTIDAO']??'';
    nameCertificateController.text =  widget.listData[0]['CARTORIO_CERTIDAO']??'';
    bookCertificateController.text =  widget.listData[0]['LIVRO_CERTIDAO']??'';
    sheetCertificateController.text =  widget.listData[0]['FOLHA_CERTIDAO']??'';
    termCertificateController.text =  widget.listData[0]['TERMO_CERTIDAO']??'';
    dateCertificateController.text =  widget.listData[0]['DT_EMISSAO_CERTIDAO']??'';
    dateCertificateDB = dateCertificateController.text;
    CTPSController.text =  widget.listData[0]['NUM_CTPS'].toString()=='null'?'':widget.listData[0]['NUM_CTPS'].toString();
    numberCTPSController.text =  widget.listData[0]['NUM_SERIE_CTPS'].toString()=='null'?'':widget.listData[0]['NUM_SERIE_CTPS'].toString();
    selectCTPSUF =  widget.listData[0]['ESTADO_UF_CTPS'];
    PISController.text =  widget.listData[0]['NUM_PIS_PASEP'].toString()=='null'?'':widget.listData[0]['NUM_PIS_PASEP'].toString();
    enableCityCard = widget.listData[0]['FL_RETIROU_CARTAO'] == 'S'?true:false;
    NISController.text =  widget.listData[0]['NUM_NIS'].toString()??'';
    incomeController.text =  widget.listData[0]['RENDA_MENSAL']==null?'R\$ 0,00':'R\$ ${widget.listData[0]['RENDA_MENSAL'].toString().replaceAll('.', ',')}';
    professionalController.text =  widget.listData[0]['PROFISSAO']??'';
    dateDeathController.text =  widget.listData[0]['DT_OBITO']??'';
    dateDeathDB = dateDeathController.text;
    enableBlocked =  widget.listData[0]['BLOQUEIO']==1?true:false;
    setState(() {});
  }

  @override
  void initState() {
    super.initState();
    searchCityBirthController.addListener(_searchCityBirth);
    searchCityController.addListener(_searchCity);
    getCity();
    getUnit();
    loadVillgeDB();
    loadTypeStreetDB();
    loadSubdivisionsDB();
    loadLists();
      if(widget.listData.length!=0){
        getData();
        edit = true;
      }
  }

  @override
  Widget build(BuildContext context) {

    double height = MediaQuery.of(context).size.height;
    double width = MediaQuery.of(context).size.width;

    return WillPopScope(
      onWillPop: ()=> OnBackButton().onBackButton(context),
      child: Scaffold(
        appBar: AppBarDefault().appbar(context, 'RKM AB - Cadastro Cidadão'),
        body: Container(
          height: double.infinity,
          width: double.infinity,
          decoration: ConstVariable().backgroundGradient,
          child: ListView(
            children: [
              SubtitleAppbarCitizen(title: 1,edit: showTab),
              showCheckError?Card(
                margin: EdgeInsets.all(10),
                child: Container(
                  padding: EdgeInsets.all(10),
                  child: Row(
                    children: [
                      Icon(Icons.warning,color: Colors.red,),
                      TextDefault(text: errorTopo,color: ColorPalette.red,fontSize: 15,)
                    ],
                  ),
                ),
                color: ColorPalette.white,
              ):Container(),
              Card(
                margin: EdgeInsets.all(10),
                child: Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: Column(
                    children: [
                      edit?ButtonDefault(
                        onPressed: (){
                          setState(() {
                            edit = false;
                            editing = true;
                          });
                        },
                        title: 'Alterar',
                        borderColor: ColorPalette.edit,
                        background: ColorPalette.edit,
                        textColor: ColorPalette.white,
                        width: double.infinity,
                      ):ButtonDefault(
                        onPressed: ()=>checkSave(),
                        title: 'Salvar',
                        borderColor: ColorPalette.appBar,
                        background: ColorPalette.appBar,
                        textColor: ColorPalette.white,
                        width: double.infinity,
                      ),
                      ButtonDefault(
                        onPressed: ()=>Navigator.pop(context),
                        title: 'Cancelar',
                        borderColor: ColorPalette.blackButton,
                        background: ColorPalette.blackButton,
                        textColor: ColorPalette.white,
                        width: double.infinity,
                      )
                    ],
                  ),
                ),
              ),
              Card(
                margin: EdgeInsets.all(10),
                child: Column(
                  children: [
                    TitleContainers(title: 'Indentificação'),
                    Row(
                      children: [
                        Container(
                          height: height*0.5,
                          width: width*0.2,
                          child: Icon(Icons.person,size: 80,),
                        ),
                        Column(
                          mainAxisAlignment: MainAxisAlignment.start,
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            InputWithSubtitle(
                              controller: nameController,
                              subtitle: 'Nome',
                              errorInput: nameController.text.isNotEmpty?'':'Campo Obrigatório',
                              labelInput: 'Nome',
                              widthInput: width*0.7,
                              widthSubtitle: width*0.7,
                              hintInput: 'Escreva aqui',
                              enabled: !edit,
                              onChanged: (v)=>setState((){}),
                            ),
                            InputWithSubtitle(
                              controller: nameSocialController,
                              subtitle: 'Nome Social',
                              errorInput: 'Campo Obrigatório',
                              labelInput: 'Nome Social',
                              widthInput: width*0.7,
                              widthSubtitle: width*0.7,
                              hintInput: 'Escreva aqui',
                              mandatory: false,
                              enabled: !edit,
                              onChanged: (v)=>setState((){}),
                            ),
                            DropdownWithSubtitle(
                              list: ConstVariable().listGender,
                              subtitle: 'Sexo',
                              hintDropdown: 'Sexo',
                              select: selectGender,
                              widthSubtitle: width*0.6,
                              widthDropdown:  width*0.69,
                              widthContainerDropdown: width*0.6,
                              onChanged: edit?null:(value){
                                setState(() {
                                  selectGender = value!;
                                });
                              },
                            ),
                            selectGender==null?ErrorDefault():Container(),
                            Container(
                              width: width*0.75,
                              child: Row(
                                children: [
                                  GestureDetector(
                                    onTap:edit?null: ()=>escolherprazoInicio(context,'birth'),
                                    child: Container(
                                      alignment: Alignment.centerLeft,
                                      height: 58,
                                      margin: EdgeInsets.symmetric(horizontal: 15,vertical: 5),
                                      padding: EdgeInsets.symmetric(horizontal: 8,vertical: 10),
                                      decoration: BoxDecoration(
                                          border: Border.all(color: ColorPalette.black54),
                                          borderRadius: BorderRadius.all(
                                              Radius.circular(5.0)
                                          ),
                                      ),
                                      width: width*0.7,
                                      child: TextDefault(
                                        text: date,
                                        color: Colors.black,
                                        fontSize: 16,
                                      ),
                                    ),
                                  )
                                ],
                              ),
                            ),
                            date == 'Data de Nascimento'?ErrorDefault():Container(),
                            DropdownWithSubtitle(
                              list: listMaritalStatus,
                              subtitle: 'Estado Civil',
                              hintDropdown: 'Estado Civil',
                              select: selectMaritalStatus,
                              widthSubtitle: width*0.6,
                              widthDropdown:  width*0.69,
                              widthContainerDropdown: width*0.6,
                              onChanged:edit?null: (value){
                                setState(() {
                                  selectMaritalStatus = value!;
                                  for(int i = 0;ConstVariable().listMaritalStatus.length >i;i++){
                                    if(ConstVariable().listMaritalStatus[i].title == selectMaritalStatus){
                                      selectMaritalStatusCod = ConstVariable().listMaritalStatus[i].cod;
                                      print(selectMaritalStatusCod);
                                    }
                                  }
                                  if(selectMaritalStatus=='CASADO(A)'){
                                    enableSpouse = true;
                                  }else{
                                    enableSpouse = false;
                                  }
                                });
                              },
                            ),
                            InputWithSubtitle(
                              controller: spouseController,
                              subtitle: 'Cônjuge',
                              errorInput: enableSpouse?'Campo Obrigatório':'',
                              labelInput: 'Cônjuge',
                              widthInput: width*0.7,
                              widthSubtitle: width*0.2,
                              hintInput: 'Escreva aqui',
                              enabled: enableSpouse,
                              onChanged: (v)=>setState((){}),
                            ),
                            DropdownWithSubtitle(
                              list: ConstVariable().listNationality,
                              subtitle: 'Naturalidade',
                              hintDropdown: 'Naturalidade',
                              select: selectNaturality,
                              widthSubtitle: width*0.6,
                              widthDropdown:  width*0.69,
                              widthContainerDropdown: width*0.6,
                              onChanged:edit?null: (value){
                                setState(() {
                                  selectNaturality = value!;
                                  if(selectNaturality!='BRASILEIRO'){
                                    if(selectNaturality=='ESTRANGEIRO'){
                                      selectNaturalityCod = 2;
                                    }else{
                                      selectNaturalityCod = 3;
                                    }
                                    cityBirthController.text = 'MUNICIPIO IGNORADO - SP';
                                  }else{
                                    cityBirthController.text = '';
                                    selectNaturalityCod = 1;
                                  }
                                });
                              },
                            ),
                            selectNaturality==null?ErrorDefault():Container(),
                            GestureDetector(
                              onTap: cityBirthController.text == 'MUNICIPIO IGNORADO - SP' || edit?null:(){
                                searchCityController.text = '';
                                searchCityBirthController.text = '';
                                searchCity('birth');
                                showDialog(
                                  context: context,
                                  builder: (context){
                                    return AlertDialog(
                                      scrollable: true,
                                      content: StatefulBuilder(
                                          builder: (context, setState) {

                                            return Column(
                                              children: [
                                                InputSearchText(
                                                  onChanged: (v){
                                                    setState((){
                                                      searchCity('birth');
                                                    });
                                                  },
                                                  controller: searchCityBirthController,
                                                  width: width*0.8,
                                                  hint: 'Buscar...',
                                                  color: ColorPalette.titleContainer,
                                                  border: false,
                                                ),
                                                Container(
                                                  padding: EdgeInsets.symmetric(vertical: 10),
                                                  width:  width*0.8,
                                                  child:  Container(
                                                    width: width*0.8,
                                                    height: height*0.6,
                                                    padding: EdgeInsets.symmetric(horizontal: 10),
                                                    child: ListView.separated(
                                                        separatorBuilder:(context,index)=> Divider(color: ColorPalette.black54,height: 5,),
                                                        itemCount: showResultSearchCity.length,
                                                        itemBuilder: (context,index){
                                                          return Container(
                                                            width: width*0.8,
                                                            color: ColorPalette.white,
                                                            child: ListTile(
                                                              onTap: ()async{
                                                                List splitted = [];
                                                                setState(() {
                                                                  cityBirthController.text =  showResultSearchCity[index];
                                                                  splitted = cityBirthController.text.split(' - ');
                                                                  print(splitted[0]);
                                                                  Navigator.pop(context);
                                                                });
                                                                resultListNasc = await DBQuerys().buscaMunicipioporNome(splitted[0]);
                                                                print(resultListNasc[0]['ID_MUNICIPIO'],);
                                                                print(resultListNasc[0]['NO_MUNICIPIO'],);
                                                                print(resultListNasc[0]['UF_ESTADO'],);
                                                              },
                                                              title: TextDefault(
                                                                color: ColorPalette.black54,
                                                                text:  showResultSearchCity[index],
                                                                fontSize: 16,
                                                                maxLines: 2,
                                                              ),
                                                            ),
                                                          );
                                                        }
                                                    ),
                                                  ),
                                                ),
                                              ],
                                            );
                                          }),
                                    );
                                  },
                                );
                              },
                              child: InputWithSubtitle(
                                controller: cityBirthController,
                                subtitle: 'Município de Nascimento',
                                errorInput: cityBirthController.text.isNotEmpty?'':'Campo Obrigatório',
                                labelInput: 'Município de Nascimento',
                                widthInput: width*0.7,
                                widthSubtitle: width*0.2,
                                hintInput: 'Escreva aqui',
                                enabled: false,
                                onChanged: (v)=>setState((){}),
                              ),
                            ),
                            DropdownWithSubtitle(
                              list: listBreed,
                              subtitle: 'Raça/Cor',
                              hintDropdown: 'Raça/Cor',
                              select: selectBreed,
                              widthSubtitle: width*0.6,
                              widthDropdown:  width*0.69,
                              widthContainerDropdown: width*0.6,
                              onChanged:edit?null: (value){
                                setState(() {
                                  selectBreed = value!;
                                  for(int i = 0;ConstVariable().listBreed.length >i;i++){
                                    if(ConstVariable().listBreed[i].title == selectBreed){
                                      selectBreedCod = ConstVariable().listBreed[i].cod;
                                      print(selectBreedCod);
                                    }
                                  }
                                });
                              },
                            ),
                            selectBreed==null?ErrorDefault():Container(),
                            DropdownWithSubtitle(
                              list: listScooling,
                              subtitle: 'Escolaridade',
                              hintDropdown: 'Escolaridade',
                              select: selectScooling,
                              widthSubtitle: width*0.6,
                              widthDropdown:  width*0.69,
                              widthContainerDropdown: width*0.6,
                              onChanged:edit?null: (value){
                                setState(() {
                                  selectScooling = value!;
                                  for(int i = 0;ConstVariable().listScooling.length >i;i++){
                                    if(ConstVariable().listScooling[i].title == selectScooling){
                                      selectScoolingCod = ConstVariable().listScooling[i].cod;
                                      print(selectScoolingCod);
                                    }
                                  }
                                });
                              },
                            ),
                            DropdownWithSubtitle(
                              list: listDeficiency,
                              subtitle: 'Deficiência',
                              hintDropdown: 'Deficiência',
                              select: selectDeficiency,
                              widthSubtitle: width*0.6,
                              widthDropdown:  width*0.69,
                              widthContainerDropdown: width*0.6,
                              onChanged:edit?null: (value){
                                setState(() {
                                  selectDeficiency = value!;
                                  for(int i = 0;ConstVariable().itensDeficiency.length >i;i++){
                                    if(ConstVariable().itensDeficiency[i].title == selectDeficiency){
                                      selectDeficiencyCod = ConstVariable().itensDeficiency[i].cod;
                                      print(selectDeficiencyCod);
                                    }
                                  }
                                });
                              },
                            ),
                            selectDeficiency==null?ErrorDefault():Container(),
                            InputWithSubtitle(
                              controller: nameMotherController,
                              subtitle: 'Nome da Mãe',
                              errorInput: enableMother?'':'Campo Obrigatório',
                              labelInput: 'Nome da Mãe',
                              widthInput: width*0.7,
                              widthSubtitle: width*0.2,
                              hintInput: 'Escreva aqui',
                              enabled: !enableMother && !edit,
                              onChanged: (v)=>setState((){}),
                            ),
                            SwitchWithSubtitle(
                              width: width*0.65,
                              title: 'Desconhece Mãe',
                              value: enableMother,
                              onChanged:edit?null:  (value){
                                setState(() {
                                  enableMother = value;
                                  if(enableMother){
                                    nameMotherController.text = '';
                                  }
                                });
                              },
                            ),
                            InputWithSubtitle(
                              controller: nameFatherController,
                              subtitle: 'Nome do Pai',
                              errorInput: enableFather?'':'Campo Obrigatório',
                              labelInput: 'Nome do Pai',
                              widthInput: width*0.7,
                              widthSubtitle: width*0.2,
                              hintInput: 'Escreva aqui',
                              enabled: !enableFather && !edit,
                              onChanged: (v)=>setState((){}),
                            ),
                            SwitchWithSubtitle(
                              width: width*0.65,
                              title: 'Desconhece Pai',
                              value: enableFather,
                              onChanged: edit?null: (value){
                                setState(() {
                                  enableFather = value;
                                  if(enableFather){
                                    nameFatherController.text = '';
                                  }
                                });
                              },
                            ),
                          ],
                        )
                      ],
                    )
                  ],
                ),
              ),
              Card(
                margin: EdgeInsets.all(10),
                child: Column(
                  children: [
                    TitleContainers(title: 'Identificação da Saúde'),
                    Row(
                      children: [
                        Container(
                          height: height*0.4,
                          width: width*0.2,
                          child: Icon(Icons.medical_services_rounded,size: 80,),
                        ),
                        Column(
                          mainAxisAlignment: MainAxisAlignment.start,
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            InputWithSubtitle(
                              controller: unitController,
                              subtitle: 'Unidade',
                              errorInput: 'Campo Obrigatório',
                              labelInput: 'Unidade',
                              widthInput: width*0.7,
                              widthSubtitle: width*0.7,
                              hintInput: 'Escreva aqui',
                              enabled: false,
                              onChanged: (v)=>setState((){}),
                            ),
                            InputWithSubtitle(
                              controller: medicalRecordController,
                              subtitle: 'Prontuário',
                              errorInput: 'Campo Obrigatório',
                              labelInput: 'Prontuário',
                              widthInput: width*0.7,
                              widthSubtitle: width*0.7,
                              hintInput: 'Escreva aqui',
                              enabled: false,
                              onChanged: (v)=>setState((){}),
                            ),
                            InputWithSubtitle(
                              controller: medicalRecordProvController,
                              subtitle: 'Prontuário Provisório',
                              errorInput: 'Campo Obrigatório',
                              labelInput: 'Prontuário Provisório',
                              widthInput: width*0.7,
                              widthSubtitle: width*0.7,
                              hintInput: 'Escreva aqui',
                              enabled: false,
                              onChanged: (v)=>setState((){}),
                            ),
                            DropdownWithSubtitle(
                              subtitle: 'Classificação',
                              select: selectClassification,
                              widthSubtitle: width*0.6,
                              widthDropdown:  width*0.69,
                              widthContainerDropdown: width*0.6,
                              hintDropdown: 'Classificação',
                              onChanged:edit?null: (value)async{
                                  selectClassification = value;
                                  if(selectClassification=='OUTRO MUNICIPIO'){
                                    selectClassificationCOD = 3;
                                    cityController.clear();
                                    codIBGEController.clear();
                                    cepController.clear();
                                    numberController.clear();

                                    selectCountry = null;
                                    selectVillage = null;
                                    selectStreet = null;
                                    selectTypeStreet = null;

                                    AlertDialogDefault().alert(
                                        context,
                                        'Aviso',
                                        'As informações dos campos Bairro, Tipo Logradouro, Nome Logradouro, CEP,'
                                            'Número, Loteamento e Complemento deverão ser inseridos no campo Observações!',
                                        'OK'
                                    );
                                  }else{
                                    if(selectClassification=='PROVISORIO'){
                                      selectClassificationCOD = 2;
                                    }else{
                                      selectClassificationCOD = 1;
                                    }
                                    changedCity();
                                    selectCountry = 'BRASIL';
                                  }
                                  setState(() {});
                              },
                              list: [
                                'MUNICIPE',
                                'PROVISORIO',
                                'OUTRO MUNICIPIO',
                              ]
                            ),
                            selectClassification==null?ErrorDefault():Container(),
                            InputWithSubtitle(
                              controller: numberFamilyController,
                              subtitle: 'Número da Família',
                              errorInput: '',
                              labelInput: 'Número da Família',
                              widthInput: width*0.7,
                              widthSubtitle: width*0.7,
                              mandatory: false,
                              enabled: !edit,
                              hintInput: 'Escreva aqui',
                              onChanged: (v)=>setState((){}),
                            ),
                          ],
                        ),
                      ]
                    ),
                  ],
                ),
              ),
              Card(
                margin: EdgeInsets.all(10),
                child: Column(
                  children: [
                    TitleContainers(title: 'Endereço'),
                    Row(
                        children: [
                          Container(
                            height: height*0.4,
                            width: width*0.2,
                            child: Icon(Icons.map_outlined,size: 80,),
                          ),
                          Column(
                            mainAxisAlignment: MainAxisAlignment.start,
                            mainAxisSize: MainAxisSize.min,
                            children: [
                              DropdownWithSubtitle(
                                  subtitle: 'Pais de Residência',
                                  select: selectCountry,
                                  widthSubtitle: width*0.6,
                                  widthDropdown:  width*0.69,
                                  widthContainerDropdown: width*0.6,
                                  hintDropdown: 'Pais de Residência',
                                  onChanged:selectClassification!='OUTRO MUNICIPIO'?null:(value){
                                    setState(() {
                                      selectCountry = value;
                                      if(selectCountry=='OUTRO'){
                                          cityController.text= 'MUNICIPIO IGNORADO - SP';
                                          resultListResid =  [{"ID_MUNICIPIO":1,"CODIGO_IBGE":"000000","NO_MUNICIPIO":"MUNICIPIO IGNORADO","UF_ESTADO":"--","ID_PAIS":33}];
                                          codIBGEController.text = '000000';
                                          numberController.clear();
                                          selectVillage = null;
                                          selectStreet = null;
                                          idBairro = '';
                                          idTipo = 0;
                                          cepController.text = '';

                                        AlertDialogDefault().alert(
                                            context,
                                            'Aviso',
                                            'As informações dos campos Bairro, Tipo Logradouro, Nome Logradouro, CEP,'
                                                'Número, Loteamento e Complemento deverão ser inseridos no campo Observações!',
                                            'OK'
                                        );
                                      }else{
                                        cityController.text = '';
                                        codIBGEController.text = '';
                                      }
                                    });
                                  },
                                  list: [
                                    'BRASIL',
                                    'OUTRO',
                                  ]
                              ),
                              selectCountry==null?ErrorDefault():Container(),
                              GestureDetector(
                                onTap: selectClassification!='OUTRO MUNICIPIO'|| cityController.text == 'MUNICIPIO IGNORADO - SP'?null: (){
                                  searchCityController.text = '';
                                  searchCityBirthController.text = '';
                                  searchCity('city');
                                  showDialog(
                                    context: context,
                                    builder: (context){
                                      return AlertDialog(
                                        scrollable: true,
                                        content: StatefulBuilder(
                                            builder: (context, setState) {
                                              return Column(
                                                children: [
                                                  InputSearchText(
                                                    onChanged: (v){
                                                      setState((){
                                                        searchCity('city');
                                                      });
                                                    },
                                                    controller: searchCityController,
                                                    width: width*0.8,
                                                    hint: 'Buscar...',
                                                    color: ColorPalette.titleContainer,
                                                    border: false,
                                                  ),
                                                  Container(
                                                    padding: EdgeInsets.symmetric(vertical: 10),
                                                    width:  width*0.8,
                                                    child:  Container(
                                                      width: width*0.8,
                                                      height: height*0.6,
                                                      padding: EdgeInsets.symmetric(horizontal: 10),
                                                      child: ListView.separated(
                                                          separatorBuilder:(context,index)=> Divider(color: ColorPalette.black54,height: 5,),
                                                          itemCount: showResultSearchCity.length,
                                                          itemBuilder: (context,index){
                                                            return Container(
                                                              width: width*0.8,
                                                              color: ColorPalette.white,
                                                              child: ListTile(
                                                                onTap: ()async{
                                                                  List splitted = [];
                                                                  setState(() {
                                                                    cityController.text =  showResultSearchCity[index];
                                                                    codIBGEController.text =  showResultSearchIbge[index];
                                                                    splitted = cityController.text.split(' - ');
                                                                    // print("IBGE ${showResultSearchIbge[index]}");
                                                                    Navigator.pop(context);
                                                                  });
                                                                  resultListResid = await DBQuerys().buscaMunicipioporNome(splitted[0]);
                                                                  print(resultListResid[0]['ID_MUNICIPIO'],);
                                                                  print(resultListResid[0]['NO_MUNICIPIO'],);
                                                                  print(resultListResid[0]['UF_ESTADO'],);
                                                                },
                                                                title: TextDefault(
                                                                  color: ColorPalette.black54,
                                                                  text:  showResultSearchCity[index],
                                                                  fontSize: 16,
                                                                  maxLines: 2,
                                                                ),
                                                              ),
                                                            );
                                                          }
                                                      ),
                                                    ),
                                                  ),
                                                ],
                                              );
                                            }),
                                      );
                                    },
                                  );
                                },
                                child: InputWithSubtitle(
                                  controller: cityController,
                                  subtitle: 'Município de Residência',
                                  errorInput: 'Campo Obrigatório',
                                  labelInput: 'Município de Residência',
                                  widthInput: width*0.7,
                                  widthSubtitle: width*0.2,
                                  hintInput: 'Escreva aqui',
                                  enabled: false,
                                  onChanged: (v)=>setState((){}),
                                ),
                              ),
                              InputWithSubtitle(
                                controller: codIBGEController,
                                subtitle: 'Cód. IBGE',
                                errorInput: '',
                                labelInput: 'Cód. IBGE',
                                widthInput: width*0.7,
                                widthSubtitle: width*0.2,
                                hintInput: 'Escreva aqui',
                                enabled: false,
                                onChanged: (v)=>setState((){}),
                              ),
                              DropdownWithSubtitle(
                                  subtitle: 'Bairro',
                                  select: selectVillage,
                                  widthSubtitle: width*0.6,
                                  widthDropdown:  width*0.69,
                                  widthContainerDropdown: width*0.6,
                                  hintDropdown: 'Bairro',
                                  onChanged:selectClassification=='OUTRO MUNICIPIO' || edit?null: (value)async{
                                    setState(() {
                                      selectVillage = value;
                                      selectTypeStreet = null;
                                      selectStreet = null;
                                      idBairro = '';
                                      idTipo = 0;
                                    });
                                    idBairro = await DBQuerys().buscaBairro(selectVillage);
                                  },
                                  list: villageDB
                              ),
                              selectClassification!='OUTRO MUNICIPIO' && selectVillage == null?ErrorDefault():Container(),
                              DropdownWithSubtitle(
                                  subtitle: 'Tipo de Logradouro',
                                  select: selectTypeStreet,
                                  widthSubtitle: width*0.6,
                                  widthDropdown:  width*0.69,
                                  widthContainerDropdown: width*0.6,
                                  hintDropdown: 'Tipo de Logradouro',
                                  onChanged:selectClassification=='OUTRO MUNICIPIO' || selectVillage == null || edit?null: (value)async{
                                    setState(() {
                                      selectTypeStreet = value;
                                      selectStreet = null;
                                    });
                                    idTipo = await DBQuerys().buscaTipoLogradouro(selectTypeStreet);
                                    if(idBairro!='' && idTipo!=''){
                                      loadStreetDB();
                                    }
                                  },
                                  list: typeStreetDB
                              ),
                              selectTypeStreet!='OUTRO MUNICIPIO' && selectTypeStreet == null && selectCountry == null?ErrorDefault():Container(),
                              DropdownWithSubtitle(
                                  subtitle: 'Nome do Logradouro',
                                  select: selectStreet,
                                  widthSubtitle: width*0.6,
                                  widthDropdown:  width*0.69,
                                  widthContainerDropdown: width*0.6,
                                  hintDropdown: 'Nome do Logradouro',
                                  onChanged:selectClassification=='OUTRO MUNICIPIO' || selectVillage == null || edit?null: (value){
                                    setState(() {
                                      selectStreet = value;
                                    });
                                  },
                                  list: streetDB
                              ),
                              InputWithSubtitle(
                                typeInput: 'cep',
                                controller: cepController,
                                subtitle: 'CEP(só números)',
                                errorInput: selectClassification!='OUTRO MUNICIPIO'&& cepController.text.isEmpty?'Campo Obrigatório':cepController.text.length!=8?'CEP incorreto':'',
                                labelInput: 'CEP(só números)',
                                widthInput: width*0.7,
                                widthSubtitle: width*0.2,
                                hintInput: 'Escreva aqui',
                                enabled: selectClassification!='OUTRO MUNICIPIO' && !edit?true:false,
                                onChanged: (v)=>setState((){}),
                              ),
                              Container(
                                width: width*0.7,
                                child: Row(
                                  children: [
                                    InputWithSubtitle(
                                      controller: numberController,
                                      subtitle: 'Número',
                                      errorInput: 'Campo Obrigatório',
                                      labelInput: 'Número',
                                      widthInput: width*0.4,
                                      widthSubtitle: width*0.2,
                                      widthError: 0.4,
                                      hintInput: 'Escreva aqui',
                                      enabled: selectClassification!='OUTRO MUNICIPIO' && !checkBoxNumber && !edit?true:false,
                                      onChanged: (v)=>setState((){}),
                                    ),
                                    Checkbox(
                                      value: checkBoxNumber,
                                      onChanged:edit?null: (value){
                                        setState(() {
                                          checkBoxNumber = value!;
                                          if(checkBoxNumber){
                                            numberController.text = '0';
                                          }else{
                                            numberController.clear();
                                          }
                                        });
                                      }
                                    ),
                                    Spacer(),
                                    Padding(
                                      padding: const EdgeInsets.symmetric(horizontal: 10.0),
                                      child: TextDefault(text: 'SEM NÚMERO',fontSize: 15,),
                                    )
                                  ],
                                ),
                              ),
                              DropdownWithSubtitle(
                                  subtitle: 'Loteamento/Subdistrito',
                                  select: selectSubdivision,
                                  widthSubtitle: width*0.6,
                                  widthDropdown:  width*0.69,
                                  widthContainerDropdown: width*0.6,
                                  hintDropdown: 'Loteamento/Subdistrito',
                                  onChanged: selectClassification=='OUTRO MUNICIPIO' || selectVillage == null || edit?null:(value)async{
                                    setState(() {
                                      selectSubdivision = value;
                                    });
                                    selectSubdivisionCOD = await DBQuerys().buscaLoteamentoPorDesc(selectSubdivision!);
                                  },
                                  list: subdivisionDB
                              ),
                              InputWithSubtitle(
                                controller: complementController,
                                subtitle: 'Complemento',
                                errorInput: 'Campo Obrigatório',
                                labelInput: 'Complemento',
                                widthInput: width*0.7,
                                widthSubtitle: width*0.2,
                                hintInput: 'Escreva aqui',
                                mandatory: false,
                                enabled: !edit,
                                onChanged: (v)=>setState((){}),
                              ),
                              InputWithSubtitle(
                                controller: referencePointController,
                                subtitle: 'Ponto de Referência',
                                errorInput: 'Campo Obrigatório',
                                labelInput: 'Ponto de Referência',
                                widthInput: width*0.7,
                                widthSubtitle: width*0.2,
                                hintInput: 'Escreva aqui',
                                mandatory: false,
                                enabled: !edit,
                                onChanged: (v)=>setState((){}),
                              ),
                              DropdownWithSubtitle(
                                  subtitle: 'Zona',
                                  select: selectZone,
                                  widthSubtitle: width*0.6,
                                  widthDropdown:  width*0.69,
                                  widthContainerDropdown: width*0.6,
                                  hintDropdown: 'Zona',
                                  onChanged:edit?null: (value){
                                    setState(() {
                                      selectZone = value;
                                      if(selectZone == 'URBANA'){
                                        selectZoneCod = 1;
                                      }else{
                                        selectZoneCod = 2;
                                      }
                                    });
                                  },
                                  list: ['URBANA','RURAL']
                              ),
                            ],
                          ),
                        ]
                    ),
                  ],
                ),
              ),
              Card(
                margin: EdgeInsets.all(10),
                child: Column(
                  children: [
                    TitleContainers(title: 'Contato'),
                    Row(
                        children: [
                          Container(
                            height: height*0.4,
                            width: width*0.2,
                            child: Icon(Icons.medical_services_rounded,size: 80,),
                          ),
                          Padding(
                            padding: const EdgeInsets.symmetric(horizontal: 10.0),
                            child: Column(
                              mainAxisAlignment: MainAxisAlignment.start,
                              mainAxisSize: MainAxisSize.min,
                              children: [
                                InputWithSubtitle(
                                  controller: foneDDDController,
                                  subtitle: 'Telefone - DDD',
                                  errorInput: 'Campo Obrigatório',
                                  labelInput: 'Telefone - DDD',
                                  widthInput: width*0.7,
                                  widthSubtitle: width*0.7,
                                  hintInput: 'Escreva aqui',
                                  enabled: !edit,
                                  mandatory: false,
                                  onChanged: (v)=>setState((){}),
                                ),
                                InputWithSubtitle(
                                  controller: foneController,
                                  subtitle: 'Telefone (Só Números)',
                                  errorInput: 'Campo Obrigatório',
                                  labelInput: 'Telefone(Só Números)',
                                  widthInput: width*0.7,
                                  widthSubtitle: width*0.7,
                                  hintInput: 'Escreva aqui',
                                  enabled: !edit,
                                  mandatory: false,
                                  onChanged: (v)=>setState((){}),
                                ),
                                InputWithSubtitle(
                                  controller: mobileDDDController,
                                  subtitle: 'Celular - DDD',
                                  errorInput: 'Campo Obrigatório',
                                  labelInput: 'Celular - DDD',
                                  widthInput: width*0.7,
                                  widthSubtitle: width*0.7,
                                  hintInput: 'Escreva aqui',
                                  enabled: !edit,
                                  mandatory: false,
                                  onChanged: (v)=>setState((){}),
                                ),
                                InputWithSubtitle(
                                  controller: mobileController,
                                  subtitle: 'Celular (Só Números)',
                                  errorInput: 'Campo Obrigatório',
                                  labelInput: 'Celular (Só Números)',
                                  widthInput: width*0.7,
                                  widthSubtitle: width*0.7,
                                  hintInput: 'Escreva aqui',
                                  enabled: !edit,
                                  mandatory: false,
                                  onChanged: (v)=>setState((){}),
                                ),
                                InputWithSubtitle(
                                  controller: messageDDDController,
                                  subtitle: 'Recado - DDD',
                                  errorInput: 'Campo Obrigatório',
                                  labelInput: 'Recado - DDD',
                                  widthInput: width*0.7,
                                  widthSubtitle: width*0.7,
                                  hintInput: 'Escreva aqui',
                                  enabled: !edit,
                                  onChanged: (v)=>setState((){}),
                                ),
                                InputWithSubtitle(
                                  controller: messageController,
                                  subtitle: 'Recado (Só Números)',
                                  errorInput: 'Campo Obrigatório',
                                  labelInput: 'Recado (Só Números)',
                                  widthInput: width*0.7,
                                  widthSubtitle: width*0.7,
                                  hintInput: 'Escreva aqui',
                                  enabled: !edit,
                                  onChanged: (v)=>setState((){}),
                                ),
                                InputWithSubtitle(
                                  controller: emailController,
                                  subtitle: 'E-mail',
                                  errorInput: 'Campo Obrigatório',
                                  labelInput: 'E-mail',
                                  widthInput: width*0.7,
                                  widthSubtitle: width*0.7,
                                  hintInput: 'Escreva aqui',
                                  mandatory: false,
                                  enabled: !edit,
                                  onChanged: (v)=>setState((){}),
                                ),
                              ],
                            ),
                          ),
                        ]
                    ),
                  ],
                ),
              ),
              Card(
                margin: EdgeInsets.all(10),
                child: Column(
                  children: [
                    TitleContainers(title: 'Observações'),
                    Row(
                        children: [
                          Container(
                            height: height*0.2,
                            width: width*0.2,
                            child: Icon(Icons.sell,size: 80,),
                          ),
                          Padding(
                            padding: const EdgeInsets.symmetric(horizontal: 10.0),
                            child: Column(
                              mainAxisAlignment: MainAxisAlignment.start,
                              mainAxisSize: MainAxisSize.min,
                              children: [
                                InputWithSubtitle(
                                  controller: observationController,
                                  subtitle: 'Observação',
                                  errorInput: 'Campo Obrigatório',
                                  labelInput: 'Observação',
                                  widthInput: width*0.7,
                                  widthSubtitle: width*0.7,
                                  hintInput: 'Escreva aqui',
                                  textInputType: TextInputType.multiline,
                                  maxLines: 5,
                                  enabled: !edit,
                                  mandatory: false,
                                  onChanged: (v)=>setState((){}),
                                ),
                              ],
                            ),
                          ),
                        ]
                    ),
                  ],
                ),
              ),
              Card(
                margin: EdgeInsets.all(10),
                child: Column(
                  children: [
                    TitleContainers(title: 'Documentos'),
                    Row(
                        children: [
                          Container(
                            height: height*0.4,
                            width: width*0.2,
                            child: Icon(Icons.description_outlined,size: 80,),
                          ),
                          Column(
                            mainAxisAlignment: MainAxisAlignment.start,
                            mainAxisSize: MainAxisSize.min,
                            children: [
                              InputWithSubtitle(
                                controller: CPFController,
                                subtitle: 'CPF (Só Números)',
                                errorInput: 'Campo Obrigatório',
                                labelInput: 'CPF (Só Números)',
                                widthInput: width*0.7,
                                widthSubtitle: width*0.7,
                                hintInput: 'Escreva aqui',
                                mandatory: false,
                                enabled: !edit,
                                onChanged: (v)async{
                                  if(CPFController.text.isNotEmpty){
                                    checkCPF = await MainControllers().validaCPF(v,editing);
                                  }else{
                                    checkCPF = 'ok';
                                  }
                                  setState((){});
                                }
                              ),
                              checkCPF!='ok' && checkCPF!='' ?Container(
                                  width: width*0.7,child: TextDefault(text: checkCPF,fontSize: 15,color: ColorPalette.red,)
                              ):Container(),
                              InputWithSubtitle(
                                controller: CNSController,
                                subtitle: 'CNS',
                                errorInput: 'Campo Obrigatório',
                                labelInput: 'CNS',
                                widthInput: width*0.7,
                                widthSubtitle: width*0.7,
                                hintInput: 'Escreva aqui',
                                mandatory: false,
                                enabled: !edit,
                                onChanged: (v)async{
                                  //783107557570002
                                  if(CNSController.text.isNotEmpty){
                                    checkCNS = await MainControllers().validaCNS(v,editing);
                                  }else{
                                    checkCNS = 'ok';
                                  }
                                  setState((){});
                                }
                              ),
                              checkCNS!='ok' && checkCNS!='' ?Container(
                                  width: width*0.7,child: TextDefault(text: checkCNS,fontSize: 15,color: ColorPalette.red,)
                              ):Container(),
                              InputWithSubtitle(
                                controller: voterController,
                                subtitle: 'Título de Eleitor',
                                errorInput: 'Campo Obrigatório',
                                labelInput: 'Título de Eleitor',
                                widthInput: width*0.7,
                                widthSubtitle: width*0.7,
                                hintInput: 'Escreva aqui',
                                enabled: !edit,
                                mandatory: false,
                                onChanged: (v)=>setState((){}),
                              ),
                              InputWithSubtitle(
                                controller: RGController,
                                subtitle: 'RG',
                                errorInput: 'Campo Obrigatório',
                                labelInput: 'RG',
                                widthInput: width*0.7,
                                widthSubtitle: width*0.7,
                                hintInput: 'Escreva aqui',
                                mandatory: false,
                                enabled: !edit,
                                onChanged: (v)=>setState((){}),
                              ),
                              InputWithSubtitle(
                                controller: RGComplementController,
                                subtitle: 'RG - Complemento',
                                errorInput: 'Campo Obrigatório',
                                labelInput: 'RG - Complemento',
                                widthInput: width*0.7,
                                widthSubtitle: width*0.7,
                                hintInput: 'Escreva aqui',
                                mandatory: false,
                                enabled: !edit,
                                onChanged: (v)=>setState((){}),
                              ),
                              DropdownWithSubtitle(
                                  subtitle: 'RG - UF',
                                  select: selectRGUF,
                                  widthSubtitle: width*0.6,
                                  widthDropdown:  width*0.69,
                                  widthContainerDropdown: width*0.6,
                                  hintDropdown: 'RG - UF',
                                  onChanged:edit?null: (value){
                                    setState(() {
                                      selectRGUF = value;
                                    });
                                  },
                                  list: ConstVariable().RGUF
                              ),
                              InputWithSubtitle(
                                controller: RGOrganController,
                                subtitle: 'RG - Órgão',
                                errorInput: 'Campo Obrigatório',
                                labelInput: 'RG - Órgão',
                                widthInput: width*0.7,
                                widthSubtitle: width*0.7,
                                hintInput: 'Escreva aqui',
                                enabled: !edit,
                                mandatory: false,
                                onChanged: (v)=>setState((){}),
                              ),
                              GestureDetector(
                                onTap:edit?null: ()=>escolherprazoInicio(context,'rg'),
                                child: Container(
                                  alignment: Alignment.centerLeft,
                                  height: 58,
                                  margin: EdgeInsets.symmetric(horizontal: 15,vertical: 5),
                                  padding: EdgeInsets.symmetric(horizontal: 8,vertical: 10),
                                  decoration: BoxDecoration(
                                    border: Border.all(color: ColorPalette.black54),
                                    borderRadius: BorderRadius.all(
                                        Radius.circular(5.0)
                                    ),
                                  ),
                                  width: width*0.7,
                                  child: TextDefault(
                                    text: RGDateController.text,
                                    color: ColorPalette.black54,
                                    fontSize: 16,
                                  ),
                                ),
                              ),
                              DropdownWithSubtitle(
                                  subtitle: 'Tipo de certidão',
                                  select: selectTypeCertificate,
                                  widthSubtitle: width*0.6,
                                  widthDropdown:  width*0.69,
                                  widthContainerDropdown: width*0.6,
                                  hintDropdown: 'Tipo de certidão',
                                  onChanged: edit?null:(value){
                                    setState(() {
                                      selectTypeCertificate = value;
                                      for(int i = 0;ConstVariable().itensCertificate.length >i;i++){
                                        if(ConstVariable().itensCertificate[i].title == selectTypeCertificate){
                                          selectTypeCertificateCod = ConstVariable().itensCertificate[i].cod;
                                          print(selectTypeCertificateCod);
                                        }
                                      }
                                    });
                                  },
                                  list:typeCertificate
                              ),
                              InputWithSubtitle(
                                controller: numberCertificateController,
                                subtitle: 'Número da Certidão',
                                errorInput: 'Campo Obrigatório',
                                labelInput: 'Número da Certidão',
                                widthInput: width*0.7,
                                widthSubtitle: width*0.7,
                                hintInput: 'Escreva aqui',
                                mandatory: false,
                                enabled: !edit,
                                onChanged: (v)=>setState((){}),
                              ),
                              InputWithSubtitle(
                                controller: nameCertificateController,
                                subtitle: 'Nome do Cartório da Certidão',
                                errorInput: 'Campo Obrigatório',
                                labelInput: 'Nome do Cartório da Certidão',
                                widthInput: width*0.7,
                                widthSubtitle: width*0.7,
                                hintInput: 'Escreva aqui',
                                mandatory: false,
                                enabled: !edit,
                                onChanged: (v)=>setState((){}),
                              ),
                              InputWithSubtitle(
                                controller: bookCertificateController,
                                subtitle: 'Livro da Certidão',
                                errorInput: 'Campo Obrigatório',
                                labelInput: 'Livro da Certidão',
                                widthInput: width*0.7,
                                widthSubtitle: width*0.7,
                                hintInput: 'Escreva aqui',
                                mandatory: false,
                                enabled: !edit,
                                onChanged: (v)=>setState((){}),
                              ),
                              InputWithSubtitle(
                                controller: sheetCertificateController,
                                subtitle: 'Folha da Certidão',
                                errorInput: 'Campo Obrigatório',
                                labelInput: 'Folha da Certidão',
                                widthInput: width*0.7,
                                widthSubtitle: width*0.7,
                                hintInput: 'Escreva aqui',
                                mandatory: false,
                                enabled: !edit,
                                onChanged: (v)=>setState((){}),
                              ),
                              InputWithSubtitle(
                                controller: termCertificateController,
                                subtitle: 'Termo da Certidão',
                                errorInput: 'Campo Obrigatório',
                                labelInput: 'Termo da Certidão',
                                widthInput: width*0.7,
                                widthSubtitle: width*0.7,
                                hintInput: 'Escreva aqui',
                                mandatory: false,
                                enabled: !edit,
                                onChanged: (v)=>setState((){}),
                              ),
                              GestureDetector(
                                onTap:edit?null: ()=>escolherprazoInicio(context,'cert'),
                                child: Container(
                                  alignment: Alignment.centerLeft,
                                  height: 58,
                                  margin: EdgeInsets.symmetric(horizontal: 15,vertical: 5),
                                  padding: EdgeInsets.symmetric(horizontal: 8,vertical: 10),
                                  decoration: BoxDecoration(
                                    border: Border.all(color: ColorPalette.black54),
                                    borderRadius: BorderRadius.all(
                                        Radius.circular(5.0)
                                    ),
                                  ),
                                  width: width*0.7,
                                  child: TextDefault(
                                    text: dateCertificateController.text,
                                    color: ColorPalette.black54,
                                    fontSize: 16,
                                  ),
                                ),
                              ),
                              InputWithSubtitle(
                                controller: CTPSController,
                                subtitle: 'CTPS',
                                errorInput: 'Campo Obrigatório',
                                labelInput: 'CTPS',
                                widthInput: width*0.7,
                                widthSubtitle: width*0.7,
                                hintInput: 'Escreva aqui',
                                mandatory: false,
                                enabled: !edit,
                                onChanged: (v)=>setState((){}),
                              ),
                              InputWithSubtitle(
                                controller: numberCTPSController,
                                subtitle: 'Número de Série CTPS',
                                errorInput: 'Campo Obrigatório',
                                labelInput: 'Número de Série CTPS',
                                widthInput: width*0.7,
                                widthSubtitle: width*0.7,
                                hintInput: 'Escreva aqui',
                                mandatory: false,
                                enabled: !edit,
                                onChanged: (v)=>setState((){}),
                              ),
                              DropdownWithSubtitle(
                                  subtitle: 'CTPS - UF',
                                  select: selectCTPSUF,
                                  widthSubtitle: width*0.6,
                                  widthDropdown:  width*0.69,
                                  widthContainerDropdown: width*0.6,
                                  hintDropdown: 'CTPS - UF',
                                  onChanged:edit?null: (value){
                                    setState(() {
                                      selectCTPSUF = value;
                                    });
                                  },
                                  list: ConstVariable().RGUF
                              ),
                              InputWithSubtitle(
                                controller: PISController,
                                subtitle: 'PIS/PASEP',
                                errorInput: 'Campo Obrigatório',
                                labelInput: 'PIS/PASEP',
                                widthInput: width*0.7,
                                widthSubtitle: width*0.7,
                                hintInput: 'Escreva aqui',
                                mandatory: false,
                                enabled: !edit,
                                onChanged: (v)=>setState((){}),
                              ),
                              Container(
                                width: width*0.65,
                                child: Row(
                                  children: [
                                    TextDefault(text: 'Retirou cartão municipal da cidade?',fontSize: 15,color: Colors.black54),
                                    Spacer(),
                                    Switch(value: enableCityCard, onChanged:edit?null: (value)=>setState(()=>enableCityCard=value!)
                                    )
                                  ],
                                ),
                              ),
                              InputWithSubtitle(
                                controller: NISController,
                                subtitle: 'Identificação da saúde - NIS',
                                errorInput: 'Campo Obrigatório',
                                labelInput: 'Identificação da saúde - NIS',
                                widthInput: width*0.7,
                                widthSubtitle: width*0.7,
                                hintInput: 'Escreva aqui',
                                mandatory: false,
                                enabled: !edit,
                                onChanged: (v)=>setState((){}),
                              ),
                            ],
                          ),
                        ]
                    ),
                  ],
                ),
              ),
              Card(
                margin: EdgeInsets.all(10),
                child: Column(
                  children: [
                    TitleContainers(title: 'Outros'),
                    Row(
                        children: [
                          Container(
                            height: height*0.3,
                            width: width*0.2,
                            child: Icon(Icons.tag,size: 80,),
                          ),
                          Column(
                            mainAxisAlignment: MainAxisAlignment.start,
                            mainAxisSize: MainAxisSize.min,
                            children: [
                              Container(
                                color: ColorPalette.white,
                                margin: EdgeInsets.only(top: 5),
                                width: width*0.7,
                                child: TextFormField(
                                    keyboardType: TextInputType.number,
                                    inputFormatters: [
                                      FilteringTextInputFormatter.digitsOnly,
                                      CentavosInputFormatter(moeda: true),
                                    ],
                                    controller: incomeController,
                                    enabled: !edit,
                                    style: TextStyle(
                                      color: Colors.black,
                                      fontSize: 16,
                                    ),
                                    decoration: InputDecoration(
                                        fillColor: ColorPalette.appBar,
                                        labelText: 'Renda Mensal',
                                        border: OutlineInputBorder(
                                            borderSide: BorderSide(width: 1,color: ColorPalette.black54)
                                        ),
                                        focusedBorder: OutlineInputBorder(
                                          borderSide: BorderSide(width: 1, color: ColorPalette.black54),
                                          borderRadius: BorderRadius.circular(3),
                                        ),
                                        enabledBorder: OutlineInputBorder(
                                          borderSide: BorderSide(width: 1, color: ColorPalette.black54),
                                          borderRadius: BorderRadius.circular(3),
                                        ),
                                        disabledBorder: OutlineInputBorder(
                                          borderSide: BorderSide(width: 1, color: ColorPalette.black54),
                                          borderRadius: BorderRadius.circular(3),
                                        ),
                                        hintText: 'Escreva aqui',
                                        hintStyle: TextStyle(
                                          color: ColorPalette.gray,
                                          fontSize: 16,
                                        )
                                    )
                                ),
                              ),
                              InputWithSubtitle(
                                controller: professionalController,
                                subtitle: 'Profissão',
                                errorInput: 'Campo Obrigatório',
                                labelInput: 'Profissão',
                                widthInput: width*0.7,
                                widthSubtitle: width*0.7,
                                hintInput: 'Escreva aqui',
                                mandatory: false,
                                enabled: !edit,
                                onChanged: (v)=>setState((){}),
                              ),
                              GestureDetector(
                                onTap:edit?null: ()=>escolherprazoInicio(context,'death'),
                                child: Container(
                                  alignment: Alignment.centerLeft,
                                  height: 58,
                                  margin: EdgeInsets.symmetric(horizontal: 15,vertical: 5),
                                  padding: EdgeInsets.symmetric(horizontal: 8,vertical: 10),
                                  decoration: BoxDecoration(
                                    border: Border.all(color: ColorPalette.black54),
                                    borderRadius: BorderRadius.all(
                                        Radius.circular(5.0)
                                    ),
                                  ),
                                  width: width*0.7,
                                  child: TextDefault(
                                    text: dateDeathController.text,
                                    color: ColorPalette.black54,
                                    fontSize: 16,
                                  ),
                                ),
                              ),
                              Container(
                                width: width*0.65,
                                child: Row(
                                  children: [
                                    TextDefault(text: 'Bloqueado',fontSize: 15,color: ColorPalette.black54),
                                    Spacer(),
                                    Switch(value: enableBlocked, onChanged:edit?null: (value)=>setState(()=>enableBlocked=value!)),
                                  ],
                                ),
                              )
                            ],
                          ),
                        ]
                    ),
                  ],
                ),
              ),
            ]
         )
        ),
      ),
    );
  }
}
