var code = getQuery("code");
var roleItems = [];
var menuModels = [];
var treeRoot = [];

$(document).ready(function () {
    $(".container-role").on("change", "input:checkbox", function () {
        var itemName = $(this).attr("data-id");
        var nodeId = Number($(this).closest(".item-role").attr("data-node"));
        var formName = $(this).closest(".item-role").attr("data-form")
        var checkedCount = $("[data-form='" + formName + "'] input:checkbox:checked").length;
        var allCount = $("[data-form='" + formName + "'] input:checkbox").length;
        if (checkedCount === 0) {
            $("#jstree").jstree(true).uncheck_node(nodeId + "-hf1");
            $("#jstree").jstree(true).uncheck_node(nodeId + "-hf2");
        }
        else if (checkedCount === allCount) {
            $("#jstree").jstree(true).check_node(nodeId + "-hf1");
            $("#jstree").jstree(true).check_node(nodeId + "-hf2");
        }
        else {
            $("#jstree").jstree(true).uncheck_node(nodeId + "-hf1");
            $("#jstree").jstree(true).check_node(nodeId + "-hf2");
        }

        if ($(this).prop("checked")) {
            if (itemName != "-1") {
                var formAccess = $("[data-form='" + formName +"'] input:checkbox[data-id=-1]:checked").length === 1;
                if (!formAccess) {
                    $("[data-form='" + formName + "'] input:checkbox[data-id=-1]").prop("checked",true);
                    removeFromList(1, "-1", formName);
                }
            }
            removeFromList(itemName === "-1" ? 1 : 3, itemName, formName);
        }
        else {
            if (itemName === "-1") {
                var buttonAccess = $("[data-form='" + formName + "'] input:checkbox[data-id!=-1]:checked");
                buttonAccess.each(function () {
                    $(this).prop("checked", false);
                    pushToList(3, $(this).attr("data-id"), formName);
                });
            }
            pushToList(itemName === "-1" ? 1 : 3, itemName, formName);
        }
    });
    $('#jstree').parent().css('height', $(window).height() - 185);
    $("#jstree").on("check_node.jstree uncheck_node.jstree", function (e, data) {
        pushDataLevel(data, data.node.state.checked);
    });
    $('#jstree').bind('select_node.jstree', function (e, data) {
        if (data.node.original.depth == 3) {
            $(".item-role:not([hidden])").remove();
            var action = menuModels.find(c => c.ID == data.node.id);
            getPageButton(action.Href, data.node.id, action.GhId);
        }
        $('.container-role').css("display", data.node.original.depth === 3 ? "" : "none");

    });
    initial();
});

async function initial() {
    await createBpmsMenu();
    await getTreeRoot();
    if (code) {
        await getRoleList(code);
        await getRoleItems(code);
    }
    $("#jstree").jstree({
        checkbox: {
            "keep_selected_style": true,
            "tie_selection": false,
            "whole_node": false
        },
        plugins: [
            "search", "checkbox"
        ],
        core: {
            data: treeRoot
        }
    });
    setTimeout(function () {
        for (var i = 0; i < roleItems.length; i++) {
                stateCheckboxNode(roleItems[i]);
        }
    }, 600);
    closeLoading();
    $("#divMain").show();
}
function pushToList(typeCode, itemName, formName) {
    if (!roleItems.some(x => x.FormName === formName && x.ItemName === itemName && x.TypeCode === typeCode))
        roleItems.push({
            'FormName': formName,
            'ItemName': itemName,
            'TypeCode': typeCode
        });
}
function removeFromList(typeCode, itemName, formName) {
    var index = roleItems.findIndex(x => x.FormName === formName && x.ItemName === itemName && x.TypeCode === typeCode);
    if (index > -1)
        roleItems.splice(index, 1);
}
function stateCheckboxNode(roleItem) {
    var data = menuModels.find(c => c.GhId.toLowerCase() === roleItem.FormName.toLowerCase());
    if (!data)
        return;

    var id = data.ID;
    var formName = roleItem.FormName;
    var buttonAccess = roleItems.filter(x => x.FormName === formName && x.TypeCode === 3);
    var formAccess = roleItems.filter(x => x.FormName === formName && x.TypeCode === 1);
    if (formAccess.length > 0) {
        $("#jstree").jstree(true).uncheck_node(id + "-hf1");
        $("#jstree").jstree(true).uncheck_node(id + "-hf2");
    }
    else if (buttonAccess.length > 0) {
        $("#jstree").jstree(true).check_node(id + "-hf1");
        $("#jstree").jstree(true).uncheck_node(id + "-hf2");
    }
    else {
        $("#jstree").jstree(true).check_node(id + "-hf1");
        $("#jstree").jstree(true).check_node(id + "-hf2");
    }
}
function pushDataLevel(dataNode, state) {
    if (dataNode.node.original.depth == 1) {
        var level2 = menuModels.filter(function (item) { return (item.ParentID == dataNode.node.id); })
        for (var i = 0; i < level2.length; i++) {
            var level3 = menuModels.filter(function (item) { return (item.ParentID == level2[i].ID); })
            checkData(level3, state)
        }
    }
    else if (dataNode.node.original.depth == 2) {
        var level3 = menuModels.filter(function (item) { return (item.ParentID == dataNode.node.id); })
        checkData(level3, state)
    }
    else if (dataNode.node.original.depth == 3) {
        var node = menuModels.filter(function (item) { return (item.ID == dataNode.node.id); });
        checkData(node, state);
        
    }
}
function checkData(data, state) {
    for (var i = 0; i < data.length; i++) {
        if (state) {
            removeFromList(1, "-1", data[i].GhId);
            var buttonAccess = roleItems.filter(x => x.FormName === data[i].GhId && x.TypeCode === 3);
            buttonAccess.forEach(function (item) {
                index = roleItems.indexOf(item);
                if (index > -1)
                    roleItems.splice(index, 1);
            });
        }
        else{ 
            pushToList(1, "-1", data[i].GhId);
        }
        $("[data-form='" + data[i].GhId + "']").each(function (index, item) {
            $(this).find("input").prop("checked", state);
        });
    }
}
function nextStep() {
    $('#step1').hide();
    $('#step2').show();
    $('#spStep1').removeClass('step-active');
    $('#spStep2').addClass('step-active');
    $('.button-accept').val(window.top.okFinish);
    $('.label-cancel').text(window.top.previous);
    $('.button-accept').attr('onclick', 'save();return false;');
    $('.label-cancel').attr('onclick', 'previousStep();');
}
function previousStep() {
    $('#step1').show();
    $('#step2').hide();
    $('#spStep1').addClass('step-active');
    $('#spStep2').removeClass('step-active');
    $('.button-accept').val(window.top.next);
    $('.label-cancel').text(window.top._cancel);
    $('.button-accept').attr('onclick', 'nextStep();return false;');
    $('.label-cancel').attr('onclick', 'closeTopModal();');
}

