var dataList = [];
var gridBuilderNoSelect;
var gridBuilderSelect;
var _state = getQuery("state");
var currencyCode = getQuery("currencyCode");
var baseDocumentCode = getQuery("baseDocumentCode");
var articleBaseCode = getQuery("articleBaseCode");
var factorSelectedValue;
$(document).ready(function () {
    setComboCaption("cboFactor", getQuery("title"));
    gridBuilderNoSelect = $("#gridNoSelect").gridBuilder();
    gridBuilderSelect = $("#gridSelect").gridBuilder();
    $("#cboTarafH").lookupBuilder().onChanged(function () {
        $("#cboFactor").lookupBuilder().setSelectedValue("");
    });
    $("#cboStore").lookupBuilder().onChanged(function () {
        $("#cboFactor").lookupBuilder().setSelectedValue("");
    });
    $("#cboFactor").lookupBuilder().onChanged(async function () {
        var selectedValue = $("#cboFactor").lookupBuilder().getSelectedValue();
        var factorId;
        if (selectedValue) {
            factorId = selectedValue.split("|")[4];
            await getPreInvoice(factorId);
            if (baseDocumentCode && articleBaseCode) {
                dataList.forEach(function (item) {
                    var articles = articleBaseCode.split(',').map(function (x) { return { Id: Number(x) } });
                    if (articles.find(x => x.Id === item.ArticleBaseCode))
                        item.IsSelected = true;
                });
                dataList = dataList.filter(x => x.IsSelected || (!x.IsSelected && x.RemainAmount > 0));
            }
            else {
                dataList = dataList.filter(x => x.RemainAmount > 0);
            }
            loadGrid("gridSelect");
            loadGrid("gridNoSelect");
        }
        else {
            dataList = [];
            gridBuilderSelect.clearRows();
            gridBuilderNoSelect.clearRows();
        }

    });
    gridBuilderNoSelect.onExportClick(function () {
        loadGrid("gridNoSelect", { exportExcel: true });
    });
    gridBuilderSelect.onExportClick(function () {
        loadGrid("gridSelect", { exportExcel: true });
    });
    initial();
});

async function initial() {
    await $("#cboTarafH").lookupBuilder().setSelectedValue(getQuery("codeTrafH"));
    await $("#cboStore").lookupBuilder().setSelectedValue(getQuery("codeAnbar"));
    if (baseDocumentCode) {
        await getEventLookupCombo($("#cboFactor"));
        await $("#cboFactor").lookupBuilder().setSelectedValue(factorSelectedValue);
        $("#cboFactor").lookupBuilder().setEnabled(false);
        $("#cboTarafH").lookupBuilder().setEnabled(false);
        $("#cboStore").lookupBuilder().setEnabled(false);
    }
    closeLoading();
    $("#divMain").show();
}

async function getEventLookupCombo($combo, search) {
    var id = $combo.attr('id');
    if (id === "cboTarafH") {
        await ajax({
            url: "GeneralApi/GetCustomerList",
            data: { type: -1, search: search, filter: "", sort: "", pageNo: -1, selectedCode: getObjectValue("cboTarafH", 0) },
            success: function (result) {
                result.forEach(function (item) {
                    item.Code += "|" + item.CurrencyCode + "|" + item.CurrencyDecimalCount;
                });
                $combo.lookupBuilder().bindData(result);
            }
        });
    }
    else if (id === "cboStore") {
        await ajax({
            url: "SaleApi/GetStoreList",
            data: { creditType: 0, search: search, filter: "", sort: "", pageNo: -1, selectedCode: "" },
            success: function (result) {
                $combo.lookupBuilder().bindData(result);
            }
        });
    }
    else if (id === "cboFactor") {
        var data;
        await ajax({
            url: "SaleApi/GetBasisDocumentList",
            data: {
                documentTypeCode: _state || null,
                storeCode: $("#cboStore").lookupBuilder().getSelectedValue() || null,
                customerCode: getObjectValue("cboTarafH", 0),
                currencyCode: currencyCode || null,
                search: search,
                filter: "",
                sort: "",
                pageNo: -1,
                factorSerial: baseDocumentCode || null,
                hasRemained: !baseDocumentCode || null
            },
            success: function (result) {
                data = result;
            }
        });
        var data2 = [];
        for (var i = 0; i < data.length; i++) {
            var item = data[i];
            item.Code = item.FactorNo + "|" + item.CustomerCode + "|" + item.CurrencyCode + "|" + item.DecimalCount + "|" + item.FactorSerial + "|" + item.CurrencyRate + "|" + item.NumberingSave + "|" + item.DocumentTypeParentCode + "|" + item.CodeAtf;
            item.Name = item.FactorNo + " | " + item.FactorDateLocal + " | " + item.CustomerName + " | " + numberWithCommas(item.TotalPrice, item.DecimalCount);
            if (baseDocumentCode)
                factorSelectedValue = item.Code;
            data2.push(item);
        }
        $combo.lookupBuilder().bindData(data2);
    }
}

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];
        }
    }
}

function loadGrid(gridId, objectParameter) {
    var isExportExcel = objectParameter && objectParameter.exportExcel ? true : false;
    var selected = gridId === "gridSelect";
    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 save() {
    var data = dataList.filter(x => x.IsSelected);
    if (data.length === 0) {
        showMsgModal(0, window.top.detailDocumentNotSelected);
        return;
    }
    var selectedFactor = $("#cboFactor").lookupBuilder().getSelectedValue().split("|");
    var tarafHCode = selectedFactor[1];
    var currencyCode = selectedFactor[2];
    var currencyDecimalCount = selectedFactor[3];
    var currencyRate = selectedFactor[5];
    var numberingSave = selectedFactor[6];
    var documentTypeParentCode = selectedFactor[7];
    var codeAtf = selectedFactor[8];
    refreshParent('setDataPreInvoice(' + JSON.stringify(data) + ',' + tarafHCode + ',' + $("#cboStore").lookupBuilder().getSelectedValue() + ',' + currencyCode + ',' + currencyDecimalCount + ',' + currencyRate + ',' + selectedFactor[4] + ',' + numberingSave + ',' + documentTypeParentCode + ',' + codeAtf +')');
    closeTopModal();
}

function AddSingle() {
    var codes = gridBuilderNoSelect.getSelectedRowsCellValue("Code");
    if (codes.length === 0) {
        var activeRowCode = gridBuilderNoSelect.getActiveRowCellValue("Code");
        if (activeRowCode)
            codes.push(activeRowCode);
    }
    addRightToLeftKala(codes);
}
function addRightToLeftKala(value) {
    for (var i = 0; i < value.length; i++) {
        var item = dataList.find(x => x.Code == Number(value[i]));
        item.IsSelected = true;
    }
    gridBuilderNoSelect.setUnselected(-1);
    gridBuilderSelect.setUnselected(-1);

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

    loadGrid("gridNoSelect");
    loadGrid("gridSelect");
}
function removeAll() {
    gridBuilderSelect.setSelected(-1);
    var code = gridBuilderSelect.getSelectedRowsCellValue('Code');
    addLeftToRightKala(code);
}

async function getPreInvoice(factorId) {
    await ajax({
        url: "SaleApi/GetPreInvoice",
        data: { factorId: factorId },
        success: function (data) {
            dataList = data;
        }
    });
}
