var gridBuilderArray = [];
var currentYear;
$(document).ready(function () {
    initial();
});
async function initial() {
    currentYear = window.top.$("#hfCurrentYear").val();
    await $("#cboFromYear").lookupBuilder().setSelectedValue(currentYear);
    $(".grid").each(function (index, grid) {
        var gridId = $(grid).attr("id");
        var builder = $(grid).gridBuilder();
        if (window.top.$("#hfCurrencySystem").val() !== "1" && (gridId === "grdDocument" || gridId === "grdArtikle")) {
            if (gridId === "grdArtikle") {
                builder.removeColumn("CurrencyName");
                builder.removeColumn("BedehkarArz");
                builder.removeColumn("BestankarArz");
            }
            else {
                builder.removeColumn("NameArz");
                builder.removeColumn("BedArz");
                builder.removeColumn("BesArz");
            }
        }
        builder.onDblClick(function () {
            var nextLevel = Number($(this.container).attr("data-level")) + 1;
            loadGrid($("[data-level='" + nextLevel + "']").attr("id"));
        });
        builder.onRowChanged(function () {
            var builder = this;
            var txt = "";
            var levelNamesArray = getLevelNamesArray();
            var parentFields = this.container.attr("data-parent").split(",");
            var rowIndex = builder.getActiveRowIndex();
            for (var i = 0; i <= levelNamesArray.length - 1; i++) {
                txt += txt.length > 0 ? "/" : "";
                if (i === levelNamesArray.length - 1) {
                    if (levelNamesArray[i] === "Tafsil")
                        txt += builder.getCellValue(rowIndex, "TafsilName");
                    else if (levelNamesArray[i] === "Document")
                        txt += builder.getCellValue(rowIndex, "Sanad_No");
                    else
                        txt += builder.getCellValue(rowIndex, "Name");
                }
                else
                    txt += builder.getCellValue(rowIndex, parentFields[i]);
            }
            $("#divLevel").html(txt);
        });
        gridBuilderArray.push({ id: gridId, builder: builder });
        builder.onExportClick(function (gridId) {
            loadGrid(gridId, { exportExcel: true });
        });
    });
    loadGrid("grdGroup");
    $("#cboFromYear").lookupBuilder().onChanged(async function () {
        var value = $("#cboFromYear").lookupBuilder().getSelectedValue();
        if (value.indexOf("|") > 0) {
            $("#txtFromDate").val(value.split("|")[1]);
            $("#txtToDate").val(value.split("|")[2]);
        }
        refreshGrid();
    });
    imgToSvg();
}
function loadGrid(gridId, objectParameter) {
    var isExportExcel = objectParameter && objectParameter.exportExcel ? true : false;
    var levelName = gridId.substr(3);
    var builder = gridBuilderArray.filter(function (item) { return item.id === gridId; })[0].builder;
    var selectedData = getSelectedCode(gridId);
    var url = "";
    var data = {};
    var isAll = $("#chkAll").prop("checked");
    var fromYear = $("#cboFromYear").lookupBuilder().getSelectedValue();
    if (fromYear && fromYear.indexOf("|") > 0)
        fromYear = fromYear.split("|")[0];
    if (levelName === "Tafsil") {
        url = "AccountingApi/GetTafsilTurnover";
        data = {
            moainCode: isAll ? -1 : selectedData["grdMoain"],
            fromDate: $("#txtFromDate").val(),
            toDate: $("#txtToDate").val(),
            year: fromYear,
            fromNo: $("#txtFromNo").val(),
            toNo: $("#txtToNo").val(),
            hasTurnover: $("#chkGardesh").prop("checked"),
            filter: builder.getFilter(),
            sort: builder.getSortFields(),
            pageNo: isExportExcel ? -1 : builder.getCurrentPageNumber()
        };
    }
    else if (levelName === "Document") {
        url = "AccountingApi/GetTurnover";
        data = {
            groupCode: isAll ? -1 : selectedData["grdGroup"],
            kolCode: isAll ? -1 : selectedData["grdKol"],
            moainCode: isAll ? -1 : selectedData["grdMoain"],
            tafsilCode: isAll ? -1 : selectedData["grdTafsil"],
            projectCode: isAll ? -1 : selectedData["grdProject"],
            costCenterCode: isAll ? -1 : selectedData["grdCostCenter"],
            fromDate: $("#txtFromDate").val(),
            toDate: $("#txtToDate").val(),
            fromYear: fromYear,
            toYear: fromYear,
            fromNo: $("#txtFromNo").val(),
            toNo: $("#txtToNo").val(),
            filter: builder.getFilter(),
            sort: builder.getSortFields(),
            pageNo: isExportExcel ? -1 : builder.getCurrentPageNumber()
        };
    }
    else if (levelName === "Artikle") {
        if (!isAll && selectedData["grdDocument"] === -1)
            return;
        url = "AccountingApi/GetArticleList";
        data = {
            documentCode: isAll ? -1 : selectedData["grdDocument"],
            isNote: false,
            filter: builder.getFilter(),
            sort: builder.getSortFields(),
            pageNo: isExportExcel ? -1 : builder.getCurrentPageNumber()
        };
    }
    else {
        url = "AccountingApi/GetReportHybridBrowsing";
        data = {
            level: $("#" + gridId).attr("data-level"),
            groupCode: isAll ? -1 : selectedData["grdGroup"],
            kolCode: isAll ? -1 : selectedData["grdKol"],
            moainCode: isAll ? -1 : selectedData["grdMoain"],
            fromDate: $("#txtFromDate").val(),
            toDate: $("#txtToDate").val(),
            fromYear: fromYear,
            toYear: fromYear,
            fromNo: $("#txtFromNo").val(),
            toNo: $("#txtToNo").val(),
            hasFirst: true,
            hasNormal: true,
            hasClose: true,
            hasEnd: true,
            hasTurnover: $("#chkGardesh").prop("checked"),
            filter: builder.getFilter(),
            sort: builder.getSortFields(),
            pageNo: isExportExcel ? -1 : builder.getCurrentPageNumber()
        };
    }
    ajax({
        gridBuilder: builder,
        url: url,
        data: data,
        success: function (data) {
            if (isExportExcel) {
                exportExcel(data, builder.getColumns(), builder.getColumnsCaption());
            }
            else {
                $('#chkAll').prop('disabled', gridId === "grdGroup");    
                $(".grid").parent().hide();
                $("#" + gridId).parent().show();
                var levelNamesArray = getLevelNamesArray();

                if (!levelNamesArray.includes(levelName))
                    $('#hfLevelName').val((levelNamesArray.length > 0 ? levelNamesArray.join(";") + ";" : "") + levelName);
                
                builder.loadData(data);
            }
        }
    });
}

