var moainList = eval($("#hfMoainList").val());
var baseDecimalCount = Number(window.top.$("#hfDecimalCount").val());
var baseCurrencyCode = Number(window.top.$("#hfBaseCurrencyCode").val());
var currencySystem = window.top.$("#hfCurrencySystem").val();
var hasCurrencySystem = currencySystem === "1";
var currencyList = eval($("#hfCurrencyList").val());
var gridBuilder;
var currentYear = window.top.$("#hfCurrentYear").val();

$(document).ready(function () {
    $("#hfMoainList").remove();
    $("#hfCurrencyList").remove();

    gridBuilder = $(".grid").gridBuilder();
    if (!hasCurrencySystem) {
        gridBuilder.removeColumn("CurrencyName");
        gridBuilder.removeColumn("CurrencyRate");
        gridBuilder.removeColumn("CurrencyDebit");
        gridBuilder.removeColumn("CurrencyCredit");
    }
    gridBuilder.onOpenCalculator(function () {
        openInModal("", "Home/Calculator", window.top.calculator, 303, 465, true, "");
    });
    gridBuilder.onRowChanged(function () {
        var rowIndex = gridBuilder.getActiveRowIndex();
        var nameMoain = gridBuilder.getCellValue(rowIndex, "MoainName");
        if (!nameMoain) {
            $("#detailCaption").html("");
            return;
        }
        var nameTafsil = gridBuilder.getCellValue(rowIndex, "TafsilName");
        var nameMHazineh = gridBuilder.getCellValue(rowIndex, "NameMHazineh");
        var nameProject = gridBuilder.getCellValue(rowIndex, "ProjectName");

        $("#detailCaption").html(nameMoain + "/" + (nameTafsil ? nameTafsil + "/" : "") + (nameMHazineh ? nameMHazineh + "/" : "") + (nameProject ? nameProject + "/" : ""));
    });
    gridBuilder.onCellChanged(gridCellChanged);
    gridBuilder.onCellBeforeLostFocus(gridCellBeforeLostFocus);
    gridBuilder.onGetComboData(getGridComboData);
    gridBuilder.onExportClick(exportSampleExcel);
    gridBuilder.onSetMaskEdit(setEventMaskEdit);
    gridBuilder.onStartEditing(startEditingGrid);
    gridBuilder.onPgmSumChanged(function () {
        updateSummaryTbl();
    });
    gridBuilder.onImportClick(function (gridId, type, base64) {
        if (type === "importXml") {
            importXml(gridId, base64);
        }
        else {
            ajax({
                loading: true,
                url: "GeneralApi/ImportExcel",
                data: {
                    key: "AccountingArticle" + "-" + currencySystem,
                    base64: base64
                },
                success: function (result) {
                    var data = eval(result.result);
                    gridBuilder.loadData(data);
                }
            });
        }
    });
    initial();

});
async function initial() {
    var newSanad = false;
    if (getQuery("CodeSanadCopy"))
        await getDocument(getQuery("CodeSanadCopy"));
    else if (getQuery("CodeSanad")) {
        $("#hfOldCode").val(getQuery("CodeSanad"));
        $("#divAutoCode").show();
        await getDocument(getQuery("CodeSanad"));
    }
    else if (getQuery("taseer")) {
        await getExchangeCurrencyDocument();
    }
    else if (getQuery("rcode")) {
        await getRecoverDocument();
    }
    else {
        newSanad = true;
        await getNewDocument();
    }
    closeLoading();
    $("#divMain").show();

    if (newSanad && !getQuery("yearclose"))
        gridBuilder.addNewRow();
}
document.onkeydown = function (event) {
    event = event || window.event;
    var rowIndex = gridBuilder.getActiveRowIndex();
    if (event.keyCode === 112) //f1 
    {
        window.top.showHelpForm();
        event.preventDefault();
    }
    else if (event.keyCode === 120)//F9
    {
        $("#btnSaveTemp").trigger('click');
    }
    else if (event.keyCode === 121)//F10
    {
        $("#btnSaveNote").trigger('click');
    }

};
$(document).click(function (event) {
    if ($(event.toElement).length > 0 && !$(event.toElement).hasClass("attached-panel") && !$(event.toElement).hasClass("dropdown-toggle") && $(event.toElement).closest(".attached-panel").length === 0 && $(event.toElement).closest(".attached-file").length === 0)
        $(".attached-panel").hide();
    window.top.closeLeftSideMenu();
});
function newSanad() {
    window.top.onCloseTab(window.location.href);
    showLoading();
    redirectUrl("InvoiceSave?openInTab=" + getQuery('openInTab'));
}
async function getNewDocument() {
    await ajax({
        url: "AccountingApi/GetNewDocument",
        success: function (result) {
            if (getQuery("yearclose")) {
                var data = refreshParent("getData()");
                var gridData = data.data;
                if (data.error) {
                    var errorArray = data.error.split(",");
                    gridData.forEach(function (item, index) {
                        if (errorArray.includes((index + 1).toString()))
                            item.color = "#d32f2f33";
                    });
                }
                gridBuilder.loadData(gridData);
            }

            if (getQuery("type") === "start") {
                result.DocumentTypeCode = 2;
                result.DocumentTypeName = window.top.opening;
            }
            else if (getQuery("type") === "close") {
                result.DocumentTypeCode = 3;
                result.DocumentTypeName = window.top.closeAccount;
            }
            else if (getQuery("type") === "end") {
                result.DocumentTypeCode = 4;
                result.DocumentTypeName = window.top.closing;
            }
            setHeader(result, null);
        }
    });
}
async function getExchangeCurrencyDocument() {
    await ajax({
        url: "AccountingApi/GetExchangeCurrencyDocument",
        data: {
            moainCode: window.parent.$("#cboMoain").lookupBuilder().getSelectedValue().split("|")[0],
            tafsilId: window.parent.$("#cboTafzil").lookupBuilder().getSelectedValue() || null,
            costCenterId: window.parent.$("#cboMarkazHazine").lookupBuilder().getSelectedValue() || null,
            projectId: window.parent.$("#cboProject").lookupBuilder().getSelectedValue() || null,
            articles: eval(window.parent.$("#hfSelectedData").val())
        },
        success: function (result) {
            if (result.Articles.length > 0) {
                gridBuilder.loadData(result.Articles);
                gridBuilder.setEnabled(false);
            }
            setHeader(result.Header, null);
        }
    });
}
async function getRecoverDocument() {
    await ajax({
        url: "AccountingApi/GetRecoverDocument",
        data: { code: getQuery("rcode") },
        success: function (result) {
            if (result.Articles.length > 0) {
                gridBuilder.loadData(result.Articles);
                gridBuilder.setEnabled(false);
            }
            setHeader(result.Header, null);
        }
    });
}
function getGridComboData($combo, search) {
    var comboId = $combo.attr("id");
    var comboBuilder = $("#" + comboId).comboBuilder();
    var rowIndex = gridBuilder.getActiveRowIndex();
    var moainCode = gridBuilder.getCellValue(rowIndex, "MoainCode");
    if (!moainCode)
        moainCode = -1;
    switch (comboId) {
        case "cboMoain":
            var list = moainList;
            if (search)
                list = list.filter(function (item) { return item.Name.indexOf(search) >= 0 || item.Code.toString().indexOf(search) >= 0; });
            comboBuilder.loadData(list);
            break;
        case "cboTafsil":
        case "cboCostCenter":
        case "cboProject":
            var level = Number($combo.attr("data-level"));

            ajax({
                url: "AccountingApi/GetTafsilList",
                data: {
                    moainCode: moainCode,
                    level: level,
                    search: search,
                    pageNo: 1
                },
                success: function (retValue) {
                    retValue.forEach(function (item) {
                        item.Code = item.Id;
                    });
                    comboBuilder.loadData(retValue);
                }
            });
            break;
        case "cboSummery":
            ajax({
                url: 'AccountingApi/GetStandardSummeryList',
                data: {
                    moainCode: moainCode,
                    pageNo: 1
                },
                success: function (retValue) {
                    var array = retValue.map(function (item) { return item.Summery; });
                    var result = $.grep(array, function (item, index) {
                        return index === $.inArray(item, array);
                    });
                    var data = [];
                    result.forEach(function (item) {
                        data.push({ Code: item, Name: item });
                    });
                    comboBuilder.loadData(data);
                }
            });
            break;
        case "cboCurrency":
            var data = [];
            currencyList.forEach(function (item) {
                data.push({ Code: item.Name, Name: item.Name });
            });
            comboBuilder.loadData(data);
            break;
    }
}
function gridCellBeforeLostFocus(rowIndex, columnIndex) {
    if (columnIndex === gridBuilder.getCellIndex("MoainCode") || columnIndex === gridBuilder.getCellIndex("CurrencyName"))
        startEditingGrid(rowIndex);
}
async function gridCellChanged(rowIndex, columnIndex) {
    if (stopEventCellChange)
        return;
    var fieldName = gridBuilder.getCellFieldName(columnIndex);
    var value = gridBuilder.getCellValue(rowIndex, columnIndex);
    var currencyCode = Number(gridBuilder.getCellValue(rowIndex, "CurrencyCode"));
    if (fieldName === "MoainCode") {
        gridBuilder.setCellValue(rowIndex, "TafsilId", "");
        gridBuilder.setCellValue(rowIndex, "CostCenterId", "");
        gridBuilder.setCellValue(rowIndex, "ProjectId", "");
        gridBuilder.rowChanged();
    }
    else if (fieldName === "TafsilId") {
        value = Number(value);
        if (!value) {
            gridBuilder.setCellValue(rowIndex, "TafsilName", "");
            setValueNonRaiseEvent(gridBuilder, rowIndex, "CurrencyName", "");
            gridBuilder.setCellValue(rowIndex, "CurrencyCode", "");
            gridBuilder.setCellValue(rowIndex, "CurrencyDecimalCount", "");
            gridBuilder.setCellValue(rowIndex, "CurrencyRate", "1");
            return;
        }
        await ajax({
            url: "AccountingApi/GetTafsilInfo",
            data: {
                tafsilId: value,
                rateCurrencyDate: $("#txtDate").val()
            },
            success: function (result) {
                if (result.Name) {
                    gridBuilder.setCellValue(rowIndex, "TafsilName", result.Name);
                    setValueNonRaiseEvent(gridBuilder, rowIndex, "CurrencyName", result.CurrencyName);
                    gridBuilder.setCellValue(rowIndex, "CurrencyCode", result.CodeArz);
                    gridBuilder.setCellValue(rowIndex, "CurrencyDecimalCount", result.DecimalCount);

                    if (result.CodeArz === baseCurrencyCode)
                        gridBuilder.setCellValue(rowIndex, "CurrencyRate", "1");
                    else
                        gridBuilder.setCellValue(rowIndex, "CurrencyRate", result.CurrencyRate);
                } else {
                    gridBuilder.setCellValue(rowIndex, "TafsilName", "");
                    setValueNonRaiseEvent(gridBuilder, rowIndex, "CurrencyName", "");
                    gridBuilder.setCellValue(rowIndex, "CurrencyCode", "");
                    gridBuilder.setCellValue(rowIndex, "CurrencyDecimalCount", "");
                    gridBuilder.setCellValue(rowIndex, "CurrencyRate", "1");
                }
                startEditingGrid(rowIndex);
                gridBuilder.rowChanged();
            }
        });
    }
    else if (fieldName === "CostCenterId" || fieldName === "ProjectId") {
        if (!value) {
            if (fieldName === "CostCenterId")
                gridBuilder.setCellValue(rowIndex, "CostCenterName", "");
            else
                gridBuilder.setCellValue(rowIndex, "ProjectName", "");
            return;
        }
        await ajax({
            url: "AccountingApi/GetTafsilInfo",
            data: { tafsilId: value },
            success: function (result) {
                if (fieldName === "CostCenterId")
                    gridBuilder.setCellValue(rowIndex, "CostCenterName", result.Name);
                else
                    gridBuilder.setCellValue(rowIndex, "ProjectName", result.Name);
                gridBuilder.rowChanged();
            }
        });
    }
    else if (fieldName === "Summary") {
        if (currencyCode !== baseCurrencyCode)
            columnIndex = gridBuilder.getCellIndex("CurrencyRate");
    }
    else if (fieldName === "Debit" || fieldName === "Credit") {
        if (fieldName === "Debit") {
            if (Number(value) > 0) {
                gridBuilder.setCellValue(rowIndex, "Credit", "0");
                if (currencyCode && currencyCode !== baseCurrencyCode) {
                    gridBuilder.setCellValue(rowIndex, "CurrencyCredit", "0");
                }
            }
        } else if (fieldName === "Credit") {
            if (Number(value) > 0) {
                gridBuilder.setCellValue(rowIndex, "Debit", "0");
                if (currencyCode && currencyCode !== baseCurrencyCode)
                    gridBuilder.setCellValue(rowIndex, "CurrencyDebit", "0");
            }
        }
        calculateRow();
    }
    else if (fieldName === "CurrencyName") {
        var currencyModel = currencyList.find(c => c.Name === value);
        if (currencyModel) {
            gridBuilder.setCellValue(rowIndex, "CurrencyCode", currencyModel.Code);
            gridBuilder.setCellValue(rowIndex, "CurrencyDecimalCount", currencyModel.DecimalCount);
            if (currencyModel.Code === baseCurrencyCode)
                gridBuilder.setCellValue(rowIndex, "CurrencyRate", "1");
            else {
                await getCurrencyRate(rowIndex, currencyModel.Code);
            }
            startEditingGrid(rowIndex);
        }
        else {
            gridBuilder.setCellValue(rowIndex, "CurrencyCode", "");
            gridBuilder.setCellValue(rowIndex, "CurrencyDecimalCount", "");
            gridBuilder.setCellValue(rowIndex, "CurrencyRate", "1");
            return;
        }
    }
    else if (fieldName === "CurrencyRate") {
        calculateRow();
    }
    else if (fieldName === "CurrencyDebit" || fieldName === "CurrencyCredit") {
        var currencyRate = numberNonCommas(gridBuilder.getCellValue(rowIndex, "CurrencyRate"), 0);
        var bedehkarArz = numberNonCommas(gridBuilder.getCellValue(rowIndex, "CurrencyDebit"), 0);
        var bestankarArz = numberNonCommas(gridBuilder.getCellValue(rowIndex, "CurrencyCredit"), 0);
        var bedehkar = numberWithCommas(bedehkarArz * currencyRate, baseDecimalCount);
        var bestankar = numberWithCommas(bestankarArz * currencyRate, baseDecimalCount);

        if (fieldName === "CurrencyDebit") {
            setValueNonRaiseEvent(gridBuilder, rowIndex, "Debit", bedehkar);
            if (Number(value) > 0) {
                gridBuilder.setCellValue(rowIndex, "Credit", "0");
                if (currencyCode && currencyCode !== baseCurrencyCode)
                    gridBuilder.setCellValue(rowIndex, "CurrencyCredit", "0");
            }

        } else if (fieldName === "CurrencyCredit") {
            setValueNonRaiseEvent(gridBuilder, rowIndex, "Credit", bestankar);
            if (Number(value) > 0) {
                gridBuilder.setCellValue(rowIndex, "Debit", "0");
                if (currencyCode && currencyCode !== baseCurrencyCode)
                    gridBuilder.setCellValue(rowIndex, "CurrencyDebit", "0");
            }
        }

        updateSummaryTbl();
    }
}
function gridKeyDown(sender, event) {
    if ($(sender).attr("id") === "cboSummery") {
        if (event.keyCode === 13) {
            var rowIndex = gridBuilder.getActiveRowIndex();
            var currencyCode = Number(gridBuilder.getCellValue(rowIndex, "CurrencyCode"));
            if (currencyCode !== baseCurrencyCode)
                gridBuilder.setEditRow(rowIndex, "CurrencyDebit", true);
        }
    }
}
function gridContextMenu(keyChar, event) {
    event.stopPropagation();
    var rowIndex = gridBuilder.getActiveRowIndex();
    switch (keyChar) {
        case "f4":
            tarazSanad(rowIndex);
            break;
        case "f7":
            if (rowIndex >= 0)
                changeBedBes(rowIndex);
            break;
        case "f12":
            if (rowIndex >= 0)
                turnover(rowIndex);
            break;
        case "f11":
            if (rowIndex >= 0)
                getTafsilRemained(rowIndex);
            break;
    }
}
function startEditingGrid(rowIndex) {
    var childCount = 0, childCountM = 0, childCountP = 0;
    var moainCode = gridBuilder.getCellValue(rowIndex, "MoainCode");
    if (!moainCode)
        return;
    var item = moainList.find(x => x.Code.toString() === moainCode);
    var nameMoain = "";
    if (item) {
        childCount = item.ChildCount;
        childCountM = item.ChildCountM;
        childCountP = item.ChildCountP;
        nameMoain = item.Name;
    }
    gridBuilder.setCellValue(rowIndex, "MoainName", nameMoain);

    gridBuilder.setEnabledCellEditor("TafsilId", childCount > 0);
    gridBuilder.setEnabledCellEditor("CostCenterId", childCountM > 0);
    gridBuilder.setEnabledCellEditor("ProjectId", childCountP > 0);

    var decimalCount = Number(gridBuilder.getCellValue(rowIndex, "CurrencyDecimalCount"));
    var currencyCode = Number(gridBuilder.getCellValue(rowIndex, "CurrencyCode"));
    gridBuilder.setEnabledCellEditor("CurrencyRate", childCount !== 0 && currencyCode !== baseCurrencyCode);
    gridBuilder.setEnabledCellEditor("CurrencyDebit", childCount !== 0 && currencyCode !== baseCurrencyCode);
    gridBuilder.setEnabledCellEditor("CurrencyCredit", childCount !== 0 && currencyCode !== baseCurrencyCode);

    if (childCount === 0 || currencyCode === baseCurrencyCode) {
        gridBuilder.setCellValue(rowIndex, "CurrencyRate", "1");
        setValueNonRaiseEvent(gridBuilder, rowIndex, "CurrencyDebit", "");
        setValueNonRaiseEvent(gridBuilder, rowIndex, "CurrencyCredit", "");
    } else {
        var $element = gridBuilder.getCellEditor("CurrencyDebit");
        if ($element)
            $element.attr("data-decimalCount", decimalCount);
        $element = gridBuilder.getCellEditor("CurrencyCredit");
        if ($element)
            $element.attr("data-decimalCount", decimalCount);
    }

}
function exportSampleExcel(gridId, type) {
    if (type === "excelSample") {
        exportExcel(null, gridBuilder.getColumns(), gridBuilder.getColumnsCaption(), true);
    } else
        exportExcel(gridBuilder.getDataArray()["data"], gridBuilder.getColumns(), gridBuilder.getColumnsCaption());
}

