var code = getQuery("code");
var selectedProductList = [];
var selectedPriceList = [];
var gridBuilderNoSelect;
var gridBuilderSelect;
var gridBuilderPrice;
var allPriceList;
var baseDecimalCount = Number(window.top.$('#hfDecimalCount').val());
$(document).ready(function () {
    gridBuilderNoSelect = $("#gridListNoSelect").gridBuilder();
    gridBuilderSelect = $("#gridListSelect").gridBuilder();
    gridBuilderPrice = $("#gridPrice").gridBuilder();
    gridBuilderPrice.onGetComboData(getGridComboData);
    gridBuilderPrice.onCellChanged(gridCellChanged);
    gridBuilderPrice.onPageChanged(gridPageChanged);
    gridBuilderPrice.onSetMaskEdit(setEventMaskEdit);
    gridBuilderPrice.onExportClick(exportSampleExcel);
    gridBuilderPrice.onImportClick(function (gridId, type, base64) {
        if (type === "importXml") {
            importXml(gridId, base64);
        }
        else {
            ajax({
                loading: true,
                url: "GeneralApi/ImportExcel",
                data: {
                    key: "DiscountList",
                    base64: base64
                },
                success: function (result) {
                    var data = eval(result.result);
                    syncProductList(data);
                    loadGrid("gridPrice");
                }
            });
        }
    });
    gridBuilderNoSelect.onExportClick(function () {
        loadGrid("gridListNoSelect", { exportExcel: true });
    });
    gridBuilderSelect.onExportClick(function () {
        loadGrid("gridListSelect", { exportExcel: true });
    });
    $(".go-step").on("click", function () {
        var level = $(this).attr("data-target");
        if (level === "step2") {
            var exceptionText = checkValidation('');
            var priceList = getSelectedPriceList();
            if (exceptionText !== "") {
                showMsgModal(0, exceptionText);
                return;
            }
            if (priceList.length === 0) {
                showMsgModal(0, window.top.selectPriceList);
                return;
            }
            if (productList.filter(x => x["IsSelected"]).length === 0) {
                showMsgModal(0, window.top.selectProduct);
                return;
            }
            showLoading();
            $("#step1").hide();
            $("#step2").show();
            for (var i = 0; i < 7; i++) {
                var state = !priceList.includes(i);
                gridBuilderPrice.setColumnVisibility("Price" + i, state);
                gridBuilderPrice.setColumnVisibility("AfterDiscount" + i, state);
            }
            setTimeout(function () {
                loadGrid("gridPrice");
            }, 10);

        }
        else {
            $("#step2").hide();
            $("#step1").show();
        }
        return false;
    });
    initial();
});
function exportSampleExcel(gridId, type) {
    var columns = gridBuilderPrice.getColumns().split(",").slice(0, 6).join(",");
    var captions = gridBuilderPrice.getColumnsCaption().split(",").slice(0, 6).join(",");
    if (type === "excelSample") {
        exportExcel(null, columns, captions, true);
    } else
        exportExcel(gridBuilderPrice.getDataArray()["data"], columns, captions);
}
function getGridComboData($combo) {
    var comboId = $combo.attr("id");
    var comboBuilder = $("#" + comboId).comboBuilder();
    var list = [{ Code: window.top.amount, Name: window.top.amount }, { Code: window.top.percent, Name: window.top.percent }];
    comboBuilder.loadData(list);
}
function gridCellChanged(rowIndex, columnIndex) {
    var fieldName = gridBuilderPrice.getCellFieldName(columnIndex);
    var priceList = getSelectedPriceList();
    if (fieldName === "DiscountTypeName" || fieldName === "PercentAmount") {
        var codePart = gridBuilderPrice.getCellValue(rowIndex, "CodePart");
        var productCode = gridBuilderPrice.getCellValue(rowIndex, "ProductCode");
        var data = productList.filter(x => x.ProductCode === Number(productCode) && (codePart || null) == x.CodePart)[0];
        var percentAmount = gridBuilderPrice.getCellValue(rowIndex, "PercentAmount");
        var discountTypeName = gridBuilderPrice.getCellValue(rowIndex, "DiscountTypeName");
        var discountType = (discountTypeName === window.top.percent ? 1 : 0)
        data["DiscountTypeName"] = discountTypeName;
        data["DiscountType"] = discountType;
        data["PercentAmount"] = percentAmount;
        gridBuilderPrice.setCellValue(rowIndex, "DiscountType", discountType);
        priceList.forEach(function (item) {
            var price = Number(gridBuilderPrice.getCellValue(rowIndex, "Price" + item));
            var afterDiscount = price - (discountType === 1 ? Number((percentAmount * price / 100).toFixed(baseDecimalCount)) : Number(percentAmount));
            gridBuilderPrice.setCellValue(rowIndex, "AfterDiscount" + item, afterDiscount);
            data["AfterDiscount" + item] = afterDiscount;
        });
        closeLoading();
    }
}
function gridPageChanged(pageNo) {
    setGridColor();
}
function loadGrid(gridId, objectParameter) {
    var isExportExcel = objectParameter && objectParameter.exportExcel ? true : false;
    var data = productList.filter(x => (gridId === "gridListSelect" || gridId === "gridPrice" ? x["IsSelected"] : !x["IsSelected"]));
    var gridBuilder = $("#" + gridId).gridBuilder();
    if (gridId === "gridPrice") {
        var priceList = getSelectedPriceList();
        for (var i = 0; i < data.length; i++) {
            var discountTypeName = data[i]["DiscountTypeName"];
            var discountType = (discountTypeName === window.top.percent ? 1 : 0);
            var percentAmount = Number(data[i]["PercentAmount"]) || 0;
            for (var j = 0; j < priceList.length; j++) {
                var price = Number(data[i]["Price" + j]);
                var afterDiscount = price - (discountType === 1 ? Number((percentAmount * price / 100).toFixed(baseDecimalCount)) : Number(percentAmount));
                data[i]["AfterDiscount" + j] = afterDiscount;
            }
            data[i]["Index"] = i + 1;
            data[i]["DiscountType"] = discountType;
        }
    }
    if (isExportExcel)
        exportExcel(data, gridBuilder.getColumns(), gridBuilder.getColumnsCaption());
    else
        gridBuilder.loadData(data);

    if (gridId === "gridPrice") {
        setGridColor();
    }
}
function addRemoveSingle(state) {
    var gridBuilder = state ? gridBuilderNoSelect : gridBuilderSelect;
    var codes = gridBuilder.getSelectedRowsCellValue("ProductCode");
    var codeParts = gridBuilder.getSelectedRowsCellValue("CodePart");
    if (codes.length === 0) {
        var activeRowCode = gridBuilder.getActiveRowCellValue("ProductCode");
        var activeRowCodePart = gridBuilder.getActiveRowCellValue("CodePart");
        if (activeRowCode) {
            codes.push(activeRowCode);
            codeParts.push(activeRowCodePart);
        }
    }
    addRemoveSelected(codes, codeParts, state);
}
function addRemoveSelected(value, parts, state) {
    var percentAmount = $("#txtAmount").val();
    for (var i = 0; i < value.length; i++) {
        var item = productList.find(x => x.ProductCode === Number(value[i]) && (x.CodePart == parts[i] || !parts[i]));
        item["IsSelected"] = state;
        item["PercentAmount"] = percentAmount;
    }
    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('ProductCode');
    var parts = gridBuilder.getSelectedRowsCellValue('CodePart');
    addRemoveSelected(code, parts, state);
}
function selectAll(state) {
    var data = productList.filter(x => (state ? !x["IsSelected"] : x["IsSelected"]));
    for (var i = 0; i < data.length; i++) {
        data[i]["IsSelected"] = state;
    }
    gridBuilderNoSelect.setUnselected(-1);
    gridBuilderSelect.setUnselected(-1);

    loadGrid("gridListNoSelect");
    loadGrid("gridListSelect");
}
function changeAmount(sender) {
    $('.isactive').removeClass('isactive').addClass('dontisactive');
    $(sender).addClass('isactive').removeClass('dontisactive');
    var isPercent = $(sender).attr("id") === "btnPercent";
    var amount = $('#txtAmount').val();
    if (isPercent && amount >= 100)
        $('#txtAmount').val('');
    if ($(sender).attr('id') === 'btnPrice') {
        $("#txtAmount").removeAttr('maxlength', '');
    }
    else if ($(sender).attr('id') === 'btnPercent') {
        $("#txtAmount").attr('maxlength', '3');
    }
}
function save() {
    var exceptionText = checkValidation('');
    if (exceptionText === '') {
        var data = getJsonValue("");
        var gridData = gridBuilderPrice.getDataArray().data;
        var isInvalidDiscount = checkDiscountAmount(gridData);
        if (isInvalidDiscount === -1) {
            isInvalidDiscount = checkAfterDiscountAmount(gridData);
            data['PriceList'] = getSelectedPriceList();
            data["DiscountListProduct"] = gridData;
            if (!isInvalidDiscount) {
                if (confirm(window.top.invalidDiscountConfirm)) {
                    saveMain(data);
                }
            }
            else
                saveMain(data);
        }
        else {
            showMsgModal(0, window.top.invalidDiscountForRow + " " + (isInvalidDiscount + 1));
        }
    }
    else {
        showMsgModal(0, exceptionText);
    }
}
function saveMain(data) {
    ajax({
        loading: true,
        url: "SaleApi/InsertDiscountList",
        data: { discountList: data },
        success: function () {
            showMsgModal(2, window.top.savedSuccessfully);
            refreshParent('loadGrid();');
            closeTopModal();
        }
    });
}
async function initial() {
    if (code)
        await getDiscountListDetail();
    await getPriceList()
    loadGrid("gridListSelect");
    loadGrid("gridListNoSelect");
    $("#divMain").show();
    closeLoading();
}
async function getDiscountListDetail() {
    await ajax({
        url: "SaleApi/GetDiscountListDetail",
        data: { code: code },
        success: function (result) {
            selectedProductList = result.DiscountListProduct;
            selectedPriceList = result.PriceList;
            selectedPriceList.forEach(function (item) {
                $("#price").find("#" + item).prop("checked", true)
            });
            setJsonValue(result);
        }
    });
}
async function getPriceList() {
    await ajax({
        url: "SaleApi/GetPriceList",
        data: {},
        success: function (result) {
            result = result.filter(x => x.UnitCode === x.MainUnitCode);
            productList = result;
            syncProductList(selectedProductList);
        }
    });
}
function getSelectedPriceList() {
    var priceList = [];
    $('#price [type="checkbox"]').each(function () {
        if ($(this).is(':checked')) {
            priceList.push(Number($(this).attr('id')));
        }
    });
    return priceList;
}
function changeAllValue() {
    var percentAmount = $("#txtAmount").val();
    var isPercent = $(".isactive").attr("id") === "btnPercent";
    var data = productList.filter(x => x["IsSelected"]);
    var discountType = (isPercent ? 1 : 0);
    if (isPercent && Number(percentAmount) >= 100) {
        showMsgModal(0, window.top.invalidDiscount);
        return;
    }
    showLoading();
    setTimeout(function () {
        var priceList = getSelectedPriceList();
        for (var i = 0; i < data.length; i++) {
            data[i]["PercentAmount"] = percentAmount;
            data[i]["DiscountTypeName"] = isPercent ? window.top.percent : window.top.amount;
            data[i]["DiscountType"] = discountType;
            for (var j = 0; j < priceList.length; j++) {
                var price = Number(data[i]["Price" + j]);
                var afterDiscount = price - (discountType === 1 ? Number((percentAmount * price / 100).toFixed(baseDecimalCount)) : Number(percentAmount));
                data[i]["AfterDiscount" + j] = afterDiscount;
            }
        }
        gridBuilderPrice.loadData(data);
        setGridColor();
        closeLoading();
    }, 10);
    $("#dicountModal").modal("hide");
}
function setGridColor() {
    var rowsCount = gridBuilderPrice.getRowsCount();
    var priceList = getSelectedPriceList();
    for (var i = 0; i < rowsCount; i++) {
        setAfterDiscountValues(i, priceList);
    }
    closeLoading();
}
function setAfterDiscountValues(rowIndex, priceList) {
    var codePart = gridBuilderPrice.getCellValue(rowIndex, "CodePart");
    var productCode = gridBuilderPrice.getCellValue(rowIndex, "ProductCode");
    var data = productList.filter(x => x.ProductCode === Number(productCode) && (codePart || null) == x.CodePart)[0];
    priceList.forEach(function (item) {
        var columnIndex = gridBuilderPrice.getCellIndex("AfterDiscount" + item);
        var td = gridBuilderPrice.container.find("tbody tr:eq(" + (rowIndex + 2) + ") td:eq(" + columnIndex + ")");
        var afterDiscount = data["AfterDiscount" + item];
        $(td).css({ "background-color": (Number(afterDiscount) <= 0 ? "#ffebee" : "#f5f5f5") });
    });
    closeLoading();
}
function openDiscountModal() {
    $("#dicountModal").modal();
}
function checkAfterDiscountAmount(data) {
    var isValid = true;
    var priceList = getSelectedPriceList();
    for (var i = 0; i < data.length; i++) {
        for (var j = 0; j < priceList.length; j++) {
            var afterDiscountValue = data[i]["AfterDiscount" + priceList[j]];
            if (afterDiscountValue <= 0) {
                isValid = false;
                break;
            }
        }
        if (!isValid)
            break;
    }
    return isValid;
}
function checkDiscountAmount(data) {
    var returnValue = -1;
    for (var i = 0; i < data.length; i++) {
        if (!data[i]["PercentAmount"] || !data[i]["DiscountTypeName"]) {
            returnValue = i;
            break;
        }
    }
    return returnValue;
}
function syncProductList(data) {
    data.forEach(function (item) {
        var selectedProduct = productList.find(x => x.ProductCode === item.ProductCode && (!item.CodePart || item.CodePart == x.CodePart));
        if (selectedProduct) {
            selectedProduct["IsSelected"] = true;
            selectedProduct["PercentAmount"] = item.PercentAmount;
            selectedProduct["DiscountType"] = item.DiscountType;
            selectedProduct["DiscountTypeName"] = item.DiscountType === 1 ? window.top.percent : window.top.amount;
        }
    });
    if (data.length === 0) {
        productList.forEach(function (item) {
            item["DiscountType"] = 1;
            item["DiscountTypeName"] = window.top.percent;
        });
    }
}