<?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>
                                Lotes XMLs NFe Chave
                            </h3>
                        </div>
                        <div class="box-content">
                            <form class="wc_form_search" action="" method="POST">
                                <fieldset>
                                    <div class="row">
                                        <div class="form-group col-lg-2">
                                            <label>CHAVE</label>
                                            <input type="text" class="form-control" name="chave" 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">BAIXADO</option>
                                                <option value="2">CANCELADO</option>
                                                <option value="3">ERRO</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-danger" onclick="link_download();">BAIXAR XML</a>
                                        </div>
                                        <div class="form-group col-lg-5">
                                            <span class="load_lote" style="margin-top: -20px;"></span>
                                        </div>
                                    </div>
                                </fieldset>
                            </form>
                            <hr />
                            <div id="load_key_nfe"></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="key_nfe_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.xml_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_key_nfe").tabulator({
        height: "450px",
        fitColumns: true,
        ajaxURL: "<?= $router->route("xml_key_nfe.selectKey"); ?>",
        ajaxParams: {action: "search_key_nfe", id_lote: "<?php echo $param['uri'];?>"},
        pagination: "remote",
        paginationSize: 100,
        paginationDataSent: {"page": "pageNo"},
        columns: [
            {title:"<input type='checkbox' class='select-all'>", formatter:selectionFormatter, width: 35},
            {title: "CHAVE", field: "xml_chave", sorter: "string"},
            {title: "STATUS", field: "xml_status", sorter: "string"}
        ],
        ajaxResponse:function(url, params, response){
            $("#key_nfe_quantify").html('<h4>'+response.quantify+'</h4>');
            return response;
        }
    });
    $("#load_key_nfe .select-all").on("change", function(){
        if($(this).is(":checked")){
            $("#load_key_nfe .row-select").prop("checked", true).closest(".tabulator-row").addClass("selected");
        }else{
            $("#load_key_nfe .row-select").prop("checked", false).closest(".tabulator-row").removeClass("selected");
        }
    });
    $('.wc_form_search').submit(function () {
        var Form = $(this);
        var Param = "&action=search_key_nfe";
        var Data = Form.serialize()+Param;


        $.ajax({
            url: "<?= $router->route("xml_key_nfe.search"); ?>",
            data: Data,
            type: 'POST',
            dataType: 'json',
            beforeSend: load_in(),
            success: function (data) {
                redirect('<?php echo url('xml_key_nfe/key/');?><?php echo $param['uri'];?>');
                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_nfe";
        $.ajax({
            url: "<?= $router->route("xml_key_nfe.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 load_lote() {
        var Data = "&action=load_lote&id=<?php echo $param['uri'];?>";
        $.ajax({
            url: "<?= $router->route("xml_key_nfe.loadLote"); ?>",
            data: Data,
            type: 'POST',
            dataType: 'json',
            beforeSend: load_in(),
            success: function (data) {
                if (data[0].type === 'error') {

                } else {
                    if(Number(data.pendente) === 0){
                        $(".load_lote").html('<strong>Total:</strong> ' + data.total + ' <br /> <strong>Baixado:</strong> ' + data.concluido + ' <br /> <strong>Pendente:</strong> '+data.pendente+' <br /> <strong>Erro/Cancelado: </strong>'+data.erro);
                    }else{
                        $(".load_lote").html('<img src="<?= asset("/load.gif"); ?>" /><br /><strong>Total:</strong> ' + data.total + ' <br /> <strong>Baixado:</strong> ' + data.concluido + ' <br /> <strong>Pendente:</strong> '+data.pendente+' <br /> <strong>Erro/Cancelado: </strong>'+data.erro);
                    }
                }
                load_out();
            },
            error: function (request, status, error) {
                load_out();
            }
        });
        return false;
    }
    function link_key(){
        var objCheckBox = $("#load_key_nfe .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('xml_key_nfe/key/');?>'+url;
        }
    }
    function link_delete(){
        var objCheckBox = $("#load_key_nfe .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('xml_key_nfe/delete/');?>'+url;
        }
    }
    function link_download(){
        var objCheckBox = $("#load_key_nfe .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));
            var Data = "&action=download&id="+url;
            $.ajax({
                url: "<?= $router->route("xml_key_nfe.zip"); ?>",
                data: Data,
                type: 'POST',
                dataType: 'json',
                beforeSend: load_in(),
                success: function (data) {
                    if(data[0].type === 'error'){
                        notify(data[0].title, data[0].message);
                    }else{
                        notify(data[0].title, data[0].message);
                        setTimeout(function(){
                            window.open('../../shared/temp/'+data.nome_arquivo, '_blank');
                        }, 1000);
                    }
                    load_out();
                }
            });
            return false;
        }
    }

    $(function(){
        setInterval(load_lote, 15000);
        load_search();
        load_lote();
    });
</script>