function levelUp(sender) {
    var currentGrid = $(sender).closest(".grid");
    var previuosLevel = Number(currentGrid.attr("data-level")) - 1;
    var levelNamesArray = getLevelNamesArray();
    levelNamesArray.pop();
    $('#hfLevelName').val(levelNamesArray.join(';'));
    $('#chkAll').prop('disabled', levelNamesArray.length <=1);  
    currentGrid.parent().hide();
    $("[data-level='" + previuosLevel + "']").parent().show();
    var builder = gridBuilderArray.filter(function (item) { return item.id === "grd" + levelNamesArray[levelNamesArray.length -1] })[0].builder;
    builder.rowChanged();
}

function levelDown(sender) {
    var builder = gridBuilderArray.filter(function (item) { return item.id === $(sender).closest(".grid").attr("id"); })[0].builder;
    builder.dblClick();
}

function refreshGrid() {
    var levelNamesArray = getLevelNamesArray();
    if (levelNamesArray.length === 0)
        return;
    loadGrid("grd" + levelNamesArray[levelNamesArray.length - 1]); 
}

function getLevelNamesArray() {
    var levelNames = $('#hfLevelName').val();
    var levelNamesArray = [];
    if (levelNames.length > 0) {
        levelNamesArray = levelNames.split(";");
    }
    return levelNamesArray;
}

