var firstLoad = true;
var dataList = [];
var gridBuilderNoSelect;
var gridBuilderSelect;
$(document).ready(function () {
    gridBuilderNoSelect = $("#gridListNoSelect").gridBuilder();
    gridBuilderSelect = $("#gridListSelect").gridBuilder();
    getEventLookupCombo($("#cboCurrency"));
    $(".go-step").on("click", function () {
        var level = $(this).attr("data-target");
        if (level === "step2") {
            var exceptionText = checkValidation('');
            if (exceptionText === "")
                getCurrencyConquest();
            else {
                showMsgModal(0, exceptionText);
                return;
            }
        }
        else if (level === "step3") {
            if (gridBuilderSelect.getRowsCount() === 0) {
                showMsgModal(0, window.top.noSelectExportConfirmation);
                return;
            }
        }
        else if (level === "step4") {
            var selectedData = gridBuilderSelect.getDataArray()["data"];
            $("#hfSelectedData").val(JSON.stringify(selectedData));
            redirectUrl("InvoiceSave?taseer=1", "iframe-InvoiceSave");
        }
        showDiv(level);
        return false;
    });
    gridBuilderNoSelect.onExportClick(function () {
        loadGrid("gridListNoSelect", { exportExcel: true });
    });
    gridBuilderSelect.onExportClick(function () {
        loadGrid("gridListSelect", { exportExcel: true });
    });
});

