var type = Number(getQuery("type"));
var code = getQuery("code");
var hasCurrencySystem = window.top.$("#hfCurrencySystem").val() === "1";
var baseDecimalCount = Number(window.top.$('#hfBaseCurrencyDecimalCount').val());
var baseCurrencyCode = Number(window.top.$('#hfBaseCurrencyCode').val());
var baseCurrencyName = window.top.$('#hfBaseCurrencyName').val();
var cboEvent = true;
$(document).ready(function () {
    if (!hasCurrencySystem)
        $("#divCurrency").hide();

    switch (type) {
        case 1:
            setComboCaption("cboCashFrom", window.top.fromTreasury);
            setComboCaption("cboCashTo", window.top.toTreasury);
            break;
        case 2:
            setComboCaption("cboCashFrom", window.top.fromTreasury);
            setComboCaption("cboCashTo", window.top.toBank);
            break;
        case 3:
            setComboCaption("cboCashFrom", window.top.fromBank);
            setComboCaption("cboCashTo", window.top.toBank);
            break;
        case 4:
            setComboCaption("cboCashFrom", window.top.fromBank);
            setComboCaption("cboCashTo", window.top.toTreasury);
            break;
    }

    $("#cboCurrency").lookupBuilder().onChanged(async function () {
        if (!cboEvent)
            return;
        var fromCode = $("#cboCashFrom").lookupBuilder().getSelectedValue();
        var toCode = $("#cboCashTo").lookupBuilder().getSelectedValue();
        var currencyCode = this.getSelectedValue().split("|")[0];
        if (fromCode && fromCode.includes("|") && fromCode.split("|")[1] !== currencyCode)
            $("#cboCashFrom").lookupBuilder().setSelectedValue("");
        if (toCode && toCode.includes("|") && toCode.split("|")[1] !== currencyCode)
            $("#cboCashTo").lookupBuilder().setSelectedValue("");
        await getCurrencyRate(currencyCode);
        setPriceBaseCurrency();
    });
    $("#txtCurrencyRate").keyup(function () {
        setPriceBaseCurrency();
    });
    $("#txtAmount").keyup(function () {
        setPriceBaseCurrency();
    });

    if (code !== "")
        getTransferDetails();
    else {
        $("#cboCurrency").lookupBuilder().setSelectedValue(baseCurrencyCode);
        $("#divMain").show();
        closeLoading();
    }

});
async function getCurrencyRate(code) {
    if (Number(code) !== baseCurrencyCode)
        await ajax({
            url: 'SaleApi/GetCurrencyRate',
            data: { currencyCode: code, date: $("#txtDate").val() },
            success: function (retValue) {
                $("#txtCurrencyRate").prop("disabled", false).val(retValue.PriceInReal === "" ? 1 : retValue.PriceInReal);
            }
        });
    else
        $("#txtCurrencyRate").prop("disabled", true).val(1);
}
async function getTransferDetails() {
    await ajax({
        url: "TreasuryApi/GetTransferDetails",
        data: { code: code },
        success: function (result) {
            loadData(result);
        }
    });
}
async function loadData(result) {
    cboEvent = false;
    var fromCode;
    var toCode;
    $("#txtDate").val(result.RequestDateLocal);
    $("#txtAmount").val(result.CurrencyPrice);
    $("#txtTozihat").val(result.Summery);
    $("#hfCode").val(code);
    switch (type) {
        case 1:
            fromCode = result.FromCashDeskCode;
            toCode = result.ToCashDeskCode;
            break;
        case 2:
            fromCode = result.FromCashDeskCode;
            toCode = result.ToBankCode;
            break;
        case 3:
            fromCode = result.FromBankCode;
            toCode = result.ToBankCode;
            break;
        case 4:
            fromCode = result.FromBankCode;
            toCode = result.ToCashDeskCode;
            break;
    }
    await $("#cboCurrency").lookupBuilder().setSelectedValue(result.CurrencyCode);
    await $("#cboCashFrom").lookupBuilder().setSelectedValue(fromCode);
    await $("#cboCashTo").lookupBuilder().setSelectedValue(toCode);
    $("#txtCurrencyRate").val(result.CurrencyRate);
    cboEvent = true;
    if (result.CurrencyCode !== baseCurrencyCode)
        setPriceBaseCurrency();
    $("#divMain").show();
    closeLoading();
}
function save() {
    var exceptionText = checkValidation('');
    if (exceptionText === '') {
        var fromCashDeskCode, toCashDeskCode, fromBankCode, toBankCode;
        var fromCode = $("#cboCashFrom").lookupBuilder().getSelectedValue();
        var toCode = $("#cboCashTo").lookupBuilder().getSelectedValue();
        var currency = $("#cboCurrency").lookupBuilder().getSelectedValue();
        if (fromCode.includes("|"))
            fromCode = fromCode.split("|")[0];
        if (toCode.includes("|"))
            toCode = toCode.split("|")[0];
        if (currency)
            currency = currency.split("|")[0];
        else
            currency = baseCurrencyCode
        switch (type) {
            case 1:
                fromCashDeskCode = fromCode;
                toCashDeskCode = toCode;
                break;
            case 2:
                fromCashDeskCode = fromCode;
                toBankCode = toCode;
                break;
            case 3:
                fromBankCode = fromCode;
                toBankCode = toCode;
                break;
            case 4:
                fromBankCode = fromCode;
                toCashDeskCode = toCode;
                break;
        }
        if ((type === 1 && fromCashDeskCode === toCashDeskCode) || (type === 3 && fromBankCode === toBankCode))
            showMsgModal(0, window.top.sourceDestinationNoSame);
        else {
            var currencyRate = $("#txtCurrencyRate").val();
            var data = {
                FromCashDeskCode: fromCashDeskCode,
                ToCashDeskCode: toCashDeskCode,
                FromBankCode: fromBankCode,
                ToBankCode: toBankCode,
                TrsDocumentDateLocal: $("#txtDate").val(),
                Summery: $("#txtTozihat").val(),
                Price: $("#txtAmount").val(),
                CurrencyRate: (hasCurrencySystem && currencyRate ? currencyRate : 1),
                CurrencyCode: currency
            };
            if (code)
                data["Code"] = code;

            ajax({
                loading: true,
                url: "TreasuryApi/" + (code ? "UpdateTransferCashBank" : "InsertTransferCashBank"),
                data: data,
                success: function () {
                    showMsgModal(2, code ? window.top.editedSuccessfully : window.top.savedSuccessfully);
                    var gridId = "";
                    switch (type) {
                        case 1:
                            gridId = "gridTreasuryToTreasury";
                            break;
                        case 2:
                            gridId = "gridTreasuryToBank";
                            break;
                        case 3:
                            gridId = "gridBankToBank";
                            break;
                        case 4:
                            gridId = "gridBankToTreasury";
                            break;
                    }
                    if (getQuery("manager"))
                        gridId = "grdSanadList";
                    refreshParent("loadGrid('" + gridId + "')");
                    closeTopModal();
                }
            });
        }
    }
    else {
        showMsgModal(0, exceptionText);
    }
}
async function getEventLookupCombo($combo, search, code) {
    var id = $combo.attr('id');
    var url = "";
    var data = null;
    switch (id) {
        case "cboCurrency":
            url = "GeneralApi/GetCurrencyList";
            data = { search: search, pageNo: 1, selectedCode: code };
            break;
        case "cboCashFrom":
            url = "TreasuryApi/" + (type === 1 || type === 2 ? "GetCashDeskList" : "GetBankAccountList");
            data = { bank: true, search: search, pageNo: 1, selectedCode: code };
            break;
        case "cboCashTo":
            url = "TreasuryApi/" + (type === 1 || type === 4 ? "GetCashDeskList" : "GetBankAccountList");
            data = { bank: true, search: search, pageNo: 1, selectedCode: code };
            break;
        default:
    }

    await ajax({
        url: url,
        data: data,
        success: function (result) {
            if (id === "cboCurrency") {
                $.each(result,
                    function () {
                        this.Code = this.Code + "|" + this.DecimalCount;
                    });
            }
            if (url.includes("GetBankAccountList")) {
                var currencyCode = $("#cboCurrency").lookupBuilder().getSelectedValue() || baseCurrencyCode.toString();
                if (currencyCode.includes("|"))
                    currencyCode = currencyCode.split("|")[0];
                result = result.filter(x => Number(x.TafsilCurrencyCode) === Number(currencyCode));
                $.each(result,
                    function () {
                        this.Code = this.Code + "|" + this.TafsilCurrencyCode;
                    });
            }
            if (id.includes("cboCash") && (type === 1 || type === 3)) {
                var cashCode = $("#cboCash" + (id === "cboCashFrom" ? "To" : "From")).lookupBuilder().getSelectedValue();
                if (cashCode)
                    result = result.filter(x => x.Code.toString() !== cashCode);
            }
            $combo.lookupBuilder().bindData(result);
        }
    });
}
function setPriceBaseCurrency() {
    var currencyCode = $("#cboCurrency").lookupBuilder().getSelectedValue();
    var currencyDecimalCount = baseDecimalCount;
    if (currencyCode) {
        currencyDecimalCount = currencyCode.split("|")[1];
        currencyCode = Number(currencyCode.split("|")[0]);
    }
    $("#txtAmount").attr("data-decimalcount", currencyDecimalCount)
    if (currencyCode > 0 && currencyCode !== baseCurrencyCode) {
        var price = numberNonCommas($("#txtAmount").val());
        var rate = Number($("#txtCurrencyRate").val());
        var priceBaseCurrency = Number((price * rate).toFixed(baseDecimalCount));
        $("#divPriceBaseCurrency").show();
        $("#lblPriceBaseCurrency").text(numberWithCommas(priceBaseCurrency, baseDecimalCount));
    }
    else {
        $("#divPriceBaseCurrency").hide();
    }
}