﻿//#region [Modal Importar NFe]
$('#modalImportarNFe').on('hide.bs.modal', (e) => {
    $('#formImportarNFe')[0].reset();
});
//#endregion
//#region [Modal Produto]
$.fn.adicionarProduto = async (produto) => await Swal.fire({
    html: `<div> 
                    <h2>Adição de Produto</h2> 
                    <table class="table"> 
                      <tbody>
                        <tr>
                          <th scope="row" width="25%" class="text-right">Descrição</th>
                          <td width="75%" class="text-left">${produto.response.ds_Descricao}</td>
                        </tr>
                        <tr>
                          <th scope="row" width="25%" class="text-right">Codigo</th>
                          <td width="75%" class="text-left">${produto.response.cd_Produto}</td>
                        </tr>
                        <tr>
                          <th scope="row" width="25%" class="text-right">Codigo Cliente</th>
                          <td width="75%" class="text-left">${(produto.response.cd_ProdutoCliente == null ? "Não Cadastrado" : produto.response.cd_ProdutoCliente)}</td> 
                        </tr>
                        <tr>
                          <th scope="row" width="25%" class="text-right">Fornecedor</th>
                          <td width="75%" class="text-left">${produto.response.pessoaFornecedor.ds_NomeRazaoSocial}</td>
                        </tr>
                        <tr>
                          <th scope="row" width="25%" class="text-right">CNPJ</th>
                          <td width="75%" class="text-left">${FormataCpfCnpj(produto.response.pessoaFornecedor.cd_CpfCnpj)}</td>
                        </tr>
                      </tbody>
                    </table>
             </div>
`,
    showClass: {
        popup: 'animate__animated animate__zoomIn'
    },
    hideClass: {
        popup: 'animate__animated animate__zoomOut'
    },
    customClass: {
        confirmButton: 'btn waves-effect waves-light btn-outline-primary float-right',
        cancelButton: 'btn waves-effect waves-light btn-outline-secondary float-left',
        actions: 'd-flex justify-content-between px-4 mx-1 mt-4',
        popup: 'swal-size',
        title: 'pt-4',
    },
    buttonsStyling: false,
    allowOutsideClick: false,
    allowEscapeKey: false,
    allowEnterKey: false,
    showCancelButton: true,
    confirmButtonText: 'Sim',
    cancelButtonText: 'Não',
    reverseButtons: true,
    showLoaderOnConfirm: false
}).then((result) => {
    return result.isConfirmed;
})
//#endregion
//#region [Modal Produto Duplicado]
$.fn.produtoDuplicado = async (produto) => await Swal.fire({
    title: `Adição de Produto`,
    text: `O Produto já foi adicionado anteriormente, deseja prosseguir?`,
    showClass: {
        popup: 'animate__animated animate__zoomIn'
    },
    hideClass: {
        popup: 'animate__animated animate__zoomOut'
    },
    customClass: {
        confirmButton: 'btn waves-effect waves-light btn-outline-primary float-right',
        cancelButton: 'btn waves-effect waves-light btn-outline-secondary float-left',
        actions: 'd-flex justify-content-between px-4 mx-1 mt-4',
        title: 'pt-4',
    },
    buttonsStyling: false,
    allowOutsideClick: false,
    allowEscapeKey: false,
    allowEnterKey: false,
    showCancelButton: true,
    confirmButtonText: 'Sim',
    cancelButtonText: 'Não',
    reverseButtons: true,
    showLoaderOnConfirm: false
}).then((result) => {
    return result.isConfirmed;
})
//#endregion
//#region [Modal Deletar Produto]
$.fn.deletarProduto = () => $('[data-deletar-produto]').click(async (e) => {
    var produto, _idx;
    tabelaProdutos.rows((idx, data, node) => {
        if (data.id_Row == e.target.dataset.idRow) {
            produto = data;
            _idx = idx;
        }
    })
    let result = await Swal.fire({
        title: `Remover Produto`,
        html: `Realmente deseja remover o Produto abaixo:<br />${produto.ds_Descricao}<br /><strong>Fornecedor: </strong>${produto.ds_NomeFornecedor}<br />
               <br /><br />`,
        iconHtml: '<i class="animated pulse infinite text-warning fa-duotone fa-user-slash"></i>',
        iconColor: '#fec107',
        customClass: {
            confirmButton: 'btn waves-effect waves-light btn-outline-primary',
            cancelButton: 'btn waves-effect waves-light btn-outline-danger'
        },
        buttonsStyling: false,
        allowOutsideClick: false,
        allowEscapeKey: false,
        allowEnterKey: false,
        showCancelButton: true,
        confirmButtonText: 'Sim',
        cancelButtonText: 'Não',
        reverseButtons: true
    }).then((result) => {
        return result.isConfirmed
    })
    if (result) {
        tabelaProdutos.rows(_idx).remove().draw();
    }
});
//#endregion
//#region [Modal Lotes]
$('#modalLotes')
    .on('show.bs.modal', function (b, event) {
        if (b.target.nodeName == 'INPUT')
            return;

        var produto, _idx;
        tabelaProdutos.rows((idx, data, node) => {
            if (data.id_Row == b.relatedTarget.dataset.idRow) {
                produto = data;
                _idx = idx;
            }
        });

        Object.keys(produto).map((c, i, a) => {
            $(b.currentTarget).find(`[name="${c}"]`).val(produto[c]).text(produto[c]);
        });

        $(`input[name="id_RowProduto"]`, $(this)).val(produto.id_Row);
        $(`span[name="cd_ProdutoFabricante"]`, $(this)).text(produto.cd_ProdutoFornecedor);
        $(`span[name="cd_ProdutoCliente"]`, $(this)).text(produto.cd_ProdutoCliente);
        $(`span[name="ds_ProdutoDescricao"]`, $(this)).text(produto.ds_Descricao);
        tabelaLotes.clear();
        tabelaLotes.rows.add(produto.lotes).draw();


    })
    .on('hide.bs.modal', function (b, event) {
        if (b.target.nodeName == 'INPUT')
            return;
        let linha = {};
        $(b.currentTarget).find('input').map((i, c) => {
            linha[c.name] = c.value
            c.value = '';
            c.text = '';
        });
        
        //let produtos = tabelaProdutos.rows().data().reduce(function(array,produto){
        //    let lotes = tabelaLotes.rows().data().filter(lote => lote.id_RowProduto === produto.id_Row);
        //    if(lotes.length === 0){
        //        array.push(produto);
        //        return array;
        //    }

            
        //    produto.qt_Produto = lotes.reduce(function(valor,lote){
        //        valor += parseFloat(lote.qt_Lote.replace(',','-').replace('.','').replace('-','.'));
        //        return valor;
        //    },0.0);
            
        //    produto.lotes = lotes.reduce(function(array,lote){
        //        if(lote.id_RowProduto === produto.id_Row){
        //            array.push(lote);
        //        }
        //        return array;
        //    },[]);

        //    array.push(produto);
        //    return array;
        //},[]);
        
        
    
        //tabelaProdutos.clear().draw();
        //tabelaProdutos.rows.add(produtos).draw();
        //tabelaLotes.clear().draw();


        $(`[span ="cd_ProdutoFabricante"]`, $(this)).text('');
        $(`[span ="cd_ProdutoCliente"]`, $(this)).text('');
        $(`[span ="cd_ProdutoDescricao"]`, $(this)).text('');

    });
