var productList = null;
var isValidSerial = true;
var header = null;
var documentHeader = null;
var hasCurrencySystem = false;
var firstEndState = "";
var defaultCustomerCode = $("#hfDefaultCustomer").val();
var enumDocumentTypeParentCode = {
    transferBetweenOutputStore: 14,
    transferBetweenInputStore: 15,
    codeMoadelPreInvoice: 20,
    codeMoadelSale: 1,
    codeMoadelReturnPurchase: 13,
    codeMoadelPurchase: 2,
    codeMoadelReturnSale: 10,
    codeMoadelFirstInventory: 8,
    codeMoadelEndInventory: 6,
    codeMoadelStoreReceipt: 12
};

var baseDecimalCount = Number(window.top.$('#hfDecimalCount').val());
var baseCurrencyCode = Number(window.top.$('#hfBaseCurrencyCode').val());
var baseCurrencyName = window.top.$('#hfBaseCurrencyName').val();

var gridBuilder;
var isStore = false;
var editCurrencyCode;
var articleBaseCode;
var baseDocumentTypeCode;
var baseDocumentCode;
var currentvarArtikls;
var isEffectInventory = false;
var baseFactorData;
var lastPriceModel = [];
$(document).ready(function () {
    $("#hfDefaultCustomer").remove();

    gridBuilder = $(".grid").gridBuilder();
    gridBuilder.onGetComboData(getGridComboData);
    gridBuilder.onPgmSumChanged(function () {
        updateSummeryTbl();
    });
    gridBuilder.onExportClick(exportSampleExcel);
    gridBuilder.onSetMaskEdit(setEventMaskEdit);
    gridBuilder.onStartEditing(startEditingGrid);
    gridBuilder.onRowChanged(async function (rowIndex) {
        var productName = gridBuilder.getCellValue(rowIndex, "ProductName");
        var productId = gridBuilder.getCellValue(rowIndex, "ProductId");
        var customerCode = Number(getObjectValue("cboCustomerAccount", 0));
        var storeCode = Number(getObjectValue("cboStore", 0));
        var unitCode = Number(gridBuilder.getCellValue(rowIndex, "UnitCode"));
        if (!productName) {
            clearProductShopDetail();
            return;
        }
        if (lastPriceModel.filter(x => x.ProductId === productId && x.CustomerCode === customerCode && x.StoreCode === storeCode && x.UnitCode === unitCode).length === 0)
            await getProductShopDetail(productId, rowIndex, productName, unitCode);
        setProductShopDetail(productId, customerCode, storeCode, rowIndex,unitCode);
    });
    gridBuilder.onCellBeforeLostFocus(gridCellBeforeLostFocus);
    gridBuilder.onCellChanged(gridCellChanged);
    gridBuilder.onImportClick(function (gridId, type, base64) {
        if (type === "importXml") {
            importXml(gridId, base64);
        }
        else {
            var isSale = $("#hfIsSaleSanad").val().toLowerCase() === "true";
            var inputType = $("#hfStateInOut").val() === "1";
            var currencyDecimalCount = getObjectValue("cboCurrency", 1);
            ajax({
                loading: true,
                url: "GeneralApi/ImportExcel",
                data: {
                    key: (isSale ? ("SaleArticle" + "-" + $("#hfSanadType").val() + "-" + $("#txtDate").val()) : (inputType ? "StoreInputArticle" : "StoreOutputArticle")) + "-" + currencyDecimalCount,
                    base64: base64
                },
                success: function (result) {
                    var data = eval(result.result);
                    if (isSale) {
                        data.forEach(function (item, index) {
                            var tax = item.ProductTax;
                            var toll = item.ProductToll;
                            if (tax > 0 || toll > 0) {
                                item.Tax = Number((tax * (item.SumPrice - item.Discount) / 100).toFixed(currencyDecimalCount));
                                item.Toll = Number((toll * (item.SumPrice - item.Discount) / 100).toFixed(currencyDecimalCount));
                            } else {
                                item.Toll = 0;
                                item.Tax = 0;
                            }
                            item.ValueAdded = Number(item.Tax + item.Toll).toFixed(currencyDecimalCount);
                            item.NetPrice = item.SumPrice - item.Discount + Number(item.ValueAdded);
                        });
                    }
                    gridBuilder.loadData(data);
                }
            });
        }

    });
    if ($("#hfHasKalaAnbar").val().toLowerCase() === "false")
        gridBuilder.removeColumn("ProductSerialNumber");
    $("#cboCustomerLast2").lookupBuilder().onChanged(async function () {
        var productId = $("#divProductShopDetail").attr("data-product");
        var unitCode = $("#divProductShopDetail").attr("data-unit");
        var customerCode = $("#cboCustomerLast2").lookupBuilder().getSelectedValue();
        getProductShopDetailCustomer(productId, customerCode, 2, unitCode);
    });
    $("#cboCustomerLast1").lookupBuilder().onChanged(async function () {
        var productId = $("#divProductShopDetail").attr("data-product");
        var unitCode = $("#divProductShopDetail").attr("data-unit");
        var customerCode = Number($("#cboCustomerLast1").lookupBuilder().getSelectedValue());
        var model = lastPriceModel.find(x => x.ProductId === productId && x.CustomerCode === customerCode && x.UnitCode === unitCode);
        if (!model)
            getProductShopDetailCustomer(productId, customerCode, 1, unitCode);
        else
            setLastPriceCustomer(model.LastPriceCustomer, 1);
    });
    $("#cboCustomerAccount").lookupBuilder().onChanged(async function () {
        var customerCode = Number(getObjectValue("cboCustomerAccount", 0));
        var currencyCode = Number(getObjectValue("cboCustomerAccount", 1));
        var currencyDecimalCount = Number(getObjectValue("cboCustomerAccount", 2));
        var customerName = $("#cboCustomerAccount").lookupBuilder().getSelectedText();
        if (currencyCode <= 0) {
            currencyCode = baseCurrencyCode;
            currencyDecimalCount = baseDecimalCount;
        }
        var names = customerName.split(" ");
        names.splice(0, 1);
        customerName = names.join(" ");
        $("#txtCustomerDesc").prop("disabled", customerCode !== Number(defaultCustomerCode)).val(customerName);
        await $("#cboCurrency").lookupBuilder().setSelectedValue(currencyCode + "|" + currencyDecimalCount);
        if ($("#cboPriceList").length === 1) {
            var oldValue = $("#cboPriceList").lookupBuilder().getSelectedValue();
            await getEventLookupCombo($("#cboPriceList"), "", "");
            var newValue = $("#cboPriceList").lookupBuilder().getSelectedValue();
            if (oldValue === newValue)
                $("#cboPriceList").lookupBuilder().changed();
        }
        clearProductShopDetail();
    });
    $("#cboDocumentType").lookupBuilder().onChanged(async function () {
        await cboDocumentTypeChange();
    });
    $("#cboStore").lookupBuilder().onChanged(async function () {
        if ($("#cboStoreTo").length > 0)
            $("#cboStoreTo").lookupBuilder().setSelectedValue("");

        clearProductShopDetail();
        await getProductPrices();
    });
    $("#cboPriceList").lookupBuilder().onChanged(async function () {
        var oldValue = $("#cboDiscount").lookupBuilder().getSelectedValue();
        await getEventLookupCombo($("#cboDiscount"), "", "");
        var newValue = $("#cboDiscount").lookupBuilder().getSelectedValue();
        if (oldValue === newValue)
            $("#cboDiscount").lookupBuilder().changed();
    });
    $("#cboDiscount").lookupBuilder().onChanged(async function () {
        await getProductPrices();
    });
    $("#cboCurrency").lookupBuilder().onChanged(async function () {
        var currencyCode = Number(getObjectValue("cboCurrency", 0));
        var currencyDecimaCount = getObjectValue("cboCurrency", 1);
        var currencyName = $("#cboCurrency").lookupBuilder().getSelectedText();
        var state = baseCurrencyCode === currencyCode;
        var editState = editCurrencyCode === currencyCode;
        $("#txtCurrencyRate").attr("data-decimalCount", currencyDecimaCount);
        if (!editState) {
            if (!state) {
                await ajax({
                    loading: true,
                    url: "SaleApi/GetCurrencyRate",
                    data: { currencyCode: currencyCode, date: $("#txtDate").val() },
                    success: function (retValue) {
                        $("#txtCurrencyRate").val(retValue.PriceInReal === "" ? 1 : retValue.PriceInReal);
                        $("[data-currency='true']").text(currencyName);
                    }
                });
            }
            else {
                $("#txtCurrencyRate").val(1);
                $("[data-currency='true']").text(currencyName);
            }
        }
        if (currencyCode > 0 && currencyCode !== baseCurrencyCode) {
            var currencyRate = $("#txtCurrencyRate").val();
            var netPrice = numberNonCommas($("#lblSumNetPrice").text(), 0);
            var price = Number((netPrice * currencyRate).toFixed(baseDecimalCount));
            $("#divSumNetPrice").show();
            $("#lblSumNetPriceBaseCurrency").text(convertToComma(price, baseDecimalCount));
        }
        else
            $("#divSumNetPrice").hide();
    });

    preInitial();
});
async function preInitial() {
    if (getQuery("rcode"))
        GetRecoverFactor();
    else
        initial();
}
async function initial(recoverFactor) {
    firstEndState = getQuery("firstEndState");
    hasCurrencySystem = window.top.$("#hfCurrencySystem").val() === "1";
    if (!hasCurrencySystem) {
        $("#txtCurrencyRate").prop("disabled", true);
        $("#cboCurrency").lookupBuilder().setEnabled(false);
    }
    if (getQuery("Code") === "" && $("#cboDocumentType").length === 1)
        await getEventLookupCombo($("#cboDocumentType"), "", "");

    if ($("#cboDocumentType").length === 0) {
        var data = await getDocumentType();
        setDocumentTypeHiddenField(data);
    }
    if ($("#hfFinal").val() === "1") {
        $("input[type='text'][data-id]").prop("disabled", true);
        $(".lookup-button").prop("disabled", true);
        gridBuilder.setEnabled(false);
    }

    if (getQuery("type") === "out") {
        $("#btnPony").hide();
        setComboCaption("cboDocumentType", window.top.exitType);
        setComboCaption("cboStore", window.top.exitWarehouse);
        setComboCaption("cboStoreTo", window.top.warehouseArrival);
    }
    else if (getQuery("type") !== "") {
        setComboCaption("cboDocumentType", window.top.arrivalType);
        setComboCaption("cboStore", window.top.warehouseArrival);
        setComboCaption("cboStoreTo", window.top.exitWarehouse);
    }

    if (firstEndState === "first" || firstEndState === "end" || firstEndState === "negativeKala") {
        $("#divBtnContainer").hide();
        $("#divTopContainer").css({ "margin-top": "0", "padding-top": "8px" });
        $(".grid").parent().css({ "height": "calc(100vh - 270px)" })
    }

    if (recoverFactor)
        await loadFactor(recoverFactor);
    else
        await getArtiklsWithHeader();



    var documentTypeMoadel = Number($("#hfCodeMoadel").val());
    var isSale = $("#hfIsSaleSanad").val().toLowerCase() === "true";
    var stateInOut = $('#hfStateInOut').val();
    var customerCaption = window.top.customer;
    var customerTitleCaption = window.top.customerTitle;
    if (documentTypeMoadel === enumDocumentTypeParentCode.codeMoadelPreInvoice)
        $("#divContainerCashDesk").remove();


    if (documentTypeMoadel !== enumDocumentTypeParentCode.codeMoadelPreInvoice && documentTypeMoadel !== enumDocumentTypeParentCode.codeMoadelSale) {
        $("#divContainerPrice,#divContainerDiscount").remove();
        $("#divContainerStore").addClass("no-padding").css({ "width": "100%" });
    }
    if ($("#hfSabtSanad").val().toLowerCase() === "false")
        $("#btnPony,#btnCash").hide();
    if (documentTypeMoadel === enumDocumentTypeParentCode.codeMoadelReturnPurchase || documentTypeMoadel === enumDocumentTypeParentCode.codeMoadelPurchase || (!isSale && stateInOut === "1")) {
        customerCaption = window.top.supplier;
        customerTitleCaption = window.top.supplierTitle;
    }

    $("#lblBaseCurrencyName").text(window.top.$("#hfBaseCurrencyName").val());
    if (!isStore) {
        setComboCaption("cboCustomerAccount", customerCaption);
        $("#lblCustomerTitle").text(customerTitleCaption);
    }
    setComboCaption("cboShoppingCenter", documentTypeMoadel === enumDocumentTypeParentCode.codeMoadelSale || documentTypeMoadel === enumDocumentTypeParentCode.codeMoadelReturnPurchase || documentTypeMoadel === enumDocumentTypeParentCode.codeMoadelPreInvoice ? window.top.saleCenter : window.top.purchaseCenter);

    if (stateInOut === "1") {
        gridBuilder.setColumnCaption("Amount", window.top.inputCount);
    }
    else {
        gridBuilder.setColumnCaption("Amount", window.top.outCount);
        $("#pnlSumMablagh").hide();
        if (!isSale) {
            gridBuilder.removeColumn("Price");
            gridBuilder.removeColumn("SumPrice");
            $("#divFooter").hide();
            $("#gridArtikl").parent().css({ "height": "calc(100vh - 268px)" });
        }
    }

    if (isSale || stateInOut === "1")
        $("#divFooter2").hide();

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

    if (gridBuilder.getRowsCount() === 0 && Number(getQuery("code")) <= 0 && Number(getQuery("copycode")) <= 0 && Number(getQuery("base")) <= 0 && Number(getObjectValue("cboCustomerAccount", 0)) > 0)
        gridBuilder.addNewRow();
}
$(document).click(function () {
    window.top.closeLeftSideMenu();
});
document.onkeydown = function (event) {
    event = event || window.event;
    if (event.keyCode === 13)
        event.preventDefault();
    else if (event.keyCode === 112) //f1 
    {
        window.top.showHelpForm();
        event.preventDefault();
    }
    else if (event.keyCode === 120)//F9
        $("#btnSave").trigger('click');
};
function newSanad() {
    window.top.onCloseTab(window.location.href);
    showLoading();
    if ($('#cboDocumentType').length === 1)
        redirectUrl('../Store/InOutSave?type=' + getQuery('type'));
    else
        redirectUrl('../Sale/FactorSave?sanadtype=' + $("#hfSanadType").val());
}
async function GetRecoverFactor() {
    var result;
    await ajax({
        url: "SaleApi/GetRecoverFactor",
        data: { code: getQuery("rcode") },
        success: function (resValue) {
            result = resValue;
        }
    });
    $("#hfSanadType").val(result.Header.DocumentTypeCode);
    initial(result);
}
async function getArtiklsWithHeader() {
    var data;
    var url = "";
    if (firstEndState === "first" || firstEndState === "end") {
        data = {
            sourceSalMali: firstEndState === "first" ? (window.parent.$("#cboMaliYear").lookupBuilder().getSelectedValue() || -1) : window.top.$("#hfCurrentYear").val(),
            storeCode: getQuery("codeAnbar"),
            date: getQuery("date"),
            time: getQuery("time"),
            state: firstEndState,
            firstYearOpening: (getQuery("firstyear") === "1")
        };
        url = "GetOpeningClosingStoreDocument";
    }
    else if (firstEndState === "negativeKala") {
        data = { storeCode: getQuery("codeAnbar"), date: getQuery("date") };
        url = "GetNegativeStoreInventory";
    }
    else if (firstEndState === "addedStore") {
        data = {code : getQuery("handlingCode")}
        url = "GetAddedStoreDocument";
    }
    else if (firstEndState === "reducedStore") {
        data = { code: getQuery("handlingCode") }
        url = "GetReducedStoreDocument";
    }
    else {
        data = { loadArtikles: true, documentTypeCode: $("#hfSanadType").val(), factorSerial: getQuery("code") || getQuery("copycode") || getQuery("base") || -1, isCopy: getQuery("copycode") !== "", isBase: getQuery("base") !== "" };
        url = "GetFactor";
    }
    var result;
    await ajax({
        url: "SaleApi/" + url,
        data: data,
        success: function (resValue) {
            result = resValue;

        }
    });
    currentvarArtikls = result.Artikles;
    if (url === "GetFactor" && result.Header.BaseDocumentCode) {
        baseDocumentCode = result.Header.BaseDocumentCode;
        if (baseDocumentCode) {
            var editable = false;
            if (getQuery("code")) {
                await getBaseFactorData(baseDocumentCode);
                if (baseFactorData.length > 0) {
                    editable = baseFactorData[0].Editable;
                }
            }
            setBaseForm(editable);
        }
    }
    await loadFactor(result);
}
async function loadFactor(result) {
    if (firstEndState === "addedStore" || firstEndState === "reducedStore")
        result = result.Document;
    documentHeader = result.Header;
    if (documentHeader.IsCertain) {
        $("#btnNew").hide();
        $("#btnSave").hide();
        $("#btnDiscount").hide();
        $("#btnPony").hide();
    }
    else
        $("#lblDiscount").hide();

    if (documentHeader.FactorNumber)
        $("#txtFactorNo").val(documentHeader.FactorNumber);
    if (documentHeader.CodeAtf)
        $("#txtCodeAtf").val(documentHeader.CodeAtf);

    $("#txtTime").val(documentHeader.FactorTime);
    $("#txtDate").val(documentHeader.FactorDatePersian);

    var artikls = result.Artikles;
    currentvarArtikls = artikls;
    $("#txtDesc").val(documentHeader.Summery);
    if (firstEndState === "first" || firstEndState === "end" || firstEndState === "negativeKala") {
        await $("#cboCustomerAccount").lookupBuilder().setSelectedValue(getQuery("codeTarafH"));
        await $("#cboStore").lookupBuilder().setSelectedValue(getQuery("codeAnbar"));
        $("#txtCustomerDesc").val(getQuery("tarafH")).prop("disabled", true);
        $("#txtDate").val(getQuery("date"));
        $("#txtTime").val(getQuery("time"));
        $("#cboCustomerAccount").lookupBuilder().setEnabled(false);
        $("#cboStore").lookupBuilder().setEnabled(false);
        $("#cboDocumentType").lookupBuilder().setEnabled(false);
        if (firstEndState === "negativeKala") {
            $("#divBtnContainer2").show();
            await getEventLookupCombo($("#cboDocumentType"), "", null);
        }
    }
    else if (getQuery("code") || getQuery("rcode") || getQuery("copycode") || getQuery("base") || getQuery("handlingcode")) {
        if (documentHeader.Customer2Code !== -1)
            await $("#cboCustomerAccount2").lookupBuilder().setSelectedValue(documentHeader.Customer2Code);
        if ($("#cboDocumentType").length > 0) {
            $("#cboDocumentType").lookupBuilder().setEnabled(false);
            await $("#cboDocumentType").lookupBuilder().setSelectedValue(documentHeader.DocumentTypeCode);
        }
        await $("#cboStore").lookupBuilder().setSelectedValue(documentHeader.StoreCode);
        if (Number($("#hfSanadType").val()) !== enumDocumentTypeParentCode.codeMoadelPreInvoice)
            await getEventLookupCombo($("#cboCashDesk"), "", "");

        await $("#cboMarketer").lookupBuilder().setSelectedValue(documentHeader.MarketerCode);
        if (documentHeader.FactorSerial > 0 && !getQuery("rcode")) {
            $("#txtFactorId").text(documentHeader.FactorSerial);
            $("#hfFinal").val(documentHeader.IsCertain ? "1" : "0");
        }
        if ($("#cboStoreTo").length > 0) {
            await $("#cboStoreTo").lookupBuilder().setSelectedValue(documentHeader.ToStoreCode);
        }
        
        await $("#cboCustomerAccount").lookupBuilder().setSelectedValue(getQuery("handlingcode") ? defaultCustomerCode : documentHeader.CustomerCode);
        $("#txtCustomerDesc").val(documentHeader.CustomerDesc);

        if ($("#cboShoppingCenter").length > 0)
            await $("#cboShoppingCenter").lookupBuilder().setSelectedValue(documentHeader.ShoppingCenterCode);
        if ($("#cboCustomerAccount2").length > 0)
            await $("#cboCustomerAccount2").lookupBuilder().setSelectedValue(documentHeader.Customer2Code);
        if (getQuery("code")) {
            $("#hfRegDate").val(documentHeader.RegDateLocal);
            await lockDocument(documentHeader.FactorSerial);
        }
    }
    else {
        await $("#cboCustomerAccount").lookupBuilder().setSelectedValue(defaultCustomerCode);
        if (Number($("#hfSanadType").val()) !== enumDocumentTypeParentCode.codeMoadelPreInvoice)
            await getEventLookupCombo($("#cboCashDesk"), "", "");
        if ($("#cboStore").length === 1) {
            await getEventLookupCombo($("#cboStore"), "", "");
        }
    }

    $("#txtCurrencyRate").val(documentHeader.CurrencyRate);
    editCurrencyCode = documentHeader.CurrencyCode;
    await $("#cboCurrency").lookupBuilder().setSelectedValue(documentHeader.CurrencyCode);
    editCurrencyCode = 0;
    $("[data-currency='true']").text($("#cboCurrency").lookupBuilder().getSelectedText());
    if (artikls.length > 0) {
        gridBuilder.loadData(artikls);
        if (artikls.filter(x => x.ArticleBaseCode).length > 0) {
            articleBaseCode = artikls.map(x => x.ArticleBaseCode).join(',');
            $("#cboCustomerAccount").lookupBuilder().setEnabled(false);
            $("#cboStore").lookupBuilder().setEnabled(false);
            $("#txtCustomerDesc").prop("disabled", true);
            $(".grid-new-row").parent().hide();
            $(".column-context-menu").hide();
            $(".column-delete-row").hide();
        }
    }
    if (getQuery("base") && baseDocumentTypeCode) {
        openPreInvoiceSelection($("#btnMabna")[0]);
    }
}
async function getProductPrices() {
    await ajax({
        url: "SaleApi/GetProductPrices",
        data: { date: $("#txtDate").val(), storeCode: getObjectValue("cboStore", 0), search: "", priceListCode: getObjectValue("cboPriceList", 0), documentTypeCode: $("#hfSanadType").val() || -1, discountListCode: getObjectValue("cboDiscount", 0), isShopMode: false },
        success: function (retValue) {
            productList = retValue;
        }
    });
}

