var gridBuilder;
var gridArtiklBuilder;
var enumDocumentTypeParentCode = {
    codeMoadelSale: 1,
    codeMoadelPreInvoice: 20,
    codeMoadelPurchase: 2,
    codeMoadelReturnSale: 10,
    codeMoadelReturnPurchase: 13,
    CodeMoadelAddedConflictStore: 4,
    CodeMoadelReducedConflictStore: 18,
};
$(document).ready(function () {
    gridBuilder = $("#gridDocument").gridBuilder();
    gridArtiklBuilder = $("#gridArtikle").gridBuilder();
    if (window.top.$("#hfCurrencySystem").val() !== "1") {
        gridBuilder.removeColumn("CurrencyName");
    }
    if (getQuery("type") === "")
        gridBuilder.removeColumn("ConfirmStateName");
    else if (getQuery("type") === "8") {
        gridBuilder.removeColumn("GhT_Out");
    }
    else if (getQuery("type") === "6") {
        gridBuilder.removeColumn("GhT_In");
    }
    $("#cboDocumentType").lookupBuilder().onChanged(function () {
        loadGrid('gridDocument');
    });
    gridBuilder.onExportClick(function () {
        loadGrid("gridDocument", { exportExcel: true });
    });
    gridArtiklBuilder.onExportClick(function () {
        loadGrid("gridArtikle", { exportExcel: true });
    });
    gridBuilder.onDblClick(function () {
        var rowIndex = gridBuilder.getActiveRowIndex();
        if ($('#arrowRiz').hasClass('disabled-riz') || rowIndex < 0) {
            return;
        }
        var isShop = gridBuilder.getCellValue(rowIndex, "IsShop").toString() === "true";
        if (isShop)
            return;
        $("#level2").show();
        $("#level1").hide();
        setDisabled(true);
        loadGrid("gridArtikle");
    });

    gridBuilder.onRowChanged(function () {
        var rowIndex = gridBuilder.getActiveRowIndex();
        if (rowIndex < 0)
            return;
        var stateName = gridBuilder.getCellValue(rowIndex, "StateName");
        var saleSystemParentCode = Number(gridBuilder.getCellValue(rowIndex, "SaleSystemParentCode"));
        var isPos = saleSystemParentCode === saleSystemParent.pos;
        var baseRequire = gridBuilder.getCellValue(rowIndex, "BaseRequire") === "true";
        var documentTypeParentCode = Number(gridBuilder.getCellValue(rowIndex, "FactorTypeParentCode"));
        switch (convertArabicToPersian(stateName)) {
            case window.top.nonCertain:
                $("#btnState").val(window.top.convertCertain).attr("data-state", 1);
                break;
            case window.top.certain:
                $("#btnState").val(window.top.returnFromCertain).attr("data-state", 0);
                break;
        }
        if (documentTypeParentCode === enumDocumentTypeParentCode.CodeMoadelAddedConflictStore || documentTypeParentCode === enumDocumentTypeParentCode.CodeMoadelReducedConflictStore) {
            $("#btnCopy>input").prop("disabled", true).addClass("btnTemporary-disabled").removeClass("btnTemporary");
            $("#btnDelete").prop("disabled", true).addClass("btnTemporary-disabled").removeClass("btnTemporary");
            $("#btnEdit").prop("disabled", true).addClass("btnTemporary-disabled").removeClass("btnTemporary");
        }
        else {
            $("#btnDelete").prop("disabled", isPos).removeClass("btnTemporary btnTemporary-disabled").addClass(isPos ? "btnTemporary-disabled" : "btnTemporary");
            $("#btnEdit").prop("disabled", isPos).removeClass("btnTemporary btnTemporary-disabled").addClass(isPos ? "btnTemporary-disabled" : "btnTemporary");
            $("#btnCopy>input").prop("disabled", baseRequire).removeClass("btnTemporary btnTemporary-disabled").addClass(baseRequire ? "btnTemporary-disabled" : "btnTemporary");
        }
    });
    if (getQuery("type") != "") {
        $("#btnOperation").removeClass("button-accept").addClass("button-default");
        $("#liControl").hide();
        $("#liControlDel").hide();
        $("#btnCopy").hide();
    }
    else {
        $("#btnNew").hide();
    }

    loadGrid("gridDocument");
    imgToSvg();
    closeLoading();
    $("#divMain").show();
});
function showAllArtikles(sender) {
    if ($(sender).prop("checked")) {
        loadGrid("gridArtikl");
    }
    else {
        gridBuilder.dblClick();
    }
}