$('#modalRateioLote')
    .on('show.bs.modal', function (b, event) {
        $('#modalLotes').addClass('d-none')
        if (b.target.nodeName == 'INPUT')
            return;
        var lote, _idx;
        tabelaLotes.rows((idx, data, node) => {
            if (data.id_Row == b.relatedTarget.dataset.idRow) {
                lote = data;
                _idx = idx;
            }
        });

        Object.keys(lote).map((c, i, a) => {
            $(b.currentTarget).find(`[name="${c}"]`).val(lote[c]).text(lote[c]);
        });

        let qtLote = 0, qtTotalRateio = 0;
        tabelaLotes.rows((idx, data, node) => {
            if (data.id_Row == b.relatedTarget.dataset.idRow) {
                qtLote += parseInt(data.qt_Lote.replace('.', '').replace(',', '.'));
            }
        });
        tabelaRateioLote.rows((idx, data, node) => {
            qtTotalRateio += data.qt_LoteRateio;
        });
        var resta = qtLote - qtTotalRateio;


        $(`span[name="cd_LoteRateio"]`, $(this)).text(lote.cd_Lote);
        $(`span[name="qt_Lote"]`, $(this)).text(parseInt(lote.qt_Lote.toString().replace('.', '').replace(',', '.')));
        $(`span[name="qt_LoteRestante"]`, $(this)).text(resta);
        $(`input[name="id_RowLote"]`, $(this)).val(b.relatedTarget.dataset.idRow);
        tabelaRateioLote.clear();
        if (lote.rateio)
        tabelaRateioLote.rows.add(lote.rateio).draw();


    })
    .on('hide.bs.modal', function (b, event) {
        $('#modalLotes').removeClass('d-none')
        var lotes = [];
        var id_RowLote = $('input[name="id_RowLote"]').val(); 
        //Salva Rateio!
        tabelaLotes.rows((idx, data, node) => {
            if (data.id_Row === id_RowLote)
                data.rateio = tabelaRateioLote.data().toArray();
            lotes.push(data);
        });
        tabelaLotes.clear().draw();
        tabelaLotes.rows.add(lotes).draw();
        tabelaRateioLote.clear().draw();

        $(`span[name="cd_LoteRateio"]`, $(this)).text('');
        $(`span[name="qt_Lote"]`, $(this)).text('');
        $(`span[name="qt_LoteRestante"]`, $(this)).text('');
        $(`input[name="id_RowLote"]`, $(this)).val('');
        $('#formRateioLote')[0].reset();
    });