function openPreInvoiceSelection(sender) {
    var width = "1000";
    var src = "Sale/PreInvoiceSelection?state=" + $("#hfMabnaState").val() + "&codeTrafH="
        + getObjectValue("cboCustomerAccount", 0) + "&codeAnbar=" + getObjectValue("cboStore", 0)
        + "&currencyCode=" + getObjectValue("cboCurrency", 0)
        + (baseDocumentCode ? "&baseDocumentCode=" + baseDocumentCode : "")
        + (articleBaseCode ? "&articleBaseCode=" + articleBaseCode : "")
        + "&title=" + $(sender).val();
    openInModal('', src, $(sender).val(), width, null, false);
}
function openDiscountModal(sender) {
    var title = $(sender).val();
    var currencyDecimalCount = getObjectValue("cboCurrency", 1);
    currencyDecimalCount = currencyDecimalCount === -1 ? baseDecimalCount : currencyDecimalCount;
    var valueAdded = $("#lblSumTollTax").text();
    var rowCount = gridBuilder.getRowsCount();
    var sumLastPriceIn = 0;
    for (var i = 0; i < rowCount; i++) {
        var lastPriceIn = gridBuilder.getCellValue(i, "LastPriceIn");
        var lastPriceRate = gridBuilder.getCellValue(i, "LastPriceInCurrencyRate");
        var amount = gridBuilder.getCellValue(i, "Amount");
        sumLastPriceIn += lastPriceIn * (lastPriceRate || 1) * amount;
    }
    var src = "Sale/GeneralDiscount?SumMablagh=" + $('#lblAllSumPrice').text() + "&Takhfif=" + $('#lblSumDiscount').text() + "&NetPrice=" + $('#lblSumNetPrice').text() + "&Decimalcount=" + currencyDecimalCount + "&valueAdded=" + valueAdded + "&lastPrice=" + sumLastPriceIn;
    openInModal('', src, title, 450, 486, false);
}
async function setDataPreInvoice(model, tarafHValue, storeValue, tarafHCurrencyCode, currencyDecimalCount, tarafHCurrencyRate, baseSerial, numberingSave, documentTypeParentCode, codeAtf) {
    await $("#cboCustomerAccount").lookupBuilder().setSelectedValue(tarafHValue);
    await $("#cboStore").lookupBuilder().setSelectedValue(storeValue);
    await $("#cboCurrency").lookupBuilder().setSelectedValue(tarafHCurrencyCode);
    if (!getQuery("code"))
        $("#txtCodeAtf").val(codeAtf);
    var editable = false;
    baseDocumentCode = baseSerial;
    $("#txtCurrencyRate").val(tarafHCurrencyRate);
    if (numberingSave && documentTypeParentCode !== enumDocumentTypeParentCode.codeMoadelPreInvoice)
        editable = true;
    loadBaseFactorData(model, editable);
    if (model.length > 0) {
        loadGrid(model);
        updateSummeryTbl();
    }
    setBaseForm(editable);
}
function setBaseForm(editable) {
    $("#cboCustomerAccount").lookupBuilder().setEnabled(false);
    $("#cboStore").lookupBuilder().setEnabled(editable);
    $("#cboCurrency").lookupBuilder().setEnabled(editable);
    $("#cboPriceList").lookupBuilder().setEnabled(editable);
    $("#cboDiscount").lookupBuilder().setEnabled(editable);
    $("#txtCurrencyRate").prop("disabled", !editable);
    if (editable) {
        $("#btnDiscount").show();
        $("#lblDiscount").hide();
    }
    else {
        $("#btnDiscount").hide();
        $("#lblDiscount").show();
    }

    $(".grid-new-row").parent().hide();
    $(".column-context-menu").hide();
    $(".table-body").find(".grid-empty").hide();
    if (baseDocumentCode)
        $(".column-delete-row").hide();
}

