var gridBuilderNoSelect;
var gridBuilderSelect;
var productList;
var state = getQuery("state");
var documentData;
var errorList = [];
$(document).ready(function () {
    gridBuilderNoSelect = $("#grdList").gridBuilder();
    gridBuilderSelect = $("#grdSelectList").gridBuilder();
    gridBuilderNoSelect.onExportClick(function () {
        loadGrid("grdList", { exportExcel: true });
    });
    gridBuilderSelect.onExportClick(function () {
        loadGrid("grdSelectList", { exportExcel: true });
    });
    $("#cboProductGroup").lookupBuilder().onChanged(async function () {
        loadGrid("grdList");
    });
    if (state === "1") {
        $("#txtToDate").hide();
        $("#spanFromDate").hide();
        $("#spanTitle").text(window.top.rialiStoreDeleteHelp);
        $("#lblTextHeaderTo").text(window.top.rialiToDate2)
        $("#lblTextHeaderFrom").text(window.top.rialiFromDate)
    }
    else {
        $("#txtFromDate").hide();
        $("#spanToDate").hide();
        $("#spanTitle").text(window.top.rialiStoreHelp);
        $("#lblTextHeaderTo").text(window.top.rialiToDate)
        $("#lblTextHeaderFrom").text(window.top.rialiFromDate2)
    }
    initial();
});

async function initial() {
    await getAllRialProduct();
    loadGrid("grdList");
    closeLoading();
    $("#divMain").show();
}
async function getAllRialProduct() {
    await ajax({
        url: "SaleApi/GetProductList",
        data: {
            productGroupCode: $("#cboProductGroup").lookupBuilder().getSelectedValue(),
            pageNo: -1
        },
        success: function (data) {
            productList = data;
        }
    });
}
async function getRialStoreInfo() {
    var gridData = gridBuilderSelect.getDataArray()["data"];
    await ajax({
        loading: true,
        url: "SaleApi/GetRialStoreInfo",
        data: {
            toDate: $('#txtToDate').val(),
            productCodeList: gridData.map(function (item) { return item.Code; })
        },
        success: function (result) {
            setJsonValue(result);
        }
    });
}
async function getStoreDocumentForRial(date, arrNames) {
    await ajax({
        loading: true,
        url: "SaleApi/GetStoreDocumentForRial",
        data: { toDate: date, productCodeList: arrNames },
        success: function (result) {
            documentData = result;
        }
    });
    rialStoreDocument(arrNames, date);
}
async function rialStoreDocument(productCodeList, toDate) {
    if (documentData.length > 0) {
        //var j = Math.ceil(documentData.length / 100);
        var j = documentData.length;
        showLoading();
        var div = $("<div style='position:absolute;width:300px;top:50%;left:50%;margin-top:-150px;margin-left:-150px;padding:10px 20px;background-color:#fff;z-index:9999999999;border:1px dotted #aaa' class='progress-counter' ></div>");
        $(window.top.document).find("body").append(div);
        errorList = [];
        for (var i = 0; i < j; i++) {
            var toIndex = (100 * (i + 1));
            if (toIndex > documentData.length)
                toIndex = documentData.length;
            //var list = documentData.slice(100 * i, toIndex);
            //var desc = window.top.ongoingDocuments + " " + ((100 * i) + 1) + "-" + toIndex + " " + window.top._Az + " " + + documentData.length;
            var list = documentData.slice(i, i+1);
            var desc = window.top.ongoingDocuments + " " + (i) + " " + window.top._Az + " " + documentData.length;
            div.html("<p style='text-align:center'>" + desc + "</p>");
            var log = i === j - 1;
            var isSaveInState = i === 0;
            await saveRialStoreByArticleCode(list, log, isSaveInState, productCodeList, toDate);
        }
        if (errorList.length > 0) {
            showMsgModal(0, errorList.join("<br />"));
        }
        div.remove();
        closeLoading();
        SaveSuccess();
    }
}
async function getEventLookupCombo($combo, search, code) {
    var id = $combo.attr("id");
    if (!id)
        return;
    var result;
    await ajax({
        url: "SaleApi/GetProductGroupList",
        data: { search: search, pageNo: 1 },
        success: function (resValue) {
            result = resValue;
        }
    });
    $combo.lookupBuilder().bindData(result);
}
async function saveRialStoreByArticleCode(data, log, isSaveInState, productCodeList, toDate) {
    try {
        await ajax({
            url: "SaleApi/SaveRialStoreByArticleCode",
            data: { data: data, log: log, isSaveInState: isSaveInState, productCodeList: productCodeList, toDate: toDate },
            success: function (result) {

            },
            error: function (err) {
                if (window.top.loadCompletePage !== undefined)
                    window.top.loadCompletePage = true;
                var message, description = "";
                if (err.responseJSON && err.responseJSON.Message) {
                    message = err.responseJSON.Message;
                    description = err.responseJSON.Description;
                } else
                    message = err.responseText;
                if (!message || message.includes("network-related")) {
                    $(window.top.document).find(".progress-counter").remove();
                    closeLoading();
                    showConnectionError();
                }
                else {
                    errorList.push(message);
                }
            }
        });
    }
    catch {
        //ignore
    }
}

