var gridBuilder;
var priceListTitle;
var productData;
var unitCode;
var productCode;
$(document).ready(function () {
    gridBuilder = $(".grid").gridBuilder();
    gridBuilder.onRowChanged(function () {
        var rowIndex = gridBuilder.getActiveRowIndex();
        if (rowIndex < 0)
            return;
        var productId = gridBuilder.getCellValue(rowIndex, "Id");
        var productCode = gridBuilder.getCellValue(rowIndex, "Code");
        fetchData(productId, productCode);
    });
    gridBuilder.onExportClick(function () {
        loadGrid("", "", { exportExcel: true });
    });

    var input = document.createElement("input");
    $("body").append(input);
    $(input).attr("type", "file");
    $(input).hide();
    $("input[type='file']").on("change", function (event) {
        if (this.files.length > 0) {
            var file = event.target.files[0];
            var reader = new FileReader();
            reader.readAsDataURL(file);
            reader.onload = function () {
                ajax({
                    url: "GeneralApi/ImportExcel",
                    data: {
                        key: "Product",
                        base64: reader.result
                    },
                    success: function () {
                        showMsgModal(2, window.top.doneSuccess);
                        loadGrid();
                    }
                });

            };
        }
    });

    $(".sample-excel").on("click", function () {
        ajax({
            url: "SaleApi/ExportFileSample",
            data: {
                key: "Product"
            },
            success: function (fileUrl) {
                if (fileUrl) {
                    var link = document.createElement("a");
                    link.download = "sample-product.xlsx";
                    link.href = fileUrl;
                    link.click();
                    $(link).remove();
                }
            }
        });
    });
    $(".import-excel").on("click", function () {
        $("input[type='file']").click();
    });
    loadGrid();

});
function loadGrid(gridId, productId, objectParameter) {
    var isExportExcel = objectParameter && objectParameter.exportExcel ? true : false;
    ajax({
        gridBuilder: gridBuilder,
        url: "SaleApi/GetProductList",
        data: {
            filter: gridBuilder.getFilter(),
            sort: gridBuilder.getSortFields(),
            pageNo: isExportExcel ? -1 : gridBuilder.getCurrentPageNumber()
        },
        success: function (data) {
            if (isExportExcel) {
                exportExcel(data, gridBuilder.getColumns(), gridBuilder.getColumnsCaption());
            }
            else {
                gridBuilder.loadData(data);
            }
        }
    });
}