function loadGrid(model) {
    var currencyDecimalCount = getObjectValue("cboCurrency", 1);
    var newData = [];
    var data = gridBuilder.getDataArray().data;
    for (var i = 0; i < model.length; i++) {
        var list = productList.find(function (item) { return item.Id.toLowerCase() === model[i].ProductId.toLowerCase() });
        if (!list)
            continue;
        if (data.length === 0 || !data.find(x => x.ArticleBaseCode === model[i].Code)) {
            var productTax = list.Tax;
            var productToll = list.Toll;
            var discountPerOne = Number((model[i].Discount / model[i].Amount).toFixed(currencyDecimalCount));
            var sumPrice = Number(model[i].SumPrice);
            if (model[i].Amount > model[i].RemainAmount)
                sumPrice = Number((model[i].Price * model[i].RemainAmount).toFixed(currencyDecimalCount));
            var discount = discountPerOne * model[i].RemainAmount;
            var tax = 0;
            var toll = 0;
            var valueAdded = 0;
            if (model[i].ProductTaxTypeCode > 1) {
                valueAdded = Number(((productToll + productTax) * (sumPrice - discount) / 100).toFixed(currencyDecimalCount));
                tax = Number((productTax * (sumPrice - discount) / 100).toFixed(currencyDecimalCount));
                toll = Number((valueAdded - tax).toFixed(currencyDecimalCount));
            }
            var netPrice = Number((sumPrice - discount + valueAdded).toFixed(currencyDecimalCount));
            newData.push({
                MainPrice: model[i].MainPrice,
                Price: model[i].Price,
                ProductSerialNumber: model[i].ProductSerialNumber,
                ProductStateSerialCode: model[i].ProductStateSerialCode,
                Amount: model[i].RemainAmount,
                Discount: discount,
                SumPrice: sumPrice,
                TrackingDate: model[i].TrackingDate,
                TrackingCode: model[i].TrackingCode,
                UnitCode: model[i].UnitCode,
                UnitName: model[i].UnitName,
                ProductTax: productTax,
                ProductToll: productToll,
                ArticleBaseCode: model[i].Code,
                ProductTaxTypeCode: model[i].ProductTaxTypeCode,
                ProductId: model[i].ProductId,
                ProductName: model[i].ProductName,
                Index: model[i].Index,
                Tax: tax < 0 ? 0 : tax,
                Toll: toll < 0 ? 0 : toll,
                NetPrice: netPrice < 0 ? 0 : netPrice,
                ValueAdded: valueAdded < 0 ? 0 : valueAdded
            });
        }
        else {
            newData.push(data.find(x => x.ArticleBaseCode === model[i].Code))
        }
    }
    gridBuilder.loadData(newData);
}


function discountAll(value, change) {
    var currencyDecimalCount = getObjectValue("cboCurrency", 1);
    value = value.toFixed(currencyDecimalCount);
    if (gridBuilder.getRowsCount() === 0)
        return;
    var allSumPrice = numberNonCommas($('#lblAllSumPrice').text(), 0);
    var sumDiscount = 0;
    var sumValueAdded = [];
    var data = gridBuilder.getOfflineRecordsExist();
    for (var i = 0; i < data.length; i++) {
        var sumPrice = numberNonCommas(data[i].SumPrice.newValue, 0);
        var productTax = Number(data[i].ProductTax.newValue);
        var productToll = Number(data[i].ProductToll.newValue);
        var newDiscount = Number((sumPrice * value / allSumPrice).toFixed(currencyDecimalCount));
        var valueAdded = Number(((productToll + productTax) * (sumPrice - newDiscount) / 100).toFixed(currencyDecimalCount));
        var tax = Number(((sumPrice - newDiscount) * productTax / 100).toFixed(currencyDecimalCount));
        var toll = Number((valueAdded - tax).toFixed(currencyDecimalCount));

        sumDiscount += newDiscount;
        sumValueAdded[i] = valueAdded;
        if (change) {
            data[i].Discount.newValue = newDiscount;
            data[i].ValueAdded.newValue = valueAdded;
            data[i].Tax.newValue = tax;
            data[i].Toll.newValue = toll;
            data[i].NetPrice.newValue = sumPrice - newDiscount + valueAdded;
        }
    }
    
    var remained = value - sumDiscount;
    if (remained > 0) {
        var lastRowIndex = data.length - 1;
        var sumPrice = numberNonCommas(data[lastRowIndex].SumPrice.newValue, 0);
        var productTax = Number(data[lastRowIndex].ProductTax.newValue);
        var productToll = Number(data[lastRowIndex].ProductToll.newValue);
        var discount = data[lastRowIndex].Discount.newValue;
        var newDiscount = discount + remained;
        var valueAdded = Number(((productToll + productTax) * (sumPrice - newDiscount) / 100).toFixed(currencyDecimalCount));
        var tax = Number(((sumPrice - newDiscount) * productTax / 100).toFixed(currencyDecimalCount));
        var toll = Number((valueAdded - tax).toFixed(currencyDecimalCount));
        sumValueAdded[lastRowIndex] = valueAdded;
        if (change) {
            data[lastRowIndex].Discount.newValue = newDiscount;
            data[lastRowIndex].ValueAdded.newValue = valueAdded;
            data[lastRowIndex].Tax.newValue = tax;
            data[lastRowIndex].Toll.newValue = toll;
            data[lastRowIndex].NetPrice.newValue = sumPrice - newDiscount + valueAdded;
        }
    }
    if (change) {
        gridBuilder.loadData(data);
    }

    return sumValueAdded.reduce((a, b) => a + b, 0);
}
function valueAddedAll(discount) {
    var currencyDecimalCount = getObjectValue("cboCurrency", 1);
    value = value.toFixed(currencyDecimalCount);
    if (gridBuilder.getRowsCount() === 0)
        return;
    var allSumPrice = numberNonCommas($('#lblAllSumPrice').text(), 0);
    var sumDiscount = 0;
    for (var rowIndex = 0; rowIndex < gridBuilder.getRowsCount(); rowIndex++) {
        var sumPrice = numberNonCommas(gridBuilder.getCellValue(rowIndex, "SumPrice"), 0);
        var newDiscount = Number((sumPrice * value / allSumPrice).toFixed(currencyDecimalCount));
        sumDiscount += newDiscount;
        gridBuilder.setCellValue(rowIndex, "Discount", newDiscount);
    }
    var remained = value - sumDiscount;
    if (remained > 0) {
        var lastRowIndex = gridBuilder.getRowsCount() - 1;
        var discount = gridBuilder.getCellValue(lastRowIndex, "Discount");
        gridBuilder.setCellValue(lastRowIndex, "Discount", discount + remained);
    }
}

function getGridComboData($combo, search) {
    var comboId = $combo.attr("id");
    var comboBuilder = $("#" + comboId).comboBuilder();
    var rowIndex = gridBuilder.getActiveRowIndex();
    var productId = gridBuilder.getCellValue(rowIndex, "ProductId");
    var unitName = gridBuilder.getCellValue(rowIndex, "UnitName");
    if (!productId)
        productId = "-1";
    switch (comboId) {
        case "cboProductId":
            var documentTypeMoadel = Number($("#hfCodeMoadel").val());
            var list = productList;
            if (documentTypeMoadel === enumDocumentTypeParentCode.codeMoadelSale || documentTypeMoadel === enumDocumentTypeParentCode.codeMoadelPurchase || documentTypeMoadel === enumDocumentTypeParentCode.codeMoadelPreInvoice) 
                list = list.filter(x => x.CanSale);
            if (documentTypeMoadel === enumDocumentTypeParentCode.codeMoadelReturnSale)
                list = list.filter(x => x.CanReturn);
            if (search)
                list = searchProduct(search, list);
            //list = list.filter(function (item) { return item.Name.toLowerCase().indexOf(search.toLowerCase()) >= 0 || item.Id.toLowerCase().indexOf(search.toLowerCase()) >= 0; });

            list.forEach(function (item) { item.Code = item.Id; });
            comboBuilder.loadData(list);
            break;
        case "cboProductSerial":
            $("#cboProductSerial_dropdown").hide();
            var storeCode = getObjectValue("cboStore", 0);
            var serial = gridBuilder.getCellValue(rowIndex, "ProductSerialNumber");
            var productName = gridBuilder.getCellValue(rowIndex, "ProductName");
            var price = gridBuilder.getCellValue(rowIndex, "Price");
            var discount = gridBuilder.getCellValue(rowIndex, "Discount");
            var summery = gridBuilder.getCellValue(rowIndex, "Summery");
            var state = gridBuilder.getCellValue(rowIndex, "ProductStateSerialCode");
            var isSaleSanad = $("#hfIsSaleSanad").val();
            var stateInOut = $('#hfStateInOut').val();

            var documentTypeMoadel = Number($("#hfCodeMoadel").val());
            var serialStatus = documentTypeMoadel === enumDocumentTypeParentCode.codeMoadelPurchase;
            var returnSaleMode = (documentTypeMoadel === enumDocumentTypeParentCode.codeMoadelReturnSale && !baseDocumentCode);
            if (isSaleSanad.toLowerCase() !== "true") {
                serialStatus = stateInOut === "1";
            }
            if (productId.indexOf("-") > 0)
                productId = productId.split("-")[0];

            switch (state) {
                case "1":
                    {
                        if (isEffectInventory) {
                            var remain = -1;
                            if (baseDocumentCode) {
                                var articleBaseCode = Number(gridBuilder.getCellValue(rowIndex, "ArticleBaseCode"));
                                var baseModel = baseFactorData.find(x => x.Code === articleBaseCode);
                                remain = baseModel.MaxLength;
                            }
                            var entrySerial = "Sale/EntrySerial?shenaseh=" + productId + "&state=1&storeCode=" + storeCode + "&serials=" + (!serial ? "" : serial) + "&stateInOut=" + stateInOut + "&fi=" + price + "&nameKala=" + productName + "&nameUnit=" + unitName + "&takhfif=" + (!discount ? "" : discount) + "&tozihat=" + (!summery ? "" : summery) + "&isSaleSanad=" + isSaleSanad;
                            var shopSerailSelection = "Sale/ShopSerialSelection?id=" + productId + "&store=" + storeCode + "&direct=1" + "&returnSaleMode=" + returnSaleMode + (returnSaleMode ? "&serials=" + (!serial ? "" : serial) + "&fi=" + price + "&nameKala=" + productName + "&nameUnit=" + unitName + "&takhfif=" + (!discount ? "" : discount) + "&tozihat=" + (!summery ? "" : summery) : "") + "&remain=" + remain;
                            var url = (serialStatus ? entrySerial : shopSerailSelection);
                            openInModal("", url, serialStatus ? window.top.enterProductSerial : window.top.productSerialExit, "850", "550", true);
                        }
                    }
                    break;
                case "2":
                    openInModal("", "Sale/EntryPart?shenaseh=" + productId + "&state=" + state + "&storeCode=" + storeCode + "&serials=" + (!serial ? "" : serial), window.top.enterProductPart, "850", "550");
                    break;
                case "3":
                    openInModal("", "Sale/EntryExpDate", window.top.enterProductExpDate, "600", "550");
                    break;
            }
            break;
        case "cboUnit":
            var unitList = productList.filter(function (item) { return item.Id === productId; });
            if (unitList.length > 0) {
                var data = [{ Code: unitList[0].UnitName, Name: unitList[0].UnitName }];
                unitList[0].SecondUnits.forEach(function (item) {
                    if (data.filter(function (row) { return row.Code === item.UnitName; }).length === 0)
                        data.push({ Code: item.UnitName, Name: item.UnitName });
                });
                comboBuilder.loadData(data);
            }
            break;
    }
}
function gridCellBeforeLostFocus(rowIndex, columnIndex) {
    var fieldName = gridBuilder.getCellFieldName(columnIndex);
    var value = gridBuilder.getCellValue(rowIndex, columnIndex);
    if (columnIndex === gridBuilder.getCellIndex("ProductId"))
        startEditingGrid(rowIndex);
    if (baseDocumentCode) {
        if (fieldName === "Amount") {
            var articleBaseCode = Number(gridBuilder.getCellValue(rowIndex, "ArticleBaseCode"));
            var baseModel = baseFactorData.find(x => x.Code === articleBaseCode);
            if (baseModel.MaxLength < Number(value)) {
                var lastValue = gridBuilder.getDataArray().data.find(x => x.ArticleBaseCode === articleBaseCode).Amount;
                setValueNonRaiseEvent(gridBuilder, rowIndex, "Amount", lastValue);
                showMsgModal(0, window.top.cantAddMoreThanBaseBalanceToExitOfGoods);
                return;
            }
            else
                calculateRow(rowIndex);
        }
        if (fieldName === "Price" || fieldName === "SumPrice" || fieldName === "Discount" || fieldName === "ValueAdded")
            gridCellChanged(rowIndex, columnIndex);
    }
}


