var unitData = [];
var productId = getQuery("shenaseh");
var isCopy = getQuery("isCopy");
var productCode = getQuery("code");
var gridBuilder;
var propertyColorArray = [];
var isUpdateGrid = false;
var lastClickedItem;
var comboUnitList = [];
var comboStoreList = [];

var tradeAccess = $("#hfTradeAccess").val() === "1";
var productBarcode = JSON.parse($("#hfBarcodes").val());
var productStore = JSON.parse($("#hfProductStores").val());
var productProperty = JSON.parse($("#hfProperty").val());
var productSecondUnit = JSON.parse($("#hfSecondUnit").val());
var productIsServices = $("#hfIsServices").val() === "1";

$(document).ready(function () {
    $("#hfValue").remove();
    $("#hfTradeAccess").remove();
    $("#hfBarcodes").remove();
    $("#hfProductStores").remove();
    $("#hfProperty").remove();
    $("#hfSecondUnit").remove();
    $("#hfIsServices").remove();

    gridBuilder = $(".grid").gridBuilder();
    gridBuilder.onSetMaskEdit(setEventMaskEdit);
    gridBuilder.onExportClick(exportSampleExcel);

    $("#convert").keypress(function (e) {
        if (!(e.keyCode >= 48 && e.keyCode <= 57) && e.keyCode !== 46)
            return false;
    })
    $("#colorPicker").each(function () {
        $(this).minicolors({
            control: $(this).attr('data-control') || 'hue',
            defaultValue: $(this).attr('data-defaultValue') || '',
            format: $(this).attr('data-format') || 'hex',
            keywords: $(this).attr('data-keywords') || '',
            inline: $(this).attr('data-inline') === 'true',
            letterCase: $(this).attr('data-letterCase') || 'lowercase',
            opacity: $(this).attr('data-opacity'),
            position: $(this).attr('data-position') || 'bottom',
            swatches: $(this).attr('data-swatches') ? $(this).attr('data-swatches').split('|') : [],
            change: function (value, opacity) {
                if (!value) return;
                if (opacity)
                    value += opacity;
                if (typeof console === 'object') {
                    $("#lblResult").text(value);
                }
            },
            theme: 'bootstrap'
        });
    });
    $("#pnlUnit").on("click", "img", function () {
        var rowItem = $(this).closest(".rowItem");
        var unitCode = Number(rowItem.attr("data-code"));
        if (confirm(window.top.confirmMsg)) {
            var unit = unitData.find(x => x.CodeUnit === unitCode);
            if (!unit)
                return;
            unit.IsActive = !unit.IsActive;
            rowItem.css({ "background-color": unit.IsActive ? "" : "rgba(211, 47, 47, 0.19)", "text-decoration": unit.IsActive ? "" : "line-through" });
            rowItem.find("div:nth-child(2)").css({ "text-decoration": unit.IsActive ? "none" : "line-through" });
            rowItem.find("div:nth-child(3)").css({ "text-decoration": unit.IsActive ? "none" : "line-through" });
            rowItem.find("img").attr("src", "../img/" + (unit.IsActive ? "delete.svg" : "minus.png")).attr("title", unit.IsActive ? window.top.deletee : window.top.cancelDelete);
            $("#cboUnitMain").lookupBuilder().setEnabled(unitData.length === 0 || !unitData.some(x => x.IsActive));
        }
    });
    initial();
});
async function initial() {
    $("#grdProperty").find(".import-excel").hide();
    $("#grdProperty").find(".sample-excel").hide();
    $("#cboProductGroup").lookupBuilder().onChanged(async function () {
        await getMaxProductId();
    });
    $("#cboUnitMain").lookupBuilder().onChanged(function () {
        unitData = [];
        $('#pnlUnit').empty();
        $("#divOtherUnitHeader").hide();
        $("#mainUnitText").text($("#cboUnitMain").lookupBuilder().getSelectedText());
    });
    $("#cboMoain").lookupBuilder().onChanged(function () {
        cboMoainChange();
    });
    $("#cboTaxType").lookupBuilder().onChanged(function () {
        var value = Number($("#cboTaxType").lookupBuilder().getSelectedValue());
        $("#chkTaxInPrice").prop("disabled", value === 1);
        if (value === 1)
            $("#chkTaxInPrice").prop("checked", false);
    });
    $("#confrimModal").on("hidden.bs.modal", function () {
        this.setAttribute("style", "display:none !important");
        if (lastClickedItem.item.find(".circle-color").length === 0) {
            lastClickedItem.item.prepend("<div class='circle-color' ></div>");
        }
    });
    $("#cboBarcodeType").on("change", function () {
        var serialState = Number($("#cboStateSerial").val()) === 1;
        if (serialState && Number($(this).val()) === 1) {
            showMsgModal(0, window.top.couldntbeWeightBarcode);
            $(this).val(0);
        }
    });
    $("#cboStateSerial").on("change", function (e) {
        var hasUnit = unitData.some(x => x.IsActive);
        var serialState = Number($(this).val()) === 1;
        var mainUnit = $("#cboUnitMain").lookupBuilder().getSelectedValue();
        if (serialState && hasUnit) {
            if (confirm(window.top.confirmRemoveSubunits)) {
                emptySecondUnit(true);
            }
            else
                $(this).val(0);
        }
        else {
            $("#convert").prop("disabled", serialState);
            $("#cboUnitOther").lookupBuilder().setEnabled(!serialState);
        }
        if (serialState && mainUnit && Number(mainUnit.split("|")[1]) > 0) {
            showMsgModal(0, window.top.cantHaveDecimalNumber);
            $(this).val(0);
        }
        if (serialState && Number($("#cboBarcodeType").val()) === 1) {
            showMsgModal(0, window.top.couldntbeWeightBarcode);
            $(this).val(0);
        }

    });
    $("#Name").on("change", function () {
        var data = gridBuilder.getDataArray()["data"].filter(function (item) { return item._status !== "deleted"; });
        if (data.length > 0) {
            for (var i = 0; i < gridBuilder.getRowsCount(); i++) {
                var property1 = gridBuilder.getCellValue(i, "Property01");
                var property2 = gridBuilder.getCellValue(i, "Property02");
                var property3 = gridBuilder.getCellValue(i, "Property03");
                var property4 = gridBuilder.getCellValue(i, "Property04");
                var property5 = gridBuilder.getCellValue(i, "Property05");
                var productName = $(this).val() + ($(this).val().length > 0 ? " " : "") + property1 + (property1.length > 0 ? " " : "") + property2 + (property2.length > 0 ? " " : "") + property3 + (property3.length > 0 ? " " : "") + property4 + (property4.length > 0 ? " " : "") + property5;
                gridBuilder.setCellValue(i, "Name", productName);
            }
        }
    });
    $(".btn-primary").click(function () {
        var isService = $(this).attr("data-service") === "1";
        var data = gridBuilder.getDataArray()["data"].filter(function (item) { return item._status !== "deleted"; });
        var hasUnit = unitData.some(x => x.IsActive);
        var storeCredit = $('#ddlSelectStore').selectize()[0].selectize;
        if (isService && hasUnit) {
            if (confirm(window.top.confirmServiceSubUnit)) {
                emptySecondUnit(true);
            }
            else
                return;
        }
        else
            emptySecondUnit(isService);

        if (isService && data.length > 0) {
            if (confirm(window.top.serviceConfirm)) {
                $("#hasProperty").prop("checked", false).prop("disabled", true);
                hasPropertyChange(true);
            }
            else
                return;
        }
        if (tradeAccess) {
            changeRequired("cboMoain", isService);
        }
        if (isService) {
            storeCredit.clear();
            storeCredit.disable();
            $("#cboBarcodeType").val(0);
            $("#cboStateSerial").val(0);
            $("#SefateshSaghf").val("");
            $("#hasProperty").prop("checked", false);
        }
        else
            storeCredit.enable();

        $("#hasProperty").prop("disabled", isService);
        $("#SefateshSaghf").prop("disabled", isService);
        $("#cboStateSerial").prop("disabled", isService);
        $("#cboBarcodeType").prop("disabled", isService);
        $("#divProductSpecContainer").css({ "display": (isService ? "none" : "") });
        $("#divAccountContainer").css({ "display": (!isService || !tradeAccess ? "none" : "") });
        $("#menu-property").css({ "display": (isService ? "none" : "") });
        $("#menu-account").css({ "display": (!isService || !tradeAccess ? "none" : "") });

        $(".btn-primary").removeClass("isactive").addClass("dontisactive");
        $(this).removeClass("dontisactive").addClass("isactive");
    });
    $("#pnlSpec").on("click", ".item", function () {
        var selectize = $(this).closest(".spec-container").find("[data-id='SpecValue']")[0].selectize;
        lastClickedItem = { item: $(this), selectize: selectize };
        if (lastClickedItem.item.find(".circle-color").length > 0) {
            var color = lastClickedItem.item.find(".circle-color").attr("data-color");
            $("#colorPicker").val(color || "#ffffff");
            $("#modalLabel").text(lastClickedItem.item.attr("data-value"));
            $("#confrimModal").modal();
        }
    });
    $("#barcode").selectize({
        delimiter: ",",
        persist: false,
        create: function (input) {
            return {
                value: input,
                text: input
            };
        }
    });
    $("#ddlSelectStore").selectize({
        plugins: ['remove_button'],
        sortField: 'text'
    });


    if (productCode !== "") {
        await loadData();
    }
    else {
        addRowSpec();
        hasPropertyChange();
        isUpdateGrid = true;
        closeLoading();
        $("#divMain").show();
    }
}
async function getMaxProductId() {
    var productGroupCode = $("#cboProductGroup").lookupBuilder().getSelectedValue();
    var maxProductId;
    await ajax({
        url: "SaleApi/GetMaxProductId",
        loading: false,
        data: { productGroupCode: productGroupCode },
        success: function (result) {
            maxProductId = result;
        }
    });
    await ajax({
        url: "SaleApi/GetProductGroupId",
        loading: false,
        data: { code: productGroupCode },
        success: function (result) {
            var groupIdHtml = "";
            if (result) {
                var id = maxProductId.substr(0, result.length);
                if (id === result) {
                    maxProductId = maxProductId.substr(result.length);
                }
                var groupIdArr = result.split("");
                for (var i = 0; i < groupIdArr.length; i++) {
                    groupIdHtml += "<span style='display:inline-block'>" + groupIdArr[i] + "</span>";
                }
            }
            $("#shenase").val(maxProductId);
            $("#lblGroupId").html(groupIdHtml).attr("data-value", result);
        }
    });
}
async function getEventLookupCombo($combo, search, code) {
    var id = $combo.attr("id");
    var url = "";
    var data = null;
    if (code && code.toString().indexOf("|") > 0)
        code = code.split("|")[0];
    switch (id) {
        case "cboTaxType":
            url = "SaleApi/GetTaxList";
            data = { pageNo: 1 };
            break;
        case "cboProductGroup":
            url = "SaleApi/GetProductGroupList";
            data = { pageNo: 1 };
            break;
        case "cboUnitMain": case "cboUnitOther":
            url = "SaleApi/GetUnitList";
            data = { pageNo: 1 };
            break;
        case "cboMoain":
            url = "AccountingApi/GetMoainList";
            data = { checkActive: true, search: search, selectedCode: code, pageNo: 1 };
            break;
        case "cboTafsil": case "cboCostCenter": case "cboProject":
            if (!$("#cboMoain").lookupBuilder().getSelectedValue().split("|")[0])
                return;
            url = "AccountingApi/GetTafsilList";
            data = { moainCode: $("#cboMoain").lookupBuilder().getSelectedValue().split("|")[0], level: $combo.attr("data-level"), search: search, selectedCode: code, pageNo: 1 };
            break;
    }
    if (url === "")
        return;
    await ajax({
        url: url,
        loading: false,
        data: data,
        success: function (result) {
            var newResult;
            if (id === "cboMoain") {
                $.each(result,
                    function () {
                        this.Code = this.Code +
                            "|" +
                            this.ChildCount +
                            "|" +
                            this.ChildCountM +
                            "|" +
                            this.ChildCountP;
                    });
            }
            else if (id === "cboTafsil" || id === "cboCostCenter" || id === "cboProject") {
                if (result.length > 0) {
                    newResult = [{ Name: window.top.saveFromFactor, Code: "-1" }];
                    result = newResult.concat(result);
                }
            }
            else if (id === "cboUnitOther") {
                var mainUnit = $("#cboUnitMain").lookupBuilder().getSelectedValue();
                var mainUnitCode = mainUnit ? mainUnit.split("|")[0] : 0;
                result = result.filter(function (item) { return Number(item.Code) !== Number(mainUnitCode) && !unitData.find(x => Number(x.CodeUnit) === Number(item.Code) && x.IsActive); });
            }
            else if (id === "cboUnitMain") {
                var serialState = Number($("#cboStateSerial").val()) === 1;
                if (serialState)
                    result = result.filter(x => x.DecimalCount === 0);
                $.each(result,
                    function () {
                        this.Code = this.Code + "|" + this.DecimalCount
                    });
            }
            else if (id === "cboTaxType") {
                newResult = [{ Name: window.top.notAddedValue, Code: 1 }];
                if (Number(code) > 1 && Number(code) < 5 && productCode !== "" && isCopy === "0")
                    newResult.push({ Name: window.top.addedValue, Code: 2 });
                result = newResult.concat(result);
            }
            $combo.lookupBuilder().bindData(result);
        }
    });
}
function loadData() {
    $("#barcode")[0].selectize.addOption(productBarcode.map(function (item) { return { value: item.Barcode, text: item.Barcode }; }));
    $("#barcode")[0].selectize.setValue(productBarcode.map(function (item) { return item.Barcode; }));
    $("#ddlSelectStore").selectize()[0].selectize.setValue(productStore.map(function (item) { return item.Code }));
    productSecondUnit.forEach(function (item) {
        unitData.push({
            CodeUnit: item.CodeUnit,
            Zarib: item.Ratio,
            IsActive: true
        });
    });
    for (var i = 1; i <= 5; i++) {
        if (productProperty["NameProperty0" + i]) {
            var propertyName = productProperty["NameProperty0" + i];
            var propertyValue = productProperty.ProductPartProperty.map(function (property) { return { name: property["Property0" + i], color: property["Color0" + i] }; });
            addRowSpec(propertyName, propertyValue);
        }
    }
    if (productProperty.ProductPartProperty.length > 0) {
        if (isCopy === "1") {
            productProperty.ProductPartProperty.forEach(function (item) {
                item.Code = -1;
                item.Name = $("#Name").val() + ($("#Name").val().length > 0 ? " " : "") + (item.Property01 ? item.Property01 + " " : "") + (item.Property02 ? item.Property02 + " " : "") + (item.Property03 ? item.Property03 + " " : "") + (item.Property04 ? item.Property04 + " " : "") + (item.Property05 ? item.Property05 : "");
                item.Barcode = "";
            });
        }
        gridBuilder.loadData(productProperty.ProductPartProperty);
    }
    else {
        addRowSpec();
        hasPropertyChange();
    }
    $(productIsServices ? "#btnIsKhadamat" : "#btnIsKala").click();
    isUpdateGrid = true;
    closeLoading();
    $("#divMain").show();
}
function cboMoainChange() {
    var selectedItem = $("#cboMoain").lookupBuilder().getSelectedValue().split("|");
    for (var i = 1; i <= 3; i++) {
        var $obj;
        switch (i) {
            case 1:
                $obj = $("#cboTafsil");
                break;
            case 2:
                $obj = $("#cboCostCenter");
                break;
            case 3:
                $obj = $("#cboProject");
                break;
        }
        if (Number(selectedItem[i]) === 0) {
            $obj.lookupBuilder().setEnabled(false);
            $obj.lookupBuilder().setSelectedValue("");
            changeRequired($obj.attr("id"), false);
        }
        else {
            $obj.lookupBuilder().setEnabled(true);
            changeRequired($obj.attr("id"), true);
        }
    }
}
function addUnit() {
    var rate = $('#convert').val();
    var otherUnitCode = Number($("#cboUnitOther").lookupBuilder().getSelectedValue());
    var mainUnitCode = $("#cboUnitMain").lookupBuilder().getSelectedValue();
    var otherUnitName = $("#cboUnitOther").lookupBuilder().getSelectedText();
    var mainUnitName = $("#cboUnitMain").lookupBuilder().getSelectedText();
    if (!rate || !otherUnitCode || !mainUnitCode) {
        showMsgModal(0, window.top.completeUnit);
        return;
    }
    unitData.push({
        CodeUnit: otherUnitCode,
        Zarib: rate,
        IsActive: true
    });
    var div = $(".template-unit").clone().removeAttr("hidden").removeClass("template-unit").attr("data-code", otherUnitCode);
    div.find("div:nth-child(1)").text(unitData.length + 1);
    div.find("div:nth-child(2)").text(otherUnitName);
    div.find("div:nth-child(3)").text(window.top.every + " " + rate + " " + mainUnitName + " " + window.top.aqualsOne + " " + otherUnitName);
    $('#pnlUnit').append(div);
    $("#divOtherUnitHeader").show();
    $("#cboUnitMain").lookupBuilder().setEnabled(false);
    $('#convert').val("");
    $("#cboUnitOther").lookupBuilder().setSelectedValue("");
}
function createPropertySelectizeObject($select) {
    $select.selectize({
        delimiter: ',',
        persist: false,
        plugins: ['remove_button'],
        onItemRemove: function () {
            var specContainer = this.$input.closest(".spec-container");
            var $checkBox = specContainer.find("input[type='checkbox']");
            if (this.getValue() === "")
                $checkBox.prop("disabled", false);
            setGrid(this);
        },
        onItemAdd: function (value, $item) {
            var specContainer = this.$input.closest(".spec-container");
            var $checkBox = specContainer.find("input[type='checkbox']");
            var isColor = $checkBox.prop("checked");
            if (isColor) {
                lastClickedItem = { item: $item, selectize: this };
                $("#modalLabel").text(value);
                $("#confrimModal").modal();
            }
            else
                setGrid(this);
            $checkBox.prop("disabled", true);
        },
        //maxItems: 5,
        render: {
            item: function (data, escape) {
                var item = "<div data-value='" + data.text + "' class='item' >";
                if (data.color !== "")
                    item += "<div class='circle-color' style='background-color:" + data.color + "' data-color='" + data.color + "'></div>";
                item += "<span>" + data.text + "</span></div>";
                return item;
            }
        },
        create: function (input) {
            return {
                value: input,
                text: input,
                color: ""
            };
        }
    });
}
function addRowSpec(propertyName, propertyValue) {
    var specDiv = $(".spec-container.hidden").first().clone();
    specDiv.removeAttr("hidden");
    specDiv.removeClass("hidden");
    specDiv.find("[data-id='SpecName']").val(propertyName || "");
    specDiv.find("input[type='checkbox']").prop("checked", false);
    $(".parentSpec-container").append(specDiv);
    createPropertySelectizeObject(specDiv.find("[data-id='SpecValue']"));

    specDiv.find("[data-id='SpecValue']").attr("data-required", true).addClass("validation");
    specDiv.find("[data-id='SpecValue']")[0].selectize.$dropdown.addClass("validation");
    specDiv.find("[data-id='SpecValue']")[0].selectize.$control.addClass("validation");
    specDiv.find("[data-id='SpecName']").attr("data-required", true).addClass("validation");

    if (propertyValue && propertyValue.length > 0) {
        var hasColor = propertyValue.filter(function (item) { return item.color !== null; });
        specDiv.find("[data-id='SpecValue']")[0].selectize.addOption(propertyValue.map(function (item) { return { value: item.name, text: item.name, color: item.color }; }));
        specDiv.find("[data-id='SpecValue']")[0].selectize.setValue(propertyValue.map(function (item) { return item.name; }));
        specDiv.find("[data-id='SpecValue']")[0].selectize.enable();
        if (hasColor.length > 0)
            specDiv.find("input[type='checkbox']").prop("checked", true);
    }
}
function addSpec() {
    if (!$("#hasProperty").prop("checked"))
        return;
    if ($(".spec-container").not(".hidden").length === 5)
        return;
    addRowSpec();
}
function setGrid(selectize) {
    if (!isUpdateGrid)
        return;
    var specArray = [];
    var cartesianArray = [];
    propertyColorArray = [];
    $(".spec-container").not(".hidden").each(function (index) {
        element = $(this);
        var selectizeObj = element.find("[data-id='SpecValue']")[0].selectize;
        if (selectizeObj) {
            if (selectizeObj.getValue() === "")
                return;
            var propertyRowArray = selectizeObj.getValue().split(",");

            for (var i = 0; i <= propertyRowArray.length - 1; i++) {
                propertyColorArray.push({ color: selectizeObj.options[propertyRowArray[i]].color, propertyName: propertyRowArray[i], propertyParentName: element.find("[data-id='SpecName']").val() });
            }
            specArray[index] = propertyRowArray;
        }
    });

    if (specArray.length > 0) {
        cartesianArray = cartesianProduct(specArray);
        var gridData = gridBuilder.getDataArray()["data"];

        cartesianArray.forEach(function (cartesian, index) {
            for (var i = 1; i <= 5; i++) {
                if (!cartesian[i - 1])
                    cartesian[i - 1] = "";
            }
            if (gridData.length > 0) {
                var findItem = gridData.filter(function (item) { return (item.Property01 || "") === cartesian[0] && (item.Property02 || "") === cartesian[1] && (item.Property03 || "") === cartesian[2] && (item.Property04 || "") === cartesian[3] && (item.Property05 || "") === cartesian[4]; });
                if (findItem.length > 0) {
                    var rowIndex = gridData.indexOf(findItem[0]);
                    for (var j = 1; j <= 5; j++) {
                        var color = getPropertyColor(cartesian[j - 1]);
                        gridBuilder.setCellValue(rowIndex, "Color0" + j, color);
                    }
                    return false;
                }
                else
                    updateGrid(cartesian);
            }
            else
                updateGrid(cartesian);
        });
        deleteGrid(cartesianArray);
    }
    else
        deleteGrid(null, true);
    if (selectize)
        selectize.focus();
}
function updateGrid(arr) {
    gridBuilder.addNewRow();
    var rowIndex = gridBuilder.getActiveRowIndex();

    gridBuilder.setCellValue(rowIndex, "Name", $("#Name").val() + " " + arr.join(" "));
    for (var i = 1; i <= 5; i++) {
        var color = getPropertyColor(arr[i - 1]);
        gridBuilder.setCellValue(rowIndex, "Property0" + i, arr[i - 1] || "");
        gridBuilder.setCellValue(rowIndex, "Color0" + i, color);
    }
}
function deleteGrid(cartesianArray, all) {
    if (all)
        gridBuilder.clearRows();
    var gridData = gridBuilder.getDataArray()["data"].filter(function (item) { return item._status !== "deleted"; });
    var newGridData = JSON.parse(JSON.stringify(gridData));
    gridData.forEach(function (data) {
        var findItem = cartesianArray.filter(function (cartesian) { return (data.Property01 || "") === cartesian[0] && (data.Property02 || "") === cartesian[1] && (data.Property03 || "") === cartesian[2] && (data.Property04 || "") === cartesian[3] && (data.Property05 || "") === cartesian[4]; }).length === 1;
        if (!findItem) {
            var item = newGridData.filter(function (item) { return item.Name === data.Name; })[0];
            var index = newGridData.indexOf(item);
            newGridData.splice(index, 1);
        }
    });
    gridBuilder.loadData(newGridData);
}
function cartesianProduct(arr) {
    return arr.reduce(function (a, b) {
        return a.map(function (x) {
            return b.map(function (y) {
                return x.concat([y]);
            });
        }).reduce(function (a, b) { return a.concat(b); }, []);
    }, [[]]);
}
function deleteRowSpec(element) {
    if (!$("#hasProperty").prop("checked"))
        return;
    var $divSpec = $(element).closest(".spec-container");
    $divSpec.find("[data-id='SpecValue']")[0].selectize.destroy();
    $divSpec.remove();
    setGrid();
    if ($(".spec-container").not(".hidden").length === 0)
        addRowSpec();
}
function save(isOpenFirstInventory) {
    var exceptionText = checkValidation('');
    
    if (exceptionText !== '') {
        showMsgModal(0, exceptionText);
        return;
    }
    if (!isNaN($("#shenase").val()) && $("#shenase").val().length > 12) {
        showMsgModal(0, window.top.shenasehLength);
        return;
    }
    var rate = $('#convert').val().trim();
    var otherUnit = $("#cboUnitOther").lookupBuilder().getSelectedValue();
    if ((!rate && otherUnit) || (rate && !otherUnit)) {
        showMsgModal(0, window.top.sunUnitNotFull);
        return;
    }
    if (rate && otherUnit) {
        unitData.push({
            CodeUnit: otherUnit,
            Zarib: rate
        });
    }
    var mainId = $("#hfMainId").val();
    var groupId = $("#lblGroupId").attr("data-value");
    var groupId2 = mainId.substr(0, groupId.length);
    if (productCode && isCopy === "0" && groupId && groupId2 !== groupId) {
        if (confirm(window.top.productIdChange)) {
            insert(isOpenFirstInventory);
        }
    }
    else
        insert(isOpenFirstInventory);
}
function insert(isOpenFirstInventory) {
    var data = getJsonValue('');
    var property = gridBuilder.getDataArray()["data"].filter(function (item) { return item._status !== "deleted"; });
    var productPartPropertyName = {};
    var secondUnitList = [];
    var Barcodes = [];
    var Stores = [];

    data.UnitCode = data.UnitCode ? data.UnitCode.split("|")[0] : 0;
    if (data.Barcodes && data.Barcodes.length > 0 && !$("#hasProperty").prop("checked")) {
        $(data.Barcodes.split(",")).each(function (index, item) {
            Barcodes.push({ Barcode: item });
        });
    }
    if (data.Stores && data.Stores.length > 0) {
        $(data.Stores).each(function (index, item) {
            if (Number(item) > 0)
                Stores.push({ Code: item });
        });
    }
    $(unitData).each(function (index, item) {
        if (item.IsActive)
            secondUnitList.push({ CodeUnit: item.CodeUnit, Ratio: item.Zarib });
    });

    if ($("#hasProperty").prop("checked")) {
        $(".spec-container").not(".hidden").each(function (index, obj) {
            productPartPropertyName["NameProperty0" + (index + 1)] = $(obj).find("[data-id='SpecName']").val();
        });
        productPartPropertyName["ProductPartProperty"] = property;
    }
    data["ProductPartPropertyName"] = productPartPropertyName;
    data['IsServices'] = $('#btnIsKhadamat').hasClass('isactive');
    data["SecondUnits"] = secondUnitList;
    data["FileImage"] = $('.picture-img > img').attr('src');
    data["IsInEShop"] = $("#chkIsInEShop").prop("checked");
    data["Barcodes"] = Barcodes;
    data["Stores"] = Stores;
    data["OrderCountAlarm"] = data["OrderCountAlarm"] === -1 ? 0 : data["OrderCountAlarm"];
    data["OrderCountDefault"] = data["OrderCountDefault"] === -1 ? 0 : data["OrderCountDefault"];
    data["Id"] = $("#lblGroupId").attr("data-value") + (data["Id"] || "");
    
    ajax({
        loading: true,
        url: "SaleApi/" + (getQuery("code") === '' || getQuery("isCopy") === '1' ? "InsertProduct" : "UpdateProduct"),
        data: data,
        success: function (result) {
            showMsgModal(2, result.FinalMessage);
            if (isOpenFirstInventory) {
                var productName = $("#Name").val();
                var mainUnit = $("#cboUnitMain").lookupBuilder().getSelectedValue();
                var title = window.top.firstInventory + " " + productName;
                var selectedStore = $("#ddlSelectStore").val().join(",");
                var selectedUnit = "";
                if (unitData.length > 0)
                    selectedUnit = unitData.map(x => x.CodeUnit).join(",");
                selectedUnit += (selectedUnit ? "," : "") + mainUnit.split("|")[0];
                var src = "Sale/ProductFirstInventory?code=" + $("#hfCode").val() + "&store=" + selectedStore + "&unit=" + selectedUnit + "&id=" + $("#shenase").val() + (getQuery("shop") ? "&shop=1" : "");
                var modalId = window.top.$('.gheyas-modal').last().attr('id');
                var parentId = window.top.$("#" + modalId).attr("parent-frame");
                openInModal('', src, title, "700", "550");
                var topId = window.top.$('.gheyas-modal').last().attr('id');
                window.top.$("#" + topId).attr("parent-frame", parentId);
                closeCurrentModal(modalId);
            }
            else {
                refreshParent(getQuery("shop") ? "refreshProduct(" + data.Id + ")" : "loadGrid(null,'" + data.Id + "')");
                closeTopModal();
            }
        }
    });
}

