var isMandeh;
var currentYear;
var gridBuilderArray = [];
var yearList = JSON.parse($("#hfYear").val());
$(document).ready(function () {
    $("#hfYear").remove();
    $("#cboFromYear").lookupBuilder().onChanged(async function () {
        var value = $("#cboFromYear").lookupBuilder().getSelectedValue();
        var year = yearList.find(x => x.Code === Number(value));
        if (year) {
            $("#txtFromDate").val(year.FromDatePersian);
        }
        refreshGrid();
    });
    $("#cboToYear").lookupBuilder().onChanged(async function () {
        var value = $("#cboToYear").lookupBuilder().getSelectedValue();
        var year = yearList.find(x => x.Code === Number(value));
        if (year) {
            $("#txtToDate").val(year.ToDatePersian);
        }
        refreshGrid();
    });
    if ($("#cboDocumentType").length > 0) {
        $("#cboDocumentType").lookupBuilder().onChanged(async function () {
            refreshGrid();
        });
    }
    initial();
});
async function initial() {
    var reportName = $("#hfPageName").val();
    if ($(".system-lookup-control").length === 0)
        return;
    if (window.top.$("#hfCurrencySystem").val() !== "1") {
        $("[data-currency='true']").remove();
    }
    $(".grid").each(function (index, grid) {
        var gridId = $(grid).attr("id");
        var builder = $(grid).gridBuilder();
        builder.onRowChanged(function () {
            var txt = "";
            var levelNamesArray = getLevelNamesArray();
            //if (levelNamesArray < 2)
            //    return;
            for (var i = 0; i < levelNamesArray.length; i++) {
                txt += txt.length > 0 ? "/" : "";
                txt += captionArray.filter(function (item) { return item.name === levelNamesArray[i]; })[0].title + ":";
                var builder = gridBuilderArray.filter(function (item) { return item.id === "grd" + levelNamesArray[i]; })[0].builder;
                var rowIndex = builder.getActiveRowIndex();
                if (rowIndex >= 0)
                    txt += builder.getCellValue(rowIndex, (builder.getId() === "grdTracking" ? "ProductSerialNumber" : "Name"));
            }
            $("#divLevel").html(txt);
        });
        gridBuilderArray.push({ id: gridId, builder: builder });

        builder.onExportClick(function (gridId) {
            var levelNamesArray = getLevelNamesArray();
            loadGrid(gridId, { exportExcel: true },levelNamesArray.length === 1);
        });
    });
    currentYear = window.top.$("#hfCurrentYear").val();
    await $("#cboFromYear").lookupBuilder().setSelectedValue(currentYear);
    await $("#cboToYear").lookupBuilder().setSelectedValue(currentYear);
    if ($("#cboDocumentType").length > 0)
        await $("#cboDocumentType").lookupBuilder().setSelectedValue("1,2,3,4");

    loadGrid($($(".grid")[0]).attr("id"), null,true);
}
function loadGrid(gridId, objectParameter, isTop) {
    var isExportExcel = objectParameter && objectParameter.exportExcel ? true : false;
    var levelName = gridId.substr(3);
    //if ($('#img-left-' + levelName).hasClass("selected-item-vertical") && !isTop)
    //    return;
    //if ($('#img-top-' + levelName).hasClass("selected-item") && isTop)
    //    return;
    var builder = gridBuilderArray.filter(function (item) { return item.id === gridId; })[0].builder;
    var data = getData(gridId, isTop, isExportExcel);
    ajax({
        gridBuilder: builder,
        url: data.url,
        data: data.data,
        success: function (data) {
            if (isExportExcel) {
                exportExcel(data, builder.getColumns(), builder.getColumnsCaption());
            }
            else {
                $(".grid").parent().hide();
                $("#" + gridId).parent().show();
                if (isTop) {
                    gridBuilderArray.forEach(function (item) {
                        if (item.id !== gridId)
                            item.builder.clearRows();
                    });
                    $('#hfLevelName').val(levelName);
                    $('.img-vertical > div:not(#back)').removeClass('selected-item-vertical').addClass('no-selected-item-vertical');
                    $('.img-horizontal div').removeClass('selected-item').addClass('no-selected-item');
                    $('#img-top-' + levelName).removeClass('no-selected-item').addClass('selected-item');
                    $('#back').removeClass('no-selected-item').addClass('selected-item');
                }
                else {
                    var levelNamesArray = getLevelNamesArray();
                    if (!levelNamesArray.includes(levelName))
                        $('#hfLevelName').val((levelNamesArray.length > 0 ? levelNamesArray.join(";") + ";" : "") + levelName);
                    $('#back').removeClass('selected-item').addClass('no-selected-item');
                }
                $('#img-left-' + levelName).removeClass('no-selected-item-vertical').addClass('selected-item-vertical');
                builder.loadData(data);
            }
        }
    });
}
function getLevelNamesArray() {
    var levelNames = $('#hfLevelName').val();
    var levelNamesArray = [];
    if (levelNames.indexOf(";") >= 0) {
        levelNamesArray = levelNames.split(";");
    }
    else if (levelNames.length > 0)
        levelNamesArray[0] = levelNames;

    return levelNamesArray;
}
function getData(gridId, isTop, isExportExcel) {
    var reportName = $("#hfPageName").val();
    var selectedData = getSelectedCode(gridId, isTop);
    var builder = gridBuilderArray.filter(function (item) { return item.id === gridId; })[0].builder;
    var data = {};
    var url = "";
    if (reportName === "store") {
        url = "SaleApi/GetStoreReportHybridBrowsing";
        data["level"] = $("#" + gridId).attr("data-level");
        data["storeCode"] = selectedData["grdStore"];
        data["productCode"] = selectedData["grdProduct"];
        data["documentTypeCode"] = selectedData["grdDocumentType"];
        data["customerCode"] = selectedData["grdCustomer"];
        data["customerCode2"] = selectedData["grdCustomer2"];
        data["productGroupCode"] = selectedData["grdProductGroup"];
        data["propertyCode"] = selectedData["grdProperty"];
        data["serial"] = selectedData["grdTracking"];
        data["circulation"] = $("#chkGardesh").prop("checked");
    }
    else if (reportName === "accounting") {
        var selectedDocumentType = $("#cboDocumentType").lookupBuilder().getSelectedValue().split(",");
        var finalizeState = Number($("#cboFinalState").val());
        url = "AccountingApi/GetReportHybridBrowsing";
        data["level"] = $("#" + gridId).attr("data-level");
        data["groupCode"] = selectedData["grdGroup"];
        data["kolCode"] = selectedData["grdKol"];
        data["moainCode"] = selectedData["grdMoain"];
        data["tafsilCode"] = selectedData["grdTafsil"];
        data["projectCode"] = selectedData["grdProject"];
        data["costCenterCode"] = selectedData["grdCostCenter"];
        data["fromNo"] = $("#txtFromNo").val();
        data["toNo"] = $("#txtToNo").val();
        data["finalizedState"] = finalizeState === -1 ? null : finalizeState;
        data["dtate"] = "";
        data["hasFirst"] = selectedDocumentType.includes("2");
        data["hasNormal"] = selectedDocumentType.includes("3");
        data["hasClose"] = selectedDocumentType.includes("4");
        data["hasEnd"] = selectedDocumentType.includes("1");
        data["hasTurnover"] = $("#chkGardesh").prop("checked");
    }
    else if (reportName === "sale") {
        url = "SaleApi/GetSaleReportHybridBrowsing";
        data["level"] = $("#" + gridId).attr("data-level");
        data["storeCode"] = selectedData["grdStore"] || null;
        data["productCode"] = selectedData["grdProduct"] || null;
        data["documentTypeCode"] = selectedData["grdDocumentType"] || null;
        data["customerCode"] = selectedData["grdCustomer"] || null;
        data["customer2Code"] = selectedData["grdCustomer2"] || null;
        data["productGroupCode"] = selectedData["grdProductGroup"] || null;
        data["marketerCode"] = selectedData["grdMarketer"] || null;
        data["shoppingCenterCode"] = selectedData["grdSaleCenter"] || null;
        data["circulation"] = $("#chkGardesh").prop("checked");
    }

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

    data["fromDate"] = $("#txtFromDate").val();
    data["toDate"] = $("#txtToDate").val();
    data["fromYear"] = fromYear;
    data["toYear"] = toYear;
    data["sort"] = builder.getSortFields();
    data["filter"] = builder.getFilter();
    data["pageNo"] = isExportExcel ? -1 : builder.getCurrentPageNumber();
    return { data: data, url: url };
}
function getSelectedCode(gridId, isTop, colName) {
    var data = {};
    var levelNamesArray = getLevelNamesArray();
    gridBuilderArray.forEach(function (item) {
        var value = "";
        if (levelNamesArray.includes(item.id.substr(3)) && !isTop && (item.id !== gridId || gridId === null)) {
            var rowIndex = item.builder.getActiveRowIndex();
            if (rowIndex >= 0) {
                if (colName === "Id" && (item.id === "grdTafsil" || item.id === "grdCostCenter" || item.id === "grdProject")) {
                    value = item.builder.getCellValue(rowIndex, "Id");
                    data[item.id + "Code"] = item.builder.getCellValue(rowIndex, "Code");
                }
                else if (item.id === "grdTracking") {
                    value = item.builder.getCellValue(rowIndex, "ProductSerialNumber");
                }
                else
                    value = item.builder.getCellValue(rowIndex, "Code");

                if (item.id === "grdProperty") {
                    data["grdProduct"] = item.builder.getCellValue(rowIndex, "ProductCode");
                }
            }
        }
        data[item.id] = value;
    });
    return data;
}
async function getEventLookupCombo($combo) {
    var id = $combo.attr('id');
    var data;
    if (id === "cboDocumentType") {
        data = [{ Code: 1, Name: window.top.closingDocuments }, { Code: 2, Name: window.top.openingDocuments }, { Code: 3, Name: window.top.normalDocuments }, { Code: 4, Name: window.top.documentsCloseAccounts }];
    }
    else {
        data = yearList;
    }
    $combo.lookupBuilder().bindData(data);
}
function onBackClick() {
    if ($('#back').hasClass('selected-item')) {
        return;
    }
    var levelNamesArray = getLevelNamesArray();
    var current = levelNamesArray[levelNamesArray.length - 1];

    levelNamesArray.pop();
    var before = levelNamesArray[levelNamesArray.length - 1];
    var builder = gridBuilderArray.filter(function (item) { return item.id === "grd" + before; })[0].builder;

    $('#hfLevelName').val(levelNamesArray.join(';'));
    $(".grid").parent().hide();
    $("#grd" + before).parent().show();

    if (levelNamesArray.length <= 1)
        $('#back').removeClass('no-selected-item').addClass('selected-item');
    else
        $('#back').removeClass('selected-item').addClass('no-selected-item');
    $('#img-left-' + current).removeClass('selected-item-vertical').addClass('no-selected-item-vertical');
    $('#img-left-' + before).removeClass('no-selected-item-vertical').addClass('selected-item-vertical');
    builder.rowChanged();
}
function refreshGrid() {
    var levelNamesArray = getLevelNamesArray();
    if (levelNamesArray.length === 0)
        return;
    loadGrid("grd" + levelNamesArray[levelNamesArray.length - 1], null,levelNamesArray.length === 1);
}
function openCirculation(isMod) {
    isMandeh = isMod;
    var reportName = $("#hfPageName").val();
    var src;
    var levelNamesArray = getLevelNamesArray();
    var data = getSelectedCode(null, false, "Id");
    var lastLevel = levelNamesArray[levelNamesArray.length - 1];
    var currentBuilder = gridBuilderArray.filter(function (item) { return item.id === "grd" + lastLevel })[0].builder;
    var rowIndex = currentBuilder.getActiveRowIndex();
    var fromYear = $("#cboFromYear").lookupBuilder().getSelectedValue();
    var toYear = $("#cboToYear").lookupBuilder().getSelectedValue();
    if (fromYear && fromYear.indexOf("|") > 0)
        fromYear = fromYear.split("|")[0];
    if (toYear && toYear.indexOf("|") > 0)
        toYear = toYear.split("|")[0];
    if (rowIndex < 0) {
        showMsgModal(0, window.top.chooseItem);
        return;
    }
    var title = window.top.viewTurnover;
    if (reportName === "accounting") {
        var selectedDocumentType = $("#cboDocumentType").lookupBuilder().getSelectedValue().split(",");
        src = 'Accounting/ReportTurnover?ismod=' + isMandeh + '&gp=' + data["grdGroup"] + '&kl=' + data["grdKol"] + '&mn=' + data["grdMoain"] + '&tf=' + data["grdTafsil"] + '&tfc=' + (data["grdTafsilCode"] || "") + '&hz=' + data["grdCostCenter"] + '&hzc=' + (data["grdCostCenterCode"] || "") + '&prj=' + data["grdProject"] + '&prjc=' + (data["grdProjectCode"] || "") + '&ad=' + $('#txtFromDate').val() + '&td=' + $('#txtToDate').val() + '&as=' + fromYear + '&ts=' + toYear + '&azno=' + $('#txtFromNo').val() + '&tano=' + $('#txtToNo').val() + '&sabt=' + $("#cboFinalState").val() + '&grd=' + ($('#chkGardesh').prop('checked') ? '1' : '0') + '&he=' + (selectedDocumentType.includes("1") ? '1' : '0') + '&hf=' + (selectedDocumentType.includes("2") ? '1' : '0') + '&hn=' + (selectedDocumentType.includes("3") ? '1' : '0') + '&hc=' + (selectedDocumentType.includes("4") ? '1' : '0') + "&path=" + $('#divLevel').html();
        if (isMandeh === 0)
            title = window.top.viewArticle;
    }
    else if (reportName === "store") {
        src = "Store/ReportTurnover?" + 'azDate=' + $('#txtFromDate').val() + '&taDate=' + $('#txtToDate').val() + '&azSal=' + fromYear + '&taSal=' + toYear;
        src += "&tracking=" + data["grdTracking"] + "&anbar=" + data["grdStore"];
        src += "&kala=" + data["grdProduct"] + "&sanadType=" + data["grdDocumentType"] + "&account=" + data["grdCustomer"] + "&account2=" + data["grdCustomer2"] + "&groupKala=" + data["grdProductGroup"] + "&Property=" + data["grdProperty"] + "&year=" + "&path=" + $('#divLevel').html();
    }
    else if (reportName === "sale") {
        src = "Sale/ReportTurnover?" + 'azDate=' + $('#txtFromDate').val() + '&taDate=' + $('#txtToDate').val() + '&azSal=' + fromYear + '&taSal=' + toYear;
        src += "&bazaryab=" + data["grdMarketer"] + "&saleCenter=" + data["grdSaleCenter"];
        src += "&kala=" + data["grdProduct"] + "&sanadType=" + data["grdDocumentType"] + "&account=" + data["grdCustomer"] + "&account2=" + data["grdCustomer2"] + "&groupKala=" + data["grdProductGroup"] + "&year=" + data["grdYear"] + "&path=" + $('#divLevel').html();
    }
    openInModal('', src, title);
}
function print() {
    var reportName = $("#hfPageName").val();
    var src;
    var title = window.top.report;
    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 gridCriteria = currentBuilder.getFilter();
    var rowIndex = currentBuilder.getActiveRowIndex();
    var fromYear = $("#cboFromYear").lookupBuilder().getSelectedValue();
    var toYear = $("#cboToYear").lookupBuilder().getSelectedValue();
    if (fromYear && fromYear.indexOf("|") > 0)
        fromYear = fromYear.split("|")[0];
    if (toYear && toYear.indexOf("|") > 0)
        toYear = toYear.split("|")[0];
    if (rowIndex < 0)
        return;

    var levelCurrent = getShowLevel();
    var lvl = arrayLevelName.indexOf(levelCurrent) + 1;

    data["grd" + lastLevel] = "";

    var desc = "";
    var descArray = $('#divLevel').text().split("/");
    if (descArray.length > 1) {
        descArray.pop();
        desc = descArray.join("/");
    }
    var reportDescription = "";
    var fromDate = $('#txtFromDate').val();
    var toDate = $('#txtToDate').val();

    if (fromDate !== "")
        reportDescription = window.top.fromDate + ":" + fromDate + " ";
    if (toDate !== "")
        reportDescription += window.top.toDate + ":" + toDate + " ";

    reportDescription += desc;


    if (reportName === "accounting") {
        var selectedDocumentType = $("#cboDocumentType").lookupBuilder().getSelectedValue().split(",");
        src = "Report/Default?GrpName=Moroor_HSMHL" + lvl + lvl + "&param=rep^3|lvl^" + lvl + "|sabt^" + $("#cboFinalState").val() + "|hc^" + (selectedDocumentType.includes("4") ? '1' : '0') + "|hn^" + (selectedDocumentType.includes("3") ? '1' : '0') + "|hf^" + (selectedDocumentType.includes("2") ? '1' : '0') + "|he^" + (selectedDocumentType.includes("1") ? '1' : '0') + "|trnover^" + ($('#chkGardesh').prop("checked") ? "1" : "0") + "|fd^" + $('#txtFromDate').val() + "|td^" + $('#txtToDate').val() + "|fy^" + fromYear + "|ty^" + toYear + "|fno^" + $('#txtFromNo').val() + "|tno^" + $('#txtToNo').val() + "|grp^" + data["grdGroup"] + "|kol^" + data["grdKol"] + "|mn^" + data["grdMoain"] + "|tfs^" + data["grdTafsil"] + "|cst^" + data["grdCostCenter"] + "|prj^" + data["grdProject"] + "|desc^" + reportDescription + "&gridCriteria=" + gridCriteria;
    }
    else if (reportName === "store") {
        src = "Report/Default?GrpName=MororHAnbar_L" + lvl + "&param=rep^2|lvl^" + lvl + "|trnover^" + ($('#chkGardesh').prop("checked") ? "1" : "0") + "|fd^" + $('#txtFromDate').val() + "|td^" + $('#txtToDate').val() + "|fy^" + fromYear + "|ty^" + toYear + "|prd^" + data["grdProduct"] + "|dt^" + data["grdDocumentType"] + "|str^" + data["grdStore"] + "|cus^" + data["grdCustomer"] + "|pgroup^" + data["grdProductGroup"] + "|y^" + currentYear + "|cus2^" + data["grdCustomer2"] + "|trk^" + data["grdTracking"] + "|prop^" + data["grdProperty"] + "|desc^" + $('#divLevel').html() + "&gridCriteria=" + gridCriteria;
    }
    else if (reportName === "sale") {
        src = "Report/Default?GrpName=MororSl_Tk_L" + lvl + "&param=rep^1|lvl^" + lvl + "|fd^" + $('#txtFromDate').val() + "|td^" + $('#txtToDate').val() + "|fy^" + fromYear + "|ty^" + toYear + "|prd^" + data["Product"] + "|dt^" + data["grdDocumentType"] + "|mrk^" + data["grdMarketer"] + "|str^" + data["grdStore"] + "|cus^" + data["grdCustomer"] + "|pgroup^" + data["grdProductGroup"] + "|y^" + data["grdYear"] + "|cus2^" + data["grdCustomer2"] + "|scenter^" + data["grdSaleCenter"] + "|desc^" + reportDescription + "&gridCriteria=" + gridCriteria;
    }
    openInModal('', src, title, "", "", false);

}
function ProductKardex(sender) {
    var gridId = $(sender).closest(".grid").attr("id");
    var builder = gridBuilderArray.filter(function (item) { return item.id === gridId; })[0].builder;
    var rowIndex = builder.getActiveRowIndex();
    var fromYear = $("#cboFromYear").lookupBuilder().getSelectedValue();
    var toYear = $("#cboToYear").lookupBuilder().getSelectedValue();
    if (fromYear && fromYear.indexOf("|") > 0)
        fromYear = fromYear.split("|")[0];
    if (toYear && toYear.indexOf("|") > 0)
        toYear = toYear.split("|")[0];
    if (rowIndex < 0)
        return;

    var productCode = builder.getCellValue(rowIndex, "Code");
    var productId = builder.getCellValue(rowIndex, "ProductId");
    var storeCode = "";
    var path = getLevelNamesArray();
    if (path.includes("Store")) {
        var storeRow = gridBuilderArray[0].builder.getActiveRowIndex();
        storeCode = gridBuilderArray[0].builder.getCellValue(storeRow, "Code");
    }
    openInModal('', 'Store/ProductKardex?code=' + productCode + '&shenaseh=' + productId + '&azsal=' + fromYear + '&tasal=' + toYear + '&azdate=' + $('#txtFromDate').val() + '&tadate=' + $('#txtToDate').val() + "&store=" + storeCode, window.top.productKartex);

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