var $interesses = [];
var $idInteresse = null;
var start = '01/01/0001';
var end = moment();
 
$('input[name="daterange"]').daterangepicker({
    locale: {
      format: 'DD/MM/YYYY',
      applyLabel: 'Aplicar',
        cancelLabel: 'Cancelar',
        fromLabel: 'De',
        toLabel: 'Até',
        customRangeLabel: 'Personalizado',
        daysOfWeek: [
            'Dom',
            'Seg',
            'Ter',
            'Qua',
            'Qui',
            'Sex',
            'Sáb'
        ],
        monthNames: [
            'Janeiro',
            'Fevereiro',
            'Março',
            'Abril',
            'Maio',
            'Junho',
            'Julho',
            'Agosto',
            'Setembro',
            'Outubro',
            'Novembro',
            'Dezembro'
        ],
    },
    startDate: start,
    endDate: end,
    ranges: {
       'Hoje': [moment(), moment()],
       'Ontem': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
       'Ultimos 7 Dias': [moment().subtract(6, 'days'), moment()],
       'Ultimos 30 Dias': [moment().subtract(29, 'days'), moment()],
       'Mes Atual': [moment().startOf('month'), moment().endOf('month')],
       'Ultimo Mes': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')],
       'Todos' : ['01/01/0001',moment()]
    }
});





$(window).on('load', function(){
    getTbInteresses();
    
    /* $('#tbInteresse').DataTable( {
        "order": [[ 4, "desc" ]]
    } );*/
    
    $('.bairro_editar_interesse').select2({
        width: '100%',
        language: "pt-BR",
    });
    
    $('.tipo_emp_editar_interesse').select2({
        width: '100%',
        language: "pt-BR",
    });
    
});

//Coloca um select2 no campo bairro e no tipo de empreendimento do cliente do editar interesse
$(document).ready(function() {
    
    $('.result_add_interesse_step1').hide();
    
    $('.bairro_save_interesse').select2({
        width: '100%',
        language: "pt-BR",
    });
    $('.tipo_emp_save_interesse').select2({
        width: '100%',
        language: "pt-BR",
    });
});

function getTbInteresses($pesquisa = []){
    $('#tbInteresse').DataTable().clear().draw();
     get_ajax($pesquisa, 'atendimento/ajax/interesse_ajax/getTbInteresses', 
        success =>{
            
            $interesses = [];
            
            for(key in success){
                
                $row = success[key];
                
                $interesses[$row.id_interesse] = $row;
                
                $('#tbInteresse').DataTable().row.add([
                        $row.cadastro.nome,
                        $row.cadastro.email,
                        $row.tipo_interesse,
                        $row.bairrosBadge,
                        $row.data,
                        $row.action
                    ]).draw( false );
            }
            
    });
}




//Abrir a modal de editar interesse
$('#tbInteresse').on('click', '.btnEditarInteresse' , function(e){
e.preventDefault();

    $idInteresse = $(this).data('id');
    $data = $interesses[$idInteresse];
    
    for(key in $data){
        $val = $data[key];
        $('.edit_interesse_'+key).val($val);
    }
    
    $('.edit_interesse_bairro').val($data.bairros).trigger('change');
    $('.tipo_emp_editar_interesse').val($data.tipos_emp).trigger('change');
    $('#editInteresseModal').modal('show');
   
   
});


//Abrir o alert de excluir o interesse
$('body').on('click', '.btnFiltar' , function(e){

    loadButton($(this));
    
    getTbInteresses(getForm($('#formFiltrar')));
    
});

$('body').on('change', '.atualizaFiltro' , function(e){

    loadButton($('.btnFiltar'));
    
    getTbInteresses(getForm($('#formFiltrar')));
    
});


//Abrir o alert de excluir o interesse
$('#tbInteresse').on('click', '.btnExcluirInteresse' , function(e){
e.preventDefault();

data = {
    id_interesse: $(this).data('id')
};

if(confirm("Você realmente quer excluir esse Interesse?")){
    
    get_ajax(data, 'atendimento/ajax/Interesse_ajax/excluirInteresse',
    success => {
        
        if(success.success == true){        
            
            //location.reload();
            alert('Interesse excluido com sucesso!');
            getTbInteresses(getForm($('#formFiltrar')));
        }
        else{
            alert('Erro');
        }
    });
}
});


function getForm($form)
{
    data = [];
    var nameRadio = [];
    
    //$($form).find('input:not([type=radio]):input:not([type=checkbox]):input:not([type=file])').each(function(key,value){
    $($form).find('input:not([type=radio]):input:not([type=checkbox]):input:not([type=file])').each(function(key,value){
        if(this.name != "")
            data.push({"name": this.name, "value": this.value});
    });
    
    $($form).find('input[type=file]').each(function(key,value){
        if(this.name != ""){
            data.push({"name": this.name, "value": $(this).data('value')});
        }
    });
    
    
    
    $($form).find('textarea').each(function(key,value)    {
        if(this.name != ""){
            
            if(typeof CKEDITOR !== 'undefined')
                data.push({"name": this.name, "value": CKEDITOR.instances[this.name].getData()});
            else
                data.push({"name": this.name, "value": this.value});
        }
    });
    
    
    /*$($form).find('textarea').each(function(key,value){
       
        if(this.name != "")
        {
            if(CKEDITOR.instances[this.name] != undefined){
                 //data.push({"name": this.name, "value": CKEDITOR.instances[this.name].getData()});
                 ckeditorValue = $($($($('#cke_'+this.id)[0])[0]).find('iframe').contents().find("body")).html();
                 data.push({"name": this.name, "value": ckeditorValue});
                 if(ckeditorValue == undefined)
                    data.push({"name": this.name, "value": this.value});
            }
            else
            {
                data.push({"name": this.name, "value": this.value});
            }
        }
    });*/
    
    $($form).find('input[type=radio]').each(function(key,value){
        if(nameRadio[this.name] == undefined)
            nameRadio[this.name] = '';
        if($(this).is(':checked'))
            nameRadio[this.name] = this.value;
    });
    
    for(var name in nameRadio){
        data.push({"name": name, "value": nameRadio[name]});
    };
    
    $($form).find('select option:selected').each(function(key,value)    {
        if(this.parentElement.localName == 'select')
            data.push({"name": this.parentElement.name, "value": this.value});
            
        if(this.parentElement.parentElement.localName == 'select')
            data.push({"name": this.parentElement.parentElement.name, "value": this.value});
    });
    
    $($form).find('input[type=checkbox]:checked').each(function(key,value)    {
        if(this.name != "")
            data.push({"name": this.name, "value": this.value});
    });
    
    $($form).find('input[type=checkbox]:not(:checked)').each(function(key,value)    {
        if(this.name != "")
            data.push({"name": this.name, "value": ""});
    });
    
    return data;
}


