<%@ page import="com.censoft.common.base.Pub" %><%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2020/9/11
  Time: 12:54
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page import="com.censoft.common.db.ConnectionFactory" %>
<%@ page import="com.censoft.db.Logger" %>
<%@ page import="java.sql.Connection" %>
<%@ page import="java.util.Hashtable" %>
    <%@ page import="java.util.Vector" %>
        <%
    ConnectionFactory cf = new ConnectionFactory();
    Pub pub = new Pub();
    Connection conn = null;
    Vector v_list = null;
    String page_number = pub.trimNull(request.getParameter("page_number"));
    String role_id = pub.trimNull(request.getParameter("role_id"));
    if ("".equals(page_number)) page_number = "1";
    String page_size = pub.trimNull(request.getParameter("page_size"));
    String action = pub.trimNull(request.getParameter("action"));
    if ("".equals(page_size)) page_size = "4";
    Vector select_menu = null;
    try {
        conn = com.censoft.db.DBUtil.getConnection();
        if ("update".equals(action)) {
            String menu_id = pub.trimNull(request.getParameter("menu_id"));
            boolean is_up = cf.executeUpdate(conn, "delete from t_book_role_menu_rel where role_id=?", new Object[]{role_id});
            //Logger.log(conn,"菜单授权", "授权", role_id+","+menu_id, "授权", request);
            Logger.log(conn,"菜单授权", "授权", role_id, "授权", request);
            if (!is_up) {
                out.println("error"+ cf.getMsg());
                return;
            } else {
                out.println("success");
            }
            String[] m_ids = menu_id.split(",");
            if (m_ids != null && m_ids.length > 0) {
                for (int i = 0; i < m_ids.length; i++) {
                    if (!"".equals(pub.trimNull(m_ids[i]))) {
                        is_up = cf.executeUpdate(conn, "insert into  t_book_role_menu_rel(role_id,menu_id) values (?,?)", new Object[]{role_id, pub.trimNull(m_ids[i])});
                    }
                }
            }
            if (!is_up) {
                out.println("error" + cf.getMsg());
                return;
            } else {
                out.println("success");
            }
            return;
        }
        String sql = "select * from t_book_menu  order by menu_order asc";
        v_list = cf.doQuery(conn, sql, null, new Object[]{});
        if (v_list == null) {
            out.println("查询角色出错");
            return;
        }
        select_menu = cf.doQuery(conn, "select menu_id from t_book_role_menu_rel where role_id=?", null, new Object[]{role_id});
        System.out.println(select_menu);
    } catch (Exception e) {
        out.println("查询角色信息异常" + e);
        return;
    } finally {
        if (conn != null) {
            try {
                conn.close();
            } catch (Exception e) {
            }
        }
    }
%>
<link rel="stylesheet" href="<%=request.getContextPath()%>/js/zTree/v3/css/zTreeStyle/zTreeStyle.css"
      type="text/css">
<input class="btn btn-danger radius" type="button" onclick="javascript:fun_getCheckValue();"
       value="&nbsp;&nbsp;确定授权&nbsp;&nbsp;">
<table class="table">
    <tr>
        <td width="30%" class="va-t">
            <ul id="treeDemo" class="ztree"></ul>
        </td>
        <td class="va-t">
            <iframe ID="testIframe" Name="testIframe" FRAMEBORDER=0 SCROLLING=AUTO width=100% height=390px></iframe>
        </td>
    </tr>
</table>
<form class="form form-horizontal" id="form-admin-add">
    <input type="hidden" name="role_id" id="role_id" value="<%=role_id%>"/>
    <input type="hidden" name="menu_id" id="menu_id" value=""/>
    <input type="hidden" name="action" id="action" value="update"/>
</form>
<!--_footer 作为公共模版分离出去-->
<script type="text/javascript" src="<%=request.getContextPath()%>/js/zTree/v3/js/jquery.ztree.all-3.5.min.js"></script>
<script type="text/javascript">
    var setting = {
        view: {
            dblClickExpand: false,
            showLine: false,
            selectedMulti: false
        }, check: {
            enable: true,//显示复选框
            chkStyle: "checkbox"
        },
        data: {
            simpleData: {
                enable: true,
                idKey: "id",
                pIdKey: "pId",
                rootPId: ""
            }
        },
        callback: {
            beforeClick: function (treeId, treeNode) {
                var zTree = $.fn.zTree.getZTreeObj("tree");
                if (treeNode.isParent) {
                    demoIframe.attr("src", "./btn_select-t.jsp?role_id=<%=role_id%>&menu_id=" + treeNode.id);
                    return false;
                } else {
                    demoIframe.attr("src", "./btn_select-t.jsp?role_id=<%=role_id%>&menu_id=" + treeNode.id);
                    return true;
                }
            }
        }
    };

    var zNodes = [
        <%
    if (v_list != null && v_list.size() > 0) {
        for (int i = 0; i < v_list.size(); i++) {
            Hashtable ht = (Hashtable) v_list.get(i);
            String menu_name = pub.trimNull((String) ht.get("menu_name"));
            String id = pub.trimNull((String) ht.get("id"));
            String p_id = pub.trimNull((String) ht.get("p_id"));
%>
        {
            id: "<%=id%>", pId: "<%=p_id%>", name: "<%=menu_name%>",
            open: true
        },
        <%}}%>
    ];

    var code;

    function showCode(str) {
        if (!code) code = $("#code");
        code.empty();
        code.append("<li>" + str + "</li>");
    }

    var checkedNodes = [
        <%
    if (select_menu != null && select_menu.size() > 0) {
        for (int i = 0; i < select_menu.size(); i++) {
            Hashtable ht = (Hashtable) select_menu.get(i);
            String menu_id = pub.trimNull((String) ht.get("menu_id"));
%>
        {id: "<%=menu_id%>"},
        <%}}%>
    ];
    $(document).ready(function () {
        demoIframe = $("#testIframe");
        $.fn.zTree.init($("#treeDemo"), setting, zNodes);
        var zTree = $.fn.zTree.getZTreeObj("treeDemo");
        zTree.expandAll(true);
        for (var i = 0; i < checkedNodes.length; i++) {
            // 回显选中的数据　　　
            zTree.checkNode(zTree.getNodeByParam("id", checkedNodes[i].id), true);
        }
    });

    function fun_getCheckValue() {
        var zTree = $.fn.zTree.getZTreeObj("treeDemo");
        var nodes = zTree.getChangeCheckedNodes(true);
        var result = '';
        for (var i = 0; i < nodes.length; i++) {
            result += nodes[i].id + ',';
        }
        saveForm(result);
    }

    function saveForm(menu_ids) {
        document.getElementById("menu_id").value = menu_ids;
        $.ajax({
            type: "POST",
            url: "./menu_tree_select-t.jsp",
            data: $('#form-admin-add').serialize(),
            success: function (msg) {
                if (msg.indexOf("success") >= 0) {
                    layer.msg('操作成功!', {icon: 1, time: 1000},
                        function () {
                            // var index = parent.layer.getFrameIndex(window.name);
                            // parent.layer.close(index);
                        });
                } else {
                    layer.msg('操作失败', {
                        icon: 5,
                        time: 2000 //2秒关闭（如果不配置，默认是3秒）
                    }, function () {
                        // console.log("********************8")
                    });
                }
            }
        });
    }
</script>