async function fetchData(productId, productCode) {
    showLoading();
    await ajax({
        loading:false,
        url: "SaleApi/GetProductDetail",
        data: { code: productCode, id: productId },
        success: function (data) {
            productData = data;
        }
    });
    await loadData(productData);
}
function loadData(data) {
    var product = data.Product;
    unitCode = product.UnitCode;
    productCode = product.Code;
    if (product.HasPicThumb)
        $('#picImage').attr("src", baseUrl + $("#hfProductImageFolder").val() + "/" + product.Id + ".jpg");
    else
        $('#picImage').attr("src", baseUrl + "img/product.png");

    $('#rptBarcode').empty();
    if (product.Barcodes.length > 0) {
        $(".container-barcode").show();
        var str = "";
        for (var i = 0; i < product.Barcodes.length; i++) {
            str = "<img style='margin: 10px 0 10px 10px;width: 106px;' src='Barcode?code=" + product.Barcodes[i].Barcode + "'/>";
            $('#rptBarcode').append(str);
        }
    }
    else {
        $(".container-barcode").hide();
    }

    clearControl();

    $('#lblIsServices').text(product.IsServices ? window.top._services : window.top.product);
    $('#lblGrpKala').text(checkNotNull(product.NameGroup));
    $('#lblName').text(checkNotNull(product.Id) + "/" + checkNotNull(product.Name));

    $('#lblUnitMain').text(checkNotNull(product.UnitName, window.top.notDefined, $('#lblUnitMain')));

    $('#lblUnitOther').text(checkNotNull(product.SecondUnits[0] ? product.SecondUnits[0].NameUnit : "", window.top.notDefined, $('#lblUnitOther')));
    $('#lblUnitOther1').text(checkNotNull(product.SecondUnits[1] ? product.SecondUnits[1].NameUnit : "", window.top.notDefined, $('#lblUnitOther1')));
    $('#lblUnitOther2').text(checkNotNull(product.SecondUnits[2] ? product.SecondUnits[2].NameUnit : "", window.top.notDefined, $('#lblUnitOther2')));

    $('#lblUnitOtherD').text(checkNotNull(product.SecondUnits[0] ? "(" + product.UnitName + "*" + product.SecondUnits[0].Ratio + ")" : "", '', $('#lblUnitOtherD')));
    $('#lblUnitOtherD1').text(checkNotNull(product.SecondUnits[1] ? "(" + product.UnitName + "*" + product.SecondUnits[1].Ratio + ")" : "", '', $('#lblUnitOtherD1')));
    $('#lblUnitOtherD2').text(checkNotNull(product.SecondUnits[2] ? "(" + product.UnitName + "*" + product.SecondUnits[2].Ratio + ")" : "", '', $('#lblUnitOtherD2')));

    $('#lblIsBarcod').text(checkNotNull(product.BarcodeTypeName, '', $('#lblIsBarcod')));
    $('#lblStateSerialKala').text(checkNotNull(product.StateSerialName, '', $('#lblStateSerialKala')));
    $('#lblHasSerialkala').text(checkNotNull(product.StateSerial > 0, '', $('#lblHasSerialkala')));
    $('#lblTaxType').text(checkNotNull(product.TaxTypeName, '', $('#lblTaxType')));
    $('#lblBuyPrice').text(numberWithCommas(Number(checkNotNull(product.BuyPrice, '0', $('#lblBuyPrice')))));
    $('#lblSalePrice').text(numberWithCommas(Number(checkNotNull(product.SalePrice, '0', $('#lblSalePrice')))));
    $('#lblAvgPrice').text(numberWithCommas(Number(checkNotNull(data.LastPrice.AvgPriceIn, '0', $('#lblAvgPrice')))));
    $('#lblLastBuyPrice').text(numberWithCommas(Number(checkNotNull(data.LastPrice.LastPriceIn, '0', $('#lblLastBuyPrice')))));

    $('#lblSefarshMin').text(checkNotNull(product.OrderCountDefault, '0', $('#lblSefarshMin')));
    $('#lblSefareshSaghf').text(checkNotNull(product.OrderCountAlarm, '0', $('#lblSefareshSaghf')));
    $('#lblSefarshMax').text(checkNotNull(product.OrderCountMax, '0', $('#lblSefarshMax')));
    $('#lblMade').text(checkNotNull(product.Made, window.top.notDefined, $('#lblMade')));
    $('#lblModel').text(checkNotNull(product.Model, window.top.notDefined, $('#lblModel')));
    $('#lblGhafase').text(checkNotNull(product.Shelf, window.top.notDefined, $('#lblGhafase')));
    $('#lblDescription').text(checkNotNull(product.Summery, '....', $('#lblDescription')));

    getPriceList();

}


function openModal(operation) {
    var title, src;
    if (operation === "insert") {
        title = window.top.product;
        src = "Sale/ProductSave2";
    }
    else if (operation === 'edit' || operation === 'copy') {
        var rowIndex = gridBuilder.getActiveRowIndex();
        if (rowIndex < 0)
            return;
        title = operation === 'edit' ? window.top.editProduct : window.top.copyProduct;
        var productId = gridBuilder.getCellValue(rowIndex, "Id");
        var productCode = gridBuilder.getCellValue(rowIndex, "Code");
        src = "Sale/ProductSave2?code=" + productCode + "&isCopy=" + (operation === 'copy' ? "1" : "0");
    }
    openInModal('', src, title, "", "", false);
}

function openModalBarcode() {
    var rowIndex = gridBuilder.getActiveRowIndex();
    if (rowIndex < 0)
        return;
    var productId = gridBuilder.getCellValue(rowIndex, "Id");
    var productCode = gridBuilder.getCellValue(rowIndex, "Code");
    var src = "Sale/BarcodePrint?shenaseh=" + productId + "&code=" + productCode;
    var title = window.top.printBarcode;
    openInModal("", src, title, "900", "", true);
}

function deleteRow() {
    var rowIndex = gridBuilder.getActiveRowIndex();
    if (rowIndex < 0) {
        showMsgModal(0, window.top.chooseItem);
        return;
    }
    if (confirm(window.top.deleteConfirm)) {
        ajax({
            loading:true,
            url: "SaleApi/DeleteProduct",
            data: { id: gridBuilder.getCellValue(rowIndex, "Id") },
            success: function (result) {
                showMsgModal(2, result.FinalMessage);
                loadGrid();
            }
        });
    }
}