//Da update do Interesse
$('.editInteresse').on('click',function(){
    loadButton($(this));
    $data = getForm($('.form-edit-interesse'));
    
    get_ajax($data, 'atendimento/ajax/Interesse_ajax/editarInteresse',
    success => {
        
        if(success.success == true){        
            //$(".editInteresse").prop("disabled",true);
            
            $('.result_edit_interesse').html('');
            $('.result_edit_interesse').append('<div class="alert alert-primary alert-dismissible fade show" role="alert"> '+success.msg+'<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button></div>');
            
            setTimeout(function() {
                    getTbInteresses(getForm($('#formFiltrar')));
                }, 1000);
            
        }else{
            
            $('.result_edit_interesse').html('');
            $('.result_edit_interesse').append('<div class="alert alert-danger alert-dismissible fade show" role="alert"> '+success.msg+'<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button></div>');
        }  
        
    });
    
});

//Abrir a modal de adicionar interesse step 1
$('.btn_open_interesse').on('click', function(e){
e.preventDefault();

    $('#addInteresseStep1').modal('show');
   
});

//Pesquisar o lead para adicionar interesse
$('.btn_add_interesse_step1').on('click' , function(e){
e.preventDefault();
    loadButton($(this));
    
    data = getForm($('.form-add-interesse'));
    
    get_ajax(data, 'atendimento/ajax/Interesse_ajax/avaliaCadInteresse',
    success => {
            
            alert(success.msg);
            
            
            $('.nome_add_interesse_step1').val(success.cadastro.nome);
            $('.telefone_add_interesse_step1').val(success.cadastro.telefone);
            $('.email_add_interesse_step1').val(success.cadastro.email);
            $('.cpf_add_interesse_step1').val(success.cadastro.cpf);
            
            
            $('.btn_add_interesse_step1').hide();
            $('.result_add_interesse_step1').show();
            
            $('#nome_add_interesse_step1').prop("disabled",true);
            $('#telefone_add_interesse_step1').prop("disabled",true);
            $('#email_add_interesse_step1').prop("disabled",true);
            $('#cpf_add_interesse_step1').prop("disabled",true);
            
        
    },
    erro => {
        alert(erro.msg);
        if(erro.validForm == true){
            
            $('.valida_dados_interesse').show();
        }
        
        
        
    });

});

//Salvar o interesse
$('.saveInteresse').on('click' , function(e){
e.preventDefault();
    loadButton($(this));
    
    data = getForm($('.form-add-interesse'));
    
    get_ajax(data, 'atendimento/ajax/Interesse_ajax/salvarInteresse',
    success => {
        
        alert(success.msg);
        
        $('#addInteresseStep1').modal('hide');
        getTbInteresses();
        
        //$('#tbInteresse').DataTable().row.add([
        //                $row.cadastro.nome,
        //                $row.cadastro.email,
        //                $row.tipo_interesse,
        //                $row.bairrosBadge,
        //                $row.data,
        //                $row.action
        //            ]).draw( false );
        
        
        $('#nome_add_interesse_step1').prop("disabled",false);
        $('#telefone_add_interesse_step1').prop("disabled",false);
        $('#email_add_interesse_step1').prop("disabled",false);
        $('#cpf_add_interesse_step1').prop("disabled",false);
        
        
        $('.btn_add_interesse_step1').show();
        $('.result_add_interesse_step1').hide();
        
        
        $('.nome_add_interesse_step1').val('');
        $('.telefone_add_interesse_step1').val('');
        $('.email_add_interesse_step1').val('');
        $('.cpf_add_interesse_step1').val('');
       
    },
    erro => {
        alert(erro.msg);
    });

});

//Máscara de telefone e cpf para o adicionar interesse
$('.telefone_add_interesse_step1').inputmask({
            mask: ["(99) 99999-9999"]
});

//Carregar máscara de cpf e telefone para o novo cartao
$('.cpf_add_interesse_step1').inputmask({
            mask: ["999.999.999-99"]
});

//Carregar máscara de valor monetário R$ para as faixas de preço do salvar interesse 
$(".faixa_preco_save_interesse").inputmask("currency", {
  autoUnmask: true,
  radixPoint: ",",
  groupSeparator: ".",
  allowMinus: false,
  prefix: "R$ ",
  digits: 2,
  digitsOptional: false,
  rightAlign: false,
  unmaskAsNumber: true
});