var documentCode = getQuery("codeSanad");
var state = Number(getQuery("state"));
var currencyCode = getQuery("currencyCode");
var currencyDecimalCount = getQuery("currencyDecimalCount");
var currencyName = getQuery("currencyName");
var roundingLimit = 0;
var marketState = 30;
var sale = -1;
var chequeManagerList;

var dataTable = [];
var modelFromCheque = [];
var typeId = 0;
var payable = 0;
var sumAmount = 0;
var insertedId = 1;
var checkToFundChoose = [];
var modelCheckToFund = [];
var listUsedNumberCheque = [];
var imgDelete = '<img src="../img/delete.svg" style="width:20px;" />';

var baseCurrencyCode = window.top.$("#hfBaseCurrencyCode").val();
var baseCurrencyDecimalCount = window.top.$("#hfDecimalCount").val();
var baseCurrencyName = window.top.$("#hfBaseCurrencyName").val();

$(document).ready(function () {
    if (window.top.$("#hfLanguage").val() != "fa")
        $("#cboCheckBank").parent().hide();

    var amount = getQuery("amount");
    if (!currencyCode)
        currencyCode = baseCurrencyCode;
    if (currencyDecimalCount === "")
        currencyDecimalCount = baseCurrencyDecimalCount;
    if (!currencyName)
        currencyName = baseCurrencyName;

    $("#txtAmountPos").prop("disabled", false);
    $("#lblCurrencyPos").text(currencyName);
    if (state === marketState || state === sale) {
        $("#lblDetails").text(window.top.receivedDetails);
        $("#thCashCh").text(window.top.receivedCashDesk);
        $("#lblSumAmount").text(window.top.amountReceivable);
        $("#lblTitle").text(window.top.receivedData);
        $("#thMablaghCR").text(window.top.receivedAmount);
        $("#thMablaghC").text(window.top.receivedAmount);
        $("#lblAmountPos").text(window.top.receivedAmount);
        $("#lblAmount1").text(window.top.receivedAmount);
        $("#lblAmount22").text(window.top.receivedAmount);
        $("#lblAmount33").text(window.top.receivedAmount);
        $("#readCard").text(window.top.pos);
        $("#txtAmount3").val(amount);
        if (Number(baseCurrencyCode) === Number(currencyCode))
            $("#roundDiv").show();
        else
            $("#roundDiv").hide();
        $("#checkPeyment").hide();
        setComboCaption("cboCashRecitp", window.top.receivedCashDesk);
        if (state === sale)
            $("#check").show();
        else {
            $("#divNumberRecid").hide();
            $("#divCashRecitp").hide();
            $("#divTel").hide();
            $("#divDescriptionCheck").hide();
            $("#divCash1").hide();
            $("#thCash").hide();
            $("#thCodePeygiriN").hide();
            $("#thCashCh").hide();
            $("#thTelC").hide();
            $("#check").hide();
        }

    }
    else {
        $("#lblDetails").text(window.top.paymentDetails);
        $("#thCashCh").text(window.top.paymentCashDesk);
        $("#lblSumAmount").text(window.top.amountPayable);
        $("#lblTitle").text(window.top.paymentData);
        $("#thMablaghCR").text("");
        $("#thMablaghC").text(window.top.paymentAmount);
        $("#lblAmountPos").text(window.top.paymentAmount);
        $("#lblAmount22").text(window.top.paymentAmount);
        $("#lblAmount33").text(window.top.paymentAmount);
        $("#readCard").text(window.top.withdraw);
        $("#roundDiv").hide();
        $("#checkPeyment").show();
        $("#check").hide();
        $("#txtAmount22").val(amount);
        $("#txtAmountCheckToFound").val(amount);
        $("#btnSendToPos").parent().hide();
        setComboCaption("cboCashRecitp", window.top.paymentCashDesk);
    }

    $("#lblDateFactor").text(getQuery("date"));
    $("#lblTarafh").text(getQuery("tarafH"));
    $("#lblAmountReceived").text(amount);
    $("#lblRemained").text(amount);
    $("#txtAmount1").val(amount);
    $("#txtAmountPos").val(amount);

    $("[data-mask='price']").attr("data-decimalCount", currencyDecimalCount);

    $(".main-title").click(function () {
        $('.main-title').removeClass("selected-tab-title");
        $(this).addClass("selected-tab-title");
        $('#divPonyMain>div').hide();
        $('#divTab' + $('.selected-tab-title').attr('data-id')).show();
        typeId = Number($(this).attr('data-id'));
    });
    payable = $('#txtAmount1').val();
    initial();

});
function getType(state, update) {
    var chooseType;
    if (state === 0) {
        if (update.TrsType === 2 && !update.ChequeBookCode)
            chooseType = 222;
        else if (update.TrsType === 2 && update.ChequeBookCode)
            chooseType = 22;
        else
            chooseType = update.TrsType;
    }
    else
        chooseType = update.TrsType;
    return chooseType;
}
function pushDataToTable() {
    dataTable.push({
        'id': insertedId,
        'Mablagh': getAmount(),
        'CodeSandog': getCashInfo(true),
        'NameSandogh': getCashInfo(false),
        'Code_Paygri': getCodeTracking(),
        'CodeBank': getBankInfo(true),
        'NameBankCheck': getBankInfo(false),
        'Date_Paygri': getPaygiry(),
        'TelEtc': $('#txtTel').val(),
        'Sumery': getSummery(),
        'CodeTarafHesab': getQuery('tarafHCode'),
        'Trs_Type': typeId === 22 || typeId === 222 ? 2 : typeId,
        'type': typeId,
        'CodeNoeAmaliyat': typeId === 222 ? 7 : -1,
        'CoderizKharjchek': typeId === 222 ? modelFromCheque.ArticleCode : -1,
        'NameMahal': typeId === 222 ? modelFromCheque.BankCashDeskName : '',
        'Code_Dastachak': typeId === 22 ? Number($("#cboChequeBook").lookupBuilder().getSelectedValue().split("/")[0]) : -1,
        'CurrencyName': typeId === 222 ? modelFromCheque.CurrencyName : currencyName
    });
    if (typeId === 22) {
        listUsedNumberCheque.push({ numberCheque: $("#cboNumberCheque").lookupBuilder().getSelectedValue(), dastehCheque: $("#cboChequeBook").lookupBuilder().getSelectedValue().split("/")[0] });
        $("#cboNumberCheque").lookupBuilder().setSelectedValue("");
    }
    modelFromCheque = [];
    insertedId++;
}
function setDataToPonyCheque(value) {
    typeId = 222;
    var isNew = false;
    for (var i = 0; i < value.length; i++) {
        if (!checkToFundChoose.includes(value[i])) {
            isNew = true;
            checkToFundChoose.push(value[i]);
        }
    }
    if (isNew)
        addToTable();
}
function addToTable() {
    var error = '';
    if (typeId !== 222)
        error = checkValidInfo();
    if (error === '') {
        addToModel();
        setToTable();
        showTable();
        setAmount();
    }
    else {
        showMsgModal(0, error);
    }
}
function checkValidInfo() {
    var error = '';
    var amount = 0;
    switch (typeId) {
        case 0:
            error += checkValidation('#divTab0');
            amount = numberNonCommas($('#txtAmount1').val(), 0);
            break;
        case 1:
            error += checkValidation('#divTab1');
            amount = numberNonCommas($('#txtAmountPos').val(), 0);
            break;
        case 2:
            error += checkValidation('#divTab2');
            amount = numberNonCommas($('#txtAmount3').val(), 0);
            break;
        case 22:
            error += checkValidation('#divTab22');
            amount = numberNonCommas($('#txtAmount22').val(), 0);
            break;
    }
    if (amount === 0)
        error += window.top.priceNotNull;

    return error;
}
function setAmount() {
    if (payable >= 0) {
        $('#txtAmount1').val(payable);
        $('#txtAmountPos').val(payable);
        $('#txtAmount3').val(payable);
        $('#txtAmount22').val(payable);
        $('#txtAmountCheckToFound').val(payable);
    }
    else {
        $('#txtAmount1').val(0);
        $('#txtAmountPos').val(0);
        $('#txtAmount3').val(0);
        $('#txtAmount22').val(0);
        $('#txtAmountCheckToFound').val(0);
    }
    $('#lblAmountPeyment').text(numberWithCommas(sumAmount));

}
function showTable() {
    if (dataTable.some(x => x.type === 0))
        $('#divCash').show();
    if (dataTable.some(x => x.type === 1))
        $('#divCardReader').show();
    if (dataTable.some(x => x.type === 2))
        $('#divCheck').show();
    if (dataTable.some(x => x.type === 22))
        $('#divCheckPayment').show();
    if (dataTable.some(x => x.type === 222)) {
        typeId = 22;
        $('#divCheckToFund').show();
    }
}
function setToTable() {
    var i;
    var tag;
    var summery;
    var model = dataTable.filter(function (item) { return (item.type === 0); });
    $('#bodyCash').empty();
    for (i = 0; i < model.length; i++) {
        if (state === marketState)
            $('#bodyCash').append('<tr><td>' + numberWithCommas(model[i].Mablagh) + '</td><td><a href="#header" onclick="deleteRow(' + model[i].id + ')">' + imgDelete + '</a></td></tr>');
        else
            $('#bodyCash').append('<tr><td>' + numberWithCommas(model[i].Mablagh) + '</td><td>' + model[i].NameSandogh + '</td><td>' + model[i].Code_Paygri + '</td><td><a href="#header" onclick="deleteRow(' + model[i].id + ')">' + imgDelete + '</a></td></tr>');
    }

    model = dataTable.filter(function (item) { return (item.type === 1); });
    $('#bodyCardReader').empty();
    for (var i = 0; i < model.length; i++) {
        $('#bodyCardReader').append('<tr><td>' + numberWithCommas(model[i].Mablagh) + '</td><td>' + model[i].NameBankCheck + '</td><td>' + model[i].Code_Paygri + '</td><td><a href="#header" onclick="deleteRow(' + model[i].id + ')">' + imgDelete + '</a></td></tr>');
    }

    $('#bodyCheck').empty();
    model = dataTable.filter(function (item) { return (item.type === 2); });
    for (i = 0; i < model.length; i++) {

        if (state === marketState) {
            tag = '<tr>' +
                ' <td colspan="5" class="no-padding-bottom" style="border-top: none;">' +
                '<table style="width: 100%">' +
                '<tbody>' +
                '<tr style="line-height: 16px;">' +
                '<td>' + numberWithCommas(model[i].Mablagh) + '</td>' +
                '<td>' + model[i].NameBankCheck + '</td>' +
                '<td>' + model[i].Code_Paygri + '</td>' +
                '<td>' + model[i].Date_Paygri + '</td>' +
                '<td><a href="#header" onclick="deleteRow(' + model[i].id + ')">' + imgDelete + '</a></td>' +
                '</tr>';
            $('#bodyCheck').append(tag);
        }
        else {
            tag =
                '<tr style="line-height: 16px;">' +
                '<td>' + numberWithCommas(model[i].Mablagh) + '</td>' +
                '<td>' + model[i].NameSandogh + '</td>' +
                '<td>' + model[i].NameBankCheck + '</td>' +
                '<td>' + model[i].Code_Paygri + '</td>' +
                '<td>' + model[i].Date_Paygri + '</td>' +
                '<td>' + model[i].TelEtc + '</td>' +
                '<td><a href="#header" onclick="deleteRow(' + model[i].id + ')">' + imgDelete + '</a></td>' +
                '</tr>' +
                '<tr>' +
                '<td colspan="7" style="border-top:none;border-bottom: 1px solid #cccccc; line-height: 30px;">' + window.top.desc + ':' + (model[i].Sumery ? model[i].Sumery : "----") + '</td>' +
                '</tr>';
            $('#bodyCheck').append(tag);
        }
    }

    model = dataTable.filter(function (item) { return (item.type === 22); });
    $('#bodyCheckPayment').empty();
    for (var i = 0; i < model.length; i++) {
        tag =
            '<tr style="line-height: 16px;">' +
            '<td>' + numberWithCommas(model[i].Mablagh) + '</td>' +
            '<td>' + model[i].NameBankCheck + '</td>' +
            '<td>' + model[i].Code_Paygri + '</td>' +
            '<td>' + model[i].Date_Paygri + '</td>' +
            '<td><a href="#header" onclick="deleteRow(' + model[i].id + ')">' + imgDelete + '</a></td>' +
            '</tr>' +
            '<tr>' +
            '<td colspan="5" style="border-top:none;border-bottom: 1px solid #cccccc; line-height: 30px;">' + window.top.desc + ':' + (model[i].Sumery ? model[i].Sumery : "----") + '</td>' +
            '</tr>';
        $('#bodyCheckPayment').append(tag);
    }

    model = dataTable.filter(function (item) { return (item.type === 222); });
    $('#bodyCheckToFund').empty();
    for (var i = 0; i < model.length; i++) {
        $('#bodyCheckToFund').append("<tr data-chequeId='" + model[i].CoderizKharjchek + "'><td>" + model[i].Code_Paygri + '</td><td>' + model[i].Date_Paygri + '</td>' +
            '<td>' + numberWithCommas(model[i].Mablagh) + '</td><td>' + model[i].NameBankCheck + '</td><td>' + model[i].NameMahal + '</td><td><a href="#header" onclick="deleteRow(' + model[i].id + ')">' + imgDelete + '</a></td></tr>');
    }

}
function hideTable() {
    if (dataTable.filter(function (item) { return (item.type === 0); }).length === 0)
        $('#divCash').hide();
    if (dataTable.filter(function (item) { return (item.type === 1); }).length === 0)
        $('#divCardReader').hide();
    if (dataTable.filter(function (item) { return (item.type === 2); }).length === 0)
        $('#divCheck').hide();
    if (dataTable.filter(function (item) { return (item.type === 22); }).length === 0)
        $('#divCheckPayment').hide();
    if (dataTable.filter(function (item) { return (item.type === 222); }).length === 0)
        $('#divCheckToFund').hide();
}
function deleteRow(id) {
    if (confirm(window.top.confirmMsg)) {
        var firsDataCheckOfFund = dataTable.find(c => c.id == id);
        if (firsDataCheckOfFund.type === 222) {
            checkToFundChoose = checkToFundChoose.filter(function (item) {
                return (item != firsDataCheckOfFund.CoderizKharjchek);
            });
        }
        var item = dataTable.filter(function (item) { return item.id === id; })[0];
        if (item.Trs_Type === 2) {
            listUsedNumberCheque = listUsedNumberCheque.filter(function (value) { return value.numberCheque !== item.Code_Paygri && value.dastehCheque !== item.Code_Dastachak; });
        }
        dataTable = dataTable.filter(function (item) { return (item.id != id); });
        setToTable();
        refreshAmount();
    }
    hideTable();
}
function refreshAmount() {
    var amounts = 0;
    for (var i = 0; i < dataTable.length; i++) {
        amounts += dataTable[i].Mablagh;
    }
    var received = numberNonCommas($('#lblAmountReceived').text(), 0);
    $('#lblAmountPeyment').text(numberWithCommas(amounts));
    payable = Number((received - Number(amounts)).toFixed(currencyDecimalCount));
    $('#lblRemained').text(numberWithCommas(payable));
    setRemainedTypeName(payable);

    sumAmount = amounts;
    setAmount();
}
function setRemainedTypeName(payable) {
    var color = "#00796B";
    var remainedTypeName = "";
    if (state !== 1) {
        if (payable > 0) {
            remainedTypeName = window.top.cashierDebt;
            color = "#1565C0";
        }
        else if (payable < 0) {
            remainedTypeName = window.top.cashierExtraReceive;
            color = "#C62828";
        }
    }
    else {
        if (payable > 0) {
            remainedTypeName = window.top.cashierCredit;
            color = "#1565C0";
        }
        else if (payable < 0) {
            remainedTypeName = window.top.cashierOverpayment;
            color = "#C62828";
        }
    }
    $('#lblRemainedName').text(window.top.balance + (payable !== 0 ? " " + "(" + remainedTypeName + ")" : ""));
    $('#lblRemainedName').closest(".remained-row").css({ color: color });
}
function addToModel() {
    if (typeId === 222) {
        dataTable = dataTable.filter(function (item) { return (item.type !== 222); });
        for (var i = 0; i < checkToFundChoose.length; i++) {
            modelFromCheque = chequeManagerList.find(c => c.ArticleCode == checkToFundChoose[i]);
            pushDataToTable();
        }
    }
    else {
        pushDataToTable();
    }
}
function getSummery() {
    var summery = "";
    if (typeId === 2)
        summery = $('#txtDescriptionCheck').val();
    else if (typeId === 22)
        summery = $('#txtDescription1').val();
    else if (typeId === 222)
        summery = modelFromCheque.ArticleSummery;
    return summery;
}
function getPaygiry() {
    var date = '';
    if (typeId === 2)
        date = $('#txtDateHeader').val();
    else if (typeId === 22)
        date = $('#txtDateHeader1').val();
    else if (typeId === 222)
        date = modelFromCheque.TrackingDateLocal;
    return date;
}
function getBankInfo(isValue) {
    var codeBank;
    switch (typeId) {
        case 1:
            codeBank = isValue ? $("#cboBankPos").lookupBuilder().getSelectedValue().split("|")[0] : $("#cboBankPos").lookupBuilder().getSelectedText();
            break;
        case 2:
            codeBank = isValue ? -1 : $("#cboCheckBank").lookupBuilder().getSelectedText();
            break;
        case 22:
            codeBank = isValue ? Number($("#cboChequeBook").lookupBuilder().getSelectedValue().split('/')[1]) : $("#cboChequeBook").lookupBuilder().getSelectedText();
            break;
        case 222:
            codeBank = isValue ? -1 : modelFromCheque.BankName;
            break;
        default:
            codeBank = isValue ? -1 : '';
            break;
    }
    return codeBank;
}
function openModalPonyCheque() {
    var title = window.top.checksAtCash;
    var width = "1000";
    var src = "Sale/PonyCheque?chequeCode=" + checkToFundChoose.join(",") + "&remained=" + $('#lblRemained').text() + "&received=" + $('#lblAmountReceived').text() + "&currency=" + currencyCode + "&currencyName=" + currencyName + "&currencyDecimalCount=" + currencyDecimalCount;
    openInModal('', src, title, width);
}
function getCashInfo(isValue) {
    var cash = isValue ? -1 : '';
    switch (typeId) {
        case 0:
            if ($('#cboCash').length === 1)
                cash = isValue ? $("#cboCash").lookupBuilder().getSelectedValue() : $("#cboCash").lookupBuilder().getSelectedText();
            break;
        case 2:
            if ($('#cboCashRecitp').length === 1)
                cash = isValue ? $("#cboCashRecitp").lookupBuilder().getSelectedValue() : $("#cboCashRecitp").lookupBuilder().getSelectedText();
            break;
    }
    return cash;
}
function getCodeTracking() {
    var tracking = '';
    switch (typeId) {
        case 0:
            if ($('#txtTrackingCode').length === 1)
                tracking = $('#txtTrackingCode').val();
            break;
        case 1:
            if ($('#txtCodePeygiriPos').length === 1)
                tracking = $('#txtCodePeygiriPos').val();
            break;
        case 2:
            if ($('#txtCodeCheck').length === 1)
                tracking = $('#txtCodeCheck').val();
            break;
        case 22:
            if ($('#cboNumberCheque').length === 1)
                tracking = $("#cboNumberCheque").lookupBuilder().getSelectedText();
            break;
        case 222:
            tracking = modelFromCheque.ChequeNumber;
            break;
    }
    return tracking;
}
function getAmount() {
    var amount = 0;
    switch (typeId) {
        case 0:
            amount = numberNonCommas($('#txtAmount1').val(), 0);
            break;
        case 1:
            amount = numberNonCommas($('#txtAmountPos').val(), 0);
            break;
        case 2:
            amount = numberNonCommas($('#txtAmount3').val(), 0);
            break;
        case 22:
            amount = numberNonCommas($('#txtAmount22').val(), 0);
            break;
        case 222:
            amount = Number(modelFromCheque.CurrencyPrice);
            break;
    }
    if ($("#bodyCheckToFund").find("tr[data-chequeid='" + modelFromCheque.ArticleCode + "']").length === 0) {
        sumAmount += amount;
        sumAmount = Number(sumAmount.toFixed(currencyDecimalCount));
        payable = Number((numberNonCommas(payable) - amount).toFixed(currencyDecimalCount));
        $('#lblRemained').text(numberWithCommas(payable));
        setRemainedTypeName(payable);
    }


    return amount;
}
function saveChange() {
    var control = true;
    var message = "";
    var isRound = $('#chkRound').prop('checked');
    if (isRound) {
        var remindValue = numberNonCommas($('#lblRemained').text(), 0);
        var remindDecimal = Number(Number(remindValue.toString().substr(remindValue.toString().length - roundingLimit.toString().length)).toFixed(currencyDecimalCount));
        if (remindDecimal < 0 || remindDecimal > roundingLimit) {
            showMsgModal(0, window.top.amountCeiling + numberWithCommas(roundingLimit) + ' ' + baseCurrencyName + '  ' + window.top.is);
            $('#chkRound').prop('checked', false);
            return;
        }
    }
    var payedAmount = numberNonCommas($('#lblAmountPeyment').text(), 0);
    var mainAmount = numberNonCommas($('#lblAmountReceived').text(), 0);
    var isPos = getQuery("type") === "pos";
    if (payedAmount > mainAmount) {
        if (isPos)
            message = window.top.confirmPosMoreAmount;
        else
            message = window.top.confirmAmount + " " + $('#lblRemained').text() + " " + baseCurrencyName + "  " + (getQuery("state") === "1" ? window.top.creditorAccount : window.top.debtorAccount) + " " + (state === marketState ? window.top.seller : $('#lblTarafh').text()) + " " + window.top.sureContinue;
    }
    else if (payedAmount < mainAmount) {
        if (isPos)
            message = window.top.confirmPosLessAmount;
        else
            message = window.top.confirmAmount + " " + $('#lblRemained').text() + " " + baseCurrencyName + "  " + (getQuery("state") === "1" ? window.top.creditorAccount : window.top.debtorAccount) + " " + (state === marketState ? window.top.seller : $('#lblTarafh').text()) + " " + window.top.sureContinue;
    }
    if (message && !isRound)
        control = confirm(message);
    if (control) {
        if (isPos && payedAmount < mainAmount) {
            dataTable.push({
                'id': insertedId,
                'Mablagh': mainAmount - payedAmount,
                'Trs_Type': 5,
                'CodeTarafHesab': getQuery('tarafHCode')
            });
        }
        refreshParent('save(' + JSON.stringify(dataTable) + ',' + (isRound ? remindDecimal : 0) + ')');
    }
}