async function getDocument(code) {
    await ajax({
        url: "AccountingApi/GetDocument",
        data: {
            documentCode: code,
            isNote: getQuery("CodeSanadState") === CONS.noteDocument,
            loadDetail: true,
            isCopy: getQuery("CodeSanadCopy").length > 0
        },
        success: function (result) {
            if (result.Articles.length > 0) {
                gridBuilder.loadData(result.Articles);
            }
            setHeader(result.Header, result.Attachments);
        }
    });
}
function setHeader(header, attachments) {
    $("#txtDate").val(header.DocumentDateLocal);
    $("#txtCode").val(header.Code);
    $("#txtAft").val(header.AtfCode);
    $("#txtDailyCode").val(header.DailyCode);
    $("#txtSummary").val(header.Summary);
    $("#hfOldCodeSanadState").val(header.DocumentStateCode);
    $("#hfCodeSanadType").val(header.DocumentTypeCode);
    $("#lblCodeAuto").text(header.AutoCode);
    $("#lblCodeSanadType").text(header.DocumentTypeName);
    $("#lblSanadState").text(header.DocumentStateName);
    $("#lblOwner").text(header.ExporterUserName);
    updateSummaryTbl();

    if (($("#hfOldCode").val() !== "-1" && header.ExporterSystemName !== "" && header.ExporterSystemName.toLowerCase() !== CONS.accounting.toLowerCase()) || (header.IsCertain && header.DocumentStateCode !== 1)) {
        var msg = header.IsCertain && header.DocumentStateCode !== 1 ? window.top.disabledEdit : window.top.disabledEditSystemConflict;
        $("#lblDisabledEdit").text(msg);
        $("input[type='text']").prop("disabled", true);
        $(".header").append("<label style='color:#EF6C00'>" + msg + "</label>").css({ "background-color": "#FFF3E0", "text-align": "center" });
        $(".header").find("input[type='button']").hide();
        gridBuilder.setEnabled(false);
    }
    if (attachments && attachments.length > 0) {
        $.each(attachments, function () {
            createFileContainer(this.FileId, this.FileName, this.FileSize, "");
        });
    }
}