function loadGrid(gridId, objectParameter) {
    var isExportExcel = objectParameter && objectParameter.exportExcel ? true : false;
    if (gridId === "gridDocument") {
        var selectionCriteria = gridBuilder.selectionViewMode ? "'" + gridBuilder.selectionList.join("','") + "'" : null;
        ajax({
            loading: false,
            gridBuilder: gridBuilder,
            url: "SaleApi/" + (getQuery("type") ? "GetStoreFactorList" : "GetAllFactorList"),
            data: {
                documentMode: getQuery("type") === "" ? 0 : getQuery("type") === "8" ? 7 : 8,
                fromDate: $("#txtFromDate").val(),
                toDate: $("#txtToDate").val(),
                filter: gridBuilder.getFilter(),
                sort: gridBuilder.getSortFields(),
                pageNo: isExportExcel ? -1 : gridBuilder.getCurrentPageNumber(),
                selectionCriteria: selectionCriteria,
                documentTypeCode: $("#cboDocumentType").lookupBuilder().getSelectedValue() || -1
            },
            success: function (data) {
                if (isExportExcel) {
                    exportExcel(data, gridBuilder.getColumns(), gridBuilder.getColumnsCaption());
                }
                else {
                    gridBuilder.loadData(data);
                }
            }
        });
    }
    else
        getArtikls(isExportExcel);
}
function getDetails() {
    gridBuilder.dblClick();
}
function showDocumentList() {
    if ($('#arrowSanad').hasClass('disabled-sanad'))
        return;
    $("#level2").hide();
    $("#level1").show();
    setDisabled(false);
}
function getArtikls(isExportExcel) {
    var rowIndex = gridBuilder.getActiveRowIndex();
    var factorSerial = gridBuilder.getCellValue(rowIndex, "FactorSerial");
    var loadAll = $("#chkShowAllArtikles").prop("checked");
    if (!loadAll)
        ajax({
            url: "SaleApi/GetFactor",
            data: {
                factorSerial: factorSerial,
                loadArtikles: true,
                filter: gridArtiklBuilder.getFilter(),
                sort: gridArtiklBuilder.getSortFields(),
                pageNo: isExportExcel ? -1 : gridArtiklBuilder.getCurrentPageNumber()
            },
            success: function (data) {
                if (isExportExcel) {
                    exportExcel(data.Artikles, gridArtiklBuilder.getColumns(), gridArtiklBuilder.getColumnsCaption());
                }
                else
                    gridArtiklBuilder.loadData(data.Artikles);
            }
        });
    else
        getAllArticleList(isExportExcel)
}
function getAllArticleList(isExportExcel) {
    ajax({
        loading: true,
        url: "SaleApi/GetAllArticleList",
        data: {
            isSaleDocument: false,
            filter: gridArtiklBuilder.getFilter(),
            sort: gridArtiklBuilder.getSortFields(),
            pageNo: isExportExcel ? -1 : gridArtiklBuilder.getCurrentPageNumber()
        },
        success: function (data) {
            if (isExportExcel) {
                exportExcel(data, gridArtiklBuilder.getColumns(), gridArtiklBuilder.getColumnsCaption());
            }
            else
                gridArtiklBuilder.loadData(data);
        }
    });
}


