var serialList;
var productCount = 0;

var selectedSerial = getQuery("serials");
var productId = getQuery("shenaseh");
var state = getQuery("state");
var storeCode = getQuery("storeCode");
var stateInOut = getQuery("stateInOut");
var saleSystemCode = Number(getQuery("s"));
var gridBuilder;

$(document).ready(function () {
    gridBuilder = $(".grid").gridBuilder();
    gridBuilder.onGetComboData(getGridComboData);
    gridBuilder.onExportClick(exportSampleExcel);
    gridBuilder.onCellChanged(gridCellChange);
    gridBuilder.onImportClick(function (gridId, type, base64) {
        ajax({
            loading: true,
            url: "GeneralApi/ImportExcel",
            data: {
                key: "SerialNumber",
                base64: base64
            },
            success: function (result) {
                var data = eval(result.result);
                data.forEach(function (item, index) {
                    item.SerialNumberIn = item.SerialNumber;
                    item.SerialNumberOut = item.SerialNumber;
                });
                gridBuilder.loadData(data);
            }
        });
    });
    
    initial();
});
async function initial() {
    if (saleSystemCode === 2) {
        await getLastPrice();
        $("#pnlDesc").hide();
    }
    else {
        $("#txtFi").val(numberWithCommas(getQuery("fi")));
        $("#pnlDesc").show();
    }
    $("#hfStateInOut").val(getQuery("stateInOut"));
    $("#hfIsSaleSanad").val(getQuery("isSaleSanad"));
    $("#lblNameUnit").text(getQuery("nameUnit"));
    $("#lblNameKala").text(getQuery("nameKala"));
    $("#txtTakhfif").val(getQuery("takhfif"));
    $("#txtSharh").val(getQuery("tozihat"));
    $('#txtFromNumber').focus();
    if ($("#hfStateInOut").val() === "1")
        gridBuilder.removeColumn("SerialNumberOut");
    else
        gridBuilder.removeColumn("SerialNumberIn");

    if ($("#hfIsSaleSanad").val().toLowerCase() === "false") {
        if ($("#hfStateInOut").val() === "-1")
            $("#pnlFi").hide();
        $("#pnlTakhfif").hide();
    }
    if (selectedSerial !== "") {
        $("#hfIsEditSerial").val("1");
        $("#insertPanel").hide();
        $(".import-excel").hide();
        var list = [];
        list.push({ SerialNumberOut: selectedSerial, SerialNumberIn: selectedSerial });
        gridBuilder.loadData(list);
    }
    getSerialNumbers();

    if ($("#hfIsEditSerial").val() === "1") {
        $("#importFromExcel").hide();
    }
}
async function getSerialNumbers() {
    await ajax({
        url: "SaleApi/GetProductInventoryById",
        data: {
            productId: productId,
            storeCode: storeCode,
            stateSerial: state
        },
        success: function (list) {
            serialList = list;
            list.forEach(function (item) {
                productCount += Number(item.Count);
            });
            $("#lblCount").text(productCount);
            closeLoading();
            $("#divMain").show();
        }
    });
}
function exportSampleExcel(gridId, type) {
    if (type === "excelSample") {
        var columns = gridBuilder.getColumns().split(",");
        var columnsCaption = gridBuilder.getColumnsCaption().split(",");
        exportExcel(null, columns.join(","), columnsCaption.join(","), true);
    } else
        exportExcel(gridBuilder.getDataArray()["data"], gridBuilder.getColumns(), gridBuilder.getColumnsCaption());
}
function getGridComboData($combo, search) {
    var comboId = $combo.attr("id");
    var comboBuilder = $("#" + comboId).comboBuilder();
    var list = serialList.filter(function (item) { return item.Count > 0; });
    if (search)
        list = list.filter(function (item) { return item.SerialNumber.toLowerCase().indexOf(search.toLowerCase()) >= 0 && item.Count > 0; });

    list.forEach(function (item) {
        item.Code = item.SerialNumber;
        item.Name = item.SerialNumber;
    });
    comboBuilder.loadData(list);
}
function gridCellChange(event) {
    var serial;
    var rowIndex = gridBuilder.getActiveRowIndex();
    if (getQuery("stateInOut") === "1")
        serial = gridBuilder.getCellValue(rowIndex, "SerialNumberIn");
    else
        serial = gridBuilder.getCellValue(rowIndex, "SerialNumberOut");
    var validation = checkDuplicateSerial(serial, rowIndex);
    if (!validation.valid) {
        showMsgEntry(validation.msg);
        if (gridBuilder.getRowsCount() > 1)
            gridBuilder.deleteRow(rowIndex);

    }
}
function addSerialToGrid() {
    var start = $("#txtFromNumber").val();
    var count = $("#txtCount").val();
    if (start.length === 0 || count.length === 0)
        return;
    msg = "";
    for (var i = start; i < Number(start) + Number(count); i++) {
        var validation = checkDuplicateSerial(i);
        if (validation.valid) {
            gridBuilder.addNewRow();
            var rowIndex = gridBuilder.getActiveRowIndex();
            if (stateInOut === "1")
                gridBuilder.setCellValue(rowIndex, "SerialNumberIn", i);
            else
                gridBuilder.setCellValue(rowIndex, "SerialNumberOut", i);
        }
        else {
            msg += validation.msg + "<br />";
        }
    }
    if (msg.length > 0) {
        showMsgModal(0, msg);
    }
}