async function gridCellChanged(rowIndex, columnIndex) {
    if (stopEventCellChange)
        return;
    var fieldName = gridBuilder.getCellFieldName(columnIndex);
    var value = gridBuilder.getCellValue(rowIndex, columnIndex);
    var toll = 0;
    var tax = 0;
    var valueAdded = 0;
    var currencyDecimalCount = getObjectValue("cboCurrency", 1);
    var count, sumPrice, discount, netPrice;
    var productId = fieldName === "ProductId" ? value : gridBuilder.getCellValue(rowIndex, "ProductId");
    var list = productList.filter(function (item) { return item.Id.toLowerCase() === productId.toLowerCase() });
    var amount;
    if (list.length === 0) {
        var product = findProductByBarcode(productId);
        if (!product)
            return;
        list = product.product;
        amount = product.amount;
    }
    if (list.length === 1) {
        tax = list[0].Tax;
        toll = list[0].Toll;
    }
    if (fieldName === "ProductId") {
        if (!value)
            return;
        if (list.length === 1) {
            setValueNonRaiseEvent(gridBuilder, rowIndex, "ProductId", list[0].Id);
            gridBuilder.setCellValue(rowIndex, "ProductName", list[0].Name);
            gridBuilder.setCellValue(rowIndex, "UnitCode", list[0].UnitCode);
            setValueNonRaiseEvent(gridBuilder, rowIndex, "UnitName", list[0].UnitName);
            gridBuilder.setCellValue(rowIndex, "Price", convertToComma(list[0].SalePrice));
            gridBuilder.setCellValue(rowIndex, "MainPrice", convertToComma(list[0].SalePrice));
            gridBuilder.setCellValue(rowIndex, "Discount", convertToComma(list[0].Discount));
            gridBuilder.setCellValue(rowIndex, "ProductTax", list[0].Tax);
            gridBuilder.setCellValue(rowIndex, "ProductToll", list[0].Toll);
            gridBuilder.setCellValue(rowIndex, "ProductTaxInPrice", list[0].TaxInPrice);
            gridBuilder.setCellValue(rowIndex, "ProductTaxTypeCode", list[0].TaxTypeCode);

            if (list[0].StateSerial === 1) {
                gridBuilder.setCellValue(rowIndex, "Amount", "1");
            }
            else if (amount)
                gridBuilder.setCellValue(rowIndex, "Amount", amount);

            startEditingGrid(rowIndex);

        } else {
            gridBuilder.setCellValue(rowIndex, "ProductName", "");
            gridBuilder.setCellValue(rowIndex, "UnitCode", "");
            setValueNonRaiseEvent(gridBuilder, rowIndex, "UnitName", "");
            gridBuilder.setCellValue(rowIndex, "MainPrice", "");
            gridBuilder.setCellValue(rowIndex, "Price", "");
            gridBuilder.setCellValue(rowIndex, "MainDiscount", "");
            gridBuilder.setCellValue(rowIndex, "Discount", "");
            gridBuilder.setCellValue(rowIndex, "ProductTaxTypeCode", "");
            gridBuilder.setCellValue(rowIndex, "IsPercentDiscount", "");
            gridBuilder.setCellValue(rowIndex, "ProductStateSerialCode", "");
            gridBuilder.setCellValue(rowIndex, "Amount", "");
            gridBuilder.setCellValue(rowIndex, "ProductTax", "0");
            gridBuilder.setCellValue(rowIndex, "ProductToll", "0");
            gridBuilder.setCellValue(rowIndex, "ProductTaxInPrice", "false");
        }
        gridBuilder.rowChanged(rowIndex);
    }
    else if (fieldName === "ProductSerialNumber") {
        var stateInOut = $("#hfStateInOut").val();
        if (stateInOut === "-1" && value) {
            await ajax({
                loading: true,
                url: "SaleApi/GetProductInventoryBySerial",
                data: { serialNumber: value, storeCode: getObjectValue("cboStore", 0) },
                success: function (result) {
                    if (!result.ProductId) {
                        showMsgFactor(window.top.invalidProductSerial);

                    }
                    else if (result.Count !== 1) {
                        showMsgFactor(window.top.noInventory);
                    }
                    else if (result.ProductId.length > 0) {
                        var validationMsg = checkDuplicateSerial(value);
                        if (validationMsg.length > 0) {
                            showMsgFactor(validationMsg);
                        } else {
                            if (!productId)
                                gridBuilder.setCellValue(rowIndex, "ProductId", result.ProductId);
                            var $element = gridBuilder.getCellEditor(fieldName);
                            if ($element && $element.attr("data-key-down") === "13") {
                                if (rowIndex === gridBuilder.getRowsCount() - 1) {
                                    gridBuilder.addNewRow();
                                }
                                columnIndex = gridBuilder.getCellIndex("ProductId");
                                rowIndex++;
                            }
                        }
                    }
                }
            });
        }
    }
    else if (fieldName === "UnitName") {
        var productName = gridBuilder.getCellValue(rowIndex, "ProductName");
        if (productId && productName) {
            var unitList = list[0].SecondUnits.filter(function (item) { return item.UnitName === value && item.ProductId === productId; });
            if (unitList.length > 0) {
                var price = Number(unitList[0].Price) === -1 ? 0 : Number(unitList[0].Price);
                gridBuilder.setCellValue(rowIndex, "UnitCode", unitList[0].UnitCode);
                gridBuilder.setCellValue(rowIndex, "UnitName", unitList[0].UnitName);
                gridBuilder.setCellValue(rowIndex, "Price", convertToComma(price));
                gridBuilder.setCellValue(rowIndex, "MainPrice", price);
            }
            else {
                gridBuilder.setCellValue(rowIndex, "UnitCode", list[0].UnitCode);
                gridBuilder.setCellValue(rowIndex, "UnitName", list[0].UnitName);
                gridBuilder.setCellValue(rowIndex, "Price", convertToComma(list[0].SalePrice));
                gridBuilder.setCellValue(rowIndex, "MainPrice", list[0].SalePrice);
            }
            calculateRow();
            gridBuilder.rowChanged(rowIndex);
        }
    }
    else if (fieldName === "Amount") {
        if (baseDocumentCode) {
            var articleBaseCode = Number(gridBuilder.getCellValue(rowIndex, "ArticleBaseCode"));
            var baseModel = baseFactorData.find(x => x.Code === articleBaseCode);
            if (baseModel.MaxLength < Number(value)) {
                var lastValue = gridBuilder.getDataArray().data.find(x => x.ArticleBaseCode === articleBaseCode).Amount;
                setValueNonRaiseEvent(gridBuilder, rowIndex, "Amount", lastValue);
                showMsgModal(0, window.top.cantAddMoreThanBaseBalanceToExitOfGoods);
                return;
            }
        }
        calculateRow(rowIndex);
    }
    else if (fieldName === "Price") {
        var count = Number(gridBuilder.getCellValue(rowIndex, "Amount"));
        var taxInPrice = gridBuilder.getCellValue(rowIndex, "ProductTaxInPrice").toLowerCase() === "true";
        if (taxInPrice)
            gridBuilder.setCellValue(rowIndex, "MainPrice", value);
        calculateRow(rowIndex);
    }
    else if (fieldName === "SumPrice") {
        count = numberNonCommas(gridBuilder.getCellValue(rowIndex, "Amount"), 0);
        sumPrice = numberNonCommas(value, 0);
        discount = numberNonCommas(gridBuilder.getCellValue(rowIndex, "Discount"), 0);
        if (count > 0) {
            var fi = (sumPrice / count).toFixed(currencyDecimalCount);
            setValueNonRaiseEvent(gridBuilder, rowIndex, "Price", fi);
        } else
            setValueNonRaiseEvent(gridBuilder, rowIndex, "Price", "");

        valueAdded = Number(((sumPrice - discount) * (tax + toll) / 100).toFixed(currencyDecimalCount));
        netPrice = sumPrice - discount + valueAdded;

        tax = Number(((sumPrice - discount) * tax / 100).toFixed(currencyDecimalCount));
        toll = Number((valueAdded - tax).toFixed(currencyDecimalCount));

        setValueNonRaiseEvent(gridBuilder, rowIndex, "ValueAdded", valueAdded < 0 ? 0 : convertToComma(valueAdded));
        gridBuilder.setCellValue(rowIndex, "Tax", tax < 0 ? 0 : tax);
        gridBuilder.setCellValue(rowIndex, "Toll", toll < 0 ? 0 : toll);
        gridBuilder.setCellValue(rowIndex, "NetPrice", convertToComma(netPrice < 0 ? 0 : netPrice));
        updateSummeryTbl();
    }
    else if (fieldName === "Discount") {
        var TaxInPrice = gridBuilder.getCellValue(rowIndex, "ProductTaxInPrice").toLowerCase() === "true";
        discount = numberNonCommas(value, 0);
        if (TaxInPrice && discount === 0) {
            var mainPrice = numberNonCommas(gridBuilder.getCellValue(rowIndex, "MainPrice"), 0);
            var count = numberNonCommas(gridBuilder.getCellValue(rowIndex, "Amount"), 0);
            netPrice = Number((count * mainPrice).toFixed(currencyDecimalCount));
            sumPrice = Number((netPrice * 100 / (100 + tax + toll)).toFixed(currencyDecimalCount));
            valueAdded = netPrice - sumPrice;
        }
        else {
            sumPrice = numberNonCommas(gridBuilder.getCellValue(rowIndex, "SumPrice"), 0);
            valueAdded = Number(((sumPrice - discount) * (tax + toll) / 100).toFixed(currencyDecimalCount));
            netPrice = sumPrice - discount + valueAdded;
        }

        if (discount > sumPrice) {
            discount = sumPrice;
            setValueNonRaiseEvent(gridBuilder, rowIndex, "Discount", discount);
        }
        tax = Number(((sumPrice - discount) * tax / 100).toFixed(currencyDecimalCount));
        toll = Number((valueAdded - tax).toFixed(currencyDecimalCount));

        setValueNonRaiseEvent(gridBuilder, rowIndex, "ValueAdded", valueAdded < 0 ? 0 : convertToComma(valueAdded));
        gridBuilder.setCellValue(rowIndex, "Tax", tax < 0 ? 0 : tax);
        gridBuilder.setCellValue(rowIndex, "Toll", toll < 0 ? 0 : toll);
        gridBuilder.setCellValue(rowIndex, "NetPrice", convertToComma(netPrice < 0 ? 0 : netPrice));
        updateSummeryTbl();
    }
    else if (fieldName === "ValueAdded") {
        sumPrice = numberNonCommas(gridBuilder.getCellValue(rowIndex, "SumPrice"), 0);
        discount = numberNonCommas(gridBuilder.getCellValue(rowIndex, "Discount"), 0);
        netPrice = sumPrice - discount + numberNonCommas(value, 0);

        tax = Number((value * tax / 100).toFixed(currencyDecimalCount));
        toll = Number((value - tax).toFixed(currencyDecimalCount));

        gridBuilder.setCellValue(rowIndex, "Tax", tax < 0 ? 0 : tax);
        gridBuilder.setCellValue(rowIndex, "Toll", toll < 0 ? 0 : toll);
        gridBuilder.setCellValue(rowIndex, "NetPrice", convertToComma(netPrice < 0 ? 0 : netPrice));
        updateSummeryTbl();
    }

}
function startEditingGrid(rowIndex) {
    var value = gridBuilder.getCellValue(rowIndex, "ProductId");
    if (!value) {
        if (baseDocumentCode) {
            gridBuilder.deleteRow(rowIndex);
            $(".table-body").find(".grid-empty").hide();
        }
        return;
    }

    var list = productList.filter(function (item) { return item.Id.toLowerCase() === value.toLowerCase(); });
    if (list.length === 0) {
        var product = findProductByBarcode(value);
        if (!product)
            return;
        list = product.product;
        amount = product.amount;
    }
    if (list.length === 1) {
        var documentTypeParentCode = Number($("#hfCodeMoadel").val());
        var isFixedPrice = getObjectValue("cboPriceList", 1) === "true";
        var isFixedDiscount = getObjectValue("cboDiscount", 1) === "true";
        var productStateSerialCode = list[0].StateSerial;
        
        gridBuilder.setCellValue(rowIndex, "IsPercentDiscount", list[0].DiscountType);
        gridBuilder.setCellValue(rowIndex, "MainDiscount", list[0].Discount || 0);
        gridBuilder.setCellValue(rowIndex, "ProductStateSerialCode", list[0].StateSerial);
        gridBuilder.setCellValue(rowIndex, "ProductTaxTypeCode", list[0].TaxTypeCode);
        gridBuilder.setCellValue(rowIndex, "ProductTaxInPrice", list[0].TaxInPrice);
        gridBuilder.setCellValue(rowIndex, "ProductTax", list[0].Tax);
        gridBuilder.setCellValue(rowIndex, "ProductToll", list[0].Toll);

        var isOut = $("#hfStateInOut").val() === "-1";
        if (isOut || (list[0].Tax === "0" && list[0].Toll === "0"))
            gridBuilder.setEnabledCellEditor("ValueAdded", false);
        else
            gridBuilder.setEnabledCellEditor("ValueAdded", true);

        var unitCount = list[0].UnitCount;

        if (productStateSerialCode !== 1 || documentTypeParentCode === enumDocumentTypeParentCode.codeMoadelPreInvoice) {
            gridBuilder.setEnabledCellEditor("ProductSerialNumber", false);
            gridBuilder.setEnabledCellEditor("Amount", true);
        } else {
            gridBuilder.setEnabledCellEditor("ProductSerialNumber", true);
            gridBuilder.setEnabledCellEditor("Amount", false);
        }
        if ((unitCount) > 1)
            gridBuilder.setEnabledCellEditor("UnitName", true);
        else
            gridBuilder.setEnabledCellEditor("UnitName", false);


        if (isFixedPrice) {
            gridBuilder.setEnabledCellEditor("Price", false);
            gridBuilder.setEnabledCellEditor("SumPrice", false);
        } else {
            gridBuilder.setEnabledCellEditor("Price", true);
            gridBuilder.setEnabledCellEditor("SumPrice", true);
        }

        if (isFixedDiscount)
            gridBuilder.setEnabledCellEditor("Discount", false);
        else
            gridBuilder.setEnabledCellEditor("Discount", true);

        var currencyDecimalCount = getObjectValue("cboCurrency", 1);

        var $element = gridBuilder.getCellEditor("Amount");
        if ($element)
            $element.attr("data-decimalCount", list[0].UnitDecimalCount);
        $element = gridBuilder.getCellEditor("Price");
        if ($element)
            $element.attr("data-decimalCount", currencyDecimalCount);
        $element = gridBuilder.getCellEditor("SumPrice");
        if ($element)
            $element.attr("data-decimalCount", currencyDecimalCount);
        $element = gridBuilder.getCellEditor("Discount");
        if ($element)
            $element.attr("data-decimalCount", currencyDecimalCount);


        if (baseDocumentCode) {
            var articleBaseCode = Number(gridBuilder.getCellValue(rowIndex, "ArticleBaseCode"));
            var baseModel = baseFactorData.find(x => x.Code === articleBaseCode);
            var columns = gridBuilder.getColumns().split(',');
            columns.forEach(function (item) {
                if (item === "Price" || item === "SumPrice" || item === "Discount" || item === "ValueAdded")
                    gridBuilder.setEnabledCellEditor(item, baseModel.Editable);
                else if (item !== "Amount" && item !== "ProductSerialNumber")
                    gridBuilder.setEnabledCellEditor(item, false);
            });
        }
    }


}
function gridKeyDown(sender, event) {

    if ($(sender).attr("id") === "cboProductId") {
        if (event.ctrlKey && event.keyCode === 32) {
            var title = window.top.productSearch;
            var height = "440";
            var width = "650";
            var src = "Sale/FindProduct?codeAnbar=" + getObjectValue("cboStore", 0) + "&date=" + $("#txtDate").val();
            openInModal("", src, title, width, height);
        }
    }
    else if ($(sender).attr("id") === "txtDiscount" && event.shiftKey && event.keyCode === 53) {
        var rowIndex = gridBuilder.getActiveRowIndex();
        var sumPrice = numberNonCommas(gridBuilder.getCellValue(rowIndex, "SumPrice"), 0);
        var discount = numberNonCommas(gridBuilder.getCellValue(rowIndex, "Discount"), 0);
        var currencyDecimalCount = getObjectValue("cboCurrency", 1);
        discount = (discount * sumPrice / 100).toFixed(currencyDecimalCount);
        gridBuilder.setCellValue(rowIndex, "Discount", discount);
        event.preventDefault();
    }
}
function selectedProductFromModal(value) {
    gridBuilder.setActiveRowCellValue("ProductId", value);
}
function calculateRow(rowIndex) {
    if (rowIndex === undefined)
        rowIndex = gridBuilder.getActiveRowIndex();
    var currencyDecimalCount = getObjectValue("cboCurrency", 1);
    var count = numberNonCommas(gridBuilder.getCellValue(rowIndex, "Amount"), 0);
    var price = numberNonCommas(gridBuilder.getCellValue(rowIndex, "Price"), 0);
    var mainPrice = numberNonCommas(gridBuilder.getCellValue(rowIndex, "MainPrice"), 0);
    var sumPrice = numberNonCommas(gridBuilder.getCellValue(rowIndex, "SumPrice"), 0);
    var mainDiscount = numberNonCommas(gridBuilder.getCellValue(rowIndex, "MainDiscount"), 0);
    var discount = numberNonCommas(gridBuilder.getCellValue(rowIndex, "Discount"), 0);
    var isPercentDiscount = gridBuilder.getCellValue(rowIndex, "IsPercentDiscount") === "1";
    var productTaxTypeCode = Number(gridBuilder.getCellValue(rowIndex, "ProductTaxTypeCode"));
    var TaxInPrice = gridBuilder.getCellValue(rowIndex, "ProductTaxInPrice").toLowerCase() === "true";
    var tax = Number(gridBuilder.getCellValue(rowIndex, "ProductTax"));
    var toll = Number(gridBuilder.getCellValue(rowIndex, "ProductToll"));
    var articleBaseCode = Number(gridBuilder.getCellValue(rowIndex, "ArticleBaseCode"));

    var hasDiscountList = Number(getObjectValue("cboDiscount", 0)) > 0;
    sumPrice = Number((count * price).toFixed(currencyDecimalCount));

    if (baseDocumentCode) {
        discount = calculateBaseDiscount(articleBaseCode, count);
    }
    else if (hasDiscountList)
        discount = isPercentDiscount ? Number((mainDiscount * sumPrice / 100).toFixed(currencyDecimalCount)) : Number((mainDiscount * count).toFixed(currencyDecimalCount));

    if (discount > sumPrice)
        discount = sumPrice;

    var valueAdded = 0;
    var netPrice = 0;
    if (productTaxTypeCode > 1) {
        if (TaxInPrice && count > 0) {
            price = Number((mainPrice * 100 / (100 + tax + toll)).toFixed(currencyDecimalCount));
            if (discount === 0) {
                netPrice = Number((count * mainPrice).toFixed(currencyDecimalCount));
                sumPrice = Number((netPrice * 100 / (100 + tax + toll)).toFixed(currencyDecimalCount));
                valueAdded = netPrice - sumPrice;
            } else {
                sumPrice = Number((count * price).toFixed(currencyDecimalCount));
                if (hasDiscountList)
                    discount = isPercentDiscount ? Number((mainDiscount * sumPrice / 100).toFixed(currencyDecimalCount)) : Number((mainDiscount * count).toFixed(currencyDecimalCount));

                if (discount > sumPrice)
                    discount = sumPrice;
                valueAdded = Number(((toll + tax) * (sumPrice - discount) / 100).toFixed(currencyDecimalCount));
            }
        }
        else
            valueAdded = Number(((toll + tax) * (sumPrice - discount) / 100).toFixed(currencyDecimalCount));
        tax = Number((tax * (sumPrice - discount) / 100).toFixed(currencyDecimalCount));
        toll = Number((valueAdded - tax).toFixed(currencyDecimalCount));
        setValueNonRaiseEvent(gridBuilder, rowIndex, "Price", convertToComma(price));
    }
    netPrice = Number((sumPrice - discount + valueAdded).toFixed(currencyDecimalCount));
    setValueNonRaiseEvent(gridBuilder, rowIndex, "SumPrice", convertToComma(sumPrice));
    setValueNonRaiseEvent(gridBuilder, rowIndex, "Discount", convertToComma(discount));
    gridBuilder.setCellValue(rowIndex, "Toll", toll < 0 ? 0 : toll);
    gridBuilder.setCellValue(rowIndex, "Tax", tax < 0 ? 0 : tax);
    setValueNonRaiseEvent(gridBuilder, rowIndex, "ValueAdded", convertToComma(valueAdded < 0 ? 0 : valueAdded));
    setValueNonRaiseEvent(gridBuilder, rowIndex, "NetPrice", convertToComma(netPrice < 0 ? 0 : netPrice));
    updateSummeryTbl();
}
function calculateBaseDiscount(articleBaseCode, count) {
    var currencyDecimalCount = getObjectValue("cboCurrency", 1);
    var baseModel = baseFactorData.find(x => x.Code === articleBaseCode);
    var discount = 0;
    if (baseModel.Discount > 0) {
        if (baseModel.Amount === count)
            return baseModel.Discount;
        discount = Number((baseModel.Discount / baseModel.Amount).toFixed(currencyDecimalCount));
    }
    return discount * count;
}
function calculateDiscount(rowIndex, value) {
    var currencyDecimalCount = getObjectValue("cboCurrency", 1);
    var productId = gridBuilder.getCellValue(rowIndex, "ProductId");
    var list = productList.filter(function (item) { return item.Id.toLowerCase() === productId.toLowerCase() });
    var tax = list[0].Tax;
    var toll = list[0].Toll;
    var sumPrice = numberNonCommas(gridBuilder.getCellValue(rowIndex, "SumPrice"), 0);
    var discount = numberNonCommas(value, 0);
    if (discount > sumPrice) {
        discount = sumPrice;
        setValueNonRaiseEvent(gridBuilder, rowIndex, "Discount", discount);
    }
    var valueAdded = Number(((sumPrice - discount) * (tax + toll) / 100).toFixed(currencyDecimalCount));
    var netPrice = sumPrice - discount + valueAdded;

    tax = Number(((sumPrice - discount) * tax / 100).toFixed(currencyDecimalCount));
    toll = Number((valueAdded - tax).toFixed(currencyDecimalCount));

    setValueNonRaiseEvent(gridBuilder, rowIndex, "ValueAdded", valueAdded < 0 ? 0 : convertToComma(valueAdded));
    gridBuilder.setCellValue(rowIndex, "Tax", tax < 0 ? 0 : tax);
    gridBuilder.setCellValue(rowIndex, "Toll", toll < 0 ? 0 : toll);
    gridBuilder.setCellValue(rowIndex, "NetPrice", convertToComma(netPrice < 0 ? 0 : netPrice));
    updateSummeryTbl();
}
function updateSummeryTbl() {

    var sumPrice = gridBuilder.getSumColumn("SumPrice");
    var discount = gridBuilder.getSumColumn("Discount");
    var valueAdded = gridBuilder.getSumColumn("ValueAdded");
    var netPrice = gridBuilder.getSumColumn("NetPrice");
    var currencyCode = Number(getObjectValue("cboCurrency", 0));

    $("#lblAllSumPrice").text(convertToComma(sumPrice));
    $("#lblSumDiscount").text(convertToComma(discount));
    $("#lblSumTollTax").text(convertToComma(valueAdded));
    $("#lblSumNetPrice").text(convertToComma(netPrice));

    if (currencyCode > 0 && currencyCode !== baseCurrencyCode) {
        var currencyRate = numberNonCommas($("#txtCurrencyRate").val());
        var price = Number((netPrice * currencyRate).toFixed(baseDecimalCount));
        $("#divSumNetPrice").show();
        $("#lblSumNetPriceBaseCurrency").text(convertToComma(price, baseDecimalCount));
    }
    else {
        $("#divSumNetPrice").hide();
    }
    if (!baseDocumentCode && gridBuilder.getRowsCount() === 0) {
        $("#cboCustomerAccount").lookupBuilder().setEnabled(true);
        $("#cboStore").lookupBuilder().setEnabled(true);
        $("#cboCurrency").lookupBuilder().setEnabled(true);
        $("#txtCurrencyRate").prop("disabled", false);
        $(".grid-new-row").show();
        $(".column-context-menu").show();
    }
}
async function setSerial(isEntry, productId, list, price, discount, summery) {
    var serialList = list.split(",");
    var fieldArray = ["ArticleBaseCode", "ProductTax", "ProductToll", "ProductTaxInPrice", "ProductTaxTypeCode", "ProductId", "ProductName", "UnitCode", "UnitNameProduct", "UnitName", "Amount", "Price", "MainPrice", "Discount", "IsPercentDiscount", "ProductStateSerialCode"];
    var rowIndex = lastRow = gridBuilder.getActiveRowIndex();
    var baseModel = null;
    var articleBaseCode = Number(gridBuilder.getCellValue(rowIndex, "ArticleBaseCode"));
    if (baseDocumentCode) {
        baseModel = baseFactorData.find(x => x.Code === articleBaseCode);
        if (baseModel.MaxLength < serialList.length) {
            showMsgModal(0, window.top.cantAddMoreThanBaseBalanceToExitOfGoods);
            return;
        }
    }
    for (var i = 0; i < serialList.length; i++) {
        if (i > 0) {
            gridBuilder.addNewRow();
            gridBuilder.endEditGrid();
            lastRow++;
            fieldArray.forEach(function (field) {
                var value;
                if (field === "ArticleBaseCode")
                    value = articleBaseCode;
                else if (field === "Amount")
                    value = 1;
                else
                    value = gridBuilder.getCellValue(rowIndex, field);
                setValueNonRaiseEvent(gridBuilder, lastRow, field, value);
            });
            calculateRow(lastRow);
        }

        var serial = serialList[i];
        if (serial.indexOf("=") > 0)
            serial = serial.split("=")[0];

        gridBuilder.setCellValue(lastRow, "ProductSerialNumber", serial);
        gridBuilder.setCellValue(lastRow, "Amount", 1);
        if (isEntry.toLowerCase() === "true") {
            gridBuilder.setCellValue(lastRow, "Price", numberNonCommas(price));
            gridBuilder.setCellValue(lastRow, "MainPrice", numberNonCommas(price));
            gridBuilder.setCellValue(lastRow, "Discount", discount);
            gridBuilder.setCellValue(lastRow, "Amount", 1);
            gridBuilder.setCellValue(lastRow, "Summery", summery);
            calculateRow(lastRow);
        }
    }
}
function checkDuplicateSerial(serial) {
    var msg = "";
    isValidSerial = true;
    var rowIndex = gridBuilder.getActiveRowIndex();
    for (var i = 0; i < gridBuilder.getRowsCount(); i++) {
        var productSerial = gridBuilder.getCellValue(i, "ProductSerialNumber");
        if (productSerial === serial && rowIndex !== i) {
            msg = window.top._serial + serial + window.top.duplicate;
            isValidSerial = false;
            return false;
        }
    }
    return msg;
}
function showMsgFactor(msg) {
    $('#divReturnDelete').empty();
    tag = '<label class="float-right" style="font-size: 12px; color: #fff; font-weight: normal; word-break: break-word; margin:6px 10px;line-height: 2;">' + msg + '</label>';
    $('#divReturnDelete').append(tag);
    $("#divReturnDelete").addClass("show");
    setTimeout(function () {
        $("#divReturnDelete").removeClass("show");
    }, 5000);
}


