<?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>
                                NFSe
                            </h3>
                        </div>
                        <div class="box-content">
                            <form class="wc_form_search" action="" method="POST">
                                <fieldset>
                                    <div class="row">
                                        <div class="form-group col-lg-4">
                                            <label>EMPRESA</label>
                                            <input type="hidden" class="autocomplete_company_completo_id" name="id_empresa"/>
                                            <input type="text" class="form-control autocomplete_company_completo" name="empresa" onblur="set_blank();" autocomplete="off"/>
                                        </div>
                                        <div class="form-group col-lg-2">
                                            <label>DATA INICIAL</label>
                                            <input type="date" class="form-control" name="data_inicial" autocomplete="off"/>
                                        </div>
                                        <div class="form-group col-lg-2">
                                            <label>DATA FINAL</label>
                                            <input type="date" class="form-control" name="data_final" autocomplete="off"/>
                                        </div>
                                        <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>EMITENTE</label>
                                            <input type="text" class="form-control" name="emitente" autocomplete="off"/>
                                        </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_search();" href="#">BUSCAR NFSE</a>
                                            <a class="btn btn-warning" onclick="link_download_zip();" href="#">DOWNLOAD ARQUIVOS</a>
                                            <a class="btn btn-danger" onclick="link_danfe();" href="#">DANFE</a>
                                        </div>
                                    </div>
                                </fieldset>
                            </form>
                            <hr />
                            <div id="load_doc"></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="doc_quantify" align="center"><h4></h4></div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>


<div id="modal-download" class="modal fade" role="dialog">
    <div class="modal-dialog modal-lg" style="width: 75%">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                <h4 class="modal-title" id="myModalLabel">Downloads XMLs</h4>
            </div>
            <div class="modal-body">

                <hr />
                <div class="row">
                    <input type="hidden" class="ide_nfs_download"/>
                    <input type="hidden" class="inicio_nfs_download" value="0">
                    <span class="load_info_new" style="display: none;"><img src="<?= asset("/load.gif");?>"/> - Aguarde fazendo o download</span>
                    <div class="col-lg-12">
                        <div class="load_retorno_download"></div>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">FECHAR</button>

                <button type="button" class="btn btn-blue" onclick="download();">FAZER DOWNLOAD</button>
            </div>
        </div>
    </div>
</div>

<div id="modal-download-zip" class="modal fade" role="dialog">
    <div class="modal-dialog modal-xl">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                <h4 class="modal-title" id="myModalLabel">Downloads XMLs Para Seu Dispositivo</h4>
            </div>
            <div class="modal-body">

                <hr />
                <div class="row">
                    <input type="hidden" class="ide_nfs_download_zip"/>
                    <span class="load_info_new" style="display: none;"><img src="<?= asset("/load.gif");?>"/> - Aguarde fazendo o download</span>
                    <div class="col-lg-12">
                        <div class="load_retorno_download_zip"></div>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">FECHAR</button>

                <button type="button" class="btn btn-blue" onclick="download_xml();">PROCESSAR ARQUIVOS</button>
            </div>
        </div>
    </div>
</div>

<div id="modal-danfe-zip" class="modal fade" role="dialog">
    <div class="modal-dialog modal-xl">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                <h4 class="modal-title" id="myModalLabel">Gerar Danfe</h4>
            </div>
            <div class="modal-body">

                <hr />
                <div class="row">
                    <input type="hidden" class="ide_nfs_danfe_zip"/>
                    <span class="load_info_new" style="display: none;"><img src="<?= asset("/load.gif");?>"/> - Aguarde gerando os danfes</span>
                    <div class="col-lg-12">
                        <div class="load_retorno_danfe_zip"></div>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">FECHAR</button>

                <button type="button" class="btn btn-blue" onclick="danfe_xml();">PROCESSAR ARQUIVOS</button>
            </div>
        </div>
    </div>
</div>