function getShowLevel() {
    var array = $('#hfLevelName').val().split(';');
    return array[array.length - 1];
}

function getSelectedCode(gridId, isUp) {
    var data = {};
    levelNamesArray = getLevelNamesArray();
    gridBuilderArray.forEach(function (item) {
        var value = null;
        if (levelNamesArray.includes(item.id.substr(3)) && (item.id !== gridId || gridId === null)) {
            var rowIndex = item.builder.getActiveRowIndex();
            if (rowIndex >= 0) {
                if (item.id === "grdTafsil") {
                    value = item.builder.getCellValue(rowIndex, "TafsilCode");
                    data["grdProject"] = item.builder.getCellValue(rowIndex, "ProjectCode");
                    data["grdCostCenter"] = item.builder.getCellValue(rowIndex, "CostCenterCode");
                }
                else if (item.id === "grdDocument")
                    value = item.builder.getCellValue(rowIndex, "Sanad_No") || -1;
                else
                    value = item.builder.getCellValue(rowIndex, "Code");
            }
        }
        data[item.id] = value;
    });
    return data;
}

async function getEventLookupCombo($combo) {
    await ajax({
        url: "GeneralApi/GetYearList",
        async: false,
        data: { filter: "", sort: "" },
        success: function (result) {
            $.each(result,
                function () {
                    this.Code = this.Code + "|" + this.FromDatePersian + "|" + this.ToDatePersian;
                });
            result.push({ Code: -1, Name: window.top.allYear });
            $combo.lookupBuilder().bindData(result);
        }
    });
}

function print() {
    var fromYear = $("#cboFromYear").lookupBuilder().getSelectedValue();
    if (fromYear && fromYear.indexOf("|") > 0)
        fromYear = fromYear.split("|")[0];

    var levelNamesArray = getLevelNamesArray();
    var data = getSelectedCode(null, false);
    var lastLevel = levelNamesArray[levelNamesArray.length - 1];
    var currentBuilder = gridBuilderArray.filter(function (item) { return item.id === "grd" + lastLevel; })[0].builder;
    var rowIndex = currentBuilder.getActiveRowIndex();
    var fromDate = $("#txtFromDate").val();
    var toDate = $("#txtToDate").val();
    if (rowIndex < 0)
        return;
    data["grd" + lastLevel] = "";

    var gridCriteria = currentBuilder.getFilter();
    var levelCurrent = getShowLevel();
    var lvl = arrayLevelName.indexOf(levelCurrent) + 1;
    var title = window.top.report;
    var repgrp = "Gardesh_L";
    var repId = 4;
    var src = "";
    if (lvl === 6) {
        title = window.top.printDocument;
        src = "Report/Default?GrpName=SanadGheyasPlus&InSt=" + data["grdDocument"] + "&salmali=" + fromYear;
    }
    else {
        switch (lvl) {
            case 4:
                repgrp = "Articls4";
                repId = 5;
                break;
            case 5:
                repgrp = "Articls";
                repId = 6;
                break;
        }
        src = "Report/Default?GrpName=" + repgrp + "&param=rep^" + repId + "|lvl^" + lvl + "|fno^" + $('#txtFromNo').val() + "|tno^" + $('#txtToNo').val() + "|all^" + ($('#chkAll').prop('checked') ? '1' : '0') + "|trnover^" + ($('#chkGardesh').prop("checked") ? "1" : "0") + "|fd^" + fromDate + "|td^" + toDate + "|fy^" + fromYear + "|y^"+ fromYear + "|grp^" + data["grdGroup"] + "|kol^" + data["grdKol"] + "|mn^" + data["grdMoain"] + "|tfs^" + data["grdTafsil"] + "|cst^" + data["grdCostCenter"] + "|prj^" + data["grdProject"] + "|doc^" + data["grdDocument"] + "&gridCriteria^" + gridCriteria;
    }
    openInModal("", src, title,"","",false);
}