function saveCash() {
    var ponyModel = [];
    ponyModel.push({
        Mablagh: numberNonCommas($('#lblSumNetPrice').text()),
        CodeSandog: $("#cboCashDesk").lookupBuilder().getSelectedValue(),
        Trs_Type: 0
    });
    save(ponyModel);
}
function save(ponyModel, roundValue, numberingSave) {
    if (!ponyModel)
        ponyModel = null;

    var exceptionText = checkValidation("");
    if (exceptionText === '') {
        var newPonyModel = [];
        var artikles = gridBuilder.getDataArray()["data"].filter(function (item) { return item.ProductId !== null; });
        if (ponyModel !== null) {
            ponyModel.forEach(function (item) {
                newPonyModel.push({
                    Price: item.Mablagh,
                    CashDeskCode: item.CodeSandog,
                    BankCode: item.CodeBank,
                    TrackingDate: item.Date_Paygri,
                    TrackingCode: item.Code_Paygri,
                    ChequeBookCode: item.Code_Dastachak,
                    Summery: item.Sumery,
                    TrsType: item.Trs_Type,
                    TelEtc: item.TelEtc,
                    ChequeCode: item.CoderizKharjchek,
                    TrsOperationType: item.CodeNoeAmaliyat === -1 ? ($("#hfStateInOut").val() === "-1" ? 1 : 2) : item.CodeNoeAmaliyat,
                    ChequeBankName: item.NameBankCheck
                });
            });
        }
        var header = getJsonValue();
        if (header["FactorSerial"] === "")
            header["FactorSerial"] = -1;
        header["NumberingSave"] = numberingSave;
        if (getQuery("handlingCode"))
            header["StoreHandlingCode"] = getQuery("handlingCode");
        ajax({
            loading: true,
            url: "SaleApi/" + (getQuery("Code") ? "UpdateFactor" : "InsertFactor"),
            data: { header: header, artikles: artikles, trsArtikles: newPonyModel, roundValue: roundValue },
            success: function (result) {
                if (firstEndState === "first" || firstEndState === "end") {
                    window.parent.firstEndSanadLastLevel(result.Code, $("#cboDocumentType").lookupBuilder().getSelectedText(), $("#lblAllSumPrice").text());
                }
                else if (firstEndState === "negativeKala") {
                    showMsgModal(2, result.Message);
                    refreshParent("checkNegativeKala()");
                    closeTopModal();
                }
                else if (getQuery("handlingCode")) {
                    showMsgModal(2, result.Message);
                    refreshParent("loadGrid('gridStoreHandlingList')");
                    closeTopModal();
                }
                else {
                    showMsgModal(2, result.Message);
                    if (ponyModel !== null)
                        closeTopModal();
                    newSanad();
                    if (result.PrintAfterSave)
                        print(result.Code, result.CurrentYear, numberingSave, result.DefaultReportId, result.PrintAfterSave);
                }
            }
        });
    }
    else {
        showMsgModal(0, exceptionText);
    }
}
function saveOrPony() {
    var exceptionText = checkValidation("");
    if (exceptionText === '') {
        var title = window.top.clearingForm;
        var width = "1000";
        var isSaleSanad = $("#hfIsSaleSanad").val().toLowerCase() === "true";
        var src = "Sale/Pony?state=" + $('#hfStateInOut').val() + "&tarafH=" + cboCustomerAccountBuilder.getSelectedText() + "&tarafHCode=" + getObjectValue("cboCustomerAccount", 0) + "&date=" + $('#txtDate').val() + "&amount=" + (isSaleSanad ? $('#lblSumNetPrice').text() : $('#lblAllSumPrice').text()) + "&sanadType=" + $("#hfSanadType").val() + "&codeSanad=" + getQuery("Code") + "&currencyCode=" + getObjectValue("cboCurrency", 0) + "&currencyName=" + $("#cboCurrency").lookupBuilder().getSelectedText() + "&currencyDecimalCount=" + getObjectValue("cboCurrency", 1);
        openInModal("", src, title, width, "", false);
    }
    else {
        showMsgModal(0, exceptionText);
    }

}