async function getRoleList(code, search, sort) {
    await ajax({
        url: "GeneralApi/GetRoleList",
        data: { search: search, sort: sort },
        success: function (result) {
            var userRole = result.filter(x => x.Code === Number(code));
            if (userRole.length > 0) {
                setJsonValue(userRole[0], "#step1");
            }
        }
    });
}
async function getRoleItems(code) {
    await ajax({
        url: "GeneralApi/GetRoleItems",
        data: { codeRole: code },
        success: function (result) {
            roleItems = result;
        }
    });
}
async function createBpmsMenu() {
    await ajax({
        url: "GeneralApi/CreateBpmsMenu",
        success: function (result) {
            menuModels = result;
            var level3 = menuModels.filter(x => !x.Href && x.GhId);
            level3.forEach(function (item) {
                var id = item.ID;
                var parentId = item.ParentID;
                var model = menuModels.filter(x => x.ParentID === id);
                model.forEach(function (item2) {
                    item2.ParentID = parentId
                });
                var index = menuModels.indexOf(item);
                menuModels.splice(index, 1);
            });
            menuModels.forEach(function (item) {
                var documentCode = getQuery("sanadtype", item.Href);
                if (documentCode)
                    item.GhId += "_" + documentCode;
            });
        }
    });
}
async function getTreeRoot() {
    await ajax({
        url: "GeneralApi/GetTreeRoot",
        data: { menues: menuModels },
        success: function (data) {
            treeRoot = eval(data.result);
        }
    });
}
function save() {
    var data = {};
    data["Name"] = $('#txtRoleName').val();
    data["Summery"] = $('#txtTozihat').val();
    data["IsActive"] = $('#chkActive').is(':checked');
    data["Code"] = code ? code : -1;
    data["UserRoleDetails"] = roleItems;
    ajax({
        loading: true,
        url: "GeneralApi/InsertRole",
        data: data,
        success: function (result) {
            showMsgModal(2, window.top.savedSuccessfully);
            refreshParent('refresh()');
            closeTopModal();
        }
    });
}
async function getPageButton(path, nodeId, ghId) {
    await ajax({
        url: "GeneralApi/GetPageButton",
        data: { path: path },
        success: function (data) {
            data.unshift({"Caption":window.top.showForm,"Id" : "-1"});
            data.forEach(function (item) {
                var buttonAccess = !roleItems.some(x => x.FormName == ghId && x.ItemName == "-1");
                if (buttonAccess)
                    buttonAccess = !roleItems.some(x => x.FormName == ghId && x.ItemName == item.Id);

                var div = $(".template-role").clone().removeClass("template-role").removeAttr("hidden").attr("data-form", ghId).attr("data-node", nodeId);
                div.find(".caption").text(item.Caption);
                div.find("input").attr("data-id", item.Id).attr("id", "chk" + item.Id).prop("checked", buttonAccess);
                div.find("label").attr("for", "chk" + item.Id);
                $(".container-role").append(div);
            });
        }
    });
}
