/*2014-05-30 add by yb
 * describe:角色管理
 * 
 */
// 获取WEB端表格数据
function getDataWeb(orgId,roleid) {

	var contextPath = $("#contextPath").val();
	$.ajax({
		url: contextPath + "/admin/function/funcRoletreeByOrg",
		data: {
			isApp: 0,
			orgId: orgId,
			roleid: roleid
		},
		type: "POST",
		dataType: "json",
		success: function (data) {
			let setting1 = {
				edit: {
					enable: true,
					editNameSelectAll: true,
					showRenameBtn: true
				},
				data: {
					simpleData: {
						enable: true
					}
				}
			};
			//替换返回json数据中的key值 供ztree展示数据
			let jsonData = data.data;
			for (let i = 0; i < jsonData.length; i++) {
				jsonData[i]["name"] = jsonData[i]["functionName"]; //'text'是需要的字段
				jsonData[i]["pId"] = jsonData[i]["parentcode"];
				delete jsonData[i]["functionName"]; //key是要替换为'text'的字段
				delete jsonData[i]["parentcode"];
			}
			$.fn.zTree.init($("#tree2"), setting1, jsonData);
			let treeObj = $.fn.zTree.getZTreeObj("tree2");
			let nodes = treeObj.transformToArray(treeObj.getNodes());
			perm = nodes[0].perms;
			let dataArr = [],
				arr = [];
			$.each(nodes, function (index, value) {
				// if (index != 0) {
				if (value.rightType == 0) {
					dataArr.push(value);
				}
				// }
			})
			// console.log(dataArr, 888);
			// get_role_list("#table_role_web", arr);
			get_role_list("#table_role_web", dataArr);
		},
		error: function (data) {
			// alert("系统繁忙,加载失败..");
		}
	});
}
// 获取微信端表格数据
function getDataWx(orgId,roleid) {

	var contextPath = $("#contextPath").val();
	$.ajax({
		url: contextPath + "/admin/function/funcRoletreeByOrg",
		data: {
			isApp: 1,
			orgId: orgId,
			roleid: roleid
		},
		type: "POST",
		dataType: "json",
		success: function (data) {
			let setting1 = {
				edit: {
					enable: true,
					editNameSelectAll: true,
					showRenameBtn: true
				},
				data: {
					simpleData: {
						enable: true
					}
				}
			};
			//替换返回json数据中的key值 供ztree展示数据
			let jsonData = data.data;
			for (let i = 0; i < jsonData.length; i++) {
				jsonData[i]["name"] = jsonData[i]["functionName"]; //'text'是需要的字段
				jsonData[i]["pId"] = jsonData[i]["parentcode"];
				delete jsonData[i]["functionName"]; //key是要替换为'text'的字段
				delete jsonData[i]["parentcode"];
			}
			$.fn.zTree.init($("#tree1"), setting1, jsonData);
			let treeObj = $.fn.zTree.getZTreeObj("tree1");
			let nodes = treeObj.transformToArray(treeObj.getNodes());
			perm = nodes[0].perms;
			let dataArr = [],
				arr = [];
			$.each(nodes, function (index, value) {
				// if (index != 0) {
				if (value.rightType == 0) {
					dataArr.push(value);
				}
				// }
			})
			// console.log(dataArr, 888);
			// get_role_list("#table_user_wx", arr);
			get_role_list("#table_user_wx", dataArr);
		},
		error: function (data) {
			// alert("系统繁忙,加载失败..");
		}
	});
}
// 表格数据渲染
function get_role_list(element, jsonData) {
	layui.use('table', function () {
		var table = layui.table;
		table.render({
			elem: element,
			size: 'lg', //小尺寸的表格
			limit: 1000,
			cellMinWidth: 80, //全局定义常规单元格的最小宽度，layui 2.2.1 新增
			cols: [
				[{
					field: 'name',
					width: '33.33%',
					title: '一级功能',
					LAY_CHECKE: true,
					templet: function (data) {
						return "<div style='float:left;padding-left: 10px' class='operate tr1'><input name='role' type='checkbox' class='checkNo' data-bool='"+data.checked+"'/>" + data.name +
							" </div><div class='operate frt' style='padding-right: 10px' data-right='1'  data-parent='" + data.id +
							"' data-id='" + data.id + "' data-rightType='" + data.rightType + "' data-parentcode='" + data.pId +
							"'  data-treecode='" + data.treecode + "'  data-name='" + data.name + "' data-order='" + data.orderNumber + "' data-perms='" + data.perms + "'></div>"
					}
				}, {
					field: 'name',
					width: '33.33%',
					title: '二级功能',
					templet: function (data) {
						let childOne = data.children;
						let templt = " ";
						if (childOne) {
							for (var i = 0; i < childOne.length; i++) {
								let jsondata = [],
									indec = 1;
								jsondata = childOne[i].children;
								if (jsondata) {
									indec = jsondata.length
								}
								templt += "<div class='layui-table-cell laytable-cell-1-name am' style='height:" + 50 * indec +
									"px; line-height:" + 50 * indec + "px'><div style='float:left' class='operate tr2'><input name='role' type='checkbox' class='checkNo' data-bool='"+childOne[i].checked+"'/>" + childOne[i].name +
									"</div><div class='operate frt'  data-right='2'  data-parent='" + childOne[i].id +
									"' data-id='" + childOne[i].id + "' data-rightType='" + childOne[i].rightType + "' data-parentcode='" + childOne[i].pId +
									"' data-treecode='" + childOne[i].treecode + "'  data-name='" + childOne[i].name + "'  data-order='" + childOne[i].orderNumber +
									"'  data-url='" + childOne[i].url + "' data-perms='" + childOne[i].perms + "'></div></div>"
							}
						}
						return templt
					}
				}, {
					field: 'name',
					width: '33.33%',
					title: '三级功能',
					templet: function (data) {
						let childOne = data.children;
						let templt1 = " ";
						if (childOne) {
							for (var i = 0; i < childOne.length; i++) {
								let jsondata = [];
								jsondata = childOne[i].children;
								if (jsondata) {
									for (var j = 0; j < jsondata.length; j++) {
										templt1 += "<div class='layui-table-cell laytable-cell-1-name am' style='height:50px;line-height:50px'><div style='float:left' class='operate tr3'><input name='role' type='checkbox' class='checkNo' data-bool='"+jsondata[j].checked+"'/>" + jsondata[j].name +
											"</div><div class='operate frt' data-id='" + jsondata[j].id + "'  data-parent='" + jsondata[j].pId +
											"' data-rightType='" + jsondata[j].rightType + "' data-parentcode='" + jsondata[j].pId + "' data-treecode='" + data.treecode +
											"' data-name='" + jsondata[j].name + "' data-code='" + jsondata[j].systemcode + "' data-perms='" + jsondata[j].perms + "'></div></div>"
									}
								} else {
									templt1 += "<div class='layui-table-cell laytable-cell-1-name am' style='height:50px;line-height:50px'><div style='float:left' class='operate'></div></div>"
								}
							}
						}
						return templt1
					}
				}]
			],
			data: jsonData,
			id: 'reloadData',
			// page: true,
			response: {
				statusName: 'code', //数据状态的字段名称，默认：code             
				statusCode: 200, //成功的状 态码，默认：0        
				countName: "count", //数据总数的字段名称，默认：count            
				dataName: "data" //数据列表的字段名称，默认：data
			},
			done: function (res, curr, count) {
				var input = document.createElement("input"); //创建一个input标签
				input.type = "checkbox";
				input.name = "role";
				input.setAttribute("class", "checkNo");
				var i = 1;
				var divs = "<div class='layui-unselect layui-form-checkbox firstCheck' lay-skin=''><i class='layui-icon'></i></div>";
				var $element,$checks,$checkDiv;
				if (element == "#table_role_web") {
					$element = $(".web-power");
					$checks = $(".web-power .operate .checkNo");
					$checkDiv = $(".web-power .operate .layui-unselect");
				}else{
					$element = $(".wx-power");
					$checks = $(".wx-power .operate .checkNo");
					$checkDiv = $(".wx-power .operate .layui-unselect");
				}
				$.each($checks, function (index, node) {
					if(node.getAttribute("data-bool") == "true"){
						node.setAttribute("checked",true);
						$checkDiv[index].classList.add("layui-form-checked");
					}else{
						node.removeAttribute("checked");
						$checkDiv[index].classList.remove("layui-form-checked");
					}
				});
		
					$element.find("th .layui-table-cell span").before(input);
					$element.find("th .layui-table-cell span").before(divs);
					$element.find(".firstCheck").eq(0).attr("data-sort", "1");
					$element.find(".firstCheck").eq(1).attr("data-sort", "2");
					$element.find(".firstCheck").eq(2).attr("data-sort", '3');
					$element.on("click",".firstCheck",function(){
						if ($(this).hasClass("layui-form-checked")) {
							$(this).removeClass("layui-form-checked");
							if ($(this).data("sort") == 1) {
								$element.find("tbody .tr1 .checkNo").removeAttr("checked");
								$element.find("tbody .tr1 .layui-form-checked").removeClass("layui-form-checked");
							} else if ($(this).data("sort") == 2) {
								$element.find(".tr2 .checkNo").removeAttr("checked");
								$element.find("tbody .tr2 .layui-form-checked").removeClass("layui-form-checked");
							} else if ($(this).data("sort") == 3) {
								$element.find(".tr3 .checkNo").removeAttr("checked");
								$element.find(".tr3 .layui-form-checked").removeClass("layui-form-checked");
							}
						} else {
							$(this).addClass("layui-form-checked");
							if ($(this).data("sort") == 1) {
								$element.find(".tr1 .checkNo").attr("checked",true);
								$element.find(".tr1 .layui-unselect").addClass("layui-form-checked");
							} else if ($(this).data("sort") == 2) {		
								$element.find(".tr2 .checkNo").attr("checked",true);		
								$element.find(".tr1 .checkNo").attr("checked",true);					
								$element.find(".tr2 .layui-unselect").addClass("layui-form-checked");
								$element.find(".tr1 .layui-unselect").addClass("layui-form-checked");
								$element.find(".firstCheck").eq(0).addClass("layui-form-checked");
							} else if ($(this).data("sort") == 3) {
								$element.find("tbody .checkNo").attr("checked",true);		
								$element.find("tbody .layui-unselect").addClass("layui-form-checked");
								$element.find(".firstCheck").eq(0).addClass("layui-form-checked");
								$element.find(".firstCheck").eq(1).addClass("layui-form-checked");
							}
						}
					})
					$element.on("click",".operate .layui-unselect",function(){
						let id = $(this).parent().next().data("id");
						let type = $(this).parent().next().data("right");
						let classH = $(this).hasClass("layui-form-checked");
						if(classH){
							$(this).prev().attr("checked",true);
						}else{
							$(this).prev().removeAttr("checked");
						}
						if (type == 1) {
							var list = $(this).parent().parent().parent().parent().find(".checkNo");
							if (classH) {
								$(this).parent().parent().parent().parent().find(".layui-unselect").addClass("layui-form-checked");
								$.each(list,function(index,item){
									item.setAttribute("checked",true);
								})
							} else {
								$(this).parent().parent().parent().parent().find(".layui-unselect").removeClass("layui-form-checked");
								$.each(list,function(index,item){
									item.removeAttribute("checked");
								})
							}
						} else if (type == 2) {
							let thirdCode = $(this).parent().parent().parent().parent().next().find(".frt");
							let thirdCheck = $(this).parent().parent().parent().parent().next().find(".layui-unselect");
							let thirdInput = $(this).parent().parent().parent().parent().next().find(".checkNo");
							let parentT1 = $(this).parent().parent().parent().parent().prev().find(".frt");
							let parentShow1 = $(this).parent().parent().parent().parent().prev().find(".tr1 .layui-unselect");
							let parentInput = $(this).parent().parent().parent().parent().prev().find(".checkNo");
							let thisId1 = $(this).parent().next().data("parentcode");
							for (var i = 0; i < parentT1.length; i++) {
								if (parentT1[i].getAttribute("data-id") == thisId1) {
									if(classH){
										if (!parentShow1[i].classList.contains("layui-form-checked")) {
											parentInput[i].setAttribute("checked",true);
											parentShow1[i].classList.add("layui-form-checked");
										} 
									}
									if (thirdCode) {
										for (var j = 0; j < thirdCode.length; j++) {
											if (thirdCode[j].getAttribute("data-parentcode") == id) {
												if (classH) {
													thirdCheck[j].classList.add("layui-form-checked");
													thirdInput[j].setAttribute("checked",true);
												} else {
													thirdCheck[j].classList.remove("layui-form-checked");
													thirdInput[j].removeAttribute("checked");
												}
											}
										}
									}
								}
							}
						} else if (type == undefined) {
							let parentT = $(this).parent().parent().parent().parent().prev().find(".frt");
							let parentShow = $(this).parent().parent().parent().parent().prev().find(".tr2 .layui-unselect");
							let parentInput = $(this).parent().parent().parent().parent().prev().find(".tr2 .checkNo");
							let parentShowOne = $(this).parent().parent().parent().parent().prev().prev().find(".tr1 .layui-unselect");
							let parentInputOne = $(this).parent().parent().parent().parent().prev().prev().find(".tr1 .checkNo");
							let thisId = $(this).parent().next().data("parentcode");
							for (var i = 0; i < parentT.length; i++) {
								if (parentT[i].getAttribute("data-id") == thisId) {
									if(classH){
										if (!parentShow[i].classList.contains("layui-form-checked")) {
											parentInput[i].setAttribute("checked",true);
											parentShow[i].classList.add("layui-form-checked");
											if(!parentShowOne.hasClass("layui-form-checked")){
												parentInputOne.attr("checked",true);
												parentShowOne.addClass("layui-form-checked");
											}
										}
									}
								}
							}
						}
					})
			}
		});
	});
}
/**
 *查询url参数
 */