function calculateRow() {
    var rowIndex = gridBuilder.getActiveRowIndex();
    var currencyCode = Number(gridBuilder.getCellValue(rowIndex, "CurrencyCode"));
    if (currencyCode && currencyCode !== baseCurrencyCode) {
        var currencyRate = numberNonCommas(gridBuilder.getCellValue(rowIndex, "CurrencyRate"), 0);
        var decimalCount = numberNonCommas(gridBuilder.getCellValue(rowIndex, "CurrencyDecimalCount"), 0);
        var bedehkar = numberNonCommas(gridBuilder.getCellValue(rowIndex, "Debit"), 0);
        var bestankar = numberNonCommas(gridBuilder.getCellValue(rowIndex, "Credit"), 0);
        var bedehkarArz = numberWithCommas(currencyRate === 0 ? 0 : (bedehkar / currencyRate), decimalCount);
        var bestankarArz = numberWithCommas(currencyRate === 0 ? 0 : (bestankar / currencyRate), decimalCount);


        setValueNonRaiseEvent(gridBuilder, rowIndex, "CurrencyDebit", bedehkarArz);
        setValueNonRaiseEvent(gridBuilder, rowIndex, "CurrencyCredit", bestankarArz);

    }

    updateSummaryTbl();
}
function updateSummaryTbl() {

    var badahkar = gridBuilder.getSumColumn("Debit");
    var bastankar = gridBuilder.getSumColumn("Credit");
    var mode = Math.abs(badahkar - bastankar);

    $("#txtSumBadahkar").text(numberWithCommas(badahkar, baseDecimalCount));
    $("#txtSumBastankar").text(numberWithCommas(bastankar, baseDecimalCount));
    if (badahkar > bastankar) {
        $("#txtDifBadahkar").text(numberWithCommas(mode, baseDecimalCount));
        $("#txtDifBastankar").text(numberWithCommas("0", baseDecimalCount));
    }
    else {
        $("#txtDifBadahkar").text(numberWithCommas("0", baseDecimalCount));
        $("#txtDifBastankar").text(numberWithCommas(mode, baseDecimalCount));
    }
}

