var gridBuilder;
var gridArtiklesBuilder;
var isAdmin = window.top.$("#hfIsAdmin").val();
var currentYear = window.top.$("#hfCurrentYear").val();
$(document).ready(function () {
    gridBuilder = $("#gridDocument").gridBuilder();
    gridArtiklesBuilder = $("#gridArtikles").gridBuilder();
    if (isAdmin === "1") {
        $("#btnTransfer").show();
    }
    gridBuilder.onRowChanged(function (rowIndex) {
        if (rowIndex === -1)
            rowIndex = 0;
        var state = Number(gridBuilder.getCellValue(rowIndex, "DocumentStateCode"));
        var isFinal = gridBuilder.getCellValue(rowIndex, "IsFinalized").toString() === "true";
        var backStr = "", forwardStr = "";
        switch (state) {
            case 1: case 0:
                forwardStr = window.top.convertTemporary;
                backStr = window.top.convertNote;
                break;
            case 2:
                forwardStr = window.top.convertCertain;
                backStr = window.top.convertNote;
                break;
            case 3: case 4:
                forwardStr = window.top.convertFinal;
                backStr = window.top.convertTemporary;
                break;
        }
        if (state === 0) {
            $("#btnBack").prop("disabled", true);
            $("#btnForward").prop("disabled", true);
        }
        else {
            $("#btnBack").prop("disabled", (state === 1 || isFinal ? true : false)).val(backStr);
            $("#btnForward").prop("disabled", isFinal).val(forwardStr);
        }

    });
    gridBuilder.onDblClick(function () {
        var rowIndex = gridBuilder.getActiveRowIndex();
        if (rowIndex < 0) {
            return;
        }
        $("#level2").show();
        $("#level1").hide();
        $("#lblDocumentNumber").text(gridBuilder.getCellValue(rowIndex, "Code"));
        $("#lblDocumentDate").text(gridBuilder.getCellValue(rowIndex, "DocumentDateLocal"));
        $("#lblState").text(gridBuilder.getCellValue(rowIndex, "DocumentStateName"));
        $("#lblSystem").text(gridBuilder.getCellValue(rowIndex, "ExporterSystemName"));
        gridArtiklesBuilder.changeSelection(-1, false);
        loadGrid("gridArtikles");
    });
    gridArtiklesBuilder.onRowChanged(function (rowIndex) {
        var nameMoain = gridArtiklesBuilder.getCellValue(rowIndex, "MoainName");
        var nameTafsil = gridArtiklesBuilder.getCellValue(rowIndex, "TafsilName");
        var nameCostCenter = gridArtiklesBuilder.getCellValue(rowIndex, "CostCenterName");
        var nameProject = gridArtiklesBuilder.getCellValue(rowIndex, "ProjectName");
        $('#lblDetail').text(nameMoain + (nameTafsil ? " / " + nameTafsil : "") + (nameCostCenter ? " / " + nameCostCenter : "") + (nameProject ? " / " + nameProject : ""));
    });
    gridBuilder.onExportClick(function () {
        loadGrid("gridDocument", { exportExcel: true });
    });
    gridArtiklesBuilder.onExportClick(function () {
        loadGrid("gridArtikles", { exportExcel: true });
    });
    loadGrid("gridDocument");
    imgToSvg();
});
function loadGrid(gridId, objectParameter) {
    var isExportExcel = objectParameter && objectParameter.exportExcel ? true : false;
    if (gridId === "gridDocument") {
        var selectionCriteria = gridBuilder.selectionViewMode ? "'" + gridBuilder.selectionList.join("','") + "'" : null;
        var documentStateCode = Number($("#cboDocumentStateCode").val());
        ajax({
            url: "AccountingApi/GetDocumentList",
            gridBuilder: gridBuilder,
            data: {
                fromDocumentCode: $("#txtFromCode").val() || -1,
                toDocumentCode: $("#txtToCode").val() || -1,
                fromDate: $("#txtFromDate").val(),
                toDate: $("#txtToDate").val(),
                documentStateCode: documentStateCode === -1 ? null : documentStateCode,
                filter: gridBuilder.getFilter(),
                sort: gridBuilder.getSortFields(),
                pageNo: isExportExcel ? -1 : gridBuilder.getCurrentPageNumber(),
                selectionCriteria: selectionCriteria
            },
            success: function (data) {
                if (isExportExcel) {
                    exportExcel(data, gridBuilder.getColumns(), gridBuilder.getColumnsCaption());
                }
                else {
                    data.forEach(function (item) {
                        if (item.AttcCount > 0) {
                            item.AttcCount = baseUrl + "img/attach1.png";
                        }
                    });
                    gridBuilder.loadData(data);
                }
            }
        });
    }
    else {
        var rowIndex = gridBuilder.getActiveRowIndex();
        if (rowIndex < 0) {
            return;
        }
        var documentCode = gridBuilder.getCellValue(rowIndex, "Code");
        var state = Number(gridBuilder.getCellValue(rowIndex, "DocumentStateCode"));
        getArtikles(documentCode, state === 1, isExportExcel);
    }
}
function getArtikles(documentCode, isNote, isExportExcel) {
    var loadAll = $("#chkShowAllArtikles").prop("checked");
    var lstCodes = [];
    if (gridArtiklesBuilder.selectionViewMode)
        gridArtiklesBuilder.selectionList.forEach(function (x) { lstCodes.push(x.substr(0, x.length - 1)); });
    ajax({
        gridBuilder: gridArtiklesBuilder,
        url: "AccountingApi/GetArticleList",
        data: {
            documentCode: loadAll ? -1 : documentCode,
            isNote: loadAll ? false : isNote,
            filter: gridArtiklesBuilder.getFilter(),
            sort: gridArtiklesBuilder.getSortFields(),
            pageNo: isExportExcel ? -1 : gridArtiklesBuilder.getCurrentPageNumber(),
            selectionCriteria: gridArtiklesBuilder.selectionViewMode ? "'" + lstCodes.join("','") + "'" : null
        },
        success: function (data) {
            if (isExportExcel) {
                exportExcel(data, gridArtiklesBuilder.getColumns(), gridArtiklesBuilder.getColumnsCaption());
            }
            else {
                data.forEach(function (item) {
                    item.RowKey = item.Code.toString() + (item.IsNote ? "1" : "2");
                });
                gridArtiklesBuilder.loadData(data);
                $('#lblDetail').show();
            }
        }
    });
}
function getSelectedCodes() {
    var selectedCodes = gridBuilder.getSelectedRowsCellValue("Code");
    var selectedStates = gridBuilder.getSelectedRowsCellValue("DocumentStateCode");
    if (selectedCodes.length === 0) {
        var rowIndex = gridBuilder.getActiveRowIndex();
        if (rowIndex >= 0) {
            selectedCodes.push(gridBuilder.getCellValue(rowIndex, "Code"));
            selectedStates.push(gridBuilder.getCellValue(rowIndex, "DocumentStateCode"));
        }
    }
    return { codes: selectedCodes, states: selectedStates };
}
function changeDocumentState(state) {
    var selected = getSelectedCodes();
    var currentState = selected.states[0];
    if (selected.codes.length === 0) {
        showMsgModal(0, window.top.chooseItem);
        return;
    }
    if (!checkAllRecordType(selected.states)) {
        showMsgModal(0, window.top.sameTypeDocument);
        return;
    }
    if (state === "forward" && Number(currentState) === 3) {
        $("#ConfirmModal").modal();
        return;
    }
    var toState = 0;
    if (confirm(window.top.changeStatus)) {
        if (state === "forward") {
            toState = Number(currentState) + 1;
        }
        else {
            toState = Number(currentState) - 1;
        }
        ajax({
            loading: true,
            url: "AccountingApi/ChangeDocumentState",
            data: {
                codes: selected.codes,
                fromState: currentState,
                toState: toState
            },
            success: function (retValue) {
                showMsgModal(2, retValue.FinalMessage);
                gridBuilder.changeSelection(-1, false);
                loadGrid("gridDocument");
            }
        });
    }
}
function checkAllRecordType(states) {
    var type = states[0];
    var result = true;
    for (var i = 0; i < states.length; i++) {
        if (states[i] !== type) {
            result = false;
        }
    }
    return result;
}
function showDocumentList() {
    $("#level2").hide();
    $("#level1").show();
}
function showAllArtikles(sender) {
    if ($(sender).prop("checked")) {
        $(".label-value-readonly").text("---");
        loadGrid("gridArtikles");
    }
    else {
        gridBuilder.dblClick();
    }
}
function edit() {
    var rowIndex = gridBuilder.getActiveRowIndex();
    if (rowIndex < 0)
        return;

    var documentCode = gridBuilder.getCellValue(rowIndex, "Code");
    var username = gridBuilder.getCellValue(rowIndex, "ExporterUserName");
    var state = Number(gridBuilder.getCellValue(rowIndex, "DocumentStateCode"));
    var year = gridBuilder.getCellValue(rowIndex, "Year");
    var url = "Accounting/InvoiceSave?CodeSanad=" + documentCode + "&UserName=" + username + "&CodeSanadState=" + (state === 1 ? 1 : 2) + "&refmanager=1&SalMali=" + year;
    lockDocument(documentCode, url);
}
function deleteDocument() {
    var selected = getSelectedCodes();
    if (selected.codes.length === 0) {
        showMsgModal(0, window.top.chooseItem);
        return;
    }
    if (!checkAllRecordType(selected.states)) {
        showMsgModal(0, window.top.sameTypeDocument);
        return;
    }
    if (confirm(window.top.deleteConfirm)) {
        ajax({
            loading: true,
            url: 'AccountingApi/DeleteDocument',
            data: {
                codes: selected.codes,
                isNote: Number(selected.states[0]) === 1
            },
            success: function (retValue) {
                showMsgModal(2, retValue.FinalMessage);
                gridBuilder.changeSelection(-1, false);
                loadGrid("gridDocument");
            }
        });
    }
}
function printDocument() {
    var selected = getSelectedCodes();
    if (selected.codes.length === 0) {
        showMsgModal(0, window.top.chooseItem);
        return;
    }
    var title = window.top.printDocument;
    var src = "Report/Default?GrpName=SanadGheyasPlus&Inst=" + selected.codes.join(",") + "&Salmali=" + currentYear;
    openInModal('', src, title, "", "", false);
}
function splitDocument() {
    var selectedCodes = gridArtiklesBuilder.getSelectedRowsCellValue("Code");
    if (selectedCodes.length === 0) {
        var rowIndex = gridArtiklesBuilder.getActiveRowIndex();
        if (rowIndex < 0) {
            showMsgModal(0, window.top.chooseItem);
            return;
        }
        selectedCodes.push(gridArtiklesBuilder.getCellValue(rowIndex, "Code"));
    }
    if (confirm(window.top.sureParseArticles)) {
        ajax({
            loading: true,
            url: "AccountingApi/SplitDocument",
            data: { articleCodeList: selectedCodes },
            success: function (retValue) {
                showMsgModal(2, retValue.FinalMessage);
                loadGrid("gridArtikles");
            }
        });
    }
}
function mergeDocument() {
    var selected = getSelectedCodes();
    if (selected.codes.length === 0) {
        showMsgModal(0, window.top.chooseItem);
        return;
    }
    if (selected.codes.length === 1) {
        showMsgModal(0, window.top.mergeValid);
        return;
    }
    if (!checkAllRecordType(selected.states)) {
        showMsgModal(0, window.top.sameTypeDocument);
        return;
    }
    if (confirm(window.top.combineDocuments)) {
        ajax({
            loading: true,
            url: "AccountingApi/MergeDocument",
            data: { codes: selected.codes },
            success: function (retValue) {
                showMsgModal(2, retValue.FinalMessage);
                loadGrid("gridDocument");
            }
        });
    }
}
function copyDocument() {
    var rowIndex = gridBuilder.getActiveRowIndex();
    if (rowIndex < 0) {
        showMsgModal(0, window.top.chooseItem);
        return;
    }
    var code = gridBuilder.getCellValue(rowIndex, "Code");
    var state = Number(gridBuilder.getCellValue(rowIndex, "DocumentStateCode"));
    var year = Number(gridBuilder.getCellValue(rowIndex, "Year"));
    var url = "Accounting/InvoiceSave?CodeSanadCopy=" + code + "&CodeSanadState=" + (state === 1 ? 1 : 2) + "&refmanager=1&SalMali=" + year;
    lockDocument(code, url);
}
function lockDocument(code, url) {
    ajax({
        url: "GeneralApi/LockDocument",
        data: { systemName: "THS_SanadWeb", Code: code },
        success: function (retValue) {
            openInTab(url, window.top.accountDocument, "img/pages/menu/121.svg", true);
        }
    });
}
function continueFinalize() {
    openInModal('', 'Accounting/InvoiceFinalize', window.top.finalRegistration, '900', '420', false);
    $("#ConfirmModal").modal("hide");
}