<?php
$v->layout("_themesis");
?>
<div class="container-fluid nav-hidden" id="content">
    <div id="">
        <div class="container-fluid">
            <div class="row">
                <div class="col-sm-12">
                    <div class="box">
                        <div class="box-title">
                            <h3>
                                Consulta CNPJ / IE
                            </h3>
                        </div>
                        <div class="box-content">
                            <form class="wc_form_search" action="" method="POST">
                                <fieldset>
                                    <div class="row">
                                        <div class="form-group col-lg-3">
                                            <label>DATA INICIAL</label>
                                            <input type="datetime-local" class="form-control" name="data_inicial" autocomplete="off"/>
                                        </div>
                                        <div class="form-group col-lg-2">
                                            <label>DATA FINAL</label>
                                            <input type="datetime-local" class="form-control" name="data_final" autocomplete="off"/>
                                        </div>
                                        <div class="form-group col-lg-2">
                                            <label>STATUS</label>
                                            <select name="status" class="form-control">
                                                <option value=""></option>
                                                <option value="0">PENDENTE</option>
                                                <option value="1">FINALIZADO</option>
                                                <option value="0">CANCELADO</option>
                                            </select>
                                        </div>
                                    </div>
                                    <div class="row">
                                        <div class="form-group col-lg-7">
                                            <label>.</label><br />
                                            <button class="btn btn-primary">PESQUISAR</button>
                                            <a class="btn btn-blue" onclick="link_key();">VER DADOS</a>
                                            <a class="btn btn-danger" onclick="link_download();">BAIXAR EXCEL</a>
                                            <a class="btn btn-success" href="<?php echo url('consult/create');?>">CADASTRAR NOVO</a>
                                        </div>
                                    </div>
                                </fieldset>
                            </form>
                            <hr />
                            <div id="load_consult"></div>
                            <div class="row">
                                <div class="col-sm-12">
                                    <div class="box box-color blue box-condensed box-bordered">
                                        <div class="box-title" align="center">
                                            <h3>
                                                QUANTIDADE
                                            </h3>
                                        </div>
                                        <div class="box-content">
                                            <div id="consult_quantify" align="center"><h4></h4></div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<script>
    var selectionFormatter = function(value, data, cell, row, options, formatterParams){
        var rowSelect = $("<input type='checkbox' class='row-select' value='"+data.lote_consulta_id+"'>");

        rowSelect.on("change", function(){
            if($(this).is(":checked")){
                $(this).closest(".tabulator-row").addClass("selected");
            }else{
                $(this).closest(".tabulator-row").removeClass("selected");
            }
        });
        return rowSelect;
    }
    $("#load_consult").tabulator({
        height: "450px",
        fitColumns: true,
        ajaxURL: "<?= $router->route("consult.select"); ?>",
        ajaxParams: {action: "search_key_cte"},
        pagination: "remote",
        paginationSize: 100,
        paginationDataSent: {"page": "pageNo"},
        columns: [
            {title:"<input type='checkbox' class='select-all'>", formatter:selectionFormatter, width: 35},
            {title: "ID", field: "lote_consulta_id", sorter: "int", width: 75},
            {title: "STATUS", field: "lote_consulta_status", sorter: "string"},
            {title: "DATA HORA", field: "lote_consulta_date_hour", sorter: "string"},
            {title: "DATA HORA FINAL", field: "lote_consulta_date_hour_end", sorter: "string"},
            {title: "TEMPO", field: "lote_temp", sorter: "string"},
            {title: "GASTO", field: "lote_quantify", sorter: "string"}
        ],
        ajaxResponse:function(url, params, response){
            $("#consult_quantify").html('<h4>'+response.quantify+'</h4>');
            return response;
        }
    });
    $("#load_consult .select-all").on("change", function(){
        if($(this).is(":checked")){
            $("#load_consult .row-select").prop("checked", true).closest(".tabulator-row").addClass("selected");
        }else{
            $("#load_consult .row-select").prop("checked", false).closest(".tabulator-row").removeClass("selected");
        }
    });
    $('.wc_form_search').submit(function () {
        var Form = $(this);
        var Param = "&action=search_key_consult";
        var Data = Form.serialize()+Param;


        $.ajax({
            url: "<?= $router->route("consult.search"); ?>",
            data: Data,
            type: 'POST',
            dataType: 'json',
            beforeSend: load_in(),
            success: function (data) {
                redirect('<?php echo url('consult/index');?>');
                load_out();
            },
            error: function (request, status, error) {
                notify('Opss', 'Operação não pode ser finalizada!!');
            }
        });
        return false;
    });
    function load_search(){
        var Data = "&action=search_key_consult";
        $.ajax({
            url: "<?= $router->route("consult.searchRead"); ?>",
            data: Data,
            type: 'POST',
            dataType: 'json',
            beforeSend: load_in(),
            success: function (data) {
                if(data.type === 'ok'){
                    var Form = $(".wc_form_search");
                    $.each(data.info, function (key, value) {
                        Form.find("input[name='" + key + "'], select[name='" + key + "']").val(value);
                    });
                }
                load_out();
            },
            error: function (request, status, error) {
                load_out();
            }
        });
        return false;
    }
    function link_key(){
        var objCheckBox = $("#load_consult .row-select");
        var sel = 0;
        var selecionadas = "";
        for (i=0; i < objCheckBox.length; i++) {
            if (objCheckBox[i].checked) {
                sel++;
                selecionadas += objCheckBox[i].value+",";
            }
        }
        if(Number(sel) === 0){
            notify('Ops', 'É preciso selecionar um registro');
        }else if(Number(sel) > 1){
            notify('Ops', 'É preciso selecionar apenas um registro');
        }else{
            var url = selecionadas.substr(0,(selecionadas.length - 1));
            window.location = '<?php echo url('consult/key/');?>'+url;
        }
    }
    function link_delete(){
        var objCheckBox = $("#load_consult .row-select");
        var sel = 0;
        var selecionadas = "";
        for (i=0; i < objCheckBox.length; i++) {
            if (objCheckBox[i].checked) {
                sel++;
                selecionadas += objCheckBox[i].value+",";
            }
        }
        if(Number(sel) === 0){
            notify('Ops', 'É preciso selecionar um registro');
        }else if(Number(sel) > 1){
            notify('Ops', 'É preciso selecionar apenas um registro');
        }else{
            var url = selecionadas.substr(0,(selecionadas.length - 1));
            window.location = '<?php echo url('consult/delete/');?>'+url;
        }
    }
    function link_download(){
        var objCheckBox = $("#load_consult .row-select");
        var sel = 0;
        var selecionadas = "";
        for (i=0; i < objCheckBox.length; i++) {
            if (objCheckBox[i].checked) {
                sel++;
                selecionadas += objCheckBox[i].value+",";
            }
        }
        if(Number(sel) === 0){
            notify('Ops', 'É preciso selecionar um registro');
        }else{
            var url = selecionadas.substr(0,(selecionadas.length - 1));
            window.open('../shared/zip/lote'+url+'.rar', '_blank');
        }
    }

    $(function(){
        load_search();
    });
</script>