function tarazSanad(rowIndex) {
    var currencyCode = Number(gridBuilder.getCellValue(rowIndex, "CurrencyCode"));
    var decimalCount = Number(gridBuilder.getCellValue(rowIndex, "CurrencyDecimalCount"));
    decimalCount = currencyCode ? decimalCount : baseDecimalCount;
    var bed = gridBuilder.getSumColumn("Debit");
    var bes = gridBuilder.getSumColumn("Credit");
    if (bed === bes)
        return;
    var badahkar = numberNonCommas(gridBuilder.getCellValue(rowIndex, "Debit"), 0);
    var bastankar = numberNonCommas(gridBuilder.getCellValue(rowIndex, "Credit"), 0);
    var bedehkarArz = numberNonCommas(gridBuilder.getCellValue(rowIndex, "CurrencyDebit"), 0);
    var bestankarArz = numberNonCommas(gridBuilder.getCellValue(rowIndex, "CurrencyCredit"), 0);

    if (badahkar > 0 || bastankar > 0 || bedehkarArz > 0 || bestankarArz > 0) {
        gridBuilder.addNewRow();
        rowIndex = gridBuilder.getRowsCount() - 1;
    }
    if (bed > bes)
        gridBuilder.setCellValue(rowIndex, 'Credit', numberWithCommas(bed - bes, decimalCount));
    else
        gridBuilder.setCellValue(rowIndex, 'Debit', numberWithCommas(bes - bed, decimalCount));
}
function changeBedBes(rowIndex) {
    var bedehkar = numberNonCommas(gridBuilder.getCellValue(rowIndex, "Debit"), 0);
    var bestankar = numberNonCommas(gridBuilder.getCellValue(rowIndex, "Credit"), 0);
    gridBuilder.setCellValue(rowIndex, "Debit", bestankar);
    gridBuilder.setCellValue(rowIndex, "Credit", bedehkar);
    calculateRow();
}
function turnover(rowIndex) {
    var moainCode = gridBuilder.getCellValue(rowIndex, "MoainCode");
    var tafsilId = gridBuilder.getCellValue(rowIndex, "TafsilId");
    var costCenterId = gridBuilder.getCellValue(rowIndex, "CostCenterId");
    var projectId = gridBuilder.getCellValue(rowIndex, "ProjectId");
    var currencyCode = gridBuilder.getCellValue(rowIndex, "CurrencyCode");
    openInModal("", "Accounting/ReportTurnover?ismod=1&mn=" + moainCode + "&tf=" + tafsilId + "&hz=" + costCenterId + "&prj=" + projectId + "&arz=" + currencyCode + "&as=" + currentYear + "&ts=" + currentYear + "&grd=1&he=1&hf=1&hn=1&hc=1", window.top.viewTurnover);

}
function getTafsilRemained(rowIndex) {
    var moainCode = gridBuilder.getCellValue(rowIndex, "MoainCode");
    var tafsilId = gridBuilder.getCellValue(rowIndex, "TafsilId");
    var costCenterId = gridBuilder.getCellValue(rowIndex, "CostCenterId");
    var projectId = gridBuilder.getCellValue(rowIndex, "ProjectId");
    if (moainCode) {
        ajax({
            loading: true,
            url: "AccountingApi/GetTafsilRemained",
            data: {
                tafsilId: tafsilId || null,
                costCenterId: costCenterId || null,
                projectId: projectId || null,
                moainCode: moainCode || null
            },
            success: function (retValue) {
                if (retValue !== 0)
                    retValue = numberWithCommas(retValue, window.top.$("#hfDecimalCount").val()) + " " + window.top.$("#hfBaseCurrencyName").val() + " " + (retValue < 0 ? window.top.credit : window.top.debit);
                $("body").append("<div id='lblMandeh' style='border: 1px solid #efefef;background-color: #FFEB3B;padding-right: 10px;padding-left: 10px;line-height: 31px;position:absolute;top:165px;left:580px;'>" + retValue + "</div>");
                setTimeout(function () { $("#lblMandeh").remove(); }, 3000);
            }
        });
    }
}


