var productCode = getQuery("code");
var gridBuilderNoSelect;
var gridBuilderSelect;
var gridBuilderProduct;
var selectedProductPropertyList;
var selectedProductList;
var productList;
var productGroupList;
var priceList;
var discountList;
var decimalCount = Number(window.top.$('#hfDecimalCount').val());
var baseCurrencyName = window.top.$('#hfBaseCurrencyName').val();
var lastTemplateDetail;
var isValidData = true;
$(document).ready(function () {
    gridBuilderNoSelect = $("#gridListNoSelect").gridBuilder();
    gridBuilderSelect = $("#gridListSelect").gridBuilder();
    gridBuilderProduct = $("#gridListProduct").gridBuilder();
    gridBuilderProduct.onSetMaskEdit(setEventMaskEdit);
    gridBuilderProduct.onGetComboData(getGridComboData);
    gridBuilderNoSelect.onExportClick(exportSampleExcel);
    gridBuilderSelect.onExportClick(exportSampleExcel);
    gridBuilderProduct.onExportClick(exportSampleExcel);
    gridBuilderProduct.onPageChanged(gridPageChanged);

    $("#cboPrice").lookupBuilder().onChanged(async function () {
        await getEventLookupCombo($("#cboDiscount"), "", "");
        priceList = null;
    });
    $("#cboDiscount").lookupBuilder().onChanged(async function () {
        discountList = null;
    });

    initial();
});
function gridPageChanged(pageNo) {
    setGridColor();
}
function openBarcodeTemplateModal(sender) {
    var mode = $(sender).attr("id").includes("Edit") ? "edit" : "";
    $("#settingBarcodeModal").modal().attr("data-mode", mode);
    if (mode === "edit") {
        setJsonValue(lastTemplateDetail, "#settingBarcodeModal")
    }
    else {
        $("#settingBarcodeModal [data-id]").val("");
        $("#settingBarcodeModal [data-id = 'PaperTypeCode']").val(1);

    }
}

$(".go-step").on("click", function () {
    var level = $(this).attr("data-id");
    $(".steps").hide();
    $("#" + level).show();
    if (level === "step3")
        loadGrid("gridListProduct")
});

async function initial() {
    $("#cboBarcodeTemplate").lookupBuilder().onChanged(async function () {
        var templateCode = $("#cboBarcodeTemplate").lookupBuilder().getSelectedValue();
        if (templateCode)
            await getBarcodeTemplate(templateCode);
        else {
            $("#btnDelete").hide();
            $("#btnEdit").hide();
        }
    });
    await getEventLookupCombo($("#cboBarcodeTemplate"), "", "top");


    if (productCode !== "")
        await getProduct();
    await getProductGroupedByPropertyList();

    loadGrid("gridListSelect");
    loadGrid("gridListNoSelect");
}

function getGridBuilder(gridId) {
    var gridBuilder;
    switch (gridId) {
        case "gridListNoSelect":
            gridBuilder = gridBuilderNoSelect;
            break;
        case "gridListSelect":
            gridBuilder = gridBuilderSelect;
            break;
        default:
            gridBuilder = gridBuilderProduct;
    }
    return gridBuilder;
}

async function loadGrid(gridId, objectParameter) {
    var gridBuilder = getGridBuilder(gridId);
    var selected = (gridId === "gridListSelect") || (gridId === "gridListProduct");
    var isExportExcel = objectParameter && objectParameter.exportExcel ? true : false;
    var data;
    if (selected) {
        data = productList.filter(x => x["IsSelected"]);
    }
    else {
        data = productList.filter(x => !x["IsSelected"]);
    }

    if (gridId === "gridListProduct") {
        var priceCode = $("#cboPrice").lookupBuilder().getSelectedValue();
        var discountCode = $("#cboDiscount").lookupBuilder().getSelectedValue();
        if (priceCode) {
            await getPriceList();
            if (discountCode > 0)
                await getDiscountListDetail(discountCode);
        }
        data.forEach(function (item) {
            var price = 0;
            var priceAfterDiscount = 0;
            var discountAmount = "";
            if (priceList) {
                var priceItem = priceList.find(x => x.ProductId === item.Id && x.UnitCode === item.UnitCode && x.CodePart === item.CodePart);
                if (priceItem) {
                    price = priceItem["Price" + priceCode];
                    priceAfterDiscount = price;
                }
                if (discountList) {
                    var discountItem = discountList.DiscountListProduct.find(x => x.ProductCode === item.Code && x.CodePart === item.CodePart);
                    if (discountItem) {
                        var discount = Number(discountItem.DiscountType === 1 ? (discountItem.PercentAmount * price / 100).toFixed(decimalCount) : discountItem.PercentAmount);
                        priceAfterDiscount = price - discount;
                        discountAmount = discountItem.PercentAmount + (discountItem.DiscountType === 1 ? "%" : baseCurrencyName);
                    }
                }
            }
            
            item.BarcodeId = item.Barcodes[0].Barcode;
            item.Count = 1;
            item.Price = numberWithCommas(price, decimalCount);
            item.DiscountAmount = discountAmount;
            item.PriceAfterDiscount = numberWithCommas(priceAfterDiscount, decimalCount);
        });
        gridBuilder.setColumnVisibility("PriceAfterDiscount",!discountCode > 0);
        gridBuilder.setColumnVisibility("DiscountAmount", !discountCode > 0);
        gridBuilder.setColumnVisibility("Price", !priceCode > 0);
    }


    if (isExportExcel)
        exportExcel(data, gridBuilder.getColumns(), gridBuilder.getColumnsCaption());
    else
        gridBuilder.loadData(data);

    if (gridId === "gridListProduct")
        setGridColor();
}

async function getProduct() {
    await ajax({
        url: "SaleApi/GetProduct",
        data: { code: productCode },
        success: function (result) {
            if (result.ProductPartPropertyName.ProductPartProperty.length > 0)
                selectedProductPropertyList = result.ProductPartPropertyName.ProductPartProperty;
            else
                selectedProductList = result.Id;
        }
    });
}

async function getProductGroupedByPropertyList(gridBuilder) {
    await ajax({
        url: "SaleApi/GetProductGroupedByPropertyList",
        data: { pageNo: -1 },
        success: function (result) {
            result = result.filter(x => x.Barcodes.length > 0);
            if (selectedProductPropertyList) {
                selectedProductPropertyList.forEach(function (item) {
                    var selectedProduct = result.filter(x => x.CodePart === item.Code);
                    if (selectedProduct.length > 0)
                        selectedProduct[0]["IsSelected"] = true;
                });
            }
            else if (selectedProductList) {
                var selectedProduct = result.filter(x => x.Id === selectedProductList);
                if (selectedProduct.length > 0)
                    selectedProduct[0]["IsSelected"] = true;
            }
            productList = result;
        }
    });
}

function addRemoveSingle(state) {
    var gridBuilder = state ? gridBuilderNoSelect : gridBuilderSelect;
    var codes = gridBuilder.getSelectedRowsCellValue("Id");
    if (codes.length === 0) {
        var activeRowCode = gridBuilder.getActiveRowCellValue("Id");
        if (activeRowCode)
            codes.push(activeRowCode);
    }
    addRemoveSelected(codes, state);
}

function addRemoveSelected(value, state) {
    for (var i = 0; i < value.length; i++) {
        var item = productList.find(x => x.Id === value[i]);
        item.IsSelected = state;
    }
    gridBuilderNoSelect.setUnselected(-1);
    gridBuilderSelect.setUnselected(-1);
    loadGrid("gridListNoSelect");
    loadGrid("gridListSelect");
}

function addRemoveAll(state) {
    var gridBuilder = state ? gridBuilderNoSelect : gridBuilderSelect;
    gridBuilder.setSelected(-1);
    var code = gridBuilder.getSelectedRowsCellValue('Id');
    addRemoveSelected(code, state);
}

async function print() {
    var productData = [];
    var data = gridBuilderProduct.getDataArray()["data"];
    if (data.length === 0)
        return;
    data.forEach(function (item) {
        productData.push({
            ProductCode: item.Code,
            PartCode: item.CodePart,
            BarcodeCount: item.Count,
            Barcode: item.BarcodeId
        });
    });
    //var priceListCode = $("#cboPrice").lookupBuilder().getSelectedValue().split("|")[0];
    //var discountListCode = $("#cboDiscount").lookupBuilder().getSelectedValue().split("|")[0];
    await ajax({
        url: "SaleApi/InsertTempBarcode",
        data: {
            product: productData,
            //PriceListCode: $("#chPrice").prop("checked") ? priceListCode : null,
            //DiscountListCode: discountListCode
        },
        success: function (resValue) {
            var id = resValue.ReturnValue;
            var grpName = "Barcod_Web";
            var title = window.top.printBarcode;
            var url = "Report/Default?GrpName=" + grpName + "&Edit1=" + id;
            openInModal("", url, title, "", "", false);
        }
    });
}
async function generateBarcodeDiv() {
    var data = gridBuilderProduct.getDataArray()["data"];
    var info = getJsonValue();
    var barcodeData = { CompanyName: $("#hfCompanyName").val() };
    $(".barcode-template [data-id]").each(function () {
        if (!info["Print" + $(this).attr("data-id")])
            $(this).hide();
    });
    
    for (var i = 0; i < data.length; i++) {
        barcodeData["ProductId"] = data[i].Id;
        barcodeData["ProductName"] = data[i].Name;
        barcodeData["ProductUnit"] = data[i].UnitName;
        barcodeData["Price"] = data[i].Price;
        barcodeData["DiscountAmount"] = data[i].DiscountAmount;
        barcodeData["PriceAfterDiscount"] = data[i].PriceAfterDiscount;
        
        for (var j = 0; j < data[i].Count; j++) {
            var div = $(".barcode-template").clone().removeAttr("hidden").removeClass("barcode-template").attr("id", "div" + i + "_" + j);
            div.css({ "width": lastTemplateDetail.LabelWidth + "mm", "height": lastTemplateDetail.LabelHeight + "mm" });
            $(".barcode-container").append(div);
            setJsonValue(barcodeData, "#div" + i + "_" + j);
            div.find("img").attr("src", "Barcode?code=" + data[i].BarcodeId);
        }
    }
}
async function getPriceList() {
    await ajax({
        url: "SaleApi/GetPriceList",
        data: { pageNo: -1 },
        success: function (result) {
            priceList = result;
        }
    });
}
async function getDiscountListDetail(discountListCode) {
    await ajax({
        url: "SaleApi/GetDiscountListDetail",
        data: { Code: discountListCode },
        success: function (result) {
            discountList = result;
        }
    });
}
async function print2() {
    await generateBarcodeDiv();
    var pageWidth;
    var pageHeight;
    var bodyWidth;
    var newWin = window.open('', 'Print-Window');
    var link = $(window.document).find("head>link");
    switch (lastTemplateDetail.PaperTypeCode) {
        case 0:
            bodyWidth = 210;
            pageHeight = 297;
            break;
        case 1:
            bodyWidth = 297;
            pageHeight = 210;
            break;
        case 2:
            bodyWidth = 148;
            pageHeight = 210;
            break;
        case 3:
            pageHeight = 148;
            bodyWidth = 210;
            break;
        case 4:
            pageHeight = lastTemplateDetail.LabelHeight;
            bodyWidth = lastTemplateDetail.LabelWidth;
            break;
        case 5:
            pageHeight = lastTemplateDetail.LabelHeight;
            bodyWidth = (lastTemplateDetail.LabelWidth * 2);
            break;
        case 6:
            pageHeight = lastTemplateDetail.LabelHeight;
            bodyWidth = (lastTemplateDetail.LabelWidth * 3);
            break;
    }
    pageWidth = bodyWidth + lastTemplateDetail.MarginRight + lastTemplateDetail.MarginLeft;
    pageHeight = pageHeight + lastTemplateDetail.MarginTop + lastTemplateDetail.MarginBottom;
    var sizeStr = `@page {size:${pageWidth}mm ${pageHeight}mm; margin-top:${lastTemplateDetail.MarginTop}mm;margin-bottom:${lastTemplateDetail.MarginBottom}mm} @media print{html,body {width:${bodyWidth}mm;} }`;
    var html = $(".barcode-container").html();
    $(".barcode-container").empty();

    newWin.document.open();
    link.each(function () {
        newWin.document.write(this.outerHTML);
    });
    newWin.document.write(html);
    $(newWin.document).find("body").css({ "width": bodyWidth + "mm"});
    $(newWin.document).find("head").append(`<style>${sizeStr}</style>`);
    setTimeout(function () {
        newWin.document.execCommand('Print');
        newWin.close();
    },
        2000);

}

function exportSampleExcel(gridId, type) {
    var gridBuilder = getGridBuilder(gridId);
    exportExcel(gridBuilder.getDataArray()["data"], gridBuilder.getColumns(), gridBuilder.getColumnsCaption());
}

function getGridComboData($combo, search) {
    var comboId = $combo.attr("id");
    var comboBuilder = $("#" + comboId).comboBuilder();
    var rowIndex = gridBuilderProduct.getActiveRowIndex();
    var productId = gridBuilderProduct.getCellValue(rowIndex, "Id");

    if (!productId)
        productId = -1;

    var list = productList.filter(x => x["IsSelected"]);
    list = list.filter(x => x.Id === productId)[0].Barcodes;
    var data = [];

    list.forEach(function (item) { data.push({ Code: item.Barcode, Name: item.Barcode }); });
    comboBuilder.loadData(data);
}

async function getEventLookupCombo($combo, search, code) {
    var id = $combo.attr("id");
    var url;
    var data = null;
    switch (id) {
        case "cboPrice":
            url = "GeneralApi/GetCustomerPriceList";
            data = {
                search: search,
                pageNo: -1
            };
            break;
        case "cboDiscount":
            url = "SaleApi/GetDiscountList";
            data = {
                piceListCode: getObjectValue("cboPrice", 0),
                search: search,
                pageNo: -1
            };
            break;
        case "cboBarcodeTemplate":
            url = "SaleApi/GetBarcodeTemplateList";
            break;
    }
    if (!url)
        return;
    var result;
    await ajax({
        url: url,
        data: data,
        success: function (resValue) {
            result = resValue;
        }
    });
    if (id === "cboDiscount") {
        result.push({ Code: -1, Name: window.top.noDiscount });
    }
    if (code === "top") {
        $combo.lookupBuilder().setSelectedValue(result.length > 0 ? result[0].Code : "");
    }
    $combo.lookupBuilder().bindData(result);
}

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];
        }
    }
}
async function saveBarcodeTemplate() {
    var data = getJsonValue("#settingBarcodeModal");
    var error = checkValidation("#settingBarcodeModal");
    if (error === "") {
        var mode = $("#settingBarcodeModal").attr("data-mode");
        if (mode === "edit")
            data["Code"] = $("#cboBarcodeTemplate").lookupBuilder().getSelectedValue();
        await ajax({
            url: "SaleApi/" + (mode === "edit" ? "UpdateBarcodeTemplate" : "InsertBarcodeTemplate"),
            data: data,
            loading:true,
            success: function (result) {
                data["Code"] = result.ReturnValue;
                data["PaperTypeName"] = $("#cboPaperType option:selected").text();
                data["StandardCodeName"] = $("#cboStandardCode option:selected").text();
                lastTemplateDetail = data;
                $("#cboBarcodeTemplate").lookupBuilder().setSelectedValue(result.ReturnValue);
                $("#settingBarcodeModal").modal("hide");
                setJsonValue(data,"#divPaperInfo");
                showMsgModal(2, window.top.savedSuccessfully);
            }
        });
    }
    else {
        showMsgModal(0, error);
    }
}
async function getBarcodeTemplate(code) {
    await ajax({
        url: "SaleApi/GetBarcodeTemplate",
        data: { code: code },
        success: function (result) {
            result["PaperTypeName"] = $("#cboPaperType option[value=" + result.PaperTypeCode + "]").text();
            result["StandardCodeName"] = $("#cboStandardCode option[value=" + result.StandardCode + "]").text();
            setJsonValue(result, "#divPaperInfo");
            lastTemplateDetail = result;
        }
    });
}
async function deleteBarcodeTemplate() {
    if (confirm(window.top.deleteConfirm))
        var code = $("#cboBarcodeTemplate").lookupBuilder().getSelectedValue();
        await ajax({
            url: "SaleApi/DeleteBarcodeTemplate",
            data: { code: code },
            success: function () {
                showMsgModal(2, window.top.deletedSuccessfully);
                getEventLookupCombo($("#cboBarcodeTemplate"), "", "top");
            }
        });
}
function setGridColor() {
    var rowsCount = gridBuilderProduct.getRowsCount();
    var chDiscount = $("#chDiscount").prop("checked");
    var chPrice = $("#chPrice").prop("checked");
    var chPriceAfterDiscount = $("#chPriceAfterDiscount").prop("checked");
    for (var i = 0; i < rowsCount; i++) {
        var productId = gridBuilderProduct.getCellValue(i, "Id");
        var item = productList.find(x => x.Id === productId);
        if (chDiscount && (!item.DiscountAmount || numberNonCommas(item.DiscountAmount.replace("%","")) === 0)) {
            changeColor(i, "DiscountAmount");
        }
        if (chPrice && numberNonCommas(item.Price) === 0) {
            changeColor(i, "Price");
        }
        if (chPriceAfterDiscount && numberNonCommas(item.PriceAfterDiscount) === 0) {
            changeColor(i, "PriceAfterDiscount");
        }
    }
}
function changeColor(rowIndex,columnName) {
    var columnIndex = gridBuilderProduct.getCellIndex(columnName);
    var td = gridBuilderProduct.container.find("tbody tr:eq(" + (rowIndex + 2) + ") td:eq(" + columnIndex + ")");
    $(td).css({ "background-color": "#ffebee" });
}
function chkPrintDiscountChange(sender) {
    //var state = $(sender).prop("checked");
    //changeRequired("cboDiscount", state);
    //$("#cboDiscount").lookupBuilder().setEnabled(state)
    //$("#cboDiscount").lookupBuilder().setSelectedValue("");
}