function print(type) {
    var rowIndex = gridBuilder.getActiveRowIndex();
    if (rowIndex < 0)
        return;
    var productCode = gridBuilder.getCellValue(rowIndex, "Code");
    var title = type === "barcode" ? window.top.printBarcode : window.top._print;
    var url = type === "barcode" ? "Report/Default?GrpName=PrintBarcode&Kala=" + productCode : "Report/Default?GrpName=KaraReport&SqlWhere=" + gridBuilder.getFilter();
    openInModal("", url, title, "", "", false);
}

function clearControl() {
    $('#lblIsServices').text('');
    $('#lblGrpKala').text('');
    $('#lblName').text('');
    $('#lblUnitMain').text('');
    $('#lblUnitOther').text('');
    $('#lblUnitOther1').text('');
    $('#lblUnitOther2').text('');
    $('#lblUnitOtherD').text('');
    $('#lblUnitOtherD1').text('');
    $('#lblUnitOtherD2').text('');
    $('#lblIsBarcod').text('');
    $('#lblStateSerialKala').text('');
    $('#lblHasSerialkala').text('');
    $('#lblTaxType').text('');
    $('#lblBuyPrice').text('');
    $('#lblSalePrice').text('');
    $('#lblAvgPrice').text('');
    $('#lblLastBuyPrice').text('');
    $('#price').text('');
    $('#price1').text('');
    $('#price2').text('');
    $('#price3').text('');
    $('#price4').text('');
    $('#price5').text('');
    $('#price6').text('');
    $('#lblSefarshMin').text('');
    $('#lblSefareshSaghf').text('');
    $('#lblSefarshMax').text('');
    $('#lblMade').text('');
    $('#lblModel').text('');
    $('#lblGhafase').text('');
    $('.icon-lable-disable').remove();
    $('.icon-lable-enable').remove();
}

function checkNotNull(value, text, controller) {
    var disActive = window.top.deActive;
    var active = window.top.active;

    var taxtype_2 = window.top.addedValue;
    var taxtype_3 = window.top.addedInPrice;
    var taxtype_1 = window.top.notAddedValue;

    if (!value || value == null || value == "0") {

        if ((value !== 0 || value !== "0") && controller)
            controller.css("color", "#979797");

        return text;
    }
    else if (value == "-1") {
        return "";
    }
    else {
        if ((disActive == value || taxtype_1 == value) && controller) {
            controller.before('');
            controller.css("color", "#e24444");
            controller.before("<img class='icon-lable-disable' src='../img/pages/sale/disable.svg' style='width: 16px;' />");
        }
        else if ((value == taxtype_3 || value == taxtype_2 || value == active) && controller) {

            controller.before('');
            controller.css("color", "#16a085");
            controller.before("<img class='icon-lable-enable' src='../img/pages/sale/enable.svg' style='width: 16px;' />");
        }
        else if (controller) {
            controller.css("color", "#000");
        }
        return value;
    }
}
function getPriceList() {
    ajax({
        loading: false,
        url: "SaleApi/GetPriceList",
        data: { unitCode: unitCode, pageNo: -1, productCode: productCode },
        success: function (result) {
            if (result.length > 1) {
                var i = 0;
                $(".row-data-price").children().not(".template-price").remove();
                result.forEach(function (item) {
                    var $div = $(".template-price").clone().removeClass("template-price").removeAttr("hidden").attr("id", "divPrice" + i);
                    $(".row-data-price").append($div);
                    setJsonValue(item, "#divPrice" + i);
                    i++;
                });
                $("#divPriceProperty").show();
                $("#divPrice").hide();
            }
            else {
                $("#divPriceProperty").hide();
                $("#divPrice").show();
                $('#lblPrice').text(numberWithCommas(result[0].Price0));
                $('#lblPrice1').text(numberWithCommas(result[0].Price1));
                $('#lblPrice2').text(numberWithCommas(result[0].Price2));
                $('#lblPrice3').text(numberWithCommas(result[0].Price3));
                $('#lblPrice4').text(numberWithCommas(result[0].Price4));
                $('#lblPrice5').text(numberWithCommas(result[0].Price5));
                $('#lblPrice6').text(numberWithCommas(result[0].Price6));
            }
            closeLoading();
        }
    });
}