async function initial() {
    await getRoundingLimit();
    if (documentCode)
        await getFactorSettlement();
    if (state !== marketState && state !== sale)
        await getChequeManager();
    $("#divMain").show();
    closeLoading();
}
async function getChequeManager() {
    await ajax({
        url: "TreasuryApi/GetChequeDetailList",
        data: {
            isChequeIn: true,
            operationType: [1, 6],
            sort: "ChequeCode desc", PageNo: -1
        },
        success: function (result) {
            chequeManagerList = result;
        }
    });
}
async function getRoundingLimit() {
    await ajax({
        url: "GeneralApi/GetConfigArray",
        data: { nameList: ["RoundingLimit"] },
        success: function (result) {
            roundingLimit = Number(result[0].Value);
        }
    });
}
async function getFactorSettlement() {
    await ajax({
        url: "SaleApi/GetFactorTrs",
        data: { factorSerial: documentCode },
        success: function (result) {
            if (result.length > 0) {
                for (var i = 0; i < result.length; i++) {
                    dataTable.push({
                        'Mablagh': (result[i].CurrencyCode === baseCurrencyCode ? result[i].Price : result[i].CurrencyPrice),
                        'CodeSandog': result[i].CashDeskCode ? result[i].CashDeskCode : -1,
                        'NameSandogh': result[i].CashDeskName || "",
                        'Code_Paygri': result[i].TrackingCode || "",
                        'CodeBank': result[i].BankCode ? result[i].BankCode : -1,
                        'NameBankCheck': result[i].TrsType === 2 ? result[i].ChequeBookName || "" : result[i].BankName || "",//true = nameBank
                        'Date_Paygri': result[i].TrackingDate || "",
                        'TelEtc': result[i].TelEtc || "",
                        'Sumery': result[i].TrsArticleSummery || "",
                        'id': insertedId,
                        'CodeTarafHesab': getQuery('tarafHCode'),
                        'Trs_Type': result[i].TrsType,
                        'type': getType(state, result[i]),
                        'CodeNoeAmaliyat': result[i].TrsOperationType ? result[i].TrsOperationType : -1,
                        'CoderizKharjchek': result[i].ChequeCode ? result[i].ChequeCode : -1,
                        'NameMahal': '',
                        'Code_Dastachak': result[i].ChequeBookCode ? result[i].ChequeBookCode : -1,
                        'CurrencyCode': result[i].CurrencyCode
                    });
                    insertedId++;
                    if (getType(state, result[i]) === 22) {
                        listUsedNumberCheque.push({ "numberCheque": result[i].TrackingCode, "dastehCheque": result[i].ChequeBookCode });
                    }
                }
                refreshAmount();
                showTable();
                setToTable();
            }
        }
    });
}
async function getEventLookupCombo($combo, search, code) {
    var id = $combo.attr("id");
    var url = "";
    var data = null;
    switch (id) {
        case "cboCash": case "cboCashRecitp":
            url = "TreasuryApi/GetCashDeskList";
            data = { pageNo: 1, search: search, selectedCode: code };
            break;
        case "cboBankPos":
            url = "TreasuryApi/GetBankAccountList";
            data = { bank: (state === 1 || null), pageNo: 1, search: search, selectedCode: code };
            break;
        case "cboCheckBank":
            url = "TreasuryApi/GetBankList";
            data = {};
            break;
        case "cboChequeBook":
            url = "TreasuryApi/GetChequeListCombo";
            data = { pageNo: 1, CurrencyCode: currencyCode };
            break;
        case "cboNumberCheque":
            var selectedValue = $("#cboChequeBook").lookupBuilder().getSelectedValue();
            if (!selectedValue)
                return;
            url = "TreasuryApi/GetChequeNumbers";
            data = { code: selectedValue.split("/")[0], search: search, selectedCode: code };
            break;
    }
    if (url === "")
        return;
    await ajax({
        url: url,
        data: data,
        success: function (result) {
            if (id === "cboBankPos") {
                result = result.filter(function (item) { return Number(item.TafsilCurrencyCode) === Number(currencyCode); });
                $.each(result,
                    function () {
                        this.Code = this.Code + "|" + (this.PosType || "") + "|" + (this.PosKey || "");
                    });
            }
            else if (id === "cboNumberCheque") {
                var data = listUsedNumberCheque.filter(x => Number(x.dastehCheque) === Number($("#cboChequeBook").lookupBuilder().getSelectedValue().split("/")[0]));
                result = result.filter(x => data.filter(value => Number(x.Code) === Number(value.numberCheque)).length === 0);
            }
            $combo.lookupBuilder().bindData(result);
            if (id === "cboNumberCheque" && Number(code) <= 0 && result.length > 0) {
                $combo.lookupBuilder().setSelectedValue(result[0].Code)
            }
        }
    });
}
async function cboChequeBookChange() {
    await getEventLookupCombo($("#cboNumberCheque"), "", "");
}
function savePos() {
    addToTable();
}