//#endregion
//#region [Modal Deletar Documento]
$.fn.deletarDocumento = () => $('[data-deletar-documento]').click(async (e) => {
    var documento, _idx;
    tabelaDocumentos.rows((idx, data, node) => {
        if (data.id_Documento == e.target.dataset.idDocumento) {
            documento = data;
            _idx = idx;
        }
    })
    let result = await Swal.fire({
        title: `Remover Documento`,
        html: `Realmente deseja remover o Lote abaixo:<br />Nº ${documento.nr_Documento}-${documento.nr_Serie}`,
        iconHtml: '<i class="animated pulse infinite text-warning fa-duotone fa-user-slash"></i>',
        iconColor: '#fec107',
        customClass: {
            confirmButton: 'btn waves-effect waves-light btn-outline-primary',
            cancelButton: 'btn waves-effect waves-light btn-outline-danger'
        },
        buttonsStyling: false,
        allowOutsideClick: false,
        allowEscapeKey: false,
        allowEnterKey: false,
        showCancelButton: true,
        confirmButtonText: 'Sim',
        cancelButtonText: 'Não',
        reverseButtons: true
    }).then((result) => {
        return result.isConfirmed
    })
    if (result) {
        tabelaDocumentos.rows(_idx).remove().draw();
    }
});
//#endregion
//#region [Modal Deletar Notificação]
$.fn.deletarNotificacao = () => $('[data-deletar-notificacao]').click(async (e) => {
    var contato, _idx;
    tabelaNotificacoes.rows((idx, data, node) => {
        if (data.id_Row == e.target.dataset.idRow) {
            contato = data;
            _idx = idx;
        }
    })
    let result = await Swal.fire({
        title: `Remover Contato`,
        html: `Realmente deseja remover o Contato abaixo:<br />${lote.ds_Nome} ${lote.ds_Sobrenome}`,
        iconHtml: '<i class="animated pulse infinite text-warning fa-duotone fa-user-slash"></i>',
        iconColor: '#fec107',
        customClass: {
            confirmButton: 'btn waves-effect waves-light btn-outline-primary',
            cancelButton: 'btn waves-effect waves-light btn-outline-danger'
        },
        buttonsStyling: false,
        allowOutsideClick: false,
        allowEscapeKey: false,
        allowEnterKey: false,
        showCancelButton: true,
        confirmButtonText: 'Sim',
        cancelButtonText: 'Não',
        reverseButtons: true
    }).then((result) => {
        return result.isConfirmed
    })
    if (result) {
        contato.rows(_idx).remove().draw();
    }
});
//#endregion


//#region [Modal Editar Lote]
$.fn.editarLote = () => $('[data-editar-lote]').click((e) => {
    var lote, _idx;
    tabelaLotes.rows((idx, data, node) => {
        if (data.id_Row == e.target.dataset.idRow) {
            lote = data;
            _idx = idx;
        }
    })
    tabelaLotes.rows(_idx).remove().draw();
    $('#divFormLote').find('input').map((i, c, a) => { 
        c.value = Object(lote)[`${c.name}`]
    })
    setTimeout(() => {
        var data = tabelaLotes.data().toArray();
        tabelaLotes.clear().rows.add(data).draw();
    }, 100)
});
//#endregion
//#region [Modal Deletar Lote]
$.fn.deletarLote = () => $('[data-deletar-lote]').click(async (e) => {
    var lote, _idx;
    tabelaLotes.rows((idx, data, node) => {
        if (data.id_Row == e.target.dataset.idRow) {
            lote = data;
            _idx = idx;
        }
    })
    let result = await Swal.fire({
        title: `Remover Lote`,
        html: `Realmente deseja remover o Lote abaixo:<br />${lote.cd_Lote}`,
        iconHtml: '<i class="animated pulse infinite text-warning fa-duotone fa-user-slash"></i>',
        iconColor: '#fec107',
        customClass: {
            confirmButton: 'btn waves-effect waves-light btn-outline-primary',
            cancelButton: 'btn waves-effect waves-light btn-outline-danger'
        },
        buttonsStyling: false,
        allowOutsideClick: false,
        allowEscapeKey: false,
        allowEnterKey: false,
        showCancelButton: true,
        confirmButtonText: 'Sim',
        cancelButtonText: 'Não',
        reverseButtons: true
    }).then((result) => {
        return result.isConfirmed
    })
    if (result) {
        tabelaLotes.rows(_idx).remove().draw();
    }
});
//#endregion




