var checkedCheque = [];
var type = getQuery("type");
var systemCode = getQuery("systemcode");
var lstStore;
var posOpenCloseInfo;
function openAsnad() {
    openInTab('Sale/ShopContainer?codePosSystem=' + $("#hdfSandoghCode").val() + '&systemcode=' + systemCode, window.top.showAsnad, 'img/pages/menu/121.svg', true);
}
function openHistory() {
    openInTab('Sale/ShopCloseDocument', window.top.showAsnadHistory, 'img/pages/menu/121.svg', true);
}

$(document).ready(function () {
    initial();
});
function openPos() {
    var error = checkValidation('#divOpenPos');
    if (error === '') {
        ajax({
            loading: true,
            url: "SaleApi/OpenCashDesk",
            data: {
                storeCode: $("#cboStore").lookupBuilder().getSelectedValue(),
                price: numberNonCommas($('#txtMojodi').val(), 0),
                description: $('#txtDescription').val()
            },
            success: function () {
                location.reload();
            }
        });
    }
    else {
        showMsgModal(0, error);
    }
}
function closePos() {
    var error = checkValidation('#divClosePos');
    var notChecked = [];
    $(' [data-value]').each(function () {
        if (!$(this).prop('checked')) {
            var str = $(this).val();
            notChecked.push(str);
        }
    });

    if (error === '') {
        ajax({
            loading: true,
            url: "SaleApi/ClosePos",
            data: {
                treasuryCashDeskCode: $("#cboCashDesk").lookupBuilder().getSelectedValue(),
                shopCashDeskCode: $('#hdfSandoghCode').val(),
                cashSum: numberNonCommas($('#txtAmountCounted').val(), 0),
                finishDate: $('#txtFinishDate').val(),
                description: $('#txtDescriptionClose').val(),
                deletes: notChecked
            },
            success: function (result) {
                if (getQuery('type')) {
                    refreshParent('loadGrid()');
                    closeTopModal();
                }
                else {
                    if (result.Result) {
                        location.reload();
                    }
                }
            }
        });
    }
    else {
        showMsgModal(0, error);
    }
}
function amountCount() {
    $('#spanOperationNaghd').text(numberWithCommas(numberNonCommas($('#sapnNaghdPrice').text(), 0) - numberNonCommas($('#txtAmountCounted').val(), 0)));
    mountDifference();
    amountCounted();
}
function mountDifference() {
    var mablagh = numberNonCommas($('#spanOperationNaghd').text(), 0) + numberNonCommas($('#spanOperationVariz').text(), 0) + numberNonCommas($('#spanOperationCheque').text(), 0);
    $('#spanPayPrice').text(numberWithCommas(mablagh));
}
function amountCounted() {
    var mablagh = numberNonCommas($('#txtAmountCounted').val(), 0) + numberNonCommas($('#spanRVarizPrice').text(), 0) +
        numberNonCommas($('#spanRChequePrice').text(), 0) + numberNonCommas($('#spanRMablagh').text(), 0);
    $('#spanShomareshPrice').text(numberWithCommas(mablagh));

}
function getDataRizSanad(type) {
    ajax({
        loading: true,
        url: "SaleApi/GetDataRizSanad",
        data: { code: $('#hdfSandoghCode').val(), typePayment: type },
        async: false,
        success: function (result) {
            madeTagDetailRizSanad(result, type);
            $("#rizSanadModal").modal();
        }
    });
}
function madeTagDetailRizSanad(model, type) {
    $('#thHeaderRizSanad').empty();
    $('#tbRizSanad').empty();
    $('#divBodyModel').empty();
    var tagHeader = "";
    var tagBody = "";
    if (type == 0)//cash
    {
        tagHeader += '<tr style="display: block; width: 100%; padding: 4px 0; height: 28px;border-bottom: 2px solid #ccc;">';
        tagHeader += '<td class="stbl-td" style="width: 5%; text-align: right; display: inline-block; padding: 0px 6px;">';
        tagHeader += '<label class="lbl-sandogh-riz">' + window.top.index + '</label></td>';
        tagHeader += '<td class="stbl-td" style="width: 25%; text-align: right; display: inline-block;padding: 0px 6px;">';
        tagHeader += '<label class="lbl-sandogh-riz">' + window.top.customerName + '</label></td>';
        tagHeader += '<td class="stbl-td" style="width: 10%; text-align: right; display: inline-block;padding: 0px 6px;">';
        tagHeader += '<label class="lbl-sandogh-riz">' + window.top.Datee + '</label></td>';
        tagHeader += '<td class="stbl-td" style="width: 10%; text-align: right; display: inline-block; padding: 0px 6px;">';
        tagHeader += '<label class="lbl-sandogh-riz">' + window.top.factorNumber + '</label></td>';
        tagHeader += '<td class="stbl-td" style="width: 10%; text-align: right; display: inline-block; padding: 0px 6px;">';
        tagHeader += '<label class="lbl-sandogh-riz">' + window.top.factorAmount + '</label></td>';
        tagHeader += '<td class="stbl-td" style="width: 10%; text-align: right; display: inline-block;padding: 0px 6px;">';
        tagHeader += '<label class="lbl-sandogh-riz">' + window.top.amountIn + ' </label></td>';
        tagHeader += '<td class="stbl-td" style="width: 12%; text-align: right; display: inline-block;padding: 0px 6px;">';
        tagHeader += '<label class="lbl-sandogh-riz">' + window.top.debitAmount + ' </label></td>';
        tagHeader += '<td class="stbl-td" style="width: 18%; text-align: right; display: inline-block;padding: 0px 6px;">';
        tagHeader += '<label class="lbl-sandogh-riz">' + window.top.amountOut + ' </label></td>';
        tagHeader += '</tr>';
        $('#exampleModalLabel').text(window.top.cashListReceived);
    }
    else if (type == 1)//pos
    {
        tagHeader += '<tr style="display: block; width: 100%; padding: 4px 0; height: 28px;border-bottom: 2px solid #ccc;">';
        tagHeader += '<td class="stbl-td" style="width: 15%; text-align: right; display: inline-block; padding: 0px 6px;">';
        tagHeader += '<label class="lbl-sandogh-riz">' + window.top.factorNumber + '</label></td>';
        tagHeader += '<td class="stbl-td" style="width: 25%; text-align: right; display: inline-block;padding: 0px 6px;">';
        tagHeader += '<label class="lbl-sandogh-riz">' + window.top.customerName + '</label></td>';
        tagHeader += '<td class="stbl-td" style="width: 20%; text-align: right; display: inline-block; padding: 0px 6px;">';
        tagHeader += '<label class="lbl-sandogh-riz">' + window.top.bankCode + '</label></td>';
        tagHeader += '<td class="stbl-td" style="width: 20%; text-align: right; display: inline-block;padding: 0px 6px;">';
        tagHeader += '<label class="lbl-sandogh-riz">' + window.top.amount + ' </label>';
        tagHeader += '</td>';
        tagHeader += '<td class="stbl-td" style="width: 14%; text-align: right; display: inline-block;padding: 0px 6px;">';
        tagHeader += '<label class="lbl-sandogh-riz">' + window.top.trackingCode + '</label></td>';
        tagHeader += '</tr>';
        $('#exampleModalLabel').text(window.top.listCardReader);
    }
    else if (type == 2) { // check 
        tagHeader += '<tr style="display: block; width: 100%; padding: 4px 0; height: 28px;border-bottom: 2px solid #ccc;">';
        //tagHeader += '<td class="stbl-td" style="width: 10%; text-align: right; display: inline-block;padding: 0px 6px;">' + window.top.Choice + '</td>';
        tagHeader += '<td class="stbl-td" style="width: 13%; text-align: right; display: inline-block;padding: 0px 6px;">';
        tagHeader += '<label class="lbl-sandogh-riz">' + window.top.factorNumber + '</label></td>';
        tagHeader += '<td class="stbl-td" style="width: 25%; text-align: right; display: inline-block; padding: 0px 6px;">';
        tagHeader += '<label class="lbl-sandogh-riz">' + window.top.customerName + '</label></td>';
        //tagHeader += '<td class="stbl-td" style="width: 10%; text-align: right; display: inline-block;padding: 0px 6px;">';
        //tagHeader += '<label class="lbl-sandogh-riz">' + window.top.Datee +'</label></td>';
        tagHeader += '<td class="stbl-td" style="width: 20%; text-align: right; display: inline-block;padding: 0px 6px;">';
        tagHeader += '<label class="lbl-sandogh-riz">' + window.top.bankName  + '</label></td>';
        tagHeader += '<td class="stbl-td" style="width: 17%; text-align: right; display: inline-block;padding: 0px 6px;">';
        tagHeader += '<label class="lbl-sandogh-riz">' + window.top.amount + '</label></td>';
        tagHeader += '<td class="stbl-td" style="width: 14%; text-align: right; display: inline-block;padding: 0px 6px;">';
        tagHeader += '<label class="lbl-sandogh-riz">' + window.top.checkNumber + '</label></td>';

        tagHeader += '</tr>';
        $('#exampleModalLabel').text(window.top.checkListReceived);
    }
    $('#thHeaderRizSanad').append(tagHeader);
    if (model.length != 0) {

        for (var i = 0; i < model.length; i++) {
            if (type == 0) {

                tagBody += '<tr class="stbl-tr odd " style="height: 28px;border-bottom: 1px solid #ccc;" >';
                tagBody += '<td class="stbl-td" style="width: 5%; text-align: right; display: inline-block;padding: 0px 6px;margin: 8px 0 2px;">';
                tagBody += ' <label class="lbl-sandogh-riz">' + (i + 1) + '</label></td>';
                tagBody += '<td class="stbl-td" style="width: 25%; text-align: right; display: inline-block;padding: 0px 6px;margin: 8px 0 2px;">';
                tagBody += '<label class="lbl-sandogh-riz">' + (model[i].NameTarafH !== null ? model[i].NameTarafH : window.top.miscellaneousCustomer) + '</label>';
                tagBody += '<td class="stbl-td" style="width: 10%; text-align: right; display: inline-block;padding: 0px 6px;margin: 8px 0 2px;">';
                tagBody += '<label class="lbl-sandogh-riz">' + model[i].RegDateLocal + '</label>';
                tagBody += '<td class="stbl-td" style="width: 10%; text-align: right; display: inline-block;padding: 0px 6px;margin: 8px 0 2px;">';
                tagBody += ' <label class="lbl-sandogh-riz">' + model[i].CodeSanad + '</label></td>';
                tagBody += '<td class="stbl-td" style="width: 10%; text-align: right; display: inline-block;padding: 0px 6px;margin: 8px 0 2px;">';
                tagBody += ' <label class="lbl-sandogh-riz">' + numberWithCommas(model[i].FactorAmount) + '</label></td>';
                tagBody += '<td class="stbl-td" style="width: 10%; text-align: right; display: inline-block;padding: 0px 6px;margin: 8px 0 2px;">';
                tagBody += ' <label class="lbl-sandogh-riz">' + (model[i].MoadelBa === 1 ? numberWithCommas(model[i].Mablagh.toString()) : 0) + '</label></td>';
                tagBody += '<td class="stbl-td" style="width: 12%; text-align: right; display: inline-block;padding: 0px 6px;margin: 8px 0 2px;">';
                tagBody += ' <label class="lbl-sandogh-riz">' + numberWithCommas(model[i].DebitAmount) + '</label></td>';
                tagBody += '<td class="stbl-td" style="width: 18%; text-align: right; display: inline-block;padding: 0px 6px;margin: 8px 0 2px;">';
                tagBody += ' <label class="lbl-sandogh-riz">' + (model[i].MoadelBa !== 1 ? numberWithCommas(model[i].Mablagh.toString()) : 0) + '</label></td>';
                tagBody += '</tr>';
            }
            else if (type == 1) {
                tagBody += '<tr class="stbl-tr odd " style="height: 28px;border-bottom: 1px solid #ccc;" >';
                tagBody += '<td class="stbl-td" style="width: 15%; text-align: right; display: inline-block;padding: 0px 6px;margin: 8px 0 2px;">';
                tagBody += ' <label class="lbl-sandogh-riz">' + model[i].CodeSanad + '</label></td>';
                tagBody += '<td class="stbl-td" style="width: 25%; text-align: right; display: inline-block;padding: 0px 6px;margin: 8px 0 2px;">';
                tagBody += '<label class="lbl-sandogh-riz">' + (model[i].NameTarafH !== null ? model[i].NameTarafH : window.top.miscellaneousCustomer) + '</label>';
                tagBody += '</td>';
                tagBody += '<td class="stbl-td" style="width: 20%; text-align: right; display: inline-block;padding: 0px 6px;margin: 8px 0 2px;">';
                tagBody += '<label class="lbl-sandogh-riz">' + (model[i].NameBank !== null ? model[i].NameBank : "") + '</label></td>';
                tagBody += '<td class="stbl-td" style="width: 20%; text-align: right; display: inline-block;padding: 0px 6px;margin: 8px 0 2px;">';
                tagBody += '<label class="lbl-sandogh-riz">' + numberWithCommas(model[i].Mablagh.toString()) + '</label></td>';
                tagBody += '<td class="stbl-td" style="width: 10%; text-align: right; display: inline-block;padding: 0px 6px;margin: 8px 0 2px;">';
                tagBody += '<label class="lbl-sandogh-riz">' + (model[i].CodePeigiri || "") + '</label>';
                tagBody += '</td>';
                tagBody += '</tr>';
            }
            else if (type == 2) {

                var checkTag = checkedCheque.filter(function (item) { return (item == model[i].Code); }).length > 0 ? 'checked="checked"' : '';

                tagBody += '<tr class="stbl-tr odd" style="height: 28px;border-bottom: 1px solid #ccc;">';
                //tagBody += '<td class="stbl-td" style="width: 10%; text-align: right; display: inline-block;padding: 0px 6px;"><input data-value="' + model[i].Mablagh + '" onchange="checkedCheck(this)" type="checkbox" ' + checkTag + '  value="' + model[i].Code + '"></td>'
                tagBody += '<td class="stbl-td" style="width: 12%; text-align: right; display: inline-block;padding: 0px 6px;margin: 8px 0 2px;">';
                tagBody += ' <label class="lbl-sandogh-riz">' + model[i].CodeSanad + '</label></td>';
                tagBody += '<td class="stbl-td" style="width: 25%; text-align: right; display: inline-block;padding: 0px 6px;margin: 8px 0 2px;">';
                tagBody += '<label class="lbl-sandogh-riz">' + (model[i].NameTarafH !== null ? model[i].NameTarafH : window.top.miscellaneousCustomer) + '</label>';
                tagBody += '</td>';
                tagBody += '<td class="stbl-td" style="width: 16%; text-align: right; display: inline-block;padding: 0px 6px;margin: 8px 0 2px;">';
                tagBody += '<label class="lbl-sandogh-riz">' + (model[i].NameBank !== null ? model[i].NameBank : "") + '</label></td>';
                tagBody += '<td class="stbl-td" style="width: 19%; text-align: right; display: inline-block;padding: 0px 6px;margin: 8px 0 2px;">';
                tagBody += '<label class="lbl-sandogh-riz">' + numberWithCommas(model[i].Mablagh.toString()) + '</label></td>';
                tagBody += '<td class="stbl-td" style="width: 15%; text-align: right; display: inline-block;padding: 0px 6px;margin: 8px 0 2px;">';
                tagBody += '<label class="lbl-sandogh-riz">' + (model[i].CodePeigiri || "") + '</label>';
                tagBody += '</td>';
                tagBody += '</tr>';
            }
        }
        $('#tbRizSanad').append(tagBody);
    }
    else {
        $('#divBodyModel').append("<lable>" + window.top.noRowsToDisplay + "</lable>");
    }
}
function checkedCheck(sender) {
    var resultMablagh;
    var mablagh = Number($(sender).attr('data-value'));
    if ($(sender).prop('checked')) {
        checkedCheque.push($(sender).val());
        resultMablagh = numberNonCommas($('#spanRChequePrice').text(), 0) + mablagh;
    }
    else {
        checkedCheque = checkedCheque.filter(function (item) { return (item != $(sender).val()); });
        resultMablagh = numberNonCommas($('#spanRChequePrice').text(), 0) - mablagh;
    }
    $('#spanRChequePrice').text(numberWithCommas(resultMablagh));
    $('#spanOperationCheque').text(numberWithCommas(numberNonCommas($('#spanChequePrice').text(), 0) - numberNonCommas($('#spanRChequePrice').text(), 0)));
    mountDifference();
    amountCounted();
}
async function getEventLookupCombo($combo, search, code) {
    var id = $combo.attr('id');
    var url = "";
    var data = null;
    switch (id) {
        case "cboCashDesk":
            url = "TreasuryApi/GetCashDeskList";
            data = { search: search, pageNo: 1, selectedCode: code };
            break;
        case "cboStore":
            url = "SaleApi/GetStoreList";
            data = { search: search, pageNo: 1, selectedCode: code };
            break;
    }
    if (!url)
        return;
    await ajax({
        url: url,
        data: data,
        success: function (result) {
            if (id === "cboCashDesk") {
                if (result.length > 0) {
                    var newResult = [{ Name: window.top.notSpecified, Code: "-1" }];
                    result = newResult.concat(result);
                }
            }
            $combo.lookupBuilder().bindData(result);
        }

    });
}