function onAttachClick() {
    $("input[type=file]").click();
}
function onFileChange(sender, event) {
    if (sender.files.length > 0) {
        var file = event.target.files[0];
        var reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = function () {
            createFileContainer("-1", file.name, Math.round(file.size / 1024), reader.result);
        };
    }
}
function deleteAttach(sender) {
    var $fileBox = $(sender).closest(".attached-file");
    if (parseInt($fileBox.attr("Code")) > 0) {
        $fileBox.attr("Deleted", true);
        $fileBox.hide();
    }
    else
        $(sender).closest(".attached-file").remove();
}
function openFileDropDown() {
    $(".attached-panel").toggle();
    event.stopPropagation();
}
function getFile(element) {
    var parentElement = $(element).closest(".attached-file");
    var base64 = parentElement.attr("data-base64");
    var filename = parentElement.find("[data-id=fileName]").text();
    if (base64) {
        createFileLink(filename, base64);
    }
    else
        ajax({
            loading: true,
            url: "AccountingApi/GetAttachFileUrl",
            data: { fileId: parentElement.attr("data-fileId") },
            success: function (result) {
                createFileLink(filename, result);
            }
        });
}
function createFileContainer(fileId, filename, fileSize, base64) {
    var $data = $(".attached-file[hidden]").clone();
    $data.removeAttr("hidden");
    $data.attr("Code", fileId);
    $data.attr("Deleted", false);
    $data.find("[data-id=fileName]").text(filename);
    $data.find("[data-id=fileExtension]").attr("src", baseUrl + "img/fileFormat/" + filename.split('.').pop() + ".svg");
    $data.find("[data-id=fileSize]").text(fileSize + "KB");
    $data.attr("data-fileId", fileId);
    if (base64)
        $data.attr("data-base64", base64);
    $(".attached-file[hidden]").parent().prepend($data);
}
function createFileLink(filename, href) {
    var link = document.createElement('a');
    link.download = filename;
    link.href = href;
    link.click();
    link.remove();
}
function reloadParentIframe() {
    if (getQuery('refmanager') === '1') {
        closeCurrentTab();
    }
    else if (getQuery('yearclose') === '1') {
        refreshParent("refreshGrid('clear')");
        closeTopModal();
    }
}
function openPrint(codeSanad, year) {
    var title = window.top.printDocument;
    var src = "Report/Default?GrpName=SanadGheyasPlus&Inst=" + codeSanad + "&salmali=" + year;
    openInModal('', src, title, "", "", false);
}
function getAttachmentArray() {
    var attachArray = [];
    $.each($(".attached-file:not([hidden])"), function () {
        var obj = {};
        var code = $(this).attr("Code");
        if (code == -1)
            obj["FileAttchsString"] = $(this).attr("data-base64");
        else
            obj["FileAttchsString"] = "";
        obj["FileName"] = $(this).find("[data-id=fileName]").text();
        obj["FileId"] = code;
        obj["FileDeleted"] = $(this).attr("Deleted");
        attachArray.push(obj);
    });
    return attachArray;
}
function save(codeSanadState) {
    var exceptionText = checkValidation('');
    if (exceptionText === '') {
        var header = getJsonValue();
        var articles = gridBuilder.getDataArray()["data"].filter(function (item) { return item.MoainCode !== null; });
        articles.forEach(function (item) {
            item.CurrencyDebit = numberNonCommas(item.CurrencyDebit);
            item.CurrencyCredit = numberNonCommas(item.CurrencyCredit);
        });
        header["DocumentStateCode"] = codeSanadState;
        header["DocumentStateCodeMain"] = $("#hfOldCodeSanadState").val();
        header["Code"] = $("#hfOldCode").val();
        ajax({
            loading: true,
            url: "AccountingApi/" + (Number(header["Code"]) > 0 ? "UpdateDocument" : "InsertDocument"),
            data: {
                header: header,
                articles: articles,
                printAfter: $("#cboPrintAfter").prop("checked"),
                attachment: getAttachmentArray()
            },
            success: function (result) {
                showMsgModal(2, result.FinalMessage);
                if (getQuery("refmanager") === "1" || getQuery("yearclose") === "1") {
                    reloadParentIframe();
                }
                else {
                    if (codeSanadState === 1 && $("#cboPrintAfter").prop("checked"))
                        alert(window.top.notPrintNote);
                    else {
                        var retValue = result.ReturnValue.split("|");
                        if ($("#cboPrintAfter").prop("checked"))
                            openPrint(retValue[0], retValue[1]);
                    }
                    newSanad();
                }
            }
        });
    }
    else {
        showMsgModal(0, exceptionText);
    }
}
async function getCurrencyRate(rowIndex, currencyCode) {
    await ajax({
        url: "SaleApi/GetCurrencyRate",
        data: {
            currencyCode: currencyCode,
            date: $("#txtDate").val()
        },
        success: function (retValue) {
            gridBuilder.setCellValue(rowIndex, "CurrencyRate", retValue ? retValue.PriceInReal : 1);
        }
    });
}




