function exportSampleExcel(gridId, type) {
    if (type === "excelSample") {
        var isSale = $("#hfIsSaleSanad").val().toLowerCase() === "true";
        var columns = gridBuilder.getColumns().split(",");
        var columnsCaption = gridBuilder.getColumnsCaption().split(",");
        if (isSale) {
            columns.splice(9, 2);
            columnsCaption.splice(9, 2);
        }
        exportExcel(null, columns.join(","), columnsCaption.join(","), true);
    } else
        exportExcel(gridBuilder.getDataArray()["data"], gridBuilder.getColumns(), gridBuilder.getColumnsCaption());
}
function print(code, saleMali, numberingSave, defaultReportId, printAfterSave) {
    var title = window.top.printDocument;
    var reportName = "An_SanadN";
    var src = "Report/Default?GrpName=";
    if (isStore) {
        reportName = numberingSave ? "An_Sanad_Tedadi" : "An_Sanad_Riali";
        src += reportName + "&SalMali=" + saleMali + "&codeSanad=" + code + "&reportId=" + defaultReportId + "&printAfterSave=" + printAfterSave;
    }
    else
        src += reportName + "&SalMali=" + saleMali + "&Inst=" + code + "&reportId=" + defaultReportId + "&printAfterSave=" + printAfterSave;

    openInModal('', src, title, '', '', false);
}


async function getDocumentType() {
    var data = null;
    var documentTypeCode = $("#hfSanadType").val();
    await ajax({
        url: "SaleApi/GetDocumentType",
        data: { code: documentTypeCode },
        success: function (result) {
            if (Number(result.BaseDocumentTypeCode) > 0) {
                baseDocumentTypeCode = Number(result.BaseDocumentParentCode);
                $("#btnMabna").val(window.top.selectFrom + " " + result.BaseDocumentTypeName).show();
            }
            else
                $("#btnMabna").hide();

            data = result;
            isEffectInventory = result.IsEffectInventory;
        }
    });
    return data;
}

function setDocumentTypeHiddenField(data) {
    $("#hfStateInOut").val(data.StateInOut);
    $("#hfIsSaleSanad").val(data.IsSaleDocument.toString().toLowerCase());
    $("#hfCodeMoadel").val(data.ParentCode);
    $("#hfSabtSanad").val(data.CanSubmitDocument.toString().toLowerCase());
    $("#hfMabnaState").val(data.BaseDocumentTypeCode.toString().toLowerCase());

    isStore = data.ParentCode !== enumDocumentTypeParentCode.codeMoadelPreInvoice && data.ParentCode !== enumDocumentTypeParentCode.codeMoadelSale && data.ParentCode !== enumDocumentTypeParentCode.codeMoadelPurchase && data.ParentCode !== enumDocumentTypeParentCode.codeMoadelReturnSale && data.ParentCode !== enumDocumentTypeParentCode.codeMoadelReturnPurchase
    if (data.ParentCode == enumDocumentTypeParentCode.codeMoadelPurchase || data.ParentCode == enumDocumentTypeParentCode.codeMoadelReturnSale)
        $("#btnSave").val(window.top.creditSave);
    else if (data.ParentCode == enumDocumentTypeParentCode.codeMoadelSale || data.ParentCode == enumDocumentTypeParentCode.codeMoadelReturnPurchase)
        $("#btnSave").val(window.top.debitSave);
    else if (isStore)
        $("#btnSave").val(window.top.numbersSave);
    else
        $("#btnSave").val(window.top._register);

    if (getQuery("Code") && $("#hfSabtSanad").val().toLowerCase() === "true" && !isStore) {
        $("#btnSave").hide();
        $("#btnCash").hide();
    }
    if ($("#hfSabtSanad").val().toLowerCase() !== "true") {
        $("#btnPony").hide();
        $("#btnCash").hide();
    }
}