<script>
    function set_blank(){
        var name = $(".autocomplete_company_completo").val();
        if(name == ''){
            $(".autocomplete_company_completo_id").val('');
        }
    }
    function download(){
        var ide_nfs = $(".ide_nfs_download").val();
        var inicio_nfs = $(".inicio_nfs_download").val();

        var Data = "&action=search_doc_nfse&nfs="+ide_nfs+"&inicio="+inicio_nfs;
        $.ajax({
            url: "<?= $router->route("doc_nfse.download"); ?>",
            data: Data,
            type: 'POST',
            dataType: 'json',
            beforeSend: load_in_new(),
            success: function (data) {
                if(data[0].type === 'ok'){
                    $(".load_retorno_download").html(data.retorno);
                }else if(data[0].type === 'info') {
                    $(".load_retorno_download").html(data.retorno);
                    $(".inicio_nfs_download").val(data.count);
                    setTimeout(download, 2000);
                }else{
                    $(".load_retorno_download").html('<p>'+data[0].message+'</p>');
                }
                load_out_new();
            },
            error: function (request, status, error) {
                load_out_new();
            }
        });
        return false;
    }
    var selectionFormatter = function(value, data, cell, row, options, formatterParams){
        var rowSelect = $("<input type='checkbox' class='row-select' value='"+data.nfse_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_doc").tabulator({
        height: "650px",
        fitColumns: true,
        ajaxURL: "<?= $router->route("doc_nfse.select"); ?>",
        ajaxParams: {action: "search_doc_nfse"},
        pagination: "remote",
        paginationSize: 100,

        paginationDataSent: {"page": "pageNo"},
        columns: [
            {title:"<input type='checkbox' class='select-all'>", formatter:selectionFormatter, width: 25, frozen:true},
            {title: "EMPRESA", field: "company_name", sorter: "string"},
            {title: "CHAVE", field: "nfse_chave", sorter: "string", width: 200},
            {title: "DT EMISSÃO", field: "nfse_data_hora", sorter: "string", width: 200},
            {title: "EMIT: DOC", field: "nfse_doc", sorter: "string", width: 135},
            {title: "EMIT: NOME/RAZÃO", field: "nfse_emitente", sorter: "string", width: 250},
            {title: "LOCAL PRESTAÇÃO", field: "nfse_local_prestacao", sorter: "string", width: 120},
            {title: "DEST: DOC", field: "nfse_tomador_doc", sorter: "string", width: 135},
            {title: "DEST: NOME/RAZÃO", field: "nfse_tomador", sorter: "string", width: 250},
            {title: "VLR NOTA", field: "nfse_valor_servico", sorter: "string", width: 120}
        ],
        ajaxResponse:function(url, params, response){
            $("#doc_quantify").html('<h4>'+response.quantify+'</h4>');
            return response;
        }
    });
    $("#load_doc .select-all").on("change", function(){
        if($(this).is(":checked")){
            $("#load_doc .row-select").prop("checked", true).closest(".tabulator-row").addClass("selected");
        }else{
            $("#load_doc .row-select").prop("checked", false).closest(".tabulator-row").removeClass("selected");
        }
    });
    $('.wc_form_search').submit(function () {
        var Form = $(this);
        var Param = "&action=search_doc_nfse";
        var Data = Form.serialize()+Param;


        $.ajax({
            url: "<?= $router->route("doc_nfse.search"); ?>",
            data: Data,
            type: 'POST',
            dataType: 'json',
            beforeSend: load_in(),
            success: function (data) {
                redirect('<?php echo url('doc_nfse/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_doc_nfse";
        $.ajax({
            url: "<?= $router->route("doc_nfse.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_download_zip(){
        var objCheckBox = $("#load_doc .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));
            $(".load_retorno_download_zip").html('');
            $("#modal-download-zip").modal('show');
            $(".ide_nfs_download_zip").val(url);
        }
    }

    function link_danfe(){
        var objCheckBox = $("#load_doc .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));
            $(".load_retorno_danfe_zip").html('');
            $("#modal-danfe-zip").modal('show');
            $(".ide_nfs_danfe_zip").val(url);
        }
    }

    function download_xml(){
        var idDoc = $(".ide_nfs_download_zip").val();
        var Data = "&action=search_doc_nfse&id_doc="+idDoc;
        $.ajax({
            url: "<?= $router->route("doc_nfse.downloadZip"); ?>",
            data: Data,
            type: 'POST',
            dataType: 'json',
            beforeSend: load_in_new(),
            success: function (data) {
                if(data[0].type === 'ok'){
                    $(".load_retorno_download_zip").html(data.button);
                }else{
                    $(".load_retorno_download_zip").html(data[0].message);
                }
                load_out_new();
            },
            error: function (request, status, error) {
                load_out_new();
            }
        });
        return false;
    }

    function danfe_xml(){
        var idDoc = $(".ide_nfs_danfe_zip").val();
        var Data = "&action=search_doc_nfse&id_doc="+idDoc;
        $.ajax({
            url: "<?= $router->route("doc_nfse.danfe"); ?>",
            data: Data,
            type: 'POST',
            dataType: 'json',
            beforeSend: load_in_new(),
            success: function (data) {
                if(data[0].type === 'ok'){
                    $(".load_retorno_danfe_zip").html(data.button);
                }else{
                    $(".load_retorno_danfe_zip").html(data[0].message);
                }
                load_out_new();
            },
            error: function (request, status, error) {
                load_out_new();
            }
        });
        return false;
    }
    function link_search(){
        var Data = "&action=search_company";
        $.ajax({
            url: "<?= $router->route("doc_nfse.searchDoc"); ?>",
            data: Data,
            type: 'POST',
            dataType: 'json',
            beforeSend: load_in(),
            success: function (data) {
                if(data[0].type === 'error'){
                    notify(data[0].title, data[0].message);
                    load_out();
                }else{
                    notify(data[0].title, data[0].message);
                    load_out();
                }
            },
            error: function (request, status, error) {
                load_out();
            }
        });
        return false;
    }
    $('.modal-dialog').draggable({
        handle: ".modal-header"
    });
    $(function(){
        load_search();
    });
</script>
