# Referencia: APIs Client-Side do Fluig

## WCMAPI — API Principal

```javascript
// Usuario e tenant
WCMAPI.getUserLogin();          // Login do usuario logado
WCMAPI.getTenantCode();         // Codigo do tenant (empresa)
WCMAPI.getServerURL();          // URL base do servidor

// Iniciar processo (via XML)
WCMAPI.Create({
    type: "process",
    processId: "CODIGO_PROCESSO",
    choosedState: 0,             // atividade destino (0 = automatico)
    colleagueIds: [WCMAPI.getUserLogin()],
    comments: "Solicitacao criada via widget",
    cardData: "<CardData>...</CardData>",
    success: function(data) { },
    fail: function(xhr, status, error) { }
});
```

### Formato do CardData XML

```xml
<CardData>
    <campo_nome>Valor do Campo</campo_nome>
    <campo_valor>12345</campo_valor>
    <campo_data>2026-02-24</campo_data>
</CardData>
```

## WCMSpaceAPI — Preferencias de Widget

```javascript
// Salvar preferencias (modo edicao)
WCMSpaceAPI.PageService.UPDATEPREFERENCES({
    async: true,
    success: function(data) {
        FLUIGC.toast({ title: "Sucesso", message: "Configuracao salva!", type: "success" });
    },
    fail: function(xhr, msg, error) {
        FLUIGC.toast({ title: "Erro", message: "Falha ao salvar!", type: "danger" });
    }
});
```

## FLUIGC — Componentes UI

### Toast (notificacao)
```javascript
FLUIGC.toast({
    title: "Titulo",
    message: "Mensagem de feedback",
    type: "success"  // "success", "warning", "danger", "info"
});
```

### Modal
```javascript
var modal = FLUIGC.modal({
    title: "Titulo do Modal",
    content: "<p>Conteudo HTML</p>",
    id: "meuModal",
    size: "large",  // "small", "normal", "large", "full"
    actions: [{
        label: "Confirmar",
        autoClose: true,
        classType: "btn-primary"
    }, {
        label: "Cancelar",
        autoClose: true
    }]
});
modal.show();
```

### Loading
```javascript
FLUIGC.loading("#container").show();
FLUIGC.loading("#container").hide();
```

### Datatable
```javascript
FLUIGC.datatable("#container", {
    dataRequest: arrayDeDados,
    header: [
        { "title": "Coluna 1" },
        { "title": "Coluna 2" }
    ],
    search: { enabled: true },
    pagination: { enabled: true },
    actions: { enabled: false },
    template: function(data) {
        var html = "";
        for (var i = 0; i < data.length; i++) {
            html += "<tr><td>" + data[i].col1 + "</td><td>" + data[i].col2 + "</td></tr>";
        }
        return html;
    }
});
```

### Message Confirm
```javascript
FLUIGC.message.confirm({
    message: "Tem certeza que deseja excluir?",
    title: "Confirmacao",
    labelYes: "Sim",
    labelNo: "Nao"
}, function(result, el, ev) {
    if (result) {
        // Usuario confirmou
    }
});
```

## DatasetFactory — Consulta de Datasets (Client-side)

```javascript
// Buscar dataset via JavaScript
var dataset = DatasetFactory.getDataset(
    "ds_nome_dataset",           // nome do dataset
    ["campo1", "campo2"],        // campos (null = todos)
    [                            // constraints
        DatasetFactory.createConstraint("campo", "valor", "valor", ConstraintType.MUST)
    ],
    ["campo1;asc"]               // ordenacao (null = sem ordem)
);

// Iterar resultados
for (var i = 0; i < dataset.values.length; i++) {
    var linha = dataset.values[i];
    var valor = linha["campo1"];
}
```

### ConstraintType
```javascript
ConstraintType.MUST        // Campo DEVE ter este valor (AND)
ConstraintType.SHOULD      // Campo PODE ter este valor (OR)
ConstraintType.MUST_NOT    // Campo NAO deve ter este valor
```

## Dataset REST API (AJAX)

```javascript
// Via jQuery AJAX (alternativa ao DatasetFactory)
$.ajax({
    url: "/api/public/ecm/dataset/datasets",
    method: "POST",
    contentType: "application/json",
    data: JSON.stringify({
        name: "ds_nome_dataset",
        fields: ["campo1", "campo2"],
        constraints: [{
            _field: "campo",
            _initialValue: "valor",
            _finalValue: "valor",
            _type: 1  // 1=MUST, 2=SHOULD, 3=MUST_NOT
        }],
        order: ["campo1;asc"]
    }),
    success: function(data) {
        var valores = data.content.values;
    },
    error: function(xhr, status, error) {
        console.error("Erro dataset:", error);
    }
});
```

## FTL (Freemarker) — Variaveis Disponiveis

| Variavel | Descricao |
|---|---|
| `${instanceId}` | ID unico da instancia da widget na pagina |
| `${coreContext}` | Contexto base do Fluig |
| `${WCMSpaceAPI}` | API de espaco |
| `${i18n.getTranslation("chave")}` | Internacionalizacao |

### Incluir Recursos no FTL
```html
<#-- CSS -->
<link rel="stylesheet" href="/webdesk/apps/${application.code}/resources/css/${application.code}.css">

<#-- JS -->
<script src="/webdesk/apps/${application.code}/resources/js/${application.code}.js"></script>

<#-- Ou via coreContext -->
<link rel="stylesheet" href="${coreContext}/resources/css/${application.code}.css">
```
