var isSaleDocument = getQuery("type") !== "store";
var code = getQuery("code");
var lang = "";
var documentTypeCode;
$(document).ready(function () {
    lang = $("#hfLang").val();
    initial();
    $("#cboCodeSanadMabna").lookupBuilder().onChanged(function () {
        var baseCode = $("#cboCodeSanadMabna").lookupBuilder().getSelectedValue();
        $("#chkBaseRequire").prop("disabled", !baseCode);
        if (!baseCode)
            $("#chkBaseRequire").prop("checked", false);
    });
    $(".sub").click(function () {
        var destinationId = $(this).attr('data-child');
        $(".page-div").hide();
        $("#" + destinationId).show();
        $(".sub-title").removeClass('selected-sub-title');
        $(this).addClass("selected-sub-title");
    });
    $(".main-title").click(function () {
        $('#btnDefult').show();
        $('.main-title').removeClass("selected-main-title")
        $(this).addClass("selected-main-title");
        $('#divContainer>div').hide();
        switch ($('.selected-main-title').attr('data-id')) {
            case '1':
                $('#divGeneral').show();
                break;
            case '2':
                $('#divPrint').show();
                break;
        }
    });
    $('#PrintAfterSave').click(function () {
        if ($(this).prop('checked')) {
            toggleEnabled("cboPrintAutomaticForm", true);
        }
        else {
            toggleEnabled("cboPrintAutomaticForm", false);
        }
    });
    $('#PrintAfterSave2').click(function () {
        if ($(this).prop('checked')) {
            toggleEnabled("cboFormsSecendPrint", true);
        }

        else {
            toggleEnabled("cboFormsSecendPrint", false);
        }
    });
});
function changeFrom() {
    var value = Number($("#cboCodeMoadel").lookupBuilder().getSelectedValue().split("|")[0]);
    if (value === 2 || value === 20 || value === 0)
        $('.changeForm').css("display", "none");
    else
        $('.changeForm').css("display", "");

    //$('#lblOutkala').text('');
    //$('#lblTafsileInner').text('');

    if (value === 1) {
        setComboCaption("cboMoain_No_Out", window.top.moainEntryExitProduct);
        setComboCaption("cboHesab_No_Out", window.top.tafsilEntryExitProduct);
    }
    else if (value === 10) {
        setComboCaption("cboMoain_No_Out", window.top.moainReturnSale);
        setComboCaption("cboHesab_No_Out", window.top.tafsilReturnSale);
    }
    else if (value === 13) {
        setComboCaption("cboMoain_No_Out", window.top.moainBackPurchase);
        setComboCaption("cboHesab_No_Out", window.top.tafsilBackPurchase);
    }

    if ($("#hfHasTurnover").val() === "0") {
        if (value === 20) {
            $("#StateTasir").prop("checked", false);
        }

        if (value === 1 || value === 13 || value === 2 || value === 10) {
            $("#SabtSanad").prop("checked", true);
            $("#SabtSanad").prop("disabled", true);
        }
        else {
            $("#SabtSanad").prop("disabled", false);
        }
    }
    changeRequired("cboMoain_No_In", value !== 20);
}
function save() {
    var data = getJsonValue("");
    var exceprionText = checkValidation('',true);
    if (exceprionText === '') {
        data["StateInOut"] = $("#cboCodeMoadel").lookupBuilder().getSelectedValue().split("|")[1];
        data['Code'] = code !== "" ? code : -1;
        ajax({
            loading: true,
            url: "SaleApi/" + (code ? "UpdateDocumentType" : "InsertDocumentType"),
            data: data ,
            success: function (result) {
                documentTypeCode = result.ReturnValue;
                saveConfig();
            }
        });
    }
    else {
        showMsgModal(0, exceprionText, exceprionText, '0');
    }
}
function saveConfig() {
    showLoading();
    var model = [];
    var field;
    $(" [data-id]", "#divPrint").each(function () {
        field = $(this).attr('data-id');
        if ($(this).hasClass("check")) {
            model.push({ Param: field + documentTypeCode, Value: ($(this).prop('checked') ? "1" : "0") });
        }
        else if (field === ("DefultreportPrintAfterSave" + lang + "_") || field === "DefultreportPrintAfterSave2_") {
            model.push({ Param: field + documentTypeCode, Value: $(this).lookupBuilder().getSelectedValue() || -1 });
        }
    });
    ajax({
        url: "GeneralApi/SetConfigArray",
        data: { configList: model },
        success: function (result) {
            showMsgModal(2, window.top.savedSuccessfully);
            refreshParent('refresh(0)');
            closeTopModal();
        }
    });
}
async function initial() {
    $("#cboCodeMoadel").lookupBuilder().onChanged(function () {
        changeFrom();
    });

    if (code !== "") {
        await getDocumentType();
        await getConfig();
    }
    else {
        toggleEnabled("cboPrintAutomaticForm", false);
        toggleEnabled("cboFormsSecendPrint", false);
        closeLoading();
        $("#divMain").show();
    }
}
async function getEventLookupCombo($combo, search, code) {
    var id = $combo.attr("id");
    var url = "";
    var data = null;
    switch (id) {
        case "cboCodeMoadel":
            url = "SaleApi/GetDocumentTypeParentList";
            data = { isSaleDocument: isSaleDocument };
            break;
        case "cboCodeSanadMabna":
            url = "SaleApi/GetDocumentTypeLiteList";
            data = { search: search, selectedCode: code, pageNo: 1 };
            break;
        case "cboMoain_No_In": case "cboMoain_No_Tamam": case "cboMoain_No_Out": case "cboMoain_no_TarafH":
            url = "AccountingApi/GetMoainList";
            data = { checkActive: false, search: search, selectedCode: code, pageNo: 1 };
            break;
        case "cboHesab_No_Out":
            if (!$("#cboMoain_No_Out").lookupBuilder().getSelectedValue()) {
                $combo.lookupBuilder().clearItems();
                return;
            }
            url = "AccountingApi/GetTafsilList";
            data = { moainCode: $("#cboMoain_No_Out").lookupBuilder().getSelectedValue() || -1, level: 21, search: search, selectedCode: code, pageNo: 1 };
            break;
        case "cboHesab_No_Tamam":
            if (!$("#cboMoain_No_Tamam").lookupBuilder().getSelectedValue()) {
                $combo.lookupBuilder().clearItems();
                return;
            }
            url = "AccountingApi/GetTafsilList";
            data = { moainCode: $("#cboMoain_No_Tamam").lookupBuilder().getSelectedValue() || -1, level: 21, search: search, selectedCode: code, pageNo: 1 };
            break;
        case "cboFormsSecendPrint": case "cboPrintAutomaticForm":
            url = "SaleApi/GetSaleReportList";
            data = {};
            break;
    }
    if (url === "")
        return;
    await ajax({
        url: url,
        data: data,
        success: function (result) {
            if (id === "cboCodeMoadel") {
                $.each(result,
                    function () {
                        this.Code = this.Code + "|" + this.StateInOut;
                    });
            }
            else if (id === "cboCodeSanadMabna") {
                var newResult = [{ Name: window.top.withoutBasis, Code: "-1" }];
                result = newResult.concat(result);
            }
            $combo.lookupBuilder().bindData(result);
        }
    });
}
async function getDocumentType() {
    var data;
    await ajax({
        url: "SaleApi/GetDocumentType",
        data: { code: code },
        success: function (result) {
            data = result;
        }
    });
    await loadData(data);
}
async function loadData(result) {
    await setJsonValue(result);
    if (result.HasTurnover) {
        $("#cboCodeMoadel").lookupBuilder().setEnabled(false);
        $("#StateTasir").prop("disabled", true);
        $("#SabtSanad").prop("disabled", true);
        $("#hfHasTurnover").val("1");
    }
    if (result.BaseDocumentTypeCode <= 0)
        $("#chkBaseRequire").prop("disabled", true);
    closeLoading();
    $("#divMain").show();
}
async function getConfig() {
    var nameList = ["PrintAfterSave_" + code, "DefultreportPrintAfterSave" + lang + "_" + code, "PrintAfterSave2_" + code, "DefultreportPrintAfterSave2_" + code];
    await ajax({
        url: "GeneralApi/GetConfigArray",
        loading: false,
        data: {nameList: nameList},
        success: function (result) {
            loadConfig(result);
        }
    });
}
async function loadConfig(data) {
    for (var i = 0; i < data.length; i++) {
        var item = data[i];
        if (item.Param.includes("_"))
            item.Param = item.Param.split("_")[0] + "_";
        var $element = $("[data-id='" + item.Param + "']");
        if ($element.hasClass("check")) {
            var $lbl = $("#lbl" + item.Param);
            if (item.Value === "1") {
                $element.prop("checked", true);
                $lbl.css({ "font-weight": "700" });
            }
            else {
                switch (item.Param) {
                    case "PrintAfterSave_":
                        toggleEnabled("cboPrintAutomaticForm", Number(item.Value) !== 0);
                        break;
                    case "PrintAfterSave2_":
                        toggleEnabled("cboFormsSecendPrint", Number(item.Value) !== 0);
                        break;
                }
                $lbl.text(window.top.deActive);
            }
        }
        else if ($element.hasClass("system-lookup-control")) {
            await $element.lookupBuilder().setSelectedValue(item.Value);
        }
        else
            $element.val(item.Value);
    }
    $("#divMain").show();
    closeLoading();
}
function toggleEnabled(id, state) {
    $("#" + id).lookupBuilder().setEnabled(state);
    $("#" + id).lookupBuilder().setSelectedValue("");
    if (!state) {
        $("#" + id + " .lookup-button").removeClass("validation")
        $("#" + id).attr("data-required", "");
    }
    else {
        $("#" + id + " .lookup-button").addClass("validation")
        $("#" + id).attr("data-required", "true");
    }
}