function getQueryStr(_url, _param) {
	var rs = new RegExp("(^|)" + _param + "=([^\&]*)(\&|$)", "g").exec(_url),
		tmp;
	if (tmp = rs) {
		return tmp[2];
	}
	return "";
}
  // 模糊搜索事件
  function search_fuzzy(){
    var contextPath = $("#contextPath").val();
    $('body').on("input",'#orgId',function(event){
      var _this = $(this)
      cjqt.search_fuzzy.event_input(_this,'org__id','org__span',contextPath,'/admin/templ/getOrgListByName')
    });
    $('body').on("focus",'#orgId',function(event){
      var _this = $(this)
      cjqt.search_fuzzy.event_focus(_this,'org__id','org__span',contextPath,'/admin/templ/getOrgListByName')
    });
    $('body').on('blur','#orgId',function(event) {
      var _this = $(this)
      cjqt.search_fuzzy.event_blur(_this,'org__id')
    });
    $('body').on('click','.select_wrap>.org__span', function(event) {
      event.preventDefault();
      event.stopPropagation();
      /* Act on the event */
      var _this = $(this)
      cjqt.search_fuzzy.event_click(_this,'org__id','#orgId')
    });
  }
$(function () {
	var orgId = $("#conditionform #orgId").attr('org__id');
	var roleid = $("#roleid").val();
	getDataWeb(orgId,roleid);
  getDataWx(orgId,roleid);
  search_fuzzy()
	$("#orgId").bind("change", function () {
		orgId = $("#conditionform #orgId").attr('org__id');
  });

	//编辑提交
	$("#btn-save").bind("click", function () {
		var roleid = $("#roleid").val();
		var funcIds = "";
		var orgId = $("#conditionform #orgId").attr('org__id');
		if (roleid != "-1" && $.trim(orgId) == "") {
			alert("校区不能为空");
			$("#orgId").focus();
			return;
		}
		var name = $("#name").val();
		if ($.trim(name) == "") {
			alert("名称不能为空");
			$("#name").focus();
			return;
		}
		var nodes = $(".tables .operate .layui-unselect");
		var nodeFrt = $(".tables .frt");
		var list = [];
		$.each(nodes, function (index, node) {
			if (node.classList.contains("layui-form-checked")) {
				list.push(nodeFrt[index].getAttribute("data-id"))
			}
		});
		$.each(list, function (index, id) {
			funcIds += id + ";";
		});
    $("#funcIds").val(funcIds);
    $("#orgId").val(orgId);
		$("#conditionform").submit();
	});

	//初始化功能点
	// initTree();
});