async function isOpenCashDesk() {
    await ajax({
        url: "SaleApi/IsOpenCashDesk",
        success: function (result) {
            posOpenCloseInfo = result;
        }
    });
}

async function getStoreList() {
    await ajax({
        url: "SaleApi/GetStoreList",
        data: { creditType: 0, search: "", filter: "", sort: "", pageNo: 1, selectedCode: "", storeType: null },
        success: function (result) {
            lstStore = result;
        }
    });
}

async function initial() {
    await getStoreList();
    await isOpenCashDesk();
    loadData();

    $(".currency-name").text(window.top.$("#hfBaseCurrencyName").val());
    $('#spanOperationVariz').text(numberWithCommas(numberNonCommas($('#spanVarizPrice').text(), 0) - numberNonCommas($('#spanRVarizPrice').text(), 0)));
    $('#spanOperationCheque').text(numberWithCommas(numberNonCommas($('#spanChequePrice').text(), 0) - numberNonCommas($('#spanRChequePrice').text(), 0)));
    mountDifference();

    closeLoading();
    $("#divMain").show();
}

function loadData() {
    if (posOpenCloseInfo.PosOpenClose) {

        var posOpenClose = posOpenCloseInfo.PosOpenClose;

        if (posOpenCloseInfo.CodeAnbar !== -1) {
            var store = lstStore.filter(c => c.Code == posOpenCloseInfo.CodeAnbar);
            var lblAnbar = $("#lblAnbar");
            if (store)
                lblAnbar.text(store[0].Name).attr("Code", String(store[0].Code));
            else
                lblAnbar.text(window.top.notSpecified).attr("Code", "-1");
        }

        if (type === "1") {
            $("#btnListAnsadClose").hide();
            $("#btnListAnsad").hide();
        }

        $("#hdfSandoghCode").val(String(posOpenCloseInfo.Code));
        $("#lblStartDate").text(posOpenCloseInfo.StartDateLocal);
        $("#txtDescriptionClose").text(posOpenClose.Description);
        $("#spanCountOut").text(window.top.totalSalesDocuments + " (" + (posOpenClose.CountFrosh != -1 ? posOpenClose.CountFrosh.toString() : "0") + ")");
        $("#spanCountRef").text(window.top.totalReferenceDocuments + " (" + (posOpenClose.CountRetFrosh != -1 ? posOpenClose.CountRetFrosh.toString() : "0") + ")");
        $("#spanPriceOut").text(numberWithCommas(Number(posOpenClose.SumFrosh)));
        $("#spanPriceRef").text(numberWithCommas(Number(posOpenClose.SumRetFrosh)));
        $("#spanNaghdCount").text(posOpenClose.CountNaghdFrosh.toString() == "-1" ? "0" : posOpenClose.CountNaghdFrosh.toString());
        $("#spanVarizCount").text(posOpenClose.CountVarizFrosh.toString() == "-1" ? "0" : posOpenClose.CountVarizFrosh.toString());
        $("#spanChequCount").text(posOpenClose.CountChequFrosh.toString() == "-1" ? "0" : posOpenClose.CountChequFrosh.toString());

        posOpenClose.NaghdFrosh = posOpenClose.NaghdFrosh != -1 ? posOpenClose.NaghdFrosh : 0;
        posOpenClose.VarizFrosh = posOpenClose.VarizFrosh != -1 ? posOpenClose.VarizFrosh : 0;
        posOpenClose.ChequFrosh = posOpenClose.ChequFrosh != -1 ? posOpenClose.ChequFrosh : 0;

        var naghdPrice = Number(posOpenClose.NaghdFrosh + posOpenClose.StartBalance - (posOpenClose.SumRetFrosh != -1 ? posOpenClose.SumRetFrosh : 0) + posOpenClose.SumDebit);
        $("#sapnNaghdPrice").text(numberWithCommas(naghdPrice));
        $("#spanOperationNaghd").text(numberWithCommas(Number(naghdPrice - (posOpenClose.Naghd_Inclose != -1 ? posOpenClose.Naghd_Inclose : 0))));
        $("#txtAmountCounted").val(posOpenClose.Naghd_Inclose != -1 ? numberWithCommas(Number(posOpenClose.Naghd_Inclose)) : "0");

        $("#spanVarizPrice").text(numberWithCommas(Number(posOpenClose.VarizFrosh)));
        $("#spanRVarizPrice").text(numberWithCommas(Number(posOpenClose.VarizFrosh)));
        $("#spanOperationVariz").text(numberWithCommas(Number(posOpenClose.VarizFrosh)));

        $("#spanChequePrice").text(numberWithCommas(Number(posOpenClose.ChequFrosh)));
        $("#spanRChequePrice").text(numberWithCommas(Number(posOpenClose.ChequFrosh)));

        $("#spanOperationCheque").text("0");
        $("#spanMR").text(numberWithCommas(Number(posOpenCloseInfo.StartBalance)));

        $("#spanSumCount").text((posOpenClose.CountNaghdFrosh != -1 ? posOpenClose.CountNaghdFrosh : 0)
            + (posOpenClose.CountVarizFrosh != -1 ? posOpenClose.CountVarizFrosh : 0)
            + (posOpenClose.CountChequFrosh != -1 ? posOpenClose.CountChequFrosh : 0)).toString();
        $("#sapnAllPrice").text(numberWithCommas(Number(posOpenClose.ChequFrosh + posOpenClose.VarizFrosh + posOpenClose.NaghdFrosh + posOpenClose.SumDebit
            + posOpenClose.StartBalance - (posOpenClose.SumRetFrosh != -1 ? posOpenClose.SumRetFrosh : 0))));
        $("#spanShomareshPrice").text(numberWithCommas(Number(0 + posOpenClose.VarizFrosh + 0)));

        $("#divOpenPos").hide();
        $("#divClosePos").show();
    }
    else {
        $("#divOpenPos").show();
        $("#divClosePos").hide();
    }
}