async function cboDocumentTypeChange() {
    var selectedItem = getObjectValue("cboDocumentType");
    if (selectedItem === -1)
        return;
    selectedItem = selectedItem.split("|");
    var documentTypeCode = selectedItem[0];
    var codeMoadel = Number(selectedItem[1]);
    var sabtSanad = selectedItem[5].toLowerCase() === "true";

    setDocumentTypeHiddenField({
        IsEffectInventory: selectedItem[2],
        StateInOut: selectedItem[3],
        IsSaleDocument: selectedItem[4],
        CanSubmitDocument: selectedItem[5],
        BaseDocumentTypeCode: selectedItem[6],
        ParentCode: Number(codeMoadel),
        Code: Number(documentTypeCode)
    });

    if (codeMoadel === enumDocumentTypeParentCode.transferBetweenOutputStore || codeMoadel === enumDocumentTypeParentCode.transferBetweenInputStore) {
        $('#divTarafH').hide();
        $('#divAnbar').show();
        changeRequired("cboStoreTo", true);
    }
    else {
        $('#divTarafH').show();
        $('#divAnbar').hide();
        changeRequired("cboStoreTo", false);
    }
    await $("#cboCustomerAccount").lookupBuilder().setSelectedValue("");
    if ($("#hfStateInOut").val() === "1") {
        if (sabtSanad)
            $("#btnPony").show();
        else
            $("#btnPony").hide();
    }
    if (getQuery("Code") === "") {
        await ajax({
            url: "SaleApi/GetMaxFactorNumber",
            data: { documentTypeCode: documentTypeCode },
            success: function (result) {
                if (result !== '')
                    $('#txtFactorNo').val(result);
            }
        });
    }

    $("#hfSanadType").val(documentTypeCode);
    await getDocumentType();
}


async function getEventLookupCombo($combo, search, code) {
    var id = $combo.attr('id');
    if (!id)
        return;
    var url = "";
    var data = null;
    var documentType = $("#hfSanadType").val();
    var documentTypeParentCode = $("#hfCodeMoadel").val();
    if (code && code.toString().indexOf("|") > 0)
        code = code.split("|")[0];
    switch (id) {
        case "cboStore":
        case "cboStoreTo":
            url = "SaleApi/GetStoreList";
            data = { creditType: 0, search: search, pageNo: 1, selectedCode: code };
            break;
        case "cboShoppingCenter":
            url = "SaleApi/GetShoppingCenterList";
            data = {
                state: !(documentType === "1" || documentType === "8") ? 2 : 1,
                search: search,
                pageNo: 1,
                selectedCode: code
            };
            break;
        case "cboDiscount":
            url = "SaleApi/GetDiscountList";
            data = {
                priceListCode: getObjectValue("cboPriceList", 0),
                date: $("#txtDate").val(),
                search: search,
                pageNo: 1
            };
            break;
        case "cboCurrency":
            url = "GeneralApi/GetCurrencyList";
            data = { search: search, pageNo: 1 };
            break;
        case "cboCashDesk":
            url = "TreasuryApi/GetCashDeskList";
            data = { search: search, pageNo: 1, selectedCode: code };
            break;
        case "cboPriceList":
            url = "GeneralApi/GetCustomerPriceList";
            data = {
                customerCode: getObjectValue("cboCustomerAccount", 0),
                search: search,
                pageNo: 1,
                selectedCode: code
            };
            break;
        case "cboCustomerAccount":
        case "cboCustomerAccount2":
        case "cboCustomerLast1":
        case "cboCustomerLast2":
            url = "GeneralApi/GetCustomerList";
            var customerType = 4;
            if (documentTypeParentCode === "2" || documentTypeParentCode === "13")
                customerType = 3;
            else if (documentTypeParentCode === "14")
                customerType = -1;
            data = {
                type: customerType,
                search: search,
                pageNo: 1,
                selectedCode: code,
                sort: "Name"
            };
            break;
        case "cboMarketer":
            url = "GeneralApi/GetCustomerList";
            data = { type: 1, search: search, pageNo: 1, selectedCode: code, sort: "Name" };
            break;
        case "cboDocumentType":
            url = "SaleApi/GetDocumentTypeList";
            data = { state: 2, search: search, pageNo: 1, selectedCode: code };
            break;
    }
    if (!url)
        return;
    var result;
    await ajax({
        url: url,
        data: data,
        success: function (resValue) {
            result = resValue;
        }
    });
    if (id === "cboPriceList") {
        $.each(result,
            function () {
                this.Code = this.Code + "|" + this.IsRequire;
            });
    }
    else if (id === "cboStoreTo") {
        result = result.filter(function (item) { return item.Code !== Number($("#cboStore").lookupBuilder().getSelectedValue()); });
    }
    else if (id === "cboDiscount") {
        $.each(result,
            function () {
                this.Code = this.Code + "|" + this.IsRequire;
            });
    }
    else if (id === "cboCurrency") {
        $.each(result,
            function () {
                this.Code = this.Code + "|" + this.DecimalCount;
            });
    } else if (id === "cboCustomerAccount") {
        $.each(result,
            function () {
                this.Name = this.Code + " " + this.Name;
                this.Code = this.Code + "|" + this.CurrencyCode + "|" + this.CurrencyDecimalCount;
            });
    } else if (id === "cboCustomerAccount2") {
        $.each(result,
            function () {
                this.Name = this.Code + " " + this.Name;
            });
    } else if (id === "cboDocumentType") {
        result = result.filter(function (item) {
            if (getQuery("type") === "out")
                return item.StateInOut === -1;
            else
                return item.StateInOut === 1 && item.ParentCode !== 15;
        });
        $.each(result,
            function () {
                this.Code = this.Code +
                    "|" +
                    this.ParentCode +
                    "|" +
                    this.IsEffectInventory +
                    "|" +
                    this.StateInOut +
                    "|" +
                    this.IsSaleDocument +
                    "|" +
                    this.CanSubmitDocument +
                    "|" +
                    this.BaseDocumentTypeCode;
            });

    }
    $combo.lookupBuilder().bindData(result);
    if (!code && $combo.attr("data-required") && result.length > 0 && !search) {
        var selectedCode = result[0].Code;
        if (getQuery("firstEndState") === "negativeKala" && id === "cboDocumentType")
            selectedCode = result.filter(function (item) { return item.ParentCode === enumDocumentTypeParentCode.codeMoadelStoreReceipt; })[0].Code;
        else if (getQuery("firstEndState") === "first" && id === "cboDocumentType") {
            if (!result.some(x => x.ParentCode === enumDocumentTypeParentCode.codeMoadelFirstInventory)) {
                showMsgModal(window.top.noFirstInventory);
                return;
            }
            selectedCode = result.filter(function (item) { return item.ParentCode === enumDocumentTypeParentCode.codeMoadelFirstInventory; })[0].Code;
        }
        else if (getQuery("firstEndState") === "end" && id === "cboDocumentType") {
            if (!result.some(x => x.ParentCode === enumDocumentTypeParentCode.codeMoadelEndInventory)) {
                showMsgModal(window.top.noEndInventory);
                return;
            }
            selectedCode = result.filter(function (item) { return item.ParentCode === enumDocumentTypeParentCode.codeMoadelEndInventory; })[0].Code;
        }
        await $combo.lookupBuilder().setSelectedValue(selectedCode);
    }
}

function getObjectValue(id, splitNumber) {
    if (id === null || $("#" + id).length === 0) {
        return -1;
    }
    else {
        var value = $("#" + id).lookupBuilder().getSelectedValue() || "";
        if (value === "" || value === "-1")
            return -1;
        else {
            if (!splitNumber && splitNumber !== 0)
                return value;
            return value.split("|")[splitNumber];
        }
    }
}
function convertToComma(number, decimalCount) {
    if (!decimalCount && decimalCount !== 0)
        decimalCount = getObjectValue("cboCurrency", 1);
    return numberWithCommas(number, decimalCount);
}
function insertBarcode(e, obj) {
    if (e.keyCode === 13) {
        var product = findProductByBarcode($(obj).val());
        if (product) {
            gridBuilder.addNewRow();
            gridBuilder.endEditGrid();
            var rowIndex = gridBuilder.getRowsCount() - 1;
            gridBuilder.setCellValue(rowIndex, "ProductId", product.product[0].Id);
            gridBuilder.setCellValue(rowIndex, "Amount", product.amount);
        }
        else
            showMsgFactor(window.top.productNotFound);
        $(obj).val("");
        $(obj).focus();
    }
}
function findProductByBarcode(value) {
    value = handlePlusCharacter(value);
    var list = productList.filter(function (item) { return item.Barcodes.filter(x => x.Barcode.toLowerCase() === value.toLowerCase()).length > 0 });
    var amount = 1;
    if (list.length === 0) {
        var barcode = value.substring(0, value.length - 6);
        if (barcode !== "") {
            list = productList.filter(function (item) { return item.Barcodes.filter(x => x.Barcode.toLowerCase() === barcode.toLowerCase()).length > 0 });
            if (list.length === 1) {
                amount = value.substring(value.indexOf(barcode) + barcode.length, value.length - 1);
                if (list[0].IsWeightBarcode) {
                    amount = amount.substring(0, 2) + "." + amount.substring(2);
                }
            }
        }
    }
    if (list.length > 0) {
        return { product: list, amount: Number(amount) }
    }
    return false;
}
function handlePlusCharacter(value) {
    var valueArr = value.split("");
    var result = "";
    for (var i = 0; i < valueArr.length; i++) {
        if (i > 0 && valueArr[i - 1] === "+")
            continue;
        if (valueArr[i] === "+")
            result += valueArr[i + 1].toLowerCase();
        else
            result += valueArr[i];
    }
    return result;
}
function searchProduct(search, list) {
    var result = list;
    var searchArr = search.trim().split(" ");
    for (i = 0; i < searchArr.length; i++) {
        result = result.filter(function (item) {
            return item.Name.toLowerCase().indexOf(searchArr[i].toString().toLowerCase()) >= 0 || item.Id.toString().indexOf(searchArr[i]) === 0;
        });
    }
    return result;
}