function loadGrid(gridId, objectParameter) {
    var isExportExcel = objectParameter && objectParameter.exportExcel ? true : false;
    var selected = gridId === "grdSelectList";
    var gridBuilder = selected ? gridBuilderSelect : gridBuilderNoSelect;
    var groupCode = Number($("#cboProductGroup").lookupBuilder().getSelectedValue() ? $("#cboProductGroup").lookupBuilder().getSelectedValue() : "");
    var data;
    if (selected)
        data = productList.filter(x => x.IsSelected);
    else
        data = productList.filter(x => !x.IsSelected && (groupCode <= 0 || x.CodeGroup === groupCode));

    if (isExportExcel)
        exportExcel(data, gridBuilder.getColumns(), gridBuilder.getColumnsCaption());
    else
        gridBuilder.loadData(data);
}
function addRemoveSingle(state) {
    var gridBuilder = state ? gridBuilderNoSelect : gridBuilderSelect;
    var codes = gridBuilder.getSelectedRowsCellValue("Code");
    if (codes.length === 0) {
        var activeRowCode = gridBuilder.getActiveRowCellValue("Code");
        if (activeRowCode)
            codes.push(activeRowCode);
    }
    changeSelectedCodes(codes, state);
}
function addRemoveAll(state) {
    var gridBuilder = state ? gridBuilderNoSelect : gridBuilderSelect;
    gridBuilder.setSelected(-1);
    var code = gridBuilder.getSelectedRowsCellValue('Code');
    changeSelectedCodes(code, state);
}
function changeSelectedCodes(value, state) {
    for (var i = 0; i < value.length; i++) {
        var item = productList.find(x => x.Code === Number(value[i]));
        item.IsSelected = state;
    }
    gridBuilderNoSelect.setUnselected(-1);
    gridBuilderSelect.setUnselected(-1);

    loadGrid("grdList");
    loadGrid("grdSelectList");
}
function selectAll(state) {
    var data;
    var groupCode = Number($("#cboProductGroup").lookupBuilder().getSelectedValue() ? $("#cboProductGroup").lookupBuilder().getSelectedValue() : "");
    if (state)
        data = productList.filter(x => !x.IsSelected && (groupCode <= 0 || x.CodeGroup === groupCode));
    else
        data = productList.filter(x => x.IsSelected);

    for (var i = 0; i < data.length; i++) {
        data[i].IsSelected = state;
    }
    gridBuilderNoSelect.setUnselected(-1);
    gridBuilderSelect.setUnselected(-1);

    loadGrid("grdList");
    loadGrid("grdSelectList");
}
function save() {
    var gridData = gridBuilderSelect.getDataArray()["data"];
    var arrNames = gridData.map(function (item) { return item.Code; });
    var date = $("#" + (getQuery("state") == "1" ? "txtFromDate" : "txtToDate")).val();
    if (gridData.length > 0) {
        if (getQuery("state") == "1")
            ajax({
                loading: true,
                url: "SaleApi/DeleteRialStore",
                data: { fromDate: date, productCodeList: arrNames },
                success: function (result) {
                    SaveSuccess();
                }
            });
        else
            getStoreDocumentForRial(date, arrNames);
    }
    else {
        showMsgModal(0, window.top.selectProduct);
    }
}
function SaveSuccess() {
    $('#step1').hide();
    $('#step2').hide();
    $('#step3').hide();
    $('#step4').show();
    getRialStoreInfo();
    refreshParent("refresh()");
}
function nextStep1() {
    $('#step1').hide();
    $('#step2').show();
}
function nextStep2() {
    $('#step1').hide();
    $('#step2').hide();
    $('#step3').show();
    getRialStoreInfo();
}
function goStep1() {
    $('#step1').show();
    $('#step2').hide();
}
function goStep2() {
    $('#step2').show();
    $('#step3').hide();
}
function goStep3() {
    $('#step3').show();
    $('#step4').hide();
}





