var moainList;
var code = getQuery("code");
var state = getQuery("state").toLowerCase() === "true";
var isAccountingMode = getQuery("accounting") !== "";
var decimalCount = parseInt(window.top.$('#hfDecimalCount').val());
var gridBuilder;

$(document).ready(function () {
    gridBuilder = $(".grid").gridBuilder();
    gridBuilder.onCellChanged(gridCellChange);
    if (!isAccountingMode) {
        gridBuilder.removeColumn("MoainCode");
        gridBuilder.removeColumn("TafsilId");
        gridBuilder.removeColumn("CostCenterId");
        gridBuilder.removeColumn("ProjectId");
    }
    else {
        gridBuilder.setEnableColumn("Price", false);
        gridBuilder.setEnableColumn("Summery", false);
        gridBuilder.setEnableColumn("TrackingCode", false);
        gridBuilder.setEnableColumn("TrackingDateLocal", false);
    }
    $("#cboFund").lookupBuilder().onChanged(async function () {
        if (code === "")
            await getMaxFundDocumentNumber();
    });
    gridBuilder.onRowChanged(function () {
        var rowIndex = gridBuilder.getActiveRowIndex();
        var nameMoain = gridBuilder.getCellValue(rowIndex, "NameMoain");
        if (!nameMoain) {
            $("#detailCaption").html("");
            return;
        }
        var nameTafsil = gridBuilder.getCellValue(rowIndex, "NameTafsil");
        var nameMHazineh = gridBuilder.getCellValue(rowIndex, "NameMHazineh");
        var nameProject = gridBuilder.getCellValue(rowIndex, "NameProject");

        $("#detailCaption").html((nameMoain ? nameMoain + "/" : "") + (nameTafsil ? nameTafsil + "/" : "") + (nameMHazineh ? nameMHazineh + "/" : "") + (nameProject ? nameProject + "/" : ""));
    });
    gridBuilder.onGetComboData(getGridComboData);
    gridBuilder.onSetMaskEdit(setEventMaskEdit);
    gridBuilder.onStartEditing(startEditingGrid);
    gridBuilder.onPgmSumChanged(function () {
        updateSummeryTbl();
    });
    initial();
});
async function initial() {
    $("#txtCode").prop("disabled", true);
    if (isAccountingMode) {
        $("#cboFund").lookupBuilder().setEnabled(false);
        $("#txtCodeInFund").prop("disabled", true);
        $("#txtDate").prop("disabled", true);
        $("#txtTozihat").prop("disabled", true);

        await getMoainList();
    }

    await getFundDocument(code || -1);
    

    closeLoading();
    $("#divMain").show();

    if (code === "")
        gridBuilder.addNewRow();
}
function getMoainList() {
    ajax({
        url: "AccountingApi/GetMoainList",
        data: { checkActive: true, pageNo: -1 },
        success: function (result) {
            moainList = result;
        }
    });
}
async function getMaxFundDocumentNumber() {
    var funderCode = $("#cboFund").lookupBuilder().getSelectedValue();
    if (!funderCode)
        return;
    await ajax({
        url: "TreasuryApi/GetMaxFundDocumentNumber",
        data: { funderCode: funderCode },
        success: function (result) {
            $("#txtCodeInFund").val(result);
        }
    });
}
async function getFundDocument(code) {
    await ajax({
        url: "TreasuryApi/GetFundDocument",
        data: { code: code },
        success: function (result) {
            if (result.Articles.length > 0) {
                gridBuilder.loadData(result.Articles);
            }
            setHeader(result.Header);
        }
    });
}
async function getEventLookupCombo($combo, search, code) {
    var result;
    await ajax({
        url: "TreasuryApi/GetFunderList",
        data: { search: search, pageNo: 1, selectedCode: code },
        success: function (resValue) {
            result = resValue;
        }
    });
    result.forEach(function (item) { item.Name = item.CustomerName; });
    $combo.lookupBuilder().bindData(result);
    if (!code && result.length > 0)
        await $combo.lookupBuilder().setSelectedValue(result[0].Code);
}
async function setHeader(header) {
    $("#txtDate").val(header.DocumentDateLocal);
    $("#txtCode").val(header.DocumentSerial);
    if (code !== "") {
        $("#cboFund").lookupBuilder().setSelectedValue(header.FunderCode);
        $("#txtCodeInFund").val(header.DocumentNumber);
        $("#txtTozihat").val(header.Summery);
        $("#hfState").val(header.IsConfirm ? "1" : "0");
    }
    else
        await getEventLookupCombo($("#cboFund"));

    updateSummeryTbl();

    if (header.AccDocumentCode > 0 || state) {
        gridBuilder.setEnabled(false);

        $("#btnSave").hide();
        $("#lblDisabledEdit").text(state ? window.top.unableEditApprovedDocument : window.top.unableEditFundDocument).css({ "color":"#EF6C00"});
        $("#divBtnContainer").css({ "background-color": "#FFF3E0", "text-align": "center" });      
    }
}
function updateSummeryTbl() {
    var sumPrice = gridBuilder.getSumColumn("Price");
    $("#lblPrice").text(numberWithCommas(sumPrice));
}
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(x => x.Name.indexOf(search) >= 0 || x.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;

    }
}
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);

}
function gridCellChange(rowIndex, columnIndex) {
    
    var value = gridBuilder.getCellValue(rowIndex, columnIndex);
    var fieldName = gridBuilder.getCellFieldName(columnIndex);
    if (fieldName === "MoainCode") {
        gridBuilder.setCellValue(rowIndex, "TafsilId", "");
        gridBuilder.setCellValue(rowIndex, "CostCenterId", "");
        gridBuilder.setCellValue(rowIndex, "ProjectId", "");
        gridBuilder.setCellValue(rowIndex, "TafsilName", "");
        gridBuilder.setCellValue(rowIndex, "CostCenterName", "");
        gridBuilder.setCellValue(rowIndex, "ProjectName", "");

        startEditingGrid(rowIndex);
        gridBuilder.rowChanged();
    }

    else if (fieldName === "CostCenterId" || fieldName === "ProjectId" || fieldName === "TafsilId") {
        if (!value) {
            if (fieldName === "CostCenterId")
                gridBuilder.setCellValue(rowIndex, "CostCenterName", "");
            else
                gridBuilder.setCellValue(rowIndex, "ProjectName", "");
            return;
        }
        ajax({
            url: "AccountingApi/GetTafsilInfo",
            data: { tafsilId: value },
            success: function (result) {
                if (fieldName === "CostCenterId")
                    gridBuilder.setCellValue(rowIndex, "CostCenterName", result.Name);
                else if (fieldName === "ProjectId")
                    gridBuilder.setCellValue(rowIndex, "ProjectName", result.Name);
                else
                    gridBuilder.setCellValue(rowIndex, "TafsilName", result.Name);
                gridBuilder.rowChanged();
            }
        });
    }
    else if (fieldName === "Price") {
        updateSummeryTbl();
    }
    if (gridBuilder.isRowEditMode(rowIndex) && gridBuilder.getActiveCellIndex() === columnIndex)
        gridBuilder.setEditRow(rowIndex, columnIndex + 1, true);
}
function newSanad(isAccounting) {
    redirectUrl("FundDocumentSave?openInTab=" + getQuery('openInTab') + "&accounting=" + isAccounting);
}
function openPrint(codeSanad, year) {
    var title = window.top.printDocument;
    var src = "Report/Default?GrpName=Trs_Tankhah_Sanad&Codesanad=" + codeSanad;
    openInModal('', src, title,"","",false);
}
function save() {
    var exceptionText = checkValidation('');
    if (exceptionText === '') {
        var artikle = gridBuilder.getDataArray()["data"].filter(x => x.Summery !== null || x.Price !== null);
        var header = getJsonValue();
        var isAccounting = getQuery('accounting');
        header["IsConfirm"] = $("#hfState").val() === "1";
        ajax({
            loading: true,
            url: 'TreasuryApi/SaveFundDocument',
            data: { header: header, articles: artikle, printAfter: $("#cboPrintAfter").prop('checked') },
            success: function (retValue) {
                showMsgModal(2, retValue.FinalMessage.join("<br />"));
                if ($('#cboPrintAfter').prop('checked'))
                    openPrint(retValue.ReturnValue, window.top.$("#hfCurrentYear").val());
                newSanad(isAccounting);
            }
        });
    }
    else {
        showMsgModal(0, exceptionText);
    }
}