//#region [Consolidar Produto]
//$.fn.consolidarProdutos = async () => {
//    var produto, _idx;

//    let result = await Swal.fire({
//        title: `Consolidação de Produtos`,
//        html: `Deseja Realmente Consolidar Produtos com mesmo código e Valor Unitário??
//               <br /><br />`,
//        iconHtml: '<i class="animated pulse infinite text-info fa-duotone fa-boxes-stacked"></i>',
//        iconColor: '#03a9f3',
//        customClass: {
//            confirmButton: 'btn waves-effect waves-light btn-outline-primary',
//            cancelButton: 'btn waves-effect waves-light btn-outline-secondary'
//        },
//        buttonsStyling: false,
//        allowOutsideClick: false,
//        allowEscapeKey: false,
//        allowEnterKey: false,
//        showCancelButton: true,
//        confirmButtonText: 'Sim',
//        cancelButtonText: 'Não',
//        reverseButtons: true
//    }).then((result) => {
//        return result.isConfirmed
//    })
//    if (result) {
//        for (var i = 0; i <= tabelaProdutos.rows().count(); i++) {
//            $data = tabelaProdutos.row(i).data(); $idata = {}
//            for (var ii = 0; ii <= tabelaProdutos.rows().count(); ii++) {
//                idata = tabelaProdutos.row(ii).data();
//                if (idata)
//                    if ($data.id_Row != idata.id_Row && $data.id_Produto == idata.id_Produto && $data.cd_ProdutoCliente == idata.cd_ProdutoCliente && $data.vl_Produto == idata.vl_Produto) {
//                        idata.lotes.map((lc, li, la) => {
//                            $data.lotes.push(lc);
//                        });
//                        $data.qt_Produto = (parseFloat($data.qt_Produto.replace(',', '.')) + parseFloat(idata.qt_Produto.replace(',', '.'))).toFixed(2).replace('.', ',');
//                        tabelaProdutos.row(ii).remove().draw();
//                    }
//            }
//            tabelaProdutos.draw(true);
//        }
//        var data = tabelaProdutos.data().toArray();
//        tabelaProdutos.clear().rows.add(data).draw(true);
//    }
//};
$.fn.consolidarProdutos = async () => {
    let result = await Swal.fire({
        title: `Consolidação de Produtos`,
        html: `Deseja realmente consolidar produtos com o mesmo código e valor unitário? <br /><br />`,
        iconHtml: '<i class="animated pulse infinite text-info fa-duotone fa-boxes-stacked"></i>',
        iconColor: '#03a9f3',
        customClass: {
            confirmButton: 'btn waves-effect waves-light btn-outline-primary',
            cancelButton: 'btn waves-effect waves-light btn-outline-secondary'
        },
        buttonsStyling: false,
        allowOutsideClick: false,
        allowEscapeKey: false,
        allowEnterKey: false,
        showCancelButton: true,
        confirmButtonText: 'Sim',
        cancelButtonText: 'Não',
        reverseButtons: true
    });

    if (result.isConfirmed) {
        let numberOfRows = tabelaProdutos.rows().count();

        for (let i = 0; i < numberOfRows; i++) {
            const data = tabelaProdutos.row(i).data();
            for (let j = i + 1; j < numberOfRows; j++) {
                let innerData = tabelaProdutos.row(j).data();

                if (innerData && data.id_Row != innerData.id_Row && data.id_Produto == innerData.id_Produto && data.cd_ProdutoCliente == innerData.cd_ProdutoCliente && data.vl_Produto == innerData.vl_Produto) {
                    innerData.lotes.forEach((lc) => {
                        lc.id_RowProduto = data.id_Row
                        data.lotes.push(lc);
                    });

                    data.qt_Produto = (parseFloat(data.qt_Produto.replace(',', '.')) + parseFloat(innerData.qt_Produto.replace(',', '.'))).toFixed(2).replace('.', ',');

                    tabelaProdutos.row(j).remove();
                    j--;
                    numberOfRows--;
                }
            }
        }
        tabelaProdutos.draw(true);
        const consolidatedData = tabelaProdutos.data().toArray();
        tabelaProdutos.clear().rows.add(consolidatedData).draw(true);
    }
};

//#endregion