/****************************************************************************************
 *  FLUIG - DESLIGAMENTO DO COLABORADOR
 *  SCRIPT PRINCIPAL ORGANIZADO
 ****************************************************************************************/

$(window).on("load", function () {
    setTimeout(() => {
        iniciarFormulario();
    }, 400);
});

/****************************************************************************************
 *  INICIALIZAÇÃO DO FORMULÁRIO
 ****************************************************************************************/
function iniciarFormulario() {

    const activity = parseInt($("#activity").val() || 0);
    const formMode = $("#formMode").val() || "ADD";
    const requestDate = getCurrentDate();

    $(".activity").hide(); // Oculta todas por padrão

    if (formMode === "VIEW") {
        $(".activity").show();
        showAndBlock(["all"]);
        return;
    }

    if ([0, 4].includes(activity)) {
        $(".activity-4").show();
        $("#requesterName").val($("#requesterName").val() || $("#currentUserName").val());
        $("#emailGestorArea").val($("#requesterMail").val() || $("#currentUsermail").val());
        $("#dataAbertura").val(`${requestDate[0]} - ${requestDate[1]}`);
    }

    if (activity === 51) {
        $(".activity-4, .activity-51").show();
        showAndBlock([4]);
        $("#userAprova").val($("#currentUserName").val());
        $("#dataUserAprova").val(`${requestDate[0]} - ${requestDate[1]}`);
    }

    if (activity === 20) {
        $(".activity-4, .activity-20").show();
        showAndBlock([4, 51]);
        $("#userAprov").val($("#currentUserName").val());
        $("#dataUserAprov").val(`${requestDate[0]} - ${requestDate[1]}`);
    }

    if (activity === 22) {
        $(".activity-4, .activity-20, .activity-22").show();
        showAndBlock([4, 20, 51]);
        $("#analistaDesligamento").val($("#currentUserName").val());
        $("#dataPrevista").val(`${requestDate[0]} - ${requestDate[1]}`);
    }

    if (activity === 24) {
        $(".activity-4, .activity-20, .activity-22, .activity-24").show();
        showAndBlock([4, 20, 22, 51]);
        $("#userAprovConf").val($("#currentUserName").val());
        $("#dataUserAprovConf").val(`${requestDate[0]} - ${requestDate[1]}`);
    }

    if (activity === 5) {
        $(".activity-4, .activity-20, .activity-22, .activity-24, .activity-5").show();
        showAndBlock([4, 20, 22, 24, 51]);
        $("#analistaComunicado").val($("#currentUserName").val());
        $("#dataComunicado").val(`${requestDate[0]} - ${requestDate[1]}`);
        inicializarEstrelas();
    }


    if (activity === 15) {
        $(".activity-4, .activity-15").show();
        showAndBlock([4]);
        $("#userValidacao").val($("#currentUserName").val());
        $("#dataUserValidacao").val(`${requestDate[0]} - ${requestDate[1]}`);
    }

    $(`.activity-${activity} :input`)
        .prop("readonly", false)
        .prop("disabled", false)
        .css("background-color", "");
}

/****************************************************************************************
 *  BLOQUEIO DE ATIVIDADES ANTERIORES
 ****************************************************************************************/
function showAndBlock(list) {

    const current = parseInt($("#activity").val());

    if (list[0] === "all") {
        $(".activity :input")
            .prop("readonly", true)
            .css("pointer-events", "none")
            .css("background-color", "#eee");
        return;
    }

    list.forEach(a => {

        $(`.activity-${a}`).show();

        $(`.activity-${a} :input`).each(function () {

            if ($(this).closest(".activity").hasClass(`activity-${current}`)) return;

            // trava campos normais
            $(this)
                .prop("readonly", true)
                .css("background-color", "#eee")
                .css("pointer-events", "none");

        });
    });
}

/****************************************************************************************
 *  FUNÇÕES AUXILIARES
 ****************************************************************************************/
function getCurrentDate() {
    const now = new Date();
    const pad = n => (n < 10 ? "0" + n : n);

    return [
        `${pad(now.getDate())}/${pad(now.getMonth() + 1)}/${now.getFullYear()}`,
        `${pad(now.getHours())}:${pad(now.getMinutes())}`
    ];
}

/****************************************************************************************
 *  ESTRELAS DE AVALIAÇÃO
 ****************************************************************************************/
function inicializarEstrelas() {

    const valorSalvo = parseInt($("#ratingValue").val()) || 0;

    const stars = FLUIGC.stars(".minha-avaliacao", {
        stars: 5,
        value: valorSalvo,
        sizeClass: "icon-md"
    });

    stars.on("click", function () {
        const valor = $(".fluigicon-star-active").length;
        $("#ratingValue").val(valor);
    });

    setTimeout(() => {
        $(".minha-avaliacao .fluigicon-star").each(function (i) {
            $(this).css("color", i < valorSalvo ? "#f0ad4e" : "#ccc");
        });
    }, 200);
}

/****************************************************************************************
 *  VALIDAÇÃO DO ENVIO
 ****************************************************************************************/
var beforeSendValidate = function (state) {

    if ([0, 1, 4].includes(state)) {
        if (!$("#motivoDesligamento").val()) throw "'Detalhes da situação' é obrigatório.";
    }

    if (state == 5) {
        if (!$("#detalheSolicitacao").val()) throw "'Detalhamento da situação' é obrigatório.";
    }
};

/****************************************************************************************
 *  EVENTOS DINÂMICOS (EXIBIÇÃO DE CAMPOS)
 ****************************************************************************************/
$(document).ready(function () {

    $("#assinaturaDoc").change(function () {
        $(".consegueResolverMotivo, .consideracoesRow").hide();
        if ($(this).val() === "nao") $(".consegueResolverMotivo, .consideracoesRow").slideDown();
    }).trigger("change");

    $("input[name=feedback]").change(function () {
        $(".JustFeedback").toggle($(this).val() === "sim");
    }).trigger("change");

    $("input[name=situacaoResolvida]").change(function () {
        $(".explainAction, .ratingAction").hide();
        if ($(this).val() === "nao") $(".explainAction").show();
        if ($(this).val() === "sim") $(".ratingAction").show();
    }).trigger("change");

    $("#tipodesligamento").change(function () {
        $(".feedbackRow").toggle($(this).val() === "experiencia");
    }).trigger("change");
});

/****************************************************************************************
 *  LANÇAMENTOS (PROVENTOS / DESCONTOS)
 ****************************************************************************************/
/****************************************************************************************
 *  PROVENTOS — Adicionar linha
 ****************************************************************************************/
function addLinhaProvento() {
    let idx = wdkAddChild("tabelaProventos");
    ajustarLinhaProvento(idx);
}

/****************************************************************************************
 *  DESCONTOS — Adicionar linha
 ****************************************************************************************/
function addLinhaDesconto() {
    let idx = wdkAddChild("tabelaDescontos");
    ajustarLinhaDesconto(idx);
}

/****************************************************************************************
 *  PROVENTOS — Ajustar linha conforme categoria
 ****************************************************************************************/
function ajustarLinhaProvento(idx) {

    let categoria = $(`select[name="categoriaProvento___${idx}"]`);
    let container = $(`input[name="valorProvento___${idx}"]`).parent();

    categoria.off("change").on("change", function () {

        let valorSalvo = $(`input[name="valorProvento___${idx}"]`).val();
        container.empty();

        let cat = categoria.val();

        // === COMISSÃO / PREMIAÇÃO / AVARIAS → DINHEIRO ====
        if (["comissao", "premiacao"].includes(cat)) {
            container.append(`
                <input type="text" name="valorProvento___${idx}"
                       class="form-control money" placeholder="R$ 0,00">
            `);
        }

        // === HORAS EXTRAS → HH:MM ====
        else if (cat === "horasextras") {
            container.append(`
                <input type="text" name="valorProvento___${idx}"
                       class="form-control timehhmm" placeholder="00:00">
            `);
        }

        // === OUTRO → TEXTO LIVRE ====
        else {
            container.append(`
                <input type="text" name="valorProvento___${idx}"
                       class="form-control" placeholder="Descreva...">
            `);
        }

        // Restaurar valor
        $(`input[name="valorProvento___${idx}"]`).val(valorSalvo);

        aplicarMascaraDinheiro();
        aplicarMascaraHora();
    });

    categoria.trigger("change");
}
/****************************************************************************************
 *  DESCONTOS — Ajustar linha conforme categoria
 ****************************************************************************************/
function ajustarLinhaDesconto(idx) {

    let categoria = $(`select[name="categoriaDesconto___${idx}"]`);
    let container = $(`input[name="valorDesconto___${idx}"]`).parent();

    categoria.off("change").on("change", function () {

        let valorSalvo = $(`input[name="valorDesconto___${idx}"]`).val();
        container.empty();

        let cat = categoria.val();

        // === FALTAS → INTEIRO ====
        if (cat === "faltas") {
            container.append(`
                <input type="number" step="1" name="valorDesconto___${idx}"
                       class="form-control" placeholder="Dias de falta">
            `);
        }

        // === ATRASOS → HH:MM ====
        else if (cat === "atrasos") {
            container.append(`
                <input type="text" name="valorDesconto___${idx}"
                       class="form-control timehhmm" placeholder="00:00">
            `);
        }

        // === AVARIAS → DINHEIRO ====
        else if (cat === "avarias") {
            container.append(`
                <input type="text" name="valorDesconto___${idx}"
                       class="form-control money" placeholder="R$ 0,00">
            `);
        }

        // === OUTRO — texto livre ====
        else {
            container.append(`
                <input type="text" name="valorDesconto___${idx}"
                       class="form-control" placeholder="Descreva...">
            `);
        }

        // Restaurar valor salvo
        $(`input[name="valorDesconto___${idx}"]`).val(valorSalvo);

        aplicarMascaraDinheiro();
        aplicarMascaraHora();
    });

    categoria.trigger("change");
}

/****************************************************************************************
 *  Restauração automática ao recarregar o formulário
 ****************************************************************************************/
function restaurarTodasLinhas() {

    // PROVENTOS
    $("select.categoriaProvento").each(function () {
        let idx = this.name.split("___")[1];
        ajustarLinhaProvento(idx);
    });

    // DESCONTOS
    $("select.categoriaDesconto").each(function () {
        let idx = this.name.split("___")[1];
        ajustarLinhaDesconto(idx);
    });
}

// Sempre que o Fluig recriar o pai-filho
document.addEventListener("DOMNodeInserted", function (e) {

    if ($(e.target).closest("#tabelaProventos").length > 0 ||
        $(e.target).closest("#tabelaDescontos").length > 0) {

        setTimeout(restaurarTodasLinhas, 200);
    }
});

/****************************************************************************************
 *  Máscara de dinheiro
 ****************************************************************************************/
function aplicarMascaraDinheiro() {
    $(".money").mask("#.##0,00", { reverse: true });
}

function aplicarMascaraHora() {
    $('.timehhmm').mask('00:00');
}



// Sempre que o Fluig alterar o pai-filho, restauramos
document.addEventListener("DOMNodeInserted", function (e) {
    if ($(e.target).closest("table#tabelaLancamentos").length > 0) {
        setTimeout(restaurarLancamentos, 200);
    }
});

/****************************************************************************************
 *  ZOOM: COLABORADOR
 ****************************************************************************************/
function setSelectedZoomItem(item) {
    if (item.inputId === "colabDesliga") {
        $("#colabCpf").val(item.cpf || "");
        $("#colabadmissao").val(item.admission_at || "");
        $("#emailColaborador").val(item.email || "");
        $("#departamento").val(item.department || "");
        $("#cargoColaborador").val(item.description || "");
    }
}

function removedZoomItem(item) {
    if (item.inputId === "colabDesliga") {
        $("#colabCpf, #colabadmissao, #emailColaborador, #departamento, #cargoColaborador").val("");
    }
}
