var gridBuilder;
var gridArtiklBuilder;
var enumDocumentTypeParentCode = {
    codeMoadelSale: 1,
    codeMoadelPreInvoice: 20,
    codeMoadelPurchase: 2,
    codeMoadelReturnSale: 10,
    codeMoadelReturnPurchase: 13
};
$(document).ready(function () {
    gridBuilder = $("#gridDocument").gridBuilder();
    gridArtiklBuilder = $("#gridArtikl").gridBuilder();
    if (window.top.$("#hfCurrencySystem").val() !== "1") {
        gridBuilder.removeColumn("CurrencyName");
    }
    $("#cboDocumentType").lookupBuilder().onChanged(function () {
        loadGrid('gridDocument');
    });
    gridBuilder.onExportClick(function () {
        loadGrid("gridDocument", { exportExcel: true });
    });
    gridArtiklBuilder.onExportClick(function () {
        loadGrid("gridArtikl", { exportExcel: true });
    });
    gridBuilder.onDblClick(function () {
        var rowIndex = gridBuilder.getActiveRowIndex();
        if (rowIndex < 0) {
            return;
        }
        $("#level2").show();
        $("#level1").hide();
        setDisabled(true);
        loadGrid("gridArtikl");
    });

    gridBuilder.onRowChanged(function () {
        var rowIndex = gridBuilder.getActiveRowIndex();
        if (rowIndex < 0)
            return;
        var stateName = gridBuilder.getCellValue(rowIndex, "StateName");
        var documentTypeParentCode = gridBuilder.getCellValue(rowIndex, "FactorTypeParentCode");
        var saleSystemParentCode = gridBuilder.getCellValue(rowIndex, "SaleSystemParentCode");
        var baseRequire = gridBuilder.getCellValue(rowIndex, "BaseRequire") === "true";
        onRowChange(stateName, documentTypeParentCode, Number(saleSystemParentCode), baseRequire);
    });
    loadGrid("gridDocument");
    imgToSvg();
});
function showAllArtikles(sender) {
    if ($(sender).prop("checked")) {
        loadGrid("gridArtikl");
    }
    else {
        gridBuilder.dblClick();
    }
}
function onRowChange(stateName, documentTypeParentCode, saleSystemParentCode, baseRequire) {
    var isPos = saleSystemParentCode === saleSystemParent.pos;
    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;
    }
    $("#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");

    var $factorOperation = $("#btnFactorOperation> input");
    if (saleSystemParentCode <= saleSystemParent.trade) {
        $factorOperation.parent().hide();
        return;
    }
    switch (Number(documentTypeParentCode)) {
        case enumDocumentTypeParentCode.codeMoadelSale:
            $factorOperation.val(window.top.returnSale);
            $factorOperation.parent().show();
            break;
        case enumDocumentTypeParentCode.codeMoadelPreInvoice:
            $factorOperation.val(window.top.convertToInvoice);
            $factorOperation.parent().show();
            break;
        case enumDocumentTypeParentCode.codeMoadelPurchase:
            $factorOperation.val(window.top.returnPurchase);
            $factorOperation.parent().show();
            break;
        default:
            $factorOperation.parent().hide();
    }
    $("#btnCopy>input").prop("disabled", baseRequire).removeClass("btnTemporary btnTemporary-disabled").addClass(baseRequire ? "btnTemporary-disabled" : "btnTemporary");
}

function factorOperation() {
    var rowIndex = gridBuilder.getActiveRowIndex();
    var url = "";
    var icon = "";
    var destinationFactorType = "";

    if (rowIndex >= 0) {
        var data = getSelectedCodes();
        if (data.codes.length !== 1)
            return;
        if (Number(data.saleSystemParentCodes[0]) <= saleSystemParent.trade)
            return;
        var parentCode = data.documentTypeParentCodes[0];
        var baseType = data.documentTypeCodes[0];
        if (Number(parentCode) === enumDocumentTypeParentCode.codeMoadelReturnSale || Number(parentCode) === enumDocumentTypeParentCode.codeMoadelReturnPurchase)
            return;
        if (Number(parentCode) === enumDocumentTypeParentCode.codeMoadelSale) {
            url = "Sale/" + (Number(data.saleSystemParentCodes[0]) === saleSystemParent.shop ? "shop2?code1=" + data.codes[0] : "shop?code=" + data.codes[0] + "&ret=1&p=" + data.documentTypeParentCodes[0]);
            icon = "241";
            destinationFactorType = window.top.returnedSale;
        }
        else if (Number(parentCode) === enumDocumentTypeParentCode.codeMoadelPreInvoice) {
            url = "Sale/shop2?code1=" + data.codes[0];
            icon = "222";
            destinationFactorType = window.top.salesInvoice
        }
        else if (Number(parentCode) === enumDocumentTypeParentCode.codeMoadelPurchase) {
            url = "Sale/shop2?code1=" + data.codes[0];
            icon = "225";
            destinationFactorType = window.top.returnedPurchase
        }

        if (url) {
            url += "&systemcode=" + data.saleSystemCodes[0] + "&base=" + data.codes[0] + "&basetype=" + baseType + "&parentbase=" + parentCode;
            openInTab(url, destinationFactorType, "img/pages/menu/" + icon + ".svg", false);
        }
    }
}

function loadGrid(gridId, objectParameter) {
    var isExportExcel = objectParameter && objectParameter.exportExcel ? true : false;
    if (gridId === "gridDocument") {
        var selectionCriteria = gridBuilder.selectionViewMode ? "'" + gridBuilder.selectionList.join("','") + "'" : null;
        ajax({
            gridBuilder: gridBuilder,
            url: "SaleApi/GetSaleFactorList",
            data: {
                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 edit() {
    var data = getSelectedCodes();
    if (data.codes.length !== 1)
        return;
    if (Number(data.saleSystemParentCodes[0]) === saleSystemParent.pos)
        return;
    checkLock(data);
}

function checkLock(data, isCopy) {
    var url = "Sale/";
    ajax({
        url: "SaleApi/CheckLock",
        data: { code: data.codes[0] },
        success: function (retValue) {
            if (retValue !== '') {
                eval(retValue);
            }
            else {
                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;
                }
                switch (Number(data.saleSystemParentCodes[0])) {
                    case saleSystemParent.shop:
                        url += "Shop2?";
                        break;
                    case saleSystemParent.pos:
                        url += "Shop?";
                        break;
                    default:
                        url += "FactorSave?";
                        break;
                }
                url += isCopy ? "copycode=" : "&code=";
                url += data.codes[0] + "&sanadtype=" + data.documentTypeCodes[0] + "&systemcode=" + data.saleSystemCodes[0];
                if (Number(data.saleSystemParentCodes[0]) === saleSystemParent.shop) {
                    url += "&base=" + baseFactorSerial
                }
                openInTab(url, data.documentTypeNames[0], 'img/pages/menu/221.svg', false);
            }
        }
    });
}
function getSelectedCodes() {
    var codes = gridBuilder.getSelectedRowsCellValue("FactorSerial");
    var documentTypeParentCodes = gridBuilder.getSelectedRowsCellValue("FactorTypeParentCode");
    var saleSystemParentCodes = gridBuilder.getSelectedRowsCellValue("SaleSystemParentCode");
    var saleSystemCodes = gridBuilder.getSelectedRowsCellValue("SaleSystemCode");
    var documentTypeCodes = gridBuilder.getSelectedRowsCellValue("FactorState");
    var documentTypeNames = gridBuilder.getSelectedRowsCellValue("DocumentTypeName");

    if (codes.length === 0) {
        var rowIndex = gridBuilder.getActiveRowIndex();
        if (rowIndex >= 0) {
            codes.push(gridBuilder.getCellValue(rowIndex, "FactorSerial"));
            documentTypeParentCodes.push(gridBuilder.getCellValue(rowIndex, "FactorTypeParentCode"));
            saleSystemParentCodes.push(gridBuilder.getCellValue(rowIndex, "SaleSystemParentCode"));
            saleSystemCodes.push(gridBuilder.getCellValue(rowIndex, "SaleSystemCode"));
            documentTypeCodes.push(gridBuilder.getCellValue(rowIndex, "FactorState"));
            documentTypeNames.push(gridBuilder.getCellValue(rowIndex, "DocumentTypeName"));
        }
    }
    return { codes: codes, documentTypeParentCodes: documentTypeParentCodes, saleSystemParentCodes: saleSystemParentCodes, documentTypeCodes: documentTypeCodes, documentTypeNames: documentTypeNames, saleSystemCodes: saleSystemCodes };
}
function deleteRow() {
    var data = getSelectedCodes();
    if (data.codes.length === 0) {
        showMsgModal(0, window.top.chooseItem);
        return;
    }
    if (confirm(window.top.deleteConfirm)) {
        if (data.saleSystemParentCodes.filter(x => Number(x) === saleSystemParent.pos).length > 0) {
            showMsgModal(0, window.top.noPermissionToDeleteShopFactor);
            return;
        }
        ajax({
            loading: true,
            url: "SaleApi/DeleteFactor",
            data: { factorSerials: data.codes },
            success: function (result) {
                showMsgModal(2, result.FinalMessage);
                gridBuilder.changeSelection(-1, false);
                loadGrid("gridDocument");
            }
        });
    }
}

function changeDocumentState(sender) {
    var state = $(sender).attr("data-state") === "1";
    var data = getSelectedCodes();
    if (data.codes.length === 0) {
        showMsgModal(0, window.top.chooseItem);
        return;
    }
    if (confirm(window.top.changeStatus)) {
        ajax({
            loading: true,
            url: "SaleApi/ChangeDocumentState",
            data: { factorSerials: data.codes, state: state },
            success: function (result) {
                showMsgModal(2, result.FinalMessage[0]);
                loadGrid("gridDocument");
            }
        });
    }
}

function getDetails() {
    gridBuilder.dblClick();
}

function printDocument() {
    var rowIndex = gridBuilder.getActiveRowIndex();
    if (rowIndex < 0) {
        showMsgModal(0, window.top.chooseItem);
        return;
    }
    var factoreSerial = gridBuilder.getCellValue(rowIndex, "FactorSerial");
    var documentTypeParentCode = Number(gridBuilder.getCellValue(rowIndex, "FactorTypeParentCode"));
    var accDocumentCode = Number(gridBuilder.getCellValue(rowIndex, "DocumentCode"));
    var year = gridBuilder.getCellValue(rowIndex, "Year");
    var title = window.top.printDocument;
    var reportName = "An_SanadN";
    var url = "Report/Default?GrpName=";
    if (documentTypeParentCode !== enumDocumentTypeParentCode.codeMoadelPreInvoice && documentTypeParentCode !== enumDocumentTypeParentCode.codeMoadelSale && documentTypeParentCode !== enumDocumentTypeParentCode.codeMoadelPurchase && documentTypeParentCode !== enumDocumentTypeParentCode.codeMoadelReturnSale && documentTypeParentCode !== enumDocumentTypeParentCode.codeMoadelReturnPurchase) {
        reportName = accDocumentCode ? "An_Sanad_Riali" : "An_Sanad_Tedadi";
        url += reportName + "&codesanad=" + factoreSerial + "&SalMali=" + year;
    }
    else
        url += reportName + "&Inst=" + factoreSerial + "&SalMali=" + year;
    openInModal('', url, title, "", "", false);
}

function setDisabled(state) {
    $('#txtFromDate').attr("disabled", state);
    $('#txtToDate').attr("disabled", state);
}

function getArtikls(isExportExcel) {
    var rowIndex = gridBuilder.getActiveRowIndex();
    var factorSerial = gridBuilder.getCellValue(rowIndex, "FactorSerial");
    var loadAll = $("#chkShowAllArtikles").prop("checked");
    if (!loadAll)
        ajax({
            loading: true,
            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:true,
            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 showDocumentList() {
    $("#level2").hide();
    $("#level1").show();
    setDisabled(false);
}

function OnEndCallback(s) {
    if (s.name === 'grdSanadList') {
        if (grdSanadList.cpEvent && grdSanadList.cpEvent !== '') {
            delete grdSanadList.cpEvent;
            focusedRowChanged();
            closeLoading();
        }
    } else {
        showRizSanadCallBack();
    }
}

function printSanad() {
    if (grdSanadList.GetFocusedRowIndex() === -1) {
        showMsgModal(0, window.top.itemNotSelect);
        return;
    }
    grdSanadList.GetSelectedFieldValues('Year;FactorSerial', OnGetRowValuesPrint);
}

function OnGetRowValuesPrint(Value) {
    var codes = Value.map(function (d) { return d[1]; }).join(',');
    var title = window.top.printDocument;
    var url = "Report/Default?GrpName=An_SanadN&SalMali=" + Value[0][0] + "&Inst=" + codes;
    openInModal('', url, title, "", "", false);
}
function copyFactor() {
    var data = getSelectedCodes();
    if (data.codes.length !== 1)
        return;
    checkLock(data, true);
}





