function createDataset(fields, constraints, sortFields) {
    var dataset = DatasetBuilder.newDataset();
    dataset.addColumn("PDV");
    dataset.addColumn("LOJA");
    dataset.addColumn("RESPONSAVEL_LOJA");
    dataset.addColumn("REGIONAL");
    dataset.addColumn("UF");
    dataset.addColumn("CIDADE");
    dataset.addColumn("STATUS");
    dataset.addColumn("CANAL");
    dataset.addColumn("ID");
    dataset.addColumn("LOGIN_LOJA");
    dataset.addColumn("COLLEAGUE_ID");

    try {
        var clientService = fluigAPI.getAuthorizeClientService();
        var data = {
            companyId: String(getValue("WKCompany") || "1"),
            serviceCode: "GINSENG API",
            endpoint: "/base_pdvs",
            method: "get",
            timeoutService: "60000",
            params: {}
        };

        var vo = clientService.invoke(JSON.stringify(data));
        var response = String(vo.getResult() || "");
        var obj = JSON.parse(response);
        var list = (obj && obj.data && obj.data.length) ? obj.data : [];

        if (!list.length) {
            dataset.addRow(["", "Sem lojas retornadas", "", "", "", "", "", "", "", "", ""]);
            return dataset;
        }

        var filter = getSearchFilter(constraints);
        for (var i = 0; i < list.length; i++) {
            var item = list[i] || {};
            var pdv = clean(item.PDV);
            var loja = clean(item["PDV DESC"] || item.DESCRICAO);
            var responsavel = clean(item.GESTAO);
            var regional = clean(item.SUPERVISOR || item["REGIAO 2"] || item.REGIAO);
            var uf = clean(item.UF || item["UF 2"]);
            var cidade = clean(item.CIDADE);
            var status = clean(item.STATUS);
            var canal = clean(item.CANAL);
            var id = clean(item.id);
            var loginLoja = pdv ? (pdv + ".ginseng") : "";
            var colleagueId = resolveColleagueId(loginLoja);

            if (!matchesFilter(filter, [pdv, loja, responsavel, regional, uf, cidade, status, canal, loginLoja, colleagueId])) {
                continue;
            }

            dataset.addRow([
                pdv,
                loja,
                responsavel,
                regional,
                uf,
                cidade,
                status,
                canal,
                id,
                loginLoja,
                colleagueId
            ]);
        }
    } catch (e) {
        dataset = DatasetBuilder.newDataset();
        dataset.addColumn("ERRO");
        dataset.addRow([String(e)]);
    }

    return dataset;
}

function resolveColleagueId(login) {
    try {
        var c1 = DatasetFactory.createConstraint("login", login, login, ConstraintType.MUST);
        var c2 = DatasetFactory.createConstraint("active", "true", "true", ConstraintType.MUST);
        var ds = DatasetFactory.getDataset("colleague", null, [c1, c2], null);
        if (ds && ds.rowsCount > 0) {
            return clean(ds.getValue(0, "colleaguePK.colleagueId"));
        }
    } catch (e) {}
    return "";
}

function getSearchFilter(constraints) {
    if (!constraints || !constraints.length) return "";
    for (var i = 0; i < constraints.length; i++) {
        var c = constraints[i];
        var field = String(c.fieldName || "").toUpperCase();
        if (field === "SEARCH" || field === "LOJA" || field === "PDV") {
            return normalizeSearch(c.initialValue);
        }
    }
    return "";
}

function matchesFilter(filter, values) {
    if (!filter) return true;
    for (var i = 0; i < values.length; i++) {
        if (normalizeSearch(values[i]).indexOf(filter) > -1) return true;
    }
    return false;
}

function normalizeSearch(text) {
    var t = clean(text).toUpperCase();
    t = t.replace(/[%*_]/g, "");
    return t;
}

function clean(value) {
    return String(value || "").trim();
}
