var isInsert;
var currentYear = window.top.$("#hfCurrentYear").val();
$(document).ready(function () {
    isInsert = getQuery("id") === "";
    $("#txtSalMali").val(currentYear).prop("disabled", true);
    $("#txtCodeGroup").inputmask("9");
    $("#txtCodeKol").inputmask("999");
    $("#txtCodeMoain").inputmask("999999");
    if (isInsert) {
        getNewHeadingCode();
    }
    else
        getHeading();
});

function getNewHeadingCode() {
    ajax({
        loading: true,
        url: "AccountingApi/GetNewHeadingCode",
        data: {
            level: $("#hfLevel").val(),
            code: getQuery("pid")
        },
        success: function (result) {
            if (result) {
                var level = Number($("#hfLevel").val());
                $("input[data-id='Code']").val(result);
                if (level === 3)
                    getTafsilGroupList(null);
            }
        }
    });
}

function getHeading() {
    var level = Number($("#hfLevel").val());
    $("input[data-id='Code']").prop("disabled", true);
    $("#lblParentText").text(getQuery("pText"));
    ajax({
        loading: true,
        url: "AccountingApi/" + (level === 1 ? "GetGroup" : level === 2 ? "GetKol" : "GetMoain"),
        data: { code: getQuery("id") },
        success: function (result) {
            setJsonValue(result);
            if (level === 2) {
                switch (result.State) {
                    case 0:
                        $("#biTasir").prop("checked", true);
                        break;
                    case 2:
                        $("#bedehkar").prop("checked", true);
                        break;
                    case 1:
                        $("#bestankar").prop("checked", true);
                        break;
                }
            }
            else if (level === 3) {
                $("#chkIsActive").prop("checked", Number(result.DeActiveYear) > -1);
                if (Number(result.DeActiveYear) > -1)
                    $("#txtSalMali").val(result.DeActiveYear);
                getTafsilGroupList(result.TafsilGroupList);
            }
        }
    });
}

function getTafsilGroupList(TafsilGroupList) {
    ajax({
        loading: true,
        url: "AccountingApi/GetTafsilGroupList",
        data: { level: -1, pageNo: -1 },
        success: function (result) {
            $(".link-moain").each(function (index, element) {
                var level = Number($(element).attr("data-level"));
                var list = result.filter(function (item) { return item.Level === level; });
                var linkedList = [];
                if (TafsilGroupList !== null) {
                    linkedList = TafsilGroupList.filter(function (item) { return item.Level === level; });
                }
                setCheckBox(list, $(element), linkedList);
            });
        }
    });
}

function setCheckBox(list, $element, linkedList) {
    list.forEach(function (item) {
        var $data = $element.find(".row-data[hidden]").clone();
        var hasLink = linkedList.length > 0 ? linkedList.filter(function (linkItem) { return linkItem.Code === item.Code; }).length > 0 : false;
        $data.removeAttr("hidden");
        $data.find(".checkbox-control").attr("data-type", item.Level).attr("data-id", item.Code).attr("id", "checkbox" + item.Code).prop("checked", hasLink);
        $data.find(".checkbox-title").text(item.Name);
        $element.append($data);
    });
}

function saveKol() {
    var kolModel = getJsonValue();
    $('[data-id="State"]').each(function () {
        if ($(this).is(':checked'))
            kolModel['State'] = $(this).val();
    });
    kolModel["FinancialStatementCode"] = kolModel["FinancialStatementCode"] || null;
    save(kolModel, isInsert ? "InsertKol" : "UpdateKol");
}

function saveGroup() {
    var model = getJsonValue();
    data = { name: model["Name"], code: model["Code"] };
    save(data, isInsert ? "InsertGroup" : "UpdateGroup");
}

function saveMoain() {
    var linkArray = [];
    var model = getJsonValue();
    $("#tafsilH input[type='checkbox']").each(function () {
        if ($(this).is(':checked'))
            linkArray.push($(this).attr('data-id'));
    });
    model.TafsilGroupCodeList = linkArray;
    model.DeActiveYear = $("#chkIsActive").prop("checked") ? $("#txtSalMali").val() : null;
    model["RemainedState"] = model["RemainedState"];
    save(model, isInsert ? "InsertMoain" : "UpdateMoain");
}

function save(model, url) {
    var exceprionText = checkValidation("");
    if (exceprionText === "") {
        ajax({
            loading: true,
            url: "AccountingApi/" + url,
            data: model,
            success: function (result) {
                showMsgModal(2, result.FinalMessage);
                result = result.ReturnValue;
                var name = model["name"];
                if (result.indexOf("|") > 0) {
                    code = result.split("|")[0];
                    name = result.split("|")[1];
                }
                if (isInsert) {
                    refreshParent("addNodeToTree(" + getQuery('pid') + "," + code + ",'" + name + "');");
                }
                else {
                    refreshParent("editNodeToTree('" + name + "'," + code + ");");
                }
                closeTopModal();
            }
        });
    }
    else {
        showMsgModal(0, exceprionText);
    }
}
















