<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title></title>
    <link rel="stylesheet" th:href="@{/layui/css/layui.css}">
    <link rel="icon" th:href="@{image/sgl.png}" sizes="32x32">
    <script th:src="@{/layui/layui.js}"></script>
    <script th:src="@{/layui/jquery-3.4.1.min.js}"></script>
    <link rel="stylesheet" th:href="@{/css/common.css}">
</head>
<style>
	body{background: #f2f2f2}
	#boxDiv{background: #ffffff}
	#titleDiv{overflow: visible;}
</style>
<body class="layui-layout-body">
<div id="boxDiv" style="left:8px;right: 8px;bottom:8px;top:8px;position:absolute;">
	<div class="toolbar" id="titleDiv">
    	<div class="layui-inline">
			<span>角色名称：</span>
            <input type="text" id="searchName" placeholder="名称关键字 " autocomplete="off" class="layui-input formWidth" />
        </div>
        
        <div class="layui-inline">
			<button class="layui-btn layui-btn-sm layui-btn-normal" data-type="search" id="search"><i class="layui-icon">&#xe615;</i>查询</button>
			<button class="layui-btn layui-btn-sm layui-btn-normal" data-type="add" id="add"><i class="layui-icon">&#xe654;</i>添加</button>
   		</div>
    </div>
    	
	<table id="mainTable" lay-filter="roleTable"></table>	
	   
	<!-- 表格操作栏 --> 		
	<script type="text/html" id="barDemo">
  		<a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
  		<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
	</script>
		
	<!-- 增加 -->
	<div id="addRole" style="display:none;">
		<form id="layui-form zjUser" style="margin-top:20px;">
			<div class="layui-form-item">
                <label class="layui-form-label">名称:</label>
                <div class="layui-input-block">
                    <input type="text" id="name" required  lay-verify="required" autocomplete="off" placeholder="请输入角色名" class="layui-input formWidthTwo">
                </div>
            </div>

            <div class="layui-form-item">
            	<label class="layui-form-label">权限:</label>
            	<div class="layui-input-inline">
	            <div class="layui-unselect layui-form-select downpanel">
	                <div class="layui-select-title">
	                    <input class="layui-input formWidthTwo" autocomplete="off" name="treeclass" id="treeclass" placeholder="--请选择--"/>
	                    <input type="hidden" name="selectID" id="selectId">
	                    <i class="layui-edge"></i>
	                </div>
	                <dl class="layui-anim layui-anim-upbit">
	                    <dd>
	                        <ul id="classtree"></ul>
	                    </dd>
	                </dl>
	            </div>
	        	</div>
            </div>

		</form>
	</div>
</div>
</body>
<script th:inline="javascript">
	let menuList= [[${resourceInfo}]];
	let resourceInfo = [];
	resourceInfo.push(menuList);
</script>
<script>
	let tHeight = $(".toolbar").height()+6;
	let element ,
			table,
			laydate,
			layer,
			form,
			tree;
	let menuId="";

	layui.use(['element','table','laydate','layer','form','tree'], function(){
		element = layui.element;
		table = layui.table;
		laydate = layui.laydate;
		layer = layui.layer;
		form = layui.form;
		tree = layui.tree;

		//表格加载
		table.render({
			elem: '#mainTable',
			height: 'full-'+58,
			url: '/searchRole?roleName', //数据接口
			title: '用户表',
			page: true ,//开启分页
			limit:20,
			limits:[20,30,50],
			//toolbar: '', //开启工具栏，此处显示默认图标，可以自定义模板
			defaultToolbar: [],
			id:'roleTable',
			cols: [
				[ //表头
					//{type: 'checkbox', fixed: 'left'},
					{type: 'numbers', title: '序号', width: 50},
					{field: 'roleName', title: '名称', sort: false},
					{fixed: 'right',title:'操作', align:'center',width:150, toolbar: '#barDemo'}
				]
			]
		});

		//时间控件
		laydate.render({
			elem:'#date', //指定元素
			eventElem: '.date-input-icon',
			trigger: 'click',
		});

		//查询
		$("#search").on('click',function(){
			search();
		});

		//新增
		$("#add").on('click',function() {
			$("#name").val("");
			$("#treeclass").val("");
			$('#name').attr("disabled",false);
			tree.reload('tree', {});


			layer.open({
				type : 1,
				title : "新增内容",
				shade : 0,
				area : [ '500px', '80%' ],
				offset : 'auto',
				content : $("#addRole"),
				btn : [ '保存', '取消' ],
				btnAlign : 'c',
				yes : function(index, layero) {
					let name=$("#name").val();
					let menuId=$("#selectId").val();

					if (name == undefined ||name=='') {
						layer.msg('名称不能为空', {
							time : 500
						}) ;
						return;
					}


					let i = layer.load(0, {time: 5000});
					let param = {};
					param.roleName = $("#name").val();
					param.menuId = $("#selectId").val();
					$.ajax({
						url : '/insertRoles',
						type : "post",
						data : param,
						dataType:"json",
						success : function(data) {
							layer.close(i);
							if (data.errCode == '0') {
								layer.msg('添加成功', {
									time : 500
								});
								layer.close(index);
								$("#search").click();
							} else {
								layer.msg(data.errMsg, {
									time : 500
								});
							}
						},
						error : function() {}
					})
				},
				btn2 : function() {}
			});
		});

		//修改、删除
		let selectData;
		table.on('tool(roleTable)', function(obj){
			selectData=obj.data;
			let data = obj.data;
			$("#treeclass").val("");
			tree.reload('tree', {});

			$("#name").val(data.roleName);
			getSelectMenuId(data.roleId);

			if(obj.event === 'edit'){

				layer.open({
					type:1,
					title:"修改信息",
					shade:0,
					area: ['500px', '80%'],
					offset:'auto',
					content: $("#addRole"),
					btn: ['保存', '取消'],
					btnAlign: 'c',
					yes: function (index, layero) {
						let name=$("#name").val();
						let menuId=$("#selectId").val();

						if (name == undefined ||name=='') {
							layer.msg('名称不能为空', {
								time : 500
							}) ;
							return;
						}

						let i = layer.load(0, {time: 5000});
						let param = {};
						param.roleId = selectData.roleId;
						param.roleName = $("#name").val();
						param.menuId = $("#selectId").val();

						$.ajax({
							url:'/modifyRoleResource',
							type:"post",
							data:param,
							dataType:"json",
							success:function(data){
								layer.close(i);
								if (data.state == true) {
									layer.msg('修改成功', {
										time : 500
									});
									layer.close(index);

									let curr=$(".layui-laypage-em").next().html();
									search(curr);
								} else {
									layer.msg(data.message, {
										time : 500
									});
								}
							},
							error:function(){

							}
						})
						$('#name').attr("disabled",false);
					},
					btn2:function(){
						$('#name').attr("disabled",false);
					}
				});
			}else if(obj.event === 'del') {

				layer.confirm('确定删除么？', {
							title : '删除'
						}, function(index) {
							$.ajax({
								url : '/deleteRole',
								type : "post",
								data : {"roleId":data.roleId},
								dataType : "json",
								success : function(data) {
									if (data.state == true) {
										layer.msg('删除成功', {
											time : 500
										});
										layer.close(index);

										obj.del();
									} else {
										layer.msg(data.message, {
											time : 500
										});
									}
								},
								error : function() {}
							});
						}
				);
			}
		});

		//下拉树
		tree.render({
			elem: "#classtree",
			showCheckbox: true,
			onlyIconControl: true,
			id:"tree",
			data:resourceInfo,
			click: function (node) {
				let elm=node.elem[0];
				$(elm).children(".layui-tree-entry").find(".layui-form-checkbox").click();
				// let $select = $($(this)[0].elem).parents(".layui-form-select");
				// $select.removeClass("layui-form-selected").find('.layui-select-title>input[name="treeclass"]').val(node.data.title).end().find("input:hidden[name='selectID']").val(node.id);
			},
			oncheck:function(node){
				setSelectValue();
			}
		});


		$(".downpanel").on("click", ".layui-select-title", function (e) {
			$(".layui-form-select").not($(this).parents(".layui-form-select")).removeClass("layui-form-selected");
			$(this).parents(".downpanel").toggleClass("layui-form-selected");
			layui.stope(e);
		}).on("click", "dl", function (e) {
			layui.stope(e);
		});
		$(document).on("click", function (e) {
			$(".layui-form-select").removeClass("layui-form-selected");
		});


	});


	//根据id获取选择的id
	function getSelectMenuId(roleId) {
		$.ajax({
			url : '/getSelectMenuId',
			type : "post",
			data : {roleId:roleId},
			dataType:"json",
			success : function(data) {
				tree.setChecked('tree',data);
				setSelectValue();
			},
			error : function() {}
		})
	}

	//重载表格数据
	function search(num){
		let name = $("#searchName").val();
		//let date = $("#date").val();
		table.reload('roleTable', {
			method: 'get',
			url:'/searchRole',
			where: {
				'roleName':name
			},
			page: {
				curr: num
			}
		});
	}

	//根据选中的值设置到input中
	function setSelectValue(){
		let checkedData = tree.getChecked('tree');
		checkid = [];
		checktitle = [];
		getSelect(checkedData);
		$("#treeclass").val(checktitle);
		$("#selectId").val(checkid);
	}

	//获取树勾选的值
	let checkid = [];
	let checktitle = [];
	function getSelect(data) {
		for (let i = 0; i < data.length; i++) {
			checkid.push(data[i].id);
			checktitle.push(data[i].title);
			if (data[i].children !== undefined) {
				getSelect(data[i].children);
			}
		}
	}
</script>
</html>