function mapSelectedData(data) {
    var newData = [];
    data.forEach(function (item) {
        newData.push({});
    });
}
function getCurrencyConquest() {
    ajax({
        url: "AccountingApi/GetCurrencyConquest",
        data: {
            currencyCode: $("#cboCurrency").lookupBuilder().getSelectedValue(),
            currencyRate: $("#txtCurrencyRate").val(),
            toDate: $("#txtDate").val(),
            filter: gridBuilderNoSelect.getFilter(),
            sort: gridBuilderNoSelect.getSortFields(),
            pageNo: -1
        },
        success: function (data) {
            dataList = data;
            loadGrid("gridListNoSelect");
        }
    });
}
function loadGrid(gridId, objectParameter) {
    var isExportExcel = objectParameter && objectParameter.exportExcel ? true : false;
    var selected = gridId === "gridListSelect";
    var gridBuilder = selected ? gridBuilderSelect : gridBuilderNoSelect;

    var data = [];
    if (selected)
        data = dataList.filter(x => x.IsSelected);
    else
        data = dataList.filter(x => !x.IsSelected);

    if (isExportExcel)
        exportExcel(data, gridBuilder.getColumns(), gridBuilder.getColumnsCaption());
    else
        gridBuilder.loadData(data);
}
function getEventLookupCombo($combo, search, code) {
    var baseCurrencyCode = window.top.$("#hfBaseCurrencyCode").val();
    var id = $combo.attr('id');
    var url = "";
    var data = null;
    switch (id) {
        case "cboCurrency":
            url = "GeneralApi/GetCurrencyList";
            data = { search: search, filter: "", pageNo: 1, selectedCode: code };
            break;
        case "cboTafzil": case "cboMarkazHazine": case "cboProject":
            var level = Number($combo.parent().attr('data-level'));
            url = "AccountingApi/GetTafsilList";
            data = { moainCode: $("#cboMoain").lookupBuilder().getSelectedValue().split("|")[0], level: level, search: search, pageNo: 1, selectedCode: code };
            break;
        case "cboMoain":
            url = "AccountingApi/GetMoainList";
            data = { checkActive: false, search: search, selectedCode: code, pageNo: 1 };
            break;
    }
    ajax({
        url: url,
        data: data,
        success: function (result) {
            switch (id) {
                case "cboMoain":
                    $.each(result, function () {
                        this.Code = this.Code + "|" + this.ChildCount + "|" + this.ChildCountM + "|" + this.ChildCountP;
                    });
                    break;
                case "cboCurrency":
                    result = result.filter(function (item) { return item.Code.toString() !== baseCurrencyCode; });
                    break;
                case "cboTafzil": case "cboProject": case "cboMarkazHazine":
                    result.forEach(function (item) {
                        item.Code = item.Id;
                    });
            }
            $combo.lookupBuilder().bindData(result);
            if (firstLoad && result.length > 0 && id === "cboCurrency") {
                firstLoad = false;
                $combo.lookupBuilder().setSelectedValue(result[0].Code);
            }
        }
    });
}
function showDiv(level) {
    $(".div-step").hide();
    $("#" + level).show();
}
function cboMoainSelectedIndexChange() {
    var selectedMoain = $("#cboMoain").lookupBuilder().getSelectedValue().split("|");
    $("#cboTafzil").lookupBuilder().setEnabled(Number(selectedMoain[1]) > 0);
    if (Number(selectedMoain[1]) === 0)
        $("#cboTafzil").lookupBuilder().clearItems();

    $("#cboMarkazHazine").lookupBuilder().setEnabled(Number(selectedMoain[2]) > 0);
    if (Number(selectedMoain[2]) === 0) 
        $("#cboMarkazHazine").lookupBuilder().clearItems();

    $("#cboProject").lookupBuilder().setEnabled(Number(selectedMoain[3]) > 0);
    if (Number(selectedMoain[3]) === 0) 
        $("#cboProject").lookupBuilder().clearItems();
}
function getCurrencyRate() {
    ajax({
        loading: true,
        url: 'SaleApi/GetCurrencyRate',
        data: {
            currencyCode: $("#cboCurrency").lookupBuilder().getSelectedValue(),
            date: $("#txtDate").val()
        },
        success: function (retValue) {
            $("#txtCurrencyRate").val(retValue.PriceInReal);
        }
    });
}
function AddSingle() {
    var codes = gridBuilderNoSelect.getSelectedRowsCellValue("__RowNo_");
    if (codes.length === 0) {
        var activeRowCode = gridBuilderNoSelect.getActiveRowCellValue("__RowNo_");
        if (activeRowCode)
            codes.push(activeRowCode);
    }
    addRightToLeft(codes);
}
function addRightToLeft(value) {
    for (var i = 0; i < value.length; i++) {
        var item = dataList.find(x => x.__RowNo_ == Number(value[i]));
        item.IsSelected = true;
    }
    gridBuilderNoSelect.setUnselected(-1);
    gridBuilderSelect.setUnselected(-1);

    loadGrid("gridListNoSelect");
    loadGrid("gridListSelect");
}
function AddAll() {
    gridBuilderNoSelect.setSelected(-1);
    var code = gridBuilderNoSelect.getSelectedRowsCellValue('__RowNo_');
    addRightToLeft(code);
}
function removeSingle() {
    var codes = gridBuilderSelect.getSelectedRowsCellValue('__RowNo_');
    if (codes.length === 0) {
        var activeRowCode = gridBuilderSelect.getActiveRowCellValue("__RowNo_");
        if (activeRowCode)
            codes.push(activeRowCode);
    }
    addLeftToRight(codes);
}
function addLeftToRight(value) {
    for (var i = 0; i < value.length; i++) {
        var item = dataList.find(x => x.__RowNo_ == Number(value[i]));
        item.IsSelected = false;
    }
    gridBuilderNoSelect.setUnselected(-1);
    gridBuilderSelect.setUnselected(-1);

    loadGrid("gridListNoSelect");
    loadGrid("gridListSelect");
}
function removeAll() {
    gridBuilderSelect.setSelected(-1);
    var code = gridBuilderSelect.getSelectedRowsCellValue('__RowNo_');
    addLeftToRight(code);
}
async function save() {
    await saveDocument();
    redirectUrl();
}
async function saveDocument() {
    var childDocument = $("#iframe-InvoiceSave")[0].contentDocument;
    $(childDocument).find("#btnSaveTemp").click();
}