function setDisabled(state) {
    $('#txtFromDate').attr("disabled", state);
    $('#txtToDate').attr("disabled", state);
}
function getSelectedCodes() {
    var selectedCodes = gridBuilder.getSelectedRowsCellValue("FactorSerial");
    var selectedYears = gridBuilder.getSelectedRowsCellValue("Year");
    var selectedStates = gridBuilder.getSelectedRowsCellValue("IsCertain");
    var selectedShops = gridBuilder.getSelectedRowsCellValue("IsShop");
    var selectedParents = gridBuilder.getSelectedRowsCellValue("FactorTypeParentCode");
    var selectedAccCodes = gridBuilder.getSelectedRowsCellValue("DocumentCode");
    if (selectedCodes.length === 0) {
        var rowIndex = gridBuilder.getActiveRowIndex();
        if (rowIndex >= 0) {
            selectedCodes.push(gridBuilder.getCellValue(rowIndex, "FactorSerial"));
            selectedYears.push(gridBuilder.getCellValue(rowIndex, "Year"));
            selectedStates.push(gridBuilder.getCellValue(rowIndex, "IsCertain"));
            selectedShops.push(gridBuilder.getCellValue(rowIndex, "IsShop"));
            selectedParents.push(gridBuilder.getCellValue(rowIndex, "FactorTypeParentCode"));
            selectedAccCodes.push(gridBuilder.getCellValue(rowIndex, "DocumentCode"));
        }
    }
    return { codes: selectedCodes, years: selectedYears, states: selectedStates, isShops: selectedShops, parentCodes: selectedParents, accCodes: selectedAccCodes };
}
function printDocument() {
    var selected = getSelectedCodes();
    if (selected.codes.length === 0) {
        showMsgModal(0, window.top.chooseItem);
        return;
    }
    var title = window.top.printDocument;
    var url = "Report/Default?GrpName=";

    reportName = Number(selected.accCodes[0]) ? "An_Sanad_Riali" : "An_Sanad_Tedadi";
    url += reportName + "&codesanad=" + selected.codes.join(",") + "&SalMali=" + selected.years[0];

    openInModal('', url, title, "", "", false);
}
function deleteDocument() {
    var selected = getSelectedCodes();
    if (selected.codes.length === 0) {
        showMsgModal(0, window.top.chooseItem);
        return;
    }
    if (confirm(window.top.deleteConfirm)) {
        if (selected.isShops.some(x => x.toString() === "true")) {
            showMsgModal(0, window.top.noPermissionToDeleteShopFactor);
            return;
        }
        ajax({
            url: 'SaleApi/DeleteFactor',
            data: { factorSerials: selected.codes },
            success: function (retValue) {
                showMsgModal(2, retValue.FinalMessage);
                gridBuilder.changeSelection(-1, false);
                loadGrid("gridDocument");
            }
        });
    }
}
function storeControled(state) {
    var title = state === 0 ? window.top.retConfirmNumberControl : window.top.confirmNumberControl;
    var width = "800";
    var src = "Store/RialControls?&state=" + (state === 0);
    openInModal('', src, title, width, 540);
}
function newDocument() {
    var type = getQuery("type");
    var title = type === "8" ? window.top.openDoc : window.top.closeDoc;
    var src = "Store/" + (type === "8" ? "OpeningDocumentSave" : "ClosingDocumentSave");
    openInTab(src, title, "", true);
}
function changeFactorState(sender) {
    var selected = getSelectedCodes();
    var state = $(sender).attr("data-state") === "1";
    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.changeStatus)) {
        ajax({
            url: "SaleApi/ChangeDocumentState",
            data: { factorSerials: selected.codes, state: state },
            success: function (retValue) {
                showMsgModal(2, retValue.FinalMessage[0]);
                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 editDocument() {
    var data = getData();
    if (data)
        checkLock(data);
}
function checkLock(data, isCopy) {
    ajax({
        url: 'SaleApi/CheckLock',
        loading: false,
        data: { code: data.factorSerial },
        success: function (retValue) {
            if (retValue !== '') {
                eval(retValue);
            }
            else {
                var type = data.factorTypeTurnover === "1" ? "in" : "out";
                var title = "", icon = "";
                switch (type) {
                    case "out":
                        title = window.top.exitRequest;
                        icon = "622";
                        break;
                    default:
                        title = window.top.interRequest;
                        icon = "621";
                        break;

                }
                var url;
                var rowIndex = gridBuilder.getActiveRowIndex();
                var baseFactorSerial = gridBuilder.getCellValue(rowIndex, "BaseDocumentCode");
                var baseRequire = gridBuilder.getCellValue(rowIndex, "BaseRequire") === "true";
                if (baseRequire && isCopy) {
                    showMsgModal(0, window.top.cantCopyFactor);
                    return;
                }
                if (data.isSaleDocument) {
                    url = "Sale/";
                    switch (Number(data.saleSystemParentCode)) {
                        case saleSystemParent.shop:
                            url += "Shop2?";
                            break;
                        case saleSystemParent.pos:
                            url += "Shop?";
                            break;
                        default:
                            url += "FactorSave?";
                            break;
                    }
                    url += isCopy ? "copycode=" : "base=" + baseFactorSerial + "&code=";
                    url += data.factorSerial + "&sanadtype=" + data.factorType + "&systemcode=" + data.saleSystemCode;
                    title = data.factorTypeName;
                }
                else {
                    url = "Store/InOutSave?type=" + type + (isCopy ? "&copycode=" : "&code=") + data.factorSerial;
                }
                
                openInTab(url, title, 'img/pages/menu/' + icon + '.svg', false);
            }
        }
    });
}
function copyFactor() {
    var data = getData();
    if (data)
        checkLock(data, true);
}
function getData() {
    var rowIndex = gridBuilder.getActiveRowIndex();
    if (rowIndex < 0) {
        showMsgModal(0, window.top.chooseItem);
        return;
    }
    var factorType = gridBuilder.getCellValue(rowIndex, "FactorState");
    var factorTypeName = gridBuilder.getCellValue(rowIndex, "DocumentTypeName");
    var factorTypeTurnover = gridBuilder.getCellValue(rowIndex, "StateInOut");
    var factorTypeParentCode = gridBuilder.getCellValue(rowIndex, "FactorTypeParentCode");
    var factorSerial = gridBuilder.getCellValue(rowIndex, "FactorSerial");
    var isSaleDocument = gridBuilder.getCellValue(rowIndex, "IsSaleDocument") === "true";
    var saleSystemCode = gridBuilder.getCellValue(rowIndex, "SaleSystemCode");
    var saleSystemParentCode = gridBuilder.getCellValue(rowIndex, "SaleSystemParentCode");
    if (Number(factorTypeParentCode) === 15) {
        alert(window.top.couldntEditTransferDocuments);
        return;
    }
    return {
        factorType: factorType,
        factorTypeName: factorTypeName,
        factorTypeTurnover: factorTypeTurnover,
        factorTypeParentCode: factorTypeParentCode,
        factorSerial: factorSerial,
        isSaleDocument: isSaleDocument,
        saleSystemCode: saleSystemCode,
        saleSystemParentCode: saleSystemParentCode
    };
}