var code = getQuery("code");
var baseCurrencyCode = Number(window.top.$('#hfBaseCurrencyCode').val());
var hasCurrencySystem = window.top.$("#hfCurrencySystem").val() === "1";
var lastCustomerName = "";
var isShop = getQuery("shop");
var checkingDuplicate = true;

$(document).ready(function () {
    $("#cboTafsilGroup").lookupBuilder().onChanged(async function () {
        cboTafsilGroupChange();
    });
    $("#cboTafsil").lookupBuilder().onChanged(async function () {
        cboTafsilChange();
    });
    $('#btnHoghoghi').click(function () {
        setRealCustomer(false);
    });
    $('#btnHaghighi').click(function () {
        setRealCustomer(true);
    });
    $("[data-mask='mobile']").inputmask("99999999999");
    $("[data-mask=codeHaghighi]").inputmask("9999999999");
    $("[data-mask=codeHoghoghi]").inputmask("99999999999");
    if (code) {
        $("#cboTafsil").lookupBuilder().setEnabled(false);
        $("#cboTafsilGroup").lookupBuilder().setEnabled(false);
        var isRealCustomer = $("#hfIsRealCustomer").val().toLowerCase() === "true";
        setRealCustomer(isRealCustomer);
    }
    closeLoading();
});
function setRealCustomer(isReal) {
    $("#CodeMelli").attr("data-mask", isReal ? "codeHaghighi" : "codeHoghoghi").inputmask(isReal ? "9999999999" : "99999999999");
    $("#btnHoghoghi").removeClass(isReal ? "isactive" : "dontisactive").addClass(isReal ? 'dontisactive' : "isactive");
    $('#btnHaghighi').removeClass(isReal ? 'dontisactive' : "isactive").addClass(isReal ? 'isactive' : "dontisactive");
    $("#lblNationalCode").text(isReal ? window.top.nationalCode : window.top.nationalId);
    if (isReal && !code)
        $("[data-id='FamilyName']").attr("data-required", true).addClass("validation")
    else
        $("[data-id='FamilyName']").attr("data-required", false).removeClass("validation")
}
async function getEventLookupCombo($combo, search, code) {
    var id = $combo.attr('id');
    if (!id)
        return;
    var url = "";
    var data = null;
    if (code && code.toString().indexOf("|") > 0)
        code = code.split("|")[0];
    switch (id) {
        case "cboTafsilGroup":
            url = "AccountingApi/GetTafsilGroupList";
            data = { level: -1, search: search, pageNo: 1, selectedCode: code };
            break;
        case "cboTafsil":
            url = "AccountingApi/GetTafsilList";
            data = { tafsilGroupCode: $("#cboTafsilGroup").lookupBuilder().getSelectedValue(), level: -1, search: search, pageNo: 1, selectedCode: code, notAssignToCustomer: 1 };
            break;
        case "cboCurrency":
            url = "GeneralApi/GetCurrencyList";
            data = { search: search, pageNo: 1 };
            break;
        case "cboCustomerGroup":
            url = "GeneralApi/GetCustomerGroupList";
            data = { filter: "", sort: "", pageNo: 1 };
            break;
        case "cboProvince":
            url = "GeneralApi/GetProvinceList";
            break;
        case "cboCity":
            url = "GeneralApi/GetCityList";
            data = { provinceCode: $("#cboProvince").lookupBuilder().getSelectedValue() ? $("#cboProvince").lookupBuilder().getSelectedValue() : -1, search: search, pageNo: 1, selectedCode: code };
            break;
    }
    await ajax({
        url: url,
        data: data,
        success: function (result) {
            if (id === "cboTafsil") {
                var newResult = [{ Name: window.top.newAccount, Code: "-1|" + baseCurrencyCode }];
                $.each(result, function () {
                    this.Code = this.Code + "|" + this.CodeArz;
                });
                result = newResult.concat(result);
            }
            $combo.lookupBuilder().bindData(result);
            if (!code && $combo.attr("data-required") && result.length > 0) {
                $combo.lookupBuilder().setSelectedValue(result[0].Code);
            }
        }
    });
}
async function checkingDuplicateCustomer(name, nationalCode, mobileNo, code) {
    await ajax({
        url: "GeneralApi/CheckingDuplicateCustomer",
        data: {
            name: name,
            nationalCode: nationalCode,
            mobileNo: mobileNo,
            code: code
        },
        success: function (result) {
            var message = window.top.followingAreDuplicates;
            if (result.Result || (result.ErrorMessage && confirm(message + "\n" + result.ErrorMessage.join("\n") + "\n" + window.top.toBeRegistered)))
                checkingDuplicate = true;
            else
                checkingDuplicate = false;
        }
    });
}
async function save() {
    var exceprionText = checkValidation('');
    if (exceprionText === "") {
        var data = getJsonValue();
        data["MobileNo"] = Number(data["MobileNo"]) === -1 ? "" : data["MobileNo"];
        await checkingDuplicateCustomer(data["Name"], data["NationalCode"], data["MobileNo"], code);
        if (checkingDuplicate) {
            data["Tel"] = data["Tel"] === -1 ? "" : data["Tel"];
            data["EconomicCode"] = data["EconomicCode"] === -1 ? "" : data["EconomicCode"];
            data["CustomerBankNo"] = data["CustomerBankNo"] === -1 ? "" : data["CustomerBankNo"];
            data["IsRealCustomer"] = $("#btnHaghighi").hasClass("isactive");
            data["FileImage"] = $('.picture-img > img').attr('src');
            await ajax({
                loading: true,
                url: "GeneralApi/" + (code === "" ? "InsertCustomer" : "UpdateCustomer"),
                data: data,
                success: function (result) {
                    refreshParent(isShop ? "refreshCustomer(" + result.ReturnValue + ")" : "loadGrid()");
                    showMsgModal(2, result.FinalMessage.join("<br />"));
                    closeTopModal();
                }
            });
        }
    }
    else {
        showMsgModal(0, exceprionText);
    }
}
function cboTafsilChange() {
    if (code !== "")
        return;
    var selectedItem = $("#cboTafsil").lookupBuilder().getSelectedValue().split("|");
    var tafsilCode = Number(selectedItem[0]);
    if (tafsilCode === 0)
        return;
    if (hasCurrencySystem) {
        var currencyCode = Number(selectedItem[1]);
        $("#cboCurrency").lookupBuilder().setSelectedValue(currencyCode);
        $("#cboCurrency").lookupBuilder().setEnabled(baseCurrencyCode === currencyCode)
    }
    if (lastCustomerName !== "") {
        $("#LName").val(tafsilCode !== -1 ? $("#cboTafsil").lookupBuilder().getSelectedText() : "").prop("disabled", tafsilCode !== -1);
    }
    lastCustomerName = $("#LName").val();
}
function cboTafsilGroupChange() {
    if (code !== "")
        return;
    lastCustomerName = "";
    $("#cboTafsil").lookupBuilder().setSelectedValue("-1|" + baseCurrencyCode);
}
function cboProvinceChange() {
    $("#cboCity").lookupBuilder().setSelectedValue("");
}
function modal(id) {
    if (id !== "") {
        var operation = "insert";
        var src = "Accounting/TafsilGroupSave?code=" + id + "&id=''&depth=3&comebacktotarafhesab=1 &text='' &level=3&parentText=''&operation=" + operation + "";
        openInModal('', src, window.top.defineTafsil, "600", "348");
    }
    else {
        alert(window.top.enterTafsilGroup);
    }
}















