/**
 * TEMPLATE: dataset-soap-startprocess.js
 * =============================================
 * Dataset que inicia processos via WebService SOAP
 * (ECMWorkflowEngineService).
 *
 * PADRAO DE PRODUCAO (dsGerarVisita, dsStartProcess):
 * 1. Obter servico ECMWorkflowEngineService
 * 2. Montar cardData (dados do formulario)
 * 3. Definir responsavel e atividade destino
 * 4. Chamar service.startProcess()
 * 5. Retornar processInstanceId
 *
 * USOS COMUNS:
 * - Criar sub-processos automaticamente
 * - Iniciar processos a partir de widgets
 * - Integracao batch (iniciar N processos de uma vez)
 * - Reprocessamento de solicitacoes
 *
 * PRE-REQUISITO:
 * Servico "ECMWorkflowEngineService" cadastrado no Painel.
 * Ou usar ServiceManager.getServiceInstance("wkEngineService")
 */

function createDataset(fields, constraints, sortFields) {

    var dataset = DatasetBuilder.newDataset();
    dataset.addColumn("status");
    dataset.addColumn("processInstanceId");
    dataset.addColumn("mensagem");

    // =============================================
    // LER PARAMETROS
    // =============================================
    var processId = "${CODIGO_PROCESSO}";       // ID do processo no Fluig
    var responsavel = getValue("WKUser");       // Usuario responsavel
    var choosedState = 0;                       // 0 = atividade inicial
    var completeTask = true;                    // true = avanca automatico

    if (constraints != null) {
        for (var i = 0; i < constraints.length; i++) {
            if (constraints[i].fieldName == "processId") {
                processId = constraints[i].initialValue;
            } else if (constraints[i].fieldName == "responsavel") {
                responsavel = constraints[i].initialValue;
            } else if (constraints[i].fieldName == "choosedState") {
                choosedState = parseInt(constraints[i].initialValue);
            }
        }
    }

    // =============================================
    // CREDENCIAIS (idealmente de dataset de config)
    // =============================================
    var usuario = "${USUARIO_WS}";
    var senha = "${SENHA_WS}";
    var empresa = getValue("WKCompany");

    try {
        // =============================================
        // OBTER SERVICO
        // =============================================
        var ServiceProvider = ServiceManager.getServiceInstance("ECMWorkflowEngineService");
        var serviceLocator = ServiceProvider.instantiate(
            "com.totvs.technology.ecm.workflow.ws.ECMWorkflowEngineServiceService");
        var service = serviceLocator.getWorkflowEngineServicePort();

        // Classes auxiliares
        var objectFactory = ServiceProvider.instantiate("net.java.dev.jaxb.array.ObjectFactory");
        var ProcessAttachmentDtoArray = "com.totvs.technology.ecm.workflow.ws.ProcessAttachmentDtoArray";
        var ProcessTaskAppointmentDtoArray = "com.totvs.technology.ecm.workflow.ws.ProcessTaskAppointmentDtoArray";

        // =============================================
        // MONTAR RESPONSAVEIS
        // =============================================
        var colleagueIds = objectFactory.createStringArray();
        colleagueIds.getItem().add(responsavel);

        // =============================================
        // MONTAR DADOS DO FORMULARIO (cardData)
        // =============================================
        var cardData = objectFactory.createStringArrayArray();

        function newCardItem(chave, valor) {
            var item = objectFactory.createStringArray();
            item.getItem().add(chave);
            item.getItem().add(valor);
            return item;
        }

        // Adicionar campos do formulario
        cardData.getItem().add(newCardItem("${CAMPO_FORM_1}", "${VALOR_FORM_1}"));
        cardData.getItem().add(newCardItem("${CAMPO_FORM_2}", "${VALOR_FORM_2}"));
        // cardData.getItem().add(newCardItem("matSolic", responsavel));
        // cardData.getItem().add(newCardItem("nomeSolicitante", nomeSolicitante));

        // =============================================
        // ANEXOS (opcional)
        // =============================================
        var processAttachments = ServiceProvider.instantiate(ProcessAttachmentDtoArray);

        // =============================================
        // APONTAMENTOS (opcional)
        // =============================================
        var processAppointments = ServiceProvider.instantiate(ProcessTaskAppointmentDtoArray);

        // =============================================
        // INICIAR PROCESSO
        // =============================================
        log.info("=== ${NOME_DATASET}: iniciando processo " + processId);

        var retorno = service.startProcess(
            usuario,            // string - login
            senha,              // string - senha
            empresa,            // int - companyId
            processId,          // string - codigo do processo
            choosedState,       // int - atividade destino (0 = inicio)
            colleagueIds,       // StringArray - responsaveis
            "Iniciado automaticamente", // string - comentario
            responsavel,        // string - userId solicitante
            completeTask,       // boolean - completar tarefa
            processAttachments, // ProcessAttachmentDtoArray
            cardData,           // StringArrayArray - dados do form
            processAppointments,// ProcessTaskAppointmentDtoArray
            false               // boolean - managerMode
        );

        // =============================================
        // PROCESSAR RETORNO
        // =============================================
        var labelMsg = retorno.getItem().get(0).getItem().get(0);

        if (labelMsg == "ERROR") {
            var msgErro = retorno.getItem().get(0).getItem().get(1);
            log.error("=== ${NOME_DATASET}: ERRO ao iniciar processo: " + msgErro);
            dataset.addRow(new Array("ERRO", "", msgErro));
        } else {
            var processInstanceId = retorno.getItem().get(5).getItem().get(1);
            log.info("=== ${NOME_DATASET}: processo criado: " + processInstanceId);
            dataset.addRow(new Array("OK", processInstanceId, "Processo criado com sucesso"));
        }

    } catch (e) {
        log.error("=== ${NOME_DATASET} ERRO: " + e.message);
        dataset.addRow(new Array("ERRO", "", e.message));
    }

    return dataset;
}