function hasPropertyChange(isConfirm, element, e) {
    if (!element)
        element = $("#hasProperty");
    var check = $(element).prop("checked");
    var data = gridBuilder.getDataArray()["data"].filter(function (item) { return item._status !== "deleted"; });
    var barcodeSelectize = $('#barcode')[0].selectize;
    var barcodes = barcodeSelectize.getValue();
    if (!check && data.length > 0) {
        if (isConfirm || confirm(window.top.confirmDeleteAllFeatures)) {
            deleteGrid(null, true);
            $(".spec-container").not(".hidden").each(function () {
                $(this).remove();
            });
            addRowSpec();
        }
        else {
            e.preventDefault();
            return;
        }
    }
    else if (check && barcodes !== "") {
        if (confirm(window.top.confirmAddFeature)) {
            barcodeSelectize.clear();
        }
        else {
            e.preventDefault();
            return;
        }
    }

    if (check) {
        barcodeSelectize.disable();
        $("#btnSubmitInventory").hide();
        $(".spec-container").not(".hidden").find("[data-id='SpecValue']")[0].selectize.enable();
        $(".spec-container").not(".hidden").find("[data-id='SpecValue']").attr("data-required", true).addClass("validation");
        $(".spec-container").not(".hidden").find("[data-id='SpecValue']")[0].selectize.$dropdown.addClass("validation");
        $(".spec-container").not(".hidden").find("[data-id='SpecValue']")[0].selectize.$control.addClass("validation");
        $(".spec-container").not(".hidden").find("[data-id='SpecName']").addClass("validation");
    }
    else {
        barcodeSelectize.enable();
        $("#btnSubmitInventory").show();
        $(".spec-container").not(".hidden").find("[data-id='SpecValue']")[0].selectize.disable();
        $(".spec-container").not(".hidden").find("[data-id='SpecValue']").attr("data-required", false).removeClass("validation");
        $(".spec-container").not(".hidden").find("[data-id='SpecValue']")[0].selectize.$dropdown.removeClass("validation");
        $(".spec-container").not(".hidden").find("[data-id='SpecValue']")[0].selectize.$control.removeClass("validation");
        $(".spec-container").not(".hidden").find("[data-id='SpecName']").removeClass("validation");

    }
    $("#txtPrice").prop("disabled", check);
    $("[data-id='SpecName']").prop("disabled", !check).attr("data-required", check);
    $(".spec-container").not(".hidden").find(".checkbox-control").prop("disabled", !check).prop("checked", false);
}
function acceptColor() {
    var color = $("#colorPicker").val();
    if (lastClickedItem.item.find(".circle-color").length === 0) {
        lastClickedItem.item.prepend("<div class='circle-color' ></div>");
    }
    lastClickedItem.item.find(".circle-color").attr("data-color", color).css({ "background-color": color });
    var index = lastClickedItem.selectize.items.indexOf(lastClickedItem.item.attr("data-value"));
    var item = lastClickedItem.selectize.items[index];
    lastClickedItem.selectize.options[item].color = color;
    $("#confrimModal").modal("hide");
    setGrid(lastClickedItem.selectize);
}
function cancelColor() {
    lastClickedItem.selectize.removeItem(lastClickedItem.item.attr("data-value"));
    $("#confrimModal").modal("hide");
}
function getPropertyColor(propertyName) {
    var color = "";
    var propertyColorItem = propertyColorArray.filter(function (item) { return item.propertyName === propertyName; });
    if (propertyColorItem.length > 0) {
        color = propertyColorItem[0].color;
    }
    return color;
}
function openValueAddedModal() {
    var title = window.top.newAddedValue;
    var src = "General/ValueAddedSaveNew";
    openInModal('', src, title, "700", "550", false);
}
function exportSampleExcel(gridId, type) {
    exportExcel(gridBuilder.getDataArray()["data"], gridBuilder.getColumns(), gridBuilder.getColumnsCaption());
}
function emptySecondUnit(state) {
    if (state) {
        unitData = [];
        $("#pnlUnit").empty();
        $("#divOtherUnitHeader").hide();
    }
    $("#divSecondUnitContainer").css({ "display": (state ? "none" : "inline-block") });
    $("#menu-secondUnit").css({ "display": (state ? "none" : "") });
    $("#cboUnitMain").lookupBuilder().setEnabled(unitData.length === 0);
}