var gridBuilder;
var icon = window.top.$('.panel-tabs li.active .tab-icon').attr('src');
var title = window.top.$('.panel-tabs li.active').text().trim();
var saleSystemCode = Number(getQuery("systemcode"));
var documentTypeParentCode = Number(getQuery("parent"));
var enumDocumentTypeParentCode = {
    codeMoadelSale: 1,
    codeMoadelPreInvoice: 20,
    codeMoadelPurchase: 2,
    codeMoadelReturnSale: 10,
    codeMoadelReturnPurchase: 13
};
icon = icon.substr(icon.lastIndexOf('/') + 1).replace('.svg', '');
$(document).ready(function () {
    gridBuilder = $(".grid").gridBuilder();
    if (window.top.$("#hfCurrencySystem").val() !== "1") {
        gridBuilder.removeColumn("CurrencyName");
    }
    gridBuilder.onDblClick(function () {
        var data = getData();
        if (data)
            checkLock(data);
    });
    gridBuilder.onExportClick(function () {
        loadGrid("", { exportExcel: true });
    });
    $("#btnOperation").on("click", ".factor-base", function () {
        var toDocumentType = $(this).attr("data-type");
        var rowIndex = gridBuilder.getActiveRowIndex();
        var url = "sale/";
        var icon = "";
        var title = "";

        if (rowIndex >= 0) {
            var saleSystemParentCode = Number(gridBuilder.getCellValue(rowIndex, "SaleSystemParentCode"));
            var baseType = Number(gridBuilder.getCellValue(rowIndex, "FactorState"));
            var factorSerial = gridBuilder.getCellValue(rowIndex, "FactorSerial");
            var saleSystemCode = gridBuilder.getCellValue(rowIndex, "SaleSystemCode");
            switch (saleSystemParentCode) {
                case saleSystemParent.trade:
                    url += "factorSave?sanadtype=" + toDocumentType;
                    break;
                case saleSystemParent.shop:
                    url += "shop2?parentbase=" + documentTypeParentCode + "&basetype=" + baseType;
                    break;
                case saleSystemParent.pos:
                    url += "shop?";
                    break;
            }

            if (documentTypeParentCode === enumDocumentTypeParentCode.codeMoadelSale) {
                url += (saleSystemParentCode === saleSystemParent.pos ? "code=" + factorSerial + "&ret=1&p=" + documentTypeParentCode : "");
                icon = "241";
                title = window.top.returnedSale;
            }
            else if (documentTypeParentCode === enumDocumentTypeParentCode.codeMoadelPreInvoice) {
                icon = "222";
                title = window.top.salesInvoice
            }
            else if (documentTypeParentCode === enumDocumentTypeParentCode.codeMoadelPurchase) {
                icon = "225";
                title = window.top.returnedPurchase
            }

            if (url) {
                url += "&systemcode=" + saleSystemCode + "&base=" + factorSerial;
                openInTab(url, title, "img/pages/menu/" + icon + ".svg", false);
            }
        }

    })
    initial();
});
async function initial() {
    await getDocumentTypeList();
    loadGrid();
}

function loadGrid(gridId, objectParameter) {
    var isExportExcel = objectParameter && objectParameter.exportExcel ? true : false;
    ajax({
        loading: true,
        url: "SaleApi/GetSaleFactorList",
        data: {
            saleSystemCode: saleSystemCode,
            documentTypeCode: getQuery("sanadtype"),
            mySelf: true,
            fromDate: $("#txtFromDate").val(),
            toDate: $("#txtToDate").val(),
            filter: gridBuilder.getFilter(),
            sort: gridBuilder.getSortFields(),
            pageNo: isExportExcel ? -1 : gridBuilder.getCurrentPageNumber()
        },
        success: function (data) {
            if (isExportExcel) {
                exportExcel(data, gridBuilder.getColumns(), gridBuilder.getColumnsCaption());
            }
            else {
                gridBuilder.loadData(data);
            }
        }
    });
}
function edit() {
    gridBuilder.dblClick();
}
function newDocument() {
    var url = "";
    if (saleSystemCode === saleSystemParent.trade)
        url = "Sale/FactorSave?sanadtype=" + getQuery("sanadtype");
    else
        url = "Sale/Shop2?sanadtype=" + getQuery("sanadtype") + "&systemcode=" + saleSystemCode;
    openInTab(url, title, 'img/pages/menu/' + icon + '.svg', false);
}

function printDocument() {
    var rowIndex = gridBuilder.getActiveRowIndex();
    if (rowIndex < 0) {
        showMsgModal(0, window.top.chooseItem);
        return;
    }
    var factoreSerial = gridBuilder.getCellValue(rowIndex, "FactorSerial");
    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 checkLock(data, isCopy) {
    var url = "Sale/";
    ajax({
        url: "SaleApi/CheckLock",
        data: { code: data.factorSerial },
        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.saleSystemParentCode)) {
                    case saleSystemParent.shop:
                        url += "Shop2?";
                        break;
                    case saleSystemParent.pos:
                        url += "Shop?";
                        break;
                    default:
                        url += "FactorSave?";
                        break;
                }
                
                url += isCopy ? "copycode=" :  "&code=";
                url += data.factorSerial + "&sanadtype=" + data.factorState + "&systemcode=" + data.saleSystemCode;
                if (Number(data.saleSystemParentCode) === saleSystemParent.shop) {
                    url += "&base=" + baseFactorSerial
                }
                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 factorSerial = gridBuilder.getCellValue(rowIndex, "FactorSerial");
    var factorState = gridBuilder.getCellValue(rowIndex, "FactorState");
    var saleSystemParentCode = gridBuilder.getCellValue(rowIndex, "SaleSystemParentCode");
    var saleSystemCode = gridBuilder.getCellValue(rowIndex, "SaleSystemCode");
    return {
        factorSerial: factorSerial,
        factorState: factorState,
        saleSystemParentCode: saleSystemParentCode,
        saleSystemCode: saleSystemCode
    };
}



async function getDocumentTypeList() {
    await ajax({
        url: "SaleApi/GetDocumentTypeList",
        data: { state: 1, pageNo: -1 },
        success: function (retValue) {
            var currentType = retValue.find(x => x.Code === Number(getQuery("sanadtype")));
            gridBuilder.setCaption(currentType.Name);
            var linkedTypes = retValue.filter(x => x.BaseDocumentTypeCode === Number(getQuery("sanadtype")));
            linkedTypes.forEach(function (item) {
                $("#btnOperation").find("ul").append("<li><input type='button' class='text-right btnTemporary factor-base' style='cursor:pointer' value='" + window.top.changeTo + " " + item.Name+"' data-type="+item.Code+" /></li>")
            });
            if (!currentType.BaseRequire) {
                $("#btnOperation").find("ul").append("<li><input type='button' class='text-right btnTemporary ' onclick='copyFactor()' style='cursor:pointer' value='" + window.top.copyFactor + "'  /></li>");
            }
            if ($("#btnOperation").find("ul>li").length === 0) {
                $("#btnOperation").hide();
            }
        }
    });
}