function botaoOutrasOpcoes(btnOpcao) {
    for (let i = 0; i < btnOpcao.length; i++) {
        btnOpcao[i].addEventListener("click", function () {
            for (let j = 0; j < btnOpcao.length; j++) {
                btnOpcao[j].classList.remove("botao-activo");
            }
            btnOpcao[i].classList.add("botao-activo");
        });
    }
}

function insertLinhaDocumento(id, success, error, done) {
    $.ajax({
        url: "includes/read/queryDocumento.inc.php",
        type: "post",
        dataType: "json",
        data: {
            idDocumento: id,
        },
        success: function (data) {
            success(data);
        },
        error: function (data) {
            error(data);
        }
    }).done(function (data) {
        done(data);
    });
}

function funcaoReadModoPagamento(success, error, done) {
    $.ajax({
        url: "includes/read/modoPagamento.inc.php",
        type: "post",
        dataType: "json",
        success: function (data) {
            success(data);
        },
        error: function (data) {
            error(data);
        }
    }).done(function (data) {
        done(data);
    });
}

function funcaoQueryEntidade(id, tipoEntidade, success, error, done) {
    $.ajax({
        url: "includes/read/searchEntidade.inc.php",
        type: "post",
        dataType: "json",
        data: {
            idEntidade: id,
            idTipoEntidade: tipoEntidade
        },
        success: function (data) {
            success(data);
        },
        error: function (data) {
            error(data);
        }
    }).done(function (data) {
        done(data);
    });
}

function createDoc(idUsuario, idTipoDoc, idEntidade, idPrazoPagamento, entregue, total, troco, totalLiquido, totalImposto, descontoGlobal, success, error, done) {
    $.ajax({
        url: "includes/create/doc.inc.php",
        type: "post",
        dataType: "json",
        data: {
            idUsuario: idUsuario,
            idTipoDoc: idTipoDoc,
            idEntidade: idEntidade,
            idPrazoPagamento: idPrazoPagamento,
            entregue: entregue,
            total: total,
            troco: troco,
            totalLiquido: totalLiquido,
            totalImposto: totalImposto,
            descontoGlobal: descontoGlobal == "" ? 0 : descontoGlobal
        },
        success: function (data) {
            success(data);
        },
        error: function (data) {
            error(data);
        }
    }).done(function (data) {
        done(data);
    });
}

function createArtigoDocumento(idDocumento, idArtigo, descricao, qtd, preco, desconto, idImposto, imposto, total, success, error, done) {
    $.ajax({
        url: "includes/create/artigoDocumento.inc.php",
        type: "post",
        dataType: "json",
        data: {
            idDocumento: idDocumento,
            idArtigo: idArtigo,
            descricao: descricao,
            qtd: qtd,
            preco: preco,
            desconto: desconto,
            idImposto: idImposto,
            imposto: imposto,
            total: total,
        },
        success: function (data) {
            success(data);
        },
        error: function (data) {
            error(data);
        }
    }).done(function (data) {
        done(data);
    });
}

function createModoPagamento(idModoPagamento, idDocumento, valor, success, error, done) {
    $.ajax({
        url: "includes/create/modoPagamentoDocumento.inc.php",
        type: "post",
        dataType: "json",
        data: {
            idModoPagamento: idModoPagamento,
            idDocumento: idDocumento,
            valor: valor,
        },
        success: function (data) {
            success(data);
        },
        error: function (data) {
            error(data);
        }
    }).done(function (data) {
        done(data);
    });
}

function sumModoPagamento(modoPagamento, entregueSpan, totalSpan, totalText, totalEntregue, totalDocumento) {
    let all = 0;
    for (let i = 0; i < modoPagamento.length; i++) {
        if (modoPagamento[i].value != "") {
            all += parseFloat(modoPagamento[i].value.replace(/\ /g, '').replace(/\,/g, '.'));
        }
    }
    entregueSpan.innerText = parseFloat(all);
    entregueSpan.innerText = parseFloat(entregueSpan.innerText.replace(/\ /g, '').replace(/\,/g, '.')).toFixed(2).replace(/\ /g, '').replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ") + " Kzs";
    if (parseFloat(entregueSpan.innerText.replace(/\ /g, '').replace(/\,/g, '.')) < totalDocumento) {
        totalText.innerText = "VALOR PENDENTE";
        totalText.className = "text-danger";
        totalSpan.className = "text-danger";
        totalSpan.innerText = totalDocumento - parseFloat(entregueSpan.innerText.replace(/\ /g, '').replace(/\,/g, '.'));
        totalSpan.innerText = parseFloat(totalSpan.innerText.replace(/\ /g, '').replace(/\,/g, '.')).toFixed(2).replace(/\ /g, '').replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ") + " Kzs";
        recalcular();
    } else if (parseFloat(entregueSpan.innerText.replace(/\ /g, '').replace(/\,/g, '.')) == totalDocumento && parseFloat(entregueSpan.innerText.replace(/\ /g, '').replace(/\,/g, '.')) != 0) {
        entregueSpan.className = "";
        totalEntregue.className = "";
        totalEntregue.innerText = "ENTREGUE";
        totalText.innerText = "SEM TROCO";
        totalText.className = "text-success";
        totalSpan.className = "text-success";
        totalSpan.innerText = totalDocumento - parseFloat(entregueSpan.innerText.replace(/\ /g, '').replace(/\,/g, '.'));
        totalSpan.innerText = parseFloat(totalSpan.innerText.replace(/\ /g, '').replace(/\,/g, '.')).toFixed(2).replace(/\ /g, '').replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ") + " Kzs";
        recalcular();
    } else if (parseFloat(entregueSpan.innerText.replace(/\ /g, '').replace(/\,/g, '.')) > totalDocumento) {
        entregueSpan.className = "";
        totalEntregue.className = "";
        totalEntregue.innerText = "ENTREGUE";
        totalText.innerText = "TROCO";
        totalText.className = "text-success";
        totalSpan.className = "text-success";
        totalSpan.innerText = parseFloat(entregueSpan.innerText.replace(/\ /g, '').replace(/\,/g, '.')) - totalDocumento;
        totalSpan.innerText = parseFloat(totalSpan.innerText.replace(/\ /g, '').replace(/\,/g, '.')).toFixed(2).replace(/\ /g, '').replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ") + " Kzs";
    }
    recalcular();
}

function recalcular() {
    let total = 0;
    let tabela = document.getElementById("tabelaArtigo");
    for (i = 1; i < tabela.rows.length; i++) {
        if (tabela.rows[i].querySelector('.total').value != "") {
            total += parseFloat(tabela.rows[i].querySelector('.total').value.replace(/\ /g, '').replace(/\,/g, '.'));
        }
    }
}

function funcaoQueryArtigo(id, linhaPreco, success, error, done) {
    $.ajax({
        url: "includes/read/queryArtigoList.inc.php",
        type: "post",
        dataType: "json",
        data: {
            idArtigo: id,
            linhaPreco: linhaPreco
        },
        success: function (data) {
            success(data);
        },
        error: function (data) {
            error(data);
        }
    }).done(function (data) {
        done(data);
    });
}

function funcaoQueryImposto(id, success, error, done) {
    $.ajax({
        url: "includes/read/queryImposto.inc.php",
        type: "post",
        dataType: "json",
        data: {
            idImposto: id
        },
        success: function (data) {
            success(data);
        },
        error: function (data) {
            error(data);
        }
    }).done(function (data) {
        done(data);
    });
}

function outrasOpcoes(total, preco, qtd, desconto, imposto, opcaoTotalBruto, opcaoDescontoLinha, opcaoTotalLiquido, opcaoTotalImposto, opcaoTotalDocumento, opcaoValorPagar, arredondamento, descontoGlobalValor, descontoGlobalPorcentagem, impostoOpcao, impostoOpcaoTr) {
    let totalOpcao = 0;
    let descontoOpcao = 0;
    let totalLiquidoOpcao = 0;
    let totalImpostoOpcao = 0;

    for (let i = 0; i < total.length; i++) {
        if (total[i].value != "") {
            totalOpcao += (parseFloat(preco[i].value.replace(/\ /g, '').replace(/\,/g, '.')) * parseFloat(qtd[i].value.replace(/\ /g, '').replace(/\,/g, '.')));

            totalLiquidoOpcao += parseFloat(total[i].value.replace(/\ /g, '').replace(/\,/g, '.'));

            totalImpostoOpcao += (parseFloat(total[i].value.replace(/\ /g, '').replace(/\,/g, '.')) * (parseFloat(imposto[i].value.replace(/\ /g, '').replace(/\,/g, '.')) / 100));
        }

        if (total[i].value != "" && preco[i].value != "") {
            descontoOpcao += ((parseFloat(preco[i].value.replace(/\ /g, '').replace(/\,/g, '.')) * parseFloat(qtd[i].value.replace(/\ /g, '').replace(/\,/g, '.'))) - parseFloat(total[i].value.replace(/\ /g, '').replace(/\,/g, '.')));
        }
    }
    opcaoTotalBruto.innerText = parseFloat(totalOpcao).toFixed(2).replace(/\ /g, '').replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ");
    opcaoDescontoLinha.innerText = parseFloat(descontoOpcao).toFixed(2).replace(/\ /g, '').replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ");
    opcaoTotalLiquido.innerText = parseFloat(totalLiquidoOpcao).toFixed(2).replace(/\ /g, '').replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ");
    opcaoTotalImposto.innerText = parseFloat(totalImpostoOpcao).toFixed(2).replace(/\ /g, '').replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ");
    opcaoTotalDocumento.innerText = (parseFloat(totalLiquidoOpcao) + parseFloat(totalImpostoOpcao)).toFixed(2).replace(/\ /g, '').replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ");

    let dados = "";
    let tabela = document.getElementById("tabelaArtigo");

    for (i = 1; i < tabela.rows.length; i++) {
        if (tabela.rows[i].querySelector('.inputSearchArtigo').value != "") {
            dados += `
        <tr>
          <td class="tdTaxa"><small>${parseFloat(tabela.rows[i].querySelector('.imposto').value).toFixed(2).replace(/\ /g, '').replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ") + "%"}</small></td>
          <td class="tdIncidencia"><small>${parseFloat(tabela.rows[i].querySelector('.total').value.replace(/\ /g, '').replace(/\,/g, '.')).toFixed(2).replace(/\ /g, '').replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ")}</small></td>
          <td class="tdImposto"><small>${(parseFloat(tabela.rows[i].querySelector('.total').value.replace(/\ /g, '').replace(/\,/g, '.')) * (parseFloat(tabela.rows[i].querySelector('.imposto').value.replace(/\ /g, '').replace(/\,/g, '.')) / 100)).toFixed(2).replace(/\ /g, '').replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ")}</small></td>
          <td class="tdValor"><small>${(parseFloat(tabela.rows[i].querySelector('.total').value.replace(/\ /g, '').replace(/\,/g, '.')) + (parseFloat(tabela.rows[i].querySelector('.total').value.replace(/\ /g, '').replace(/\,/g, '.')) * (parseFloat(tabela.rows[i].querySelector('.imposto').value.replace(/\ /g, '').replace(/\,/g, '.')) / 100))).toFixed(2).replace(/\ /g, '').replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ")}</small></td>
        </tr>
      `;
        }
    }
    $("#impostoOpcao").html(dados);

    let taxaSet = new Set();

    for (let i = 0; i < $("#impostoOpcao tr").length; i++) {
        let td = $("#impostoOpcao tr")[i].querySelector('.tdTaxa');
        let tr = $("#impostoOpcao tr")[i];

        if (taxaSet.has(td.innerText)) {
            let incidenciaAtual = parseFloat(tr.querySelector('.tdIncidencia').innerText.replace(/\ /g, '').replace(/\,/g, '.'));
            let novoValorIncidencia = incidenciaAtual + parseFloat(td.parentElement.querySelector('.tdIncidencia').innerText.replace(/\ /g, '').replace(/\,/g, '.'));
            tr.querySelector('.tdIncidencia').innerHTML = `<small>${novoValorIncidencia.toFixed(2)}</small>`;
            td.parentElement.remove();
        } else {
            taxaSet.add(td.innerText);
        }
    }

    opcaoValorPagar.innerText = (parseFloat(totalLiquidoOpcao) + parseFloat(totalImpostoOpcao)).toFixed(2).replace(/\ /g, '').replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ");

    $(document).on('keyup', arredondamento, function (e) {
        if (arredondamento.value != "") {
            opcaoValorPagar.innerText = (parseFloat(totalLiquidoOpcao) + parseFloat(totalImpostoOpcao) + parseFloat(arredondamento.value.replace(/\ /g, '').replace(/\,/g, '.'))).toFixed(2).replace(/\ /g, '').replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ");
        } else {
            opcaoValorPagar.innerText = (parseFloat(totalLiquidoOpcao) + parseFloat(totalImpostoOpcao)).toFixed(2).replace(/\ /g, '').replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ");
        }
    });

    $(document).on('keyup', descontoGlobalValor, function (e) {
        if (descontoGlobalValor.value != "") {
            opcaoTotalLiquido.innerText = (parseFloat(totalLiquidoOpcao) - parseFloat(descontoGlobalValor.value.replace(/\ /g, '').replace(/\,/g, '.'))).toFixed(2).replace(/\ /g, '').replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ");

            descontoGlobalPorcentagem.value = ((parseFloat(descontoGlobalValor.value.replace(/\ /g, '').replace(/\,/g, '.')) / parseFloat(totalOpcao)) * 100).toFixed(2).replace(/\ /g, '').replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ");
        }
    });

    $(document).on('keyup', descontoGlobalPorcentagem, function (e) {
        if (descontoGlobalPorcentagem.value != "") {
            opcaoTotalLiquido.innerText = (parseFloat(totalLiquidoOpcao) - parseFloat(descontoGlobalPorcentagem.value.replace(/\ /g, '').replace(/\,/g, '.'))).toFixed(2).replace(/\ /g, '').replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ");

            descontoGlobalValor.value = ((parseFloat(descontoGlobalPorcentagem.value.replace(/\ /g, '').replace(/\,/g, '.')) / 100) * parseFloat(totalOpcao)).toFixed(2).replace(/\ /g, '').replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ");
        }
    });
}

function funcaoReadCodigoTaxa(success, error, done) {
    $.ajax({
        url: "includes/read/codigoTaxa.inc.php",
        type: "post",
        dataType: "json",
        success: function (data) {
            success(data);
        },
        error: function (data) {
            error(data);
        }
    }).done(function (data) {
        done(data);
    });
}

function funcaoReadTipoTaxa(success, error, done) {
    $.ajax({
        url: "includes/read/tipoTaxa.inc.php",
        type: "post",
        dataType: "json",
        success: function (data) {
            success(data);
        },
        error: function (data) {
            error(data);
        }
    }).done(function (data) {
        done(data);
    });
}

function funcaoReadRegiao(success, error, done) {
    $.ajax({
        url: "includes/read/regiao.inc.php",
        type: "post",
        dataType: "json",
        success: function (data) {
            success(data);
        },
        error: function (data) {
            error(data);
        }
    }).done(function (data) {
        done(data);
    });
}

function funcaoReadTaxa(success, error, done) {
    $.ajax({
        url: "includes/read/taxa.inc.php",
        type: "post",
        dataType: "json",
        success: function (data) {
            success(data);
        },
        error: function (data) {
            error(data);
        }
    }).done(function (data) {
        done(data);
    });
}

function funcaoReadTaxaEstado(estado, success, error, done) {
    $.ajax({
        url: "includes/read/taxaEstado.inc.php",
        type: "post",
        dataType: "json",
        data: {
            estado: estado
        },
        success: function (data) {
            success(data);
        },
        error: function (data) {
            error(data);
        }
    }).done(function (data) {
        done(data);
    });
}

function funcaoReadPais(success, error, done) {
    $.ajax({
        url: "includes/read/pais.inc.php",
        type: "post",
        dataType: "json",
        success: function (data) {
            success(data);
        },
        error: function (data) {
            error(data);
        }
    }).done(function (data) {
        done(data);
    });
}

let urlToFile = (url) => {
    let arr = url.split(",");
    let mime = arr[0].match(/:(.*?);/)[1];
    let data = arr[1];

    let dataString = atob(data);
    let n = dataString.length;
    let dataArr = new Uint8Array(n);
    while (n--) {
        dataArr[n] = dataString.charCodeAt(n);
    }
    let file = new File([dataArr], 'File.jpg', {
        type: mime
    });
    return file;
}

function resizeImagem(imagem, containerImagem) {
    imagem.addEventListener("change", function () {
        const reader = new FileReader();
        reader.addEventListener("load", () => {
            const imgElement = document.createElement("img");
            imgElement.src = reader.result;
            imgElement.onload = function (e) {
                const canvas = document.createElement("canvas");
                const MAX_WIDTH = 400;
                const scaleSize = MAX_WIDTH / e.target.width;
                canvas.width = MAX_WIDTH;
                canvas.height = e.target.height * scaleSize;
                const ctx = canvas.getContext("2d");
                ctx.drawImage(e.target, 0, 0, canvas.width, canvas.height);

                const srcEncoded = ctx.canvas.toDataURL(e.target, "image/jpeg");
                resizedImage = urlToFile(srcEncoded);
            }

            const uploaded_image = reader.result;
            containerImagem.style.backgroundImage = `url(${uploaded_image})`;
        });
        reader.readAsDataURL(this.files[0]);
        containerImagem.querySelector("i").style.display = "none";
    });
}

function linhaSelecionada(tabela, btn) {
    $(document).on('click', '#' + tabela + ' tbody tr', function () {
        var isSelected = $(this).hasClass('selected');
        $('#' + tabela + ' tbody tr').removeClass('selected');
        if (!isSelected) {
            $(this).addClass('selected');
            btn.removeAttribute("disabled");
        } else {
            btn.setAttribute("disabled", "disabled");
            btn.classList.remove("botao-activo");
        }
    });
}

function funcaoQueryObjecto(parametro, id, url, success, error, done) {
    var requestData = {};
    if (Array.isArray(parametro)) {
        for (let i = 0; i < parametro.length; i++){
            requestData[parametro[i]] = id[i];
        }
    } else {
        requestData[parametro] = id;
    }
    $.ajax({
        url: url,
        type: "post",
        dataType: "json",
        data: requestData,
        success: function (data) {
            success(data);
        },
        error: function (data) {
            error(data);
        }
    }).done(function (data) {
        done(data);
    });
}

function funcaoGetTabela(url, success, error, done) {
    $.ajax({
        url: url,
        type: "post",
        dataType: "json",
        success: function (data) {
            success(data);
        },
        error: function (data) {
            error(data);
        }
    }).done(function (data) {
        done(data);
    });
}