function checkDuplicateSerial(serial, index) {
    var valid = true;
    if (serial.length === 0) {
        valid = false;
        msg = window.top._serialNumber + serial + window.top.isInvalid;
    }
    else {
        var stateInOut = $("#hfStateInOut").val().toString();
        var gridData = gridBuilder.getDataArray()["data"].filter(function (item) { return item._status !== "deleted"; });
        var msg = "";
        var list = serialList.filter(function (item) { return Number(item.SerialNumber) === Number(serial); });

        if (gridData.length > 0) {
            if (gridData.filter(function (item, rowIndex) { return (getQuery("stateInOut") === "1" && Number(item.SerialNumberIn) === Number(serial) && (rowIndex !== index || index === null)) || (getQuery("stateInOut") === "-1" && Number(item.SerialNumberOut) === Number(serial) && (rowIndex !== index || index === null)); }).length > 0) {
                msg = window.top._serial + serial + window.top.duplicate;
                valid = false;
            }
        }
        if (stateInOut === "1") {
            if (list.length > 0 && valid && state == "1") {
                if (list[0].Count > 0) {
                    msg = window.top.productSerial + serial + window.top.hasInventoryNotRegister;
                    valid = false;
                }
                else if (!confirm(window.top._serial + serial + window.top.alreadyLoggedSureAdd)) {
                    valid = false;
                }
            }
        }
        else {
            if (list.length === 0) {
                msg = window.top._serialNumber + serial + window.top.isInvalid;
                valid = false;
            }
            else if (list[0].Count === 0) {
                msg = window.top.productSerial + serial + window.top.noInventory;
                valid = false;
            }
        }
    }
    var obj = {};
    obj.valid = valid;
    obj.msg = msg;
    return obj;
}
function save() {
    if (!validateAllRows()) {
        showMsgModal(0, window.top.enterCorrectSerial);
        return;
    }
    var gridData = gridBuilder.getDataArray()["data"];
    var serials = "";

    gridData = gridData.filter(function (item) { return (getQuery("stateInOut") === "1" && item.SerialNumberIn) || (getQuery("stateInOut") === "-1" && item.SerialNumberOut) });
    gridData.forEach(function (item) {
        if (getQuery("stateInOut") === "1")
            serial = item.SerialNumberIn;
        else
            serial = item.SerialNumberOut;

        var count = "1";
        if (serial !== null) {
            serials += serials.length > 0 ? "," : "";
            serials += (serial.toString().length > 0 ? serial.toString() : "") + "=" + (count !== null ? count.toString() : "1");
        }
    });
    var fi = ($("#txtFi").length === 1 ? $("#txtFi").val() : "0");
    var takhfif = ($("#txtTakhfif").length === 1 ? $("#txtTakhfif").val() : "0");
    var sharh = $("#txtSharh").val();
    var multiModal = getQuery("multiModal");

    var parameter = true + "','" + productId + "','" + serials + "','" + fi + "','" + takhfif ;
    refreshParent("setSerial('" + (saleSystemCode === 2 ? parameter : parameter + "','" + sharh)  + "','" + saleSystemCode + "')");
    if (!multiModal)
        closeTopModal();
}
function showMsgEntry(msg) {
    $('#divReturnDelete').empty();
    tag = '<label class="float-right" style="font-size: 12px; color: #fff; font-weight: normal; word-break: break-word; margin:6px 10px;line-height: 2;">' + msg + '</label>';
    $('#divReturnDelete').append(tag);
    $("#divReturnDelete").addClass("show");
    setTimeout(function () {
        $("#divReturnDelete").removeClass("show");
    }, 5000);
}
function validateAllRows() {
    var isValid = true;
    var gridData = gridBuilder.getDataArray()["data"].filter(function (item) { return item._status !== "deleted"; });
    gridData = gridData.filter(function (item) { return (getQuery("stateInOut") === "1" && item.SerialNumberIn) || (getQuery("stateInOut") === "-1" && item.SerialNumberOut) });

    var stateInOut = $("#hfStateInOut").val();
    if (gridData.length === 0) {
        isValid = false;
        return;
    }
    gridData.forEach(function (row) {
        var serial;
        if (stateInOut === "1")
            serial = row.SerialNumberIn;
        else
            serial = row.SerialNumberOut;
        if (!serial) {
            isValid = false;
            return;
        }
        var list = gridData.filter(function (item) { return Number(item.SerialNumber) === Number(serial); });
        if (list.length > 1) {
            isValid = false;
            return;
        }
        list = serialList.filter(function (item) { return Number(item.SerialNumber) === Number(serial); });
        if (stateInOut === "1") {
            if (list.length > 0 && state === "1") {
                if (list[0].Count > 0) {
                    isValid = false;
                    return;
                }
            }
        }
        else {
            if (list.length === 0) {
                isValid = false;
                return;
            }
            else if (list[0].Count === 0) {
                isValid = false;
                return;
            }
        }
    });
    return isValid;
}
async function getLastPrice() {
    await ajax({
        url: "SaleApi/GetProductShopDetail",
        loading: false,
        data: {
            ProductId: productId,
            StoreCode: storeCode,
            DocumentTypeCode: getQuery("d"),
            IsShopMode: saleSystemCode === 2
        },
        success: function (result) {
            var price = (stateInOut === "1" ? result.LastPriceIn : result.LastPriceOut);
            if (price === 0)
                price = getQuery("fi");
            $("#txtFi").val(numberWithCommas(price));
        }
    });
}




