var locationPoint = "";
var isValidImage = true;
var isChange = false;
var counter = 0;
var eventClick = "";
var strFile = "";
var productList = [];
var localProductGroupList;
$(document).keyup(function (e) {
    if (e.which == 27) {
        locationPoint = "";
        $(".lstAllProduct").hide();
        $(".cancel").click();
    }
});
$(document).ready(function () {
    $("#divListCatalog").on("click", ".category", function () {
        setToDiv(this)
    });
    $("#sortableKala").on("click", ".find-product", function () {
        findProduct(this)
    });
    $("#divListCatalog").sortable({
        containment: "parent"
    });
    $("#divListCatalog").disableSelection();
    $("#sortableKala").sortable({
        items: ".product-box:not(.state-disabled)"
    });
    $("#sortableKala").disableSelection();

    $('input[type=file]').change(function (event) {
        if (this.files.length > 0) {
            var file = event.target.files[0];
            var reader = new FileReader();
            reader.readAsDataURL(file);
            reader.onload = function () {
                strFile = reader.result
            };

            setTimeout(function () { exportAndImport(2); }, 3000);
        }
    });
    initial();
});

$("#txtProduct").bind("keyup", function (e) {
    if (e.which == 13 || e.keyCode == 13) {
        addNewGroup();
    }
});
function createCategoryDiv(i, groupName) {
    var div = "";
    div += '<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 no-padding title category" style="height:40px;' + (i == 0 ? "background-color:#e1f5fe;" : "background-color:#ffffff;") + 'border-bottom:1px solid #ccc;" data-name="' + groupName + '">';
    div += '<div  class="col-lg-2 col-md-2 col-sm-2 col-xs-2 center-vertical drag"  style="height:40px;border-bottom:1px solid #ccc; cursor:grab" >';
    div += '<img src="../img/reorder.svg"  style="width: 20px; " />';
    div += '</div>';
    div += '<div  class="col-lg-10 col-md-10 col-sm-10 col-xs-10 no-padding-right center-vertical " style="height:40px;border-bottom:1px solid #ccc;cursor: pointer;" >';
    div += '<label style="cursor: pointer;">' + groupName + '</label>';
    div += '</div>';
    div += '</div>';
    return div;
}
function createAddButton(counter) {
    var div = '<div class="col-lg-3 col-md-3 col-sm-3 col-xs-3  product-box no-padding-right-left state-disabled find-product" data-id="' + counter + '" style="padding: 0 4px !important">' +
        '<div  class="product-internal-box center-vertical" style="height: 100%; cursor: pointer;">' +
        ' <img src="../img/add.svg" style="width: 40px; height: 40px; cursor: pointer; margin: 0 auto;" />' +
        '</div>' +
        '</div>';
    return div;
}
async function initial() {
    await getLocalProductGroupList();
    await getProductList();
    setCategoryInDiv();
    closeLoading();
}
function setCategoryInDiv() {
    if (localProductGroupList.length > 0) {
        for (var i = 0; i < localProductGroupList.length; i++) {
            tag = createCategoryDiv(i, localProductGroupList[i].GroupName);
            $("#divListCatalog").append(tag);
        }
        setToDiv($("[data-name='" + localProductGroupList[0].GroupName + "']"));
    }
    $(".drag").mouseup(function () {
        $(this).css("cursor", "grab");
    });
    $(".drag").mousedown(function () {
        $(this).css("cursor", "grabbing");
    });
}
function setToDiv(sender) {
    var allowChange = true;
    if (isChange) {
        isChange = confirm(window.top.confrimRegisterChanges);
        if (isChange)
            save();
    }

    if (allowChange) {
        var groupName = $(sender).attr("data-name");
        $("#txtCategory").val(groupName);
        var dataGroup = localProductGroupList;
        $("#sortableKala").empty();
        var tag = '';
        var groupModel = dataGroup.filter(function (item) { return (item.GroupName == groupName); });
        $("#lblSelectedCategory").text(groupName);
        if (groupModel.length > 0) {
            var products = groupModel[0].Products
            if (products.length === 0) {
                var tag = createAddButton(counter++);
                $("#sortableKala").append(tag);
            }

            for (var i = 0; i < products.length; i++) {
                var productModel = productList.filter(x => x.Code === products[i].Code);
                if (productModel.length === 1) {
                    productModel = productModel[0];
                    pushToDiv(productModel.Code, productModel.Id, productModel.Name, (products.length - 1) == i ? true : false); // (model.length - 1) == i ? true : false  این کد برای پیدا کردن اخرین رکورد است برای ساخت  اخرین تگ انتخاب کالا است
                }
            }
        }
        else {
            var tag = createAddButton(counter++);
            $("#sortableKala").append(tag);
        }

        $(".lstAllProduct").hide();
        $("#divListProduct").empty();
        $("#txtSerchProduct").val("");
    }
    if (sender != "") {
        $(".title").css("background-color", " #ffffff");
        $(sender).css("background-color", " #e1f5fe");
    }

}
function findProduct(sender) {
    locationPoint = $(sender).attr("data-id");
    showDivInPage(sender, "lstAllProduct");
    setTimeout(function () { $("#txtSerchProduct").focus(); }, 50);
    $(".lstAllProduct").show();
}
$("#txtSerchProduct").bind("keyup", function (e) {

    if (e.which == 13 || e.keyCode == 13) {
        eval($('.focused-res').attr('onclick'));
    }
    else if (e.which == 38 || e.keyCode == 40) {
        var divs = $(".search-tr");
        var selectionDiv = $(".focused-res");
        var next = "";
        var previous = "";
        var i = 0;
        var scroll = 0;
        for (i = 0; i < divs.length; i++) {
            scroll += parseInt($(divs[i]).css('height'));
            if (divs[i] == selectionDiv[0]) {
                previous = divs[i - 1];
                next = divs[i + 1];
                break;
            }
        }
        switch (e.keyCode) {
            case 38:
                if (previous) {
                    $(selectionDiv[0]).removeClass('focused-res');
                    $(previous).addClass('focused-res');
                    $('#divListProduct').animate({
                        scrollTop: scroll - 40 - parseInt($(selectionDiv[0]).css('height'))
                    }, 100);
                }
                break;
            case 40:
                if (next) {
                    $(selectionDiv[0]).removeClass('focused-res');
                    $(next).addClass('focused-res');
                    $('#divListProduct').animate({
                        scrollTop: scroll
                    }, 100);
                }
                break;
        }
    }
    else {
        if ($("#txtSerchProduct").val().length > 0) {

            var json = productList;
            var result = json.filter(function (item) {
                return ((item.Name.toLowerCase().indexOf($("#txtSerchProduct").val().toLowerCase()) >= 0) || (item.Id.toString().indexOf($("#txtSerchProduct").val()) >= 0) || item.Barcodes.filter(function (item) { return item.Barcode === $("#txtSerchProduct").val(); }).length > 0);
            });
            $('#divListProduct').empty();
            if (result.length > 0) {
                var tag = "";
                for (var i = 0; i < result.length; i++) {
                    var focused = (i === 0) ? "focused-res" : "";

                    var name = result[i].Name.trim();
                    tag += "<div onclick=\"setToCol(" + result[i].Code + ",\'" + result[i].Id + "\',\'" + name + "\',true)\"  class='col-lg-12 col-md-12 col-sm-12 col-xs-12 search-tr " + focused + " ' style='cursor: pointer;padding:2px;min-height:24px'>";
                    tag += "<div class='col-md-3 col-md-3 col-md-3' >" + result[i].Id + "</div><div class='col-md-9 col-sm-9 col-xs-9'>" + result[i].Name + "</div>";
                    tag += '</div>';
                }
                $("#divListProduct").append(tag);
            }
            else {
                var tag = '<div class="col-md-12">' + window.top.productNotFound + '</div>'
                $("#divListProduct").append(tag);
            }
        }
        else {
            $("#divListProduct").empty();
        }
    }
});
function pushToDiv(productCode, productId, name, controlEndValue) {

    var tagImage = "<img src='../" + window.top.productImageUrl + "/" + productId + ".jpg' class='product-img' style='height: 72px;' data-pid='" + productId+"' onerror='errorImg(this)'; />";

    var tag = "<div class='col-lg-3 col-md-3 col-sm-3 col-xs-3  product-box no-padding-right-left '  data-value='" + productCode + "*" + name + "'  data-id='" + counter + "' style='background-color: #e8f5fc;text-align: center;padding: 0 4px !important'>";
    tag += "<div class='product-internal-box'>" +
        tagImage +
        "<div class='col-lg-12 col-md-12 col-sm-12 col-xs-12' style='padding: 5px;background-color:#fff'>" +
        "<div class='float-right' style='margin-top: 4px;'>" +
        "<label class='namePro' style='font-size: 12px;'>" + name.substring(0, 21) + "</label>" +
        "</div>" +
        "<div class='float-left'>" +
        "<img src='../img/delete.svg' onclick=\"setToCol(" + productCode + ",'','',false," + counter + ")\" class='deleteimg'  />" +
        "</div>" +
        "</div>" +
        "</div>" +
        "</div>";

    if (controlEndValue) {
        counter = counter + 1;
        tag += createAddButton(counter);
    }

    counter = counter + 1;
    $("#sortableKala").append(tag);
}
function setToCol(productCode, productId, name, deleteOrEdit, locationP) {
    var repeatName = false;
    $(".namePro").each(function () {
        if (!repeatName)
            $(this).closest(".product-box").attr("data-value") == productCode
    });

    if (!repeatName) {

        if (locationP == 0 || locationP)
            locationPoint = locationP;

        var tag = '';
        $(' [data-id="' + locationPoint + '"]').empty();
        $(' [data-id="' + locationPoint + '"]').removeClass("state-disabled");

        var tagImage = "<img src='../" + window.top.productImageUrl + "/" + productId + ".jpg' class='product-img' style=' width:100%;height: 72px;' data-pid='" + productId+"' onerror='errorImg(this);' />";


        if (deleteOrEdit) {
            isChange = true;
            $(' [data-id="' + locationPoint + '"]').removeAttr("onclick");
            $(' [data-id="' + locationPoint + '"]').attr("data-value", productCode);
            tag = '<div class="product-internal-box">' +
                tagImage +
                '<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12" style="padding: 5px;">' +
                '<div class="float-right" style="margin-top: 4px;">' +
                '<label class="namePro" style="font-size: 12px;">' + name.substring(0, 21) + '</label>' +
                '</div>' +
                '<div class="float-left">' +
                '<img src="../img/delete.svg" onclick="setToCol(\'' + productCode + '\',\'' + productId + '\',\'\',false,' + locationPoint + ')" class="deleteimg"  />' +
                '</div>' +
                '</div>' +
                '</div>';
            $(' [data-id="' + locationPoint + '"]').append(tag);
            $(".lstAllProduct").hide();
            $("#txtSerchProduct").val('');
            $("#divListProduct").empty();
        }
        else {
            $(' [data-id="' + locationPoint + '"]').remove();
            isChange = true;
        }

        if ($(' [src="../img/add.svg"]').length != 1) {
            counter++;
            var count = $(' [src="../img/delete.svg"]').length;
            var tagNewProduct = createAddButton(counter);

            $("#sortableKala").append(tagNewProduct);
        }
    }
    else
        alert(window.top.notEnterDupliProduct);
}
function errorImg(sender) {
    $(sender).hide();
    var productId = $(sender).attr("data-pid");
    ajax({
        url: "SaleApi/SaveProductImage",
        data: { productId: productId },
        async: false,
        success: function (result) {
            if (result)
                $(sender).attr("src", "../" + window.top.productImageUrl + "/" + result + ".jpg");
            else
                $(sender).attr("src", "../img/noimage.png");
            $(sender).show();
        }
    });
}
function showDivInPage(main, div) {
    var offset = $(main).offset();
    var topOffset = $(main).offset().top - $(window).scrollTop();
    var width = $(main).width();
    $("." + div).css({
        position: "absolute",
        top: (topOffset + 32) + "px",
        left: (offset.left - 200) + "px",
        width: width + 200,
    });
}
function deleteGroupProduct() {
    var selectedCategory = $("#lblSelectedCategory").text();
    if (selectedCategory && selectedCategory !== window.top.selectedCategoryName) {
        ajax({
            loading: true,
            url: "SaleApi/DeleteLocalProductGroup",
            data: { groupName: selectedCategory },
            success: function (result) {
                showMsgModal(2, window.top.deletedSuccessfully);
                refreshParent("refreshLocalProductGroup()");
                location.reload();
            }
        });
    }
}
function getDataToModel(selectedGroupName) {
    var result = [];
    $(".category").each(function () {
        var products = [];
        var groupName = $(this).attr("data-name");
        if (selectedGroupName === groupName) {
            $(' [data-value]').each(function () {
                var data = $(this).attr("data-value");
                products.push(data.split("*")[0]);
                
            });
        }
        else {
            var groupModel = localProductGroupList.filter(x => x.GroupName === groupName);
            if (groupModel.length > 0) {
                products = groupModel[0].Products.map(x => x.Code);
            }
        }
        result.push(
            {
                "GroupName": groupName,
                "Products": products
            });
    });
    return result;
}
function addNewGroup() {
    if ($('#txtProduct').val().trim() != "") {
        if (isChange) {
            if (confirm(window.top.confrimRegisterChanges)) {
                save();
            }
        }
        $("#lblSelectedCategory").text($("#txtProduct").val().trim());
        refreshDivProduct();
        isChange = false;
        $(".title").css("background-color", "#ffffff");
        var div = createCategoryDiv(0, $("#txtProduct").val().trim());
        $("#divListCatalog").append(div);

        $("#txtProduct").val("");

        $(".drag").mouseup(function () {
            $(this).css("cursor", "grab");
        });
        $(".drag").mousedown(function () {
            $(this).css("cursor", "grabbing");
        });
    }
    else {
        alert(window.top.enterGgroupName);
    }
}
function save(closeModal) {
    var selectedCategory = $("#lblSelectedCategory").text();
    if (selectedCategory && selectedCategory !== window.top.selectedCategoryName) {
        var localProductGroup = getDataToModel(selectedCategory);
        ajax({
            loading: true,
            url: "SaleApi/SaveLocalProductGroup",
            data: { localProductGroup: localProductGroup },
            success: function () {
                showMsgModal(2, window.top.savedSuccessfully);
                isChange = false;
                refreshParent("refreshLocalProductGroup()");
                if (closeModal)
                    closeTopModal();
                else
                    location.reload();
            }
        });
    }
    else {
        closeTopModal();
    }
}
function refreshDivProduct() {
    $("#sortableKala").empty();
    counter = 0;
    var tag = createAddButton(counter);
    $("#sortableKala").append(tag);
}
function exportAndImport(state) {
    if (strFile != "" && state == 2) {
        importLocalProductGroupFile(strFile);
        refreshParent("refreshLocalProductGroup()");
    }
    else if (state == 1) {
        exportLocalProductGroupFile();
    }
}
function importLocalProductGroupFile(strFile) {
    ajax({
        loading: true,
        url: "SaleApi/ImportLocalProductGroupFile",
        data: { productGroupFile: strFile },
        success: function (result) {
            showMsgModal(2, window.top.savedSuccessfully);
            refreshParent("refreshLocalProductGroup()");
            location.reload();
        }
    });
}
function exportLocalProductGroupFile() {
    ajax({
        loading: true,
        url: "SaleApi/ExportLocalProductGroupFile",
        success: function (result) {
            var link = document.createElement("a");
            link.download = "shop-product.txt";
            link.href = result;
            link.click();
            $(link).remove();
        }
    });
}
async function getProductList() {
    await ajax({
        url: "SaleApi/GetProductLiteList",
        data: { storeCode: getQuery("codeAnbar"), pageNo: -1, service: true },
        success: function (result) {
            productList = result;
        }
    });
}
async function getLocalProductGroupList() {
    await ajax({
        url: "SaleApi/GetLocalProductGroupList",
        success: function (result) {
            localProductGroupList = result;
        }
    });
}
