<%@page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
	<%@include file="/wdk/theme/je/module/public/common.jsp"%>
	<!-- 上述3个meta标签*必须*放在最前面,任何其他内容都*必须*跟随其后! -->
	<%
		String menu_code = request.getParameter("menucode");
		WDK.writeButton(out, su, menu_code);
	%>
  	<title>角色授权-数据权限</title>

    <style>
    </style>
    <script type="text/javascript" src="<%=WDK_ROOT%>/theme/je/core/js/wdk.datatable.js"></script>
    <script type="text/javascript">
    var fun_gridid = $.getUUID();
    var g_role_uuid = '';
    var _changed = [];
    var right_level_scode_data = [];
    var role_gridid  =  $.getUUID();
    $(function() {
    	$("#btn_save").linkbutton({
    		disabled: true
    	});
    	
    	var queryParams = {
  			_SRVNAME:'service.wdk.pub'
	        ,_SRVMETHOD:'wql_queryCombobox'
	        ,_DATA:$.json2str({
       			modulecode:'S_UC_ROLE_DATALEVEL'
       			,jparam:{
       				condition:''
       			}
	        })
	   		,_RSFIELD:'result'
    	};
    	$.cuajax({
    		url: 'wdk?action=wdk.pub&method=call_service&ajaxparam='+new Date().getTime(),
    		method:"post",
      		timeout:WDK_Timeout,
			data:queryParams,
      		success:function(result) {
      			right_level_scode_data = $.str2json(result);
      		},
      		error:function(result){
      			$.wait_close();
        		alert('网络错误!result='+result);
      		}
		});
    	
    	//-----------------------------------------------------------------
    	//1.应用系统
    	$.combobox({
			id:'app_select'
			,url : 'wdk?action=wdk.pub&method=call_service&ajaxparam='+new Date().getTime()
			,queryParams:{
				_SRVNAME: 'service.portal.app',
				_SRVMETHOD: 'queryAppListByAttr',
				_DATA: $.json2str({
		   			app_info: {
		   			}
		   		}),
		   		_RSTYPE: 'combobox',
		   		_RSFIELD: 'app_info',
		   		_RSPARAM: $.json2str({
	   		    	idField: 'app_uuid',
	   		    	textField: 'app_name'
	   		    })
			}
    		,height:25
    		,width:200
			,required:true
			,editable:false
			,disabled:true
			,multiple:false
		    ,initvalue:$.getSessionUser().appuuid
			,idField:'id'
			,textField:'text'
			,missingMessage:'业务类型不能为空!'
			,tipPosition:'right'
			,defaultOption:'===请选择==='
			,onSelect:function(record){
				
		     }
      		,onChange:function(newValue,oldVale){
				
      		}
		});
		
    	
    	//2 角色列表
    	var fun_param = {
            	_SRVNAME: 'service.usr.authorization',
            	_SRVMETHOD: 'queryDataRightListByRoleID',//queryDataRightListByRoleID
            	_DATA: $.json2str({
	            	op_account_uuid: $.getSessionUser().account_id,
	            	app_uuid: $.getSessionUser().appuuid,
	            	role_uuid: 'a'
	            }),
            	_RSTYPE: 'grid',
            	_RSFIELD: 'resultset',
            	_RSPARAM: $.json2str({
   					pagequery: '0'
   				})
	           
			};
    	
    	$.grid({
			id :role_gridid,
			containerid : 'role_grid',
			gridcode : "platform.uum.uum_role2func.role",
			checkbox : false,
			checkOnSelect : false,
			selectOnCheck : false,
			fitColumns: true,
			url : 'wdk?action=wdk.pub&method=call_service&ajaxparam=' + new Date().getTime(),
			queryParams : {
				_SRVNAME : 'service.usr.role',
            	_SRVMETHOD: 'queryNormalRoleList',
            	_DATA: $.json2str({
	            	op_acc: $.getSessionUser().account_id,
	            	app_uuid: $.getSessionUser().appuuid
	            }),
            	_RSTYPE: 'grid',
            	_RSFIELD: 'role_info',
            	_RSPARAM: $.json2str({
   					pagequery: "0"
	   			})
			},
			idField : 'role_uuid',
			pagination : false,
			onClickCell: function (rowIndex, rowData,field, value) {
				onClose();
				
		        //alert('onClickCell   第'+rowIndex+'行, 行数据:'+$.json2str(rowData) +'点击字段:'+ field  +'单元格的值:'+value);
		        $('#role_name').html(rowData.role_name);
		        fun_param._DATA = $.json2str({
						            	op_account_uuid: $.getSessionUser().account_id,
						            	app_uuid: $.getSessionUser().appuuid,
						            	role_uuid: rowData.role_uuid
						          });
		        $.grid_reload({ id:fun_gridid ,queryParams: fun_param });
		        g_role_uuid = rowData.role_uuid;
		        
		        _changed = [];
		        
		        $("#btn_save").linkbutton({
		    		disabled: false
		    	});
			}
		});
    	
    	// 3. 角色授权资源数据权限列表
    	
    	$.grid({
			id :fun_gridid,
			containerid : 'fun_grid',
			gridcode : "platform.uum.uum_role2func.fun",
			checkbox : true,
			checkOnSelect : true,
			selectOnCheck : true,
			fitColumns:true,
			singleSelect: false,
			url : 'wdk?action=wdk.pub&method=call_service&ajaxparam=' + new Date().getTime(),
			queryParams : fun_param,
			idField : 'resource_uuid',
			pagination : false,
			fitColumns: true,
			onClickCell: function (rowIndex, rowData,field, value) {
		        //alert('onClickCell   第'+rowIndex+'行, 行数据:'+$.json2str(rowData) +'点击字段:'+ field  +'单元格的值:'+value);
			}
    		,formatter:{
    			data_right_level_scode:'formatter_data_right_level_scode',
    			orgname_right_str:'formatter_orgname_right_str',
    			orguuid_right_str:'formatter_orguuid_right_str'
            },
    		onLoadSuccess:function(data){
    			$('[id*="level_select_"]').each(function(i,o){
	        		if(!$(o).get(0).inited){
	        			$(o).get(0).inited=true;
	        			var _id = $(o).attr('id');
	        			var comid = 'div_'+ $(o).attr('data-id');
	        			var data = $.str2json( $(o).attr('data-row'));
	        			var data_right_level_scode = data.data_right_level_scode;
	        			var org_attr_scode =  data.org_attr_scode;
	        			$.combobox({
	    					id: _id,
	    					data : right_level_scode_data
	        				,width:100
	        				,height:20
	    					,required:false
	    					,editable:false
	    					,multiple:false
	    				    ,initvalue:data_right_level_scode
	    					,idField:'id'
	    					,textField:'text'
	    					,missingMessage:'业务类型不能为空!'
	    					,tipPosition:'right'
	    					//,defaultOption:'===请选择==='
	    					,onSelect:function(record){
	    						//alert('选中   id='+record.id+'  text='+record.text);
	    				     }
	    		      		,onChange:function(newValue,oldVale){
	    						//alert('内容改变   新选中:'+newValue+'   原选中='+oldVale);
	    		      			if(!$(this).changed){
	        						$(this).changed = true;
	        						$(this).attr('scode',data_right_level_scode);
	        					}
	        					if(newValue != $(this).attr('scode')){
	        						_changed.push('1');
	        					}else{
	        						_changed.pop();
	        					}
	        					
// 	    		      			if(newValue === '06' || newValue === '07'){
								if( newValue === '07'){
	        						//_cont找不到
	        						var _cont = $('div[data-id="'+comid+'"]').parent();
	        						_cont.before('<input  id="'+comid+'" type="hidden"/>');
	        						_cont.remove();
	        						
	        						$('#treediv'+comid+'').remove();
	        						
	        						var _data = {
	        							op_acc: $.getSessionUser().account_id
	        							
            				        };
	        						var da = {
	        								level: '-1'
    	        							,include_self: '1'
    	        							,result_fields:'org_uuid,org_name,parent_uuid'
    	        							,order_expr:' display_order '
	        						}
	        						var _menthod = "queryOrgListByMU";
	        						if(org_attr_scode != "" && org_attr_scode != "00"){
	        							if(newValue === '07'){
		        							_menthod = "queryBizOrgListByMU";//多部门
		        						}
// 	        							else if(newValue === '07'){
// 		        							_menthod = "queryBizCorpListByMU";// 07
// 		        						}
	        							_data.org_attr_scode = org_attr_scode;
	        						}
	        						
	        						$.extend(_data,da);

            				        var dataParam = {
            				            _SRVNAME: 'service.usr.org',
            				            _SRVMETHOD: _menthod,
            				            _DATA: $.json2str(_data),
            				            _RSFIELD: 'resultset',//TODO:待确认
            				            _RSTYPE: 'combotree',
            				            _RSPARAM: $.json2str({
            				   	   			idField: 'org_uuid'
            				   	   			,textField: 'org_name'
            				   	   			,parentField: 'parent_uuid'
            				   	   		})
            				        };
            				        
            				        var _initid = data.orguuid_right_str;
            				        var _inittext = data.orgname_right_str;
            				        if(data_right_level_scode != newValue){
            				        	_initid = '';
            				        	_inittext = '';
            				        }
            				        
            				        $.combotree({
            				    		id:comid,
            				    		checkbox: true,
            				    		//initid: _initid,
            							//inittext: _inittext,
            							initvalue: data.orguuid_right_str,
            				    		expandall:false,
            	        				height:20,
            				    		//cascadeCheck:false,
            				    	    asyn:false,
            				    	    multiple:true,
            				    	    onlyLeafCheck:true,
            				    	    url:'wdk?action=wdk.pub&method=call_service&ajaxparam='+new Date().getTime(),
            				        	queryParams:dataParam,
            				    	    onChange:function(treeId,node){
            				    	    	//alert("onchange,treeId="+treeId+",node="+node);
            				    	    }
            				    	});

	        					}else{
	        						var con = $('#'+comid).parent();
	        						if(con[0].tagName != 'TD'){
		        						con.before('<div style=";text-align:center;;height:auto;" class="datagrid-cell datagrid-cell-c1-orgname_right_str"><input style="width: 150px;"  id="'+comid+'" type="hidden"/></div>');
		        						con.remove();
	        						}
	        					}
	    		      		}
	    			   });
	        	    }
	        	});
    		}
		});
    	$("#btn_save").on("click", function() {
    		if(!$(this).linkbutton("options").disabled){
    			save();
    		}
    	});
    	//-----------------------------------------------------------------
    });
    function formatter_data_right_level_scode(value,row,index) {
    	return row.data_right[0].data_right_level_scodename;
    	/* var _id = row.resource_uuid;
		var data = $.json2str(row);
		
		return '<input type="text" data-id="'+_id+'" id="level_select_'+ _id +'"data-row='+data+' class="txt" ></input>'; */
  	}
    function formatter_orgname_right_str(value,row,index) {
    	/* var _id = 'div_' + row.resource_uuid;
		return '<div><input style="width: 150px;"  id="'+_id+'" type="hidden"/></div>'; */
		return row.data_right[0].orgname_right_str;
  	}
    function formatter_orguuid_right_str(value,row,index) {
    	return row.data_right[0].orgname_right_str;
  	}
    function save(){
    	var _rolefunc_info = [];
		var totalRows = $.grid_getRows({ id:fun_gridid });

		$.wait_open();
        $.each(totalRows, function(index, value) {
        	var data_right_level = $.combobox_getValue({id:'level_select_'+value.resource_uuid}); 
        	var uuid = [];
        	var name = [];
        	if(data_right_level == '06' || data_right_level == '07'){
        		var t = $('#div_'+value.resource_uuid).combotree('tree');
        		var nodes = t.tree('getChecked');	
            	$.each(nodes,function(index,node){
            		uuid.push(node.id);
            		name.push(node.text);
            	});
        	}
        	
        	var orguuid_right = uuid.join(',');
        	var orgname_right = name.join(',');
            _rolefunc_info.push({
            	func_uuid: value.resource_uuid,
            	func_type_scode: value.func_type_scode,
            	data_right_level_scode: data_right_level,//取数据权限级别值
            	orguuid_right_str: orguuid_right,//取组织标志自定串
            	orgname_right_str: orgname_right//取组织名称自定串
            });
        });
        
        var data = {
    			op_account_uuid:  $.getSessionUser().account_id,
    			role_uuid: g_role_uuid,
    			rolefunc_info: _rolefunc_info
   		};
       	var dataParam = {
      			_SRVNAME: 'service.usr.authorization',
      	   	  	_SRVMETHOD: 'saveRoleFunc',
      	   		_DATA: $.json2str(data)
     		};
       	//通过界面直接调用服务
       	$.cuajax({
     			url:'wdk?action=wdk.pub&method=call_service&ajaxparam='+new Date().getTime(),
        		method:"post", 
         		timeout:WDK_Timeout,
         		data:dataParam,
         		success:function(result) {
         			_changed = [];
         			$.wait_close();
         			//返回值字符串转json
           		var jres = $.str2json(result);
               	if(jres.code=="1"){  //操作成功
               		alert('操作保存成功!');
               	}else{
               		alert(result.desc);
               	}
         		},
         		error:function(result){
         			$.wait_close();
           		alert('网络错误!result='+result);
         		}
   		});
	}
    
    function btn_edit(){
		var row = $.grid_getChecked({id:fun_gridid}); 
		if(row.length == 0){
			alert("请选择需要设置的功能菜单");
			return false;
		}
		var role = $.grid_getSelected({id:role_gridid}); 
		if(!role.role_uuid){
			alert("请选择角色");
			return false;
		} 
		var json = {};
		var func_uuid = [];
		var fun_name = [];
		for(var i=0; i<row.length; i++){
			func_uuid.push(row[i].resource_uuid);
			fun_name.push(row[i].fun_name);
		}
		if(row.length == 1){
			json.org_attr_scode = row[0].org_attr_scode;
			json.data_right_level_scode = row[0].data_right[0].data_right_level_scode;
			json.orguuid_right_str = row[0].data_right[0].orguuid_right_str;
		}else{
			json.org_attr_scode = "";
			json.data_right_level_scode = "";
			json.orguuid_right_str = "";
		}
		json.rowcount = row.length;
		json.role_uuid = g_role_uuid;
		json.role_name = role.role_name;
		json.func_uuid = func_uuid.join(",");
		json.fun_name = fun_name.join(",");
		
		var paramid = $.getUUID();
		$.getRoot()[paramid] = json;
		$.openWin({
	  		id:$.getUUID(),
	  		title:'角色权限--编辑',
	      	url:'platform/uum/uum_role2func_edit.jsp',
	      	height:420,
	      	width:750,
	      	queryParams:{
	      		paramid : paramid
	      	},
	      	onClose:function(){
	      		$.grid_reload({id:fun_gridid});
	      	}
		});
    }
    	
    
    function onClose(){
		 if(_changed.length > 0){
// 			 var issave = confirm("您已改变数据权限,是否进行保存?");
// 			 if (issave) {
				 
// 			 }
			confirmDialog("您已改变数据权限,是否进行保存?",function(){
				save(); 	 
			},function(){});
			
		 }
	}
    </script>
</head>

<body>
	<div class="easyui-layout" data-options="fit:true">
		<div data-options="region:'west',border:false,collapsed:false" style="width: 300px;">
			<div class="easyui-layout" data-options="fit:true">
				<div data-options="region:'north',border:false,collapsed:false" style="height:47px; ">
					<div style="padding: 10px;">
						<div>
							<label>应用系统</label>
							<input type="text" id="app_select"></input>
						</div>
					</div>
				</div>
				<div data-options="region:'center',border:false,collapsed:false" id="role_grid"></div>
			</div>
		</div>
		<div data-options="region:'center',border:false,collapsed:false">
			<div class="easyui-layout" data-options="fit:true">
				<div data-options="region:'north',border:false,collapsed:false" style="height:47px; line-height:45px; padding:0 10px;">
					<label for="name"><font style="font-weight:bold;font-size:15px;">授权角色:&nbsp;</font><span id="role_name"></span></label> 
			        <div style="float: right;">
			        	<a href="javascript:void(0);" class="easyui-linkbutton" data-options="iconCls:'fa fa-pencil-square-o'" onclick="btn_edit()">设置</a>
			        	<!-- <a href="javascript:void(0);" class="easyui-linkbutton" data-options="iconCls:'fa fa-save'" id="btn_save">保存</a> -->
			        </div>
				</div>
				<div data-options="region:'center',border:false,collapsed:false" id="fun_grid"></div>
			</div>
		</div>
	</div>
</body>


</html>