async function getProductShopDetail(productId, rowIndex, productName,unitCode) {
    if (productId && getObjectValue("cboStore", 0) !== -1)
        await ajax({
            url: "SaleApi/GetProductShopDetailCurrency",
            data: {
                productId: productId,
                storeCode: getObjectValue("cboStore", 0),
                documentTypeCode: $("#hfSanadType").val(),
                isShopMode: false,
                customerCode: Number(getObjectValue("cboCustomerAccount", 0)),
                unitCode : unitCode
            },
            success: function (result) {
                var customerCode = Number(getObjectValue("cboCustomerAccount", 0));
                var storeCode = Number(getObjectValue("cboStore", 0));
                var lastPrice = result.LastPriceCustomer;
                if (lastPriceModel.filter(x => x.ProductId === productId && x.CustomerCode === customerCode && x.StoreCode === storeCode && x.UnitCode === unitCode).length === 0) {
                    lastPriceModel.push({
                        StoreCode: storeCode,
                        CustomerCode: customerCode,
                        CustomerName: getCustomerName(),
                        ProductId: productId,
                        ProductName: productName,
                        PicThumb: result.PicThumb,
                        StoreStock: result.StoreStock,
                        UnitName: result.UnitName,
                        UnitCode: result.UnitCode,
                        LastPriceCustomer: {
                            Fi: Number(lastPrice.Fi).toFixed(lastPrice.DecimalCount),
                            DecimalCount: lastPrice.DecimalCount,
                            CurrencyName: lastPrice.CurrencyName,
                            CurrencyRate: lastPrice.CurrencyRate,
                            CurrencyCode: lastPrice.CurrencyCode,
                            DateLocal: lastPrice.DateLocal
                        },
                        LastPriceGeneral: {
                            Fi: Number(result.LastFi.Fi).toFixed(result.LastFi.DecimalCount),
                            DecimalCount: result.LastFi.DecimalCount,
                            CurrencyName: result.LastFi.CurrencyName,
                            CurrencyRate: result.LastFi.CurrencyRate,
                            CurrencyCode: result.LastFi.CurrencyCode,
                            DateLocal: result.LastFi.DateLocal,
                            CustomerCode: result.LastFi.CustomerCode
                        },
                        LastPriceIn: {
                            Fi: Number(result.LastPriceIn.Fi).toFixed(result.LastPriceIn.DecimalCount),
                            DecimalCount: result.LastPriceIn.DecimalCount,
                            CurrencyName: result.LastPriceIn.CurrencyName,
                            CurrencyRate: result.LastPriceIn.CurrencyRate,
                            CurrencyCode: result.LastPriceIn.CurrencyCode,
                            DateLocal: result.LastPriceIn.DateLocal,
                            CustomerCode: result.LastPriceIn.CustomerCode
                        },
                        LastPriceOut: {
                            Fi: Number(result.LastPriceOut.Fi).toFixed(result.LastPriceOut.DecimalCount),
                            DecimalCount: result.LastPriceOut.DecimalCount,
                            CurrencyName: result.LastPriceOut.CurrencyName,
                            CurrencyRate: result.LastPriceOut.CurrencyRate,
                            CurrencyCode: result.LastPriceOut.CurrencyCode,
                            DateLocal: result.LastPriceOut.DateLocal,
                            CustomerCode: result.LastPriceOut.CustomerCode
                        }

                    });
                }

                gridBuilder.setCellValue(rowIndex, "LastPriceIn", Number(result.LastPriceIn.Fi).toFixed(result.LastPriceIn.DecimalCount));
                gridBuilder.setCellValue(rowIndex, "LastPriceInCurrencyRate", result.LastPriceIn.CurrencyRate);

            }
        });
}
function setProductShopDetail(productId, customerCode, storeCode, rowIndex,unitCode) {
    var model = lastPriceModel.find(x => x.ProductId === productId && x.CustomerCode === customerCode && x.StoreCode === storeCode && x.UnitCode === unitCode);
    if (!model)
        return;

    $("#lblStoreStockOut").text(model.StoreStock + " " + model.UnitName);
    if (model.LastPriceCustomer.DateLocal) {
        var lastPrice = model.LastPriceCustomer;
        var lastPriceStr = convertToComma(model.LastPriceCustomer.Fi, model.LastPriceCustomer.DecimalCount) + " " + model.LastPriceCustomer.CurrencyName;
        var fiMoadel = convertToComma(lastPrice.Fi * lastPrice.CurrencyRate, baseDecimalCount);
        var lastPriceRialStr = "(" + fiMoadel + " " + baseCurrencyName + ")";
        $("#lblLastPriceMoadel").text(baseCurrencyCode !== lastPrice.CurrencyCode ? lastPriceRialStr : "");
    }
    else {
        lastPriceStr = "---";
        $("#lblLastPriceMoadel").text("");
    }
    $("#lblCustomerName").text(model.CustomerName);
    $("#lblProductUnit").text(model.UnitName);
    $("#imgProduct").attr("src", model.PicThumb ? model.PicThumb : "../img/product.png");
    $("#divProductShopDetail").attr("data-product", model.ProductId).attr("data-unit", unitCode);
    $("#lblMojoudi").text(model.StoreStock);
    $("#lblLastPrice").text(lastPriceStr);
    $("#lblShowDetails").show();
}
function clearProductShopDetail() {
    $("#lblLastPrice").text("");
    $("#lblLastPriceMoadel").text("");
    $("#lblCustomerName").text("");
    $("#lblProductUnit").text("");
    $("#lblMojoudi").text("");
    $("#imgProduct").attr("src", "../img/product.png");
    $("#divProductShopDetail").attr("data-product", "").attr("data-unit","");
    $("#lblShowDetails").hide();
}
function getCustomerName() {
    var customerName = $("#cboCustomerAccount").lookupBuilder().getSelectedText();
    var names = customerName.split(" ");
    names.splice(0, 1);
    var customerName = names.join(" ");
    return customerName;
}
function openShopProduct() {
    var productId = $("#divProductShopDetail").attr("data-product");
    if (!productId)
        return;
    openInModal('', 'Sale/ShopProduct?pid=' + productId, window.top.productSpecifications, '1000', '');
}
async function lockDocument(code) {
    await ajax({
        url: "GeneralApi/LockDocument",
        data: { systemName: "TAn_SanadWeb", code: code },
        success: function (result) {

        }
    });
}
async function getBaseFactorData(factorId) {
    await ajax({
        url: "SaleApi/GetPreInvoice",
        data: { factorId: factorId },
        success: function (result) {
            var editable = false;
            if (result.length > 0) {
                if (result[0].NumberingSave && result[0].DocumentTypeParentCode !== enumDocumentTypeParentCode.codeMoadelPreInvoice)
                    editable = true;
            }
            loadBaseFactorData(result, editable);
        }
    });
}
function loadBaseFactorData(model, editable) {
    baseFactorData = [];
    model.forEach(function (item) {
        var maxLength = item.RemainAmount;
        if (currentvarArtikls.find(x => x.ArticleBaseCode === item.ArticleBaseCode)) {
            var artikl = currentvarArtikls.find(x => x.ArticleBaseCode === item.ArticleBaseCode);
            maxLength = artikl.Amount + item.RemainAmount;
        }
        baseFactorData.push({
            Code: item.ArticleBaseCode,
            Amount: item.Amount,
            Discount: item.Discount,
            RemainAmount: item.RemainAmount,
            UnitCode: item.UnitCode,
            MaxLength: maxLength,
            Editable: editable
        });
    });
}
function searchCustomer(comboId) {
    if (window.event.keyCode) {
        if (window.event.ctrlKey && window.event.keyCode === 32)
            findCustomer(comboId);
    }
    else {
        findCustomer(comboId);
    }
}
function findCustomer(comboId) {
    var customerType = 1;
    if (comboId === "cboCustomerAccount" || comboId === "cboCustomerAccount2") {
        var documentTypeParentCode = $("#hfCodeMoadel").val();
        customerType = 4;
        if (documentTypeParentCode === "2" || documentTypeParentCode === "13")
            customerType = 3;
        else if (documentTypeParentCode === "14")
            customerType = -1;
    }
    var title = window.top.searchCustomer;
    var height = "440";
    var width = "650";
    var src = "Sale/FindCustomer?combo=" + comboId + "&customerType=" + customerType;
    openInModal("", src, title, width, height);
}

function selectedCustomerFromModal(combo, value) {
    $("#" + combo).lookupBuilder().setSelectedValue(value);
}
function openLastPriceModal() {
    var customerCode = Number(getObjectValue("cboCustomerAccount", 0));
    var storeCode = Number(getObjectValue("cboStore", 0));
    var productId = $("#divProductShopDetail").attr("data-product");
    var unitCode = Number($("#divProductShopDetail").attr("data-unit"));
    var model = lastPriceModel.find(x => x.ProductId === productId && x.CustomerCode === customerCode && x.StoreCode === storeCode && x.UnitCode === unitCode);
    if (!model)
        return;

    var typeName1 = "";
    var typeName2 = "";
    var isSale = $("#hfIsSaleSanad").val().toLowerCase() === "true";
    var stateInOut = Number($('#hfStateInOut').val());
    var lastPriceModel2 = stateInOut === 1 ? model.LastPriceOut : model.LastPriceIn;
    var lastPriceModel1 = stateInOut === 1 ? model.LastPriceIn : model.LastPriceOut;
    var lastPrice2 = convertToComma(lastPriceModel2.Fi, lastPriceModel2.DecimalCount) + " " + lastPriceModel2.CurrencyName;
    var lastPrice1 = convertToComma(lastPriceModel1.Fi, lastPriceModel1.DecimalCount) + " " + lastPriceModel1.CurrencyName;
    var lastPriceCustomer = convertToComma(model.LastPriceCustomer.Fi, model.LastPriceCustomer.DecimalCount) + " " + model.LastPriceCustomer.CurrencyName;

    if (baseCurrencyCode !== lastPriceModel2.CurrencyCode && lastPriceModel2.Fi > 0) {
        lastPrice2 += " " + "(" + convertToComma(lastPriceModel2.Fi * lastPriceModel2.CurrencyRate, baseDecimalCount) + " " + baseCurrencyName + ")";
    }
    if (baseCurrencyCode !== lastPriceModel1.CurrencyCode && lastPriceModel1.Fi > 0) {
        lastPrice1 += " " + "(" + convertToComma(lastPriceModel1.Fi * lastPriceModel1.CurrencyRate, baseDecimalCount) + " " + baseCurrencyName + ")"
    }
    if (baseCurrencyCode !== model.LastPriceCustomer.CurrencyCode && model.LastPriceCustomer.Fi > 0) {
        lastPriceCustomer += " " + "(" + convertToComma(model.LastPriceCustomer.Fi * model.LastPriceCustomer.CurrencyRate, baseDecimalCount) + " " + baseCurrencyName + ")"
    }

    if (isSale && stateInOut === 1) {
        typeName1 = window.top.lastFiPurchase;
        typeName2 = window.top.lastFiSale;
    }
    else if (isSale && stateInOut === -1) {
        typeName1 = window.top.lastFiSale;
        typeName2 = window.top.lastFiPurchase;
    }
    else if (!isSale && stateInOut === 1) {
        typeName1 = window.top.lastFiEnter;
        typeName2 = window.top.lastFiSale;
    }

    if (!lastPriceModel2.DateLocal)
        lastPrice2 = getEmptyPriceMessage(isSale, stateInOut * -1, false);
    if (!lastPriceModel1.DateLocal)
        lastPrice1 = getEmptyPriceMessage(isSale, stateInOut, false);
    if (!model.LastPriceCustomer.DateLocal)
        lastPriceCustomer = getEmptyPriceMessage(isSale, stateInOut, true);

    var data = {
        LastPrice1: lastPrice1,
        LastDate1: lastPriceModel1.DateLocal,
        LastPrice2: lastPrice2,
        LastDate2: lastPriceModel2.DateLocal,
        LastPriceCustomer2: lastPrice2,
        LastDateCustomer2: lastPriceModel2.DateLocal,
        LastPriceCustomer1: lastPriceCustomer,
        LastDateCustomer1: model.LastPriceCustomer.DateLocal,
        InOutName2: typeName2,
        InOutName1: typeName1,
        ProductName: model.ProductName,
        StoreStock: model.StoreStock + " " + model.UnitName
    }
    setJsonValue(data, "#divLastPriceModal");
    $("#imgProductModal").attr("src", model.PicThumb ? model.PicThumb : "../img/product.png");
    $("#cboCustomerLast1").lookupBuilder().setSelectedValue(customerCode);
    $("#cboCustomerLast2").lookupBuilder().setSelectedValue(lastPriceModel2.CustomerCode);
    setComboCaption("cboCustomerLast1", typeName1 + " " + (stateInOut === 1 ? window.top._Az : window.top._Be));
    setComboCaption("cboCustomerLast2", typeName2 + " " + (stateInOut === -1 ? window.top._Az : window.top._Be));
    $("#divLastPriceModal").modal();
}
async function getProductShopDetailCustomer(productId, customerCode, state,unitCode) {
    var stateInOut = Number($('#hfStateInOut').val()) * (state === 2 ? -1 : 1);
    await ajax({
        url: "SaleApi/GetProductShopDetailCurrency",
        data: {
            productId: productId,
            isShopMode: false,
            customerCode: customerCode,
            stateInOut: stateInOut,
            unitCode : unitCode
        },
        success: function (result) {
            setLastPriceCustomer(result.LastPriceCustomer, state);
        }
    });
}
function setLastPriceCustomer(model, state) {
    var lastPriceCustomer = "";
    if (model.DateLocal) {
        lastPriceCustomer = convertToComma(model.Fi, model.DecimalCount) + " " + model.CurrencyName;
        if (baseCurrencyCode !== model.CurrencyCode) {
            lastPriceCustomer += " " + "(" + convertToComma(model.Fi * model.CurrencyRate, baseDecimalCount) + " " + baseCurrencyName + ")"
        }
    }
    else {
        var stateInOut = Number($('#hfStateInOut').val()) * (state === 2 ? -1 : 1);
        var isSale = $("#hfIsSaleSanad").val().toLowerCase() === "true";
        lastPriceCustomer = getEmptyPriceMessage(isSale, stateInOut, true);
    }
    $("[data-id='LastPriceCustomer" + state + "']").text(lastPriceCustomer);
    $("[data-id='LastDateCustomer" + state + "']").text(model.DateLocal || "");
}
function getEmptyPriceMessage(isSale, stateInOut, isCustomer) {
    var msg = "";
    if (stateInOut === -1)
        msg = isCustomer ? window.top.noSaleCustomer : window.top.noSaleProduct;
    else if (isSale)
        msg = isCustomer ? window.top.noPurchaseCustomer : window.top.noPurchaseProduct;
    else
        msg = isCustomer ? window.top.noEnterCustomer : window.top.noEnterProduct;
    return msg;
}