/**
 * Widget: Lista de Processos
 * Descricao: Exibe processos abertos do usuario logado com FLUIGC.datatable
 * Baseado em: Workspace Igao - carrossel_imagem_dwp + start_wf_igor
 */
var widget_lista_processos = SuperWidget.extend({

    instanceId: null,
    datasetName: "ds_processos_abertos",

    init: function() {
        this.instanceId = this.options.instanceId;
        this.carregarDados();
        this.bindEvents();
    },

    bindEvents: function() {
        var self = this;

        // Filtro por texto
        $("#btnFiltrar_" + self.instanceId).on("click", function() {
            self.carregarDados();
        });

        // Enter no campo filtro
        $("#filtro_" + self.instanceId).on("keypress", function(e) {
            if (e.which === 13) {
                self.carregarDados();
            }
        });
    },

    carregarDados: function() {
        var self = this;
        var filtro = $("#filtro_" + self.instanceId).val() || "";

        // Mostra loading
        $("#loading_" + self.instanceId).show();
        $("#tabela_" + self.instanceId).hide();
        $("#vazio_" + self.instanceId).hide();

        // Buscar dados via dataset REST API
        var constraints = [];
        if (filtro) {
            constraints.push(
                DatasetFactory.createConstraint("nome_processo", filtro, filtro, ConstraintType.MUST)
            );
        }

        try {
            var dataset = DatasetFactory.getDataset(
                self.datasetName,
                null,  // campos (null = todos)
                constraints,
                null   // order
            );

            $("#loading_" + self.instanceId).hide();

            if (dataset && dataset.values && dataset.values.length > 0) {
                self.renderTabela(dataset);
            } else {
                $("#vazio_" + self.instanceId).show();
            }

        } catch (e) {
            $("#loading_" + self.instanceId).hide();
            FLUIGC.toast({
                title: "Erro",
                message: "Falha ao carregar processos: " + e.message,
                type: "danger"
            });
        }
    },

    renderTabela: function(dataset) {
        var self = this;
        var container = "#tabela_" + self.instanceId;

        // Limpar tabela anterior
        $(container).empty().show();

        // Criar datatable com FLUIGC
        FLUIGC.datatable(container, {
            dataRequest: dataset.values,
            renderContent: ".datatable-content",
            header: [
                { "title": "Processo" },
                { "title": "Solicitante" },
                { "title": "Atividade Atual" },
                { "title": "Data" },
                { "title": "Acoes" }
            ],
            search: {
                enabled: true
            },
            scroll: {
                target: container
            },
            actions: {
                enabled: false
            },
            template: function(data) {
                var html = "";
                for (var i = 0; i < data.length; i++) {
                    var item = data[i];
                    html += "<tr>";
                    html += "<td>" + (item.nome_processo || "") + "</td>";
                    html += "<td>" + (item.solicitante || "") + "</td>";
                    html += "<td>" + (item.atividade_atual || "") + "</td>";
                    html += "<td>" + (item.data_abertura || "") + "</td>";
                    html += "<td>";
                    html += '<a href="/portal/p/1/pageworkflowview?app_ecm_workflowview_top=' + item.processo_id + '" ';
                    html += 'class="btn btn-xs btn-default" title="Abrir">';
                    html += '<i class="flaticon-eye icon-sm"></i>';
                    html += "</a>";
                    html += "</td>";
                    html += "</tr>";
                }
                return html;
            }
        });
    }
});
