/*
 * 该类主要负责系统主要业务逻辑的实现,如多表处理的事务操作、权限控制等
 * 该类根据具体的业务逻辑来调用该实体对应的Dao或者多个Dao来实现数据库操作
 * 实际的数据库操作在对应的Dao或其他Dao中实现
 */

package com.blueland.bpm.manage.config.web;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.blueland.bpm.common.util.StringUtils;
import com.blueland.bpm.engine.config.model.Role;
import com.blueland.bpm.engine.config.service.RoleManager;
import com.blueland.bpm.identity.OrgService;
import com.blueland.bpm.identity.UserService;
import com.blueland.bpm.identity.model.Org;
import com.blueland.bpm.identity.model.User;
import com.blueland.bpm.manage.util.MyContants;
import com.blueland.bpm.manage.util.TreeNode;



/**
 * @author lw
 * @version 1.0
 * @since
 */

@Service
public class UserTreeManager {
	@Autowired
	// User对应的DAO类,主要用于数据库的增删改查等操作
	UserService userService;
	@Autowired
	OrgService orgService;
	
//	@Autowired
//	RoleService roleService;
	@Autowired
	private RoleManager roleService;

	public List<TreeNode> getUserOrgTree(String orgId, boolean isAssignTreeFlag,String showTreeType,String treeLevelStr,String searchUserName,
			boolean isChecked,String isCheckValue) {
		List<TreeNode> treeNodeList = new ArrayList<TreeNode>();
		if (StringUtils.isEmpty(orgId))
			return treeNodeList;
		
		Org topNode = (Org) orgService.getOrgById(orgId);
		List<TreeNode> queryNodes=queryNode( orgId, searchUserName, isChecked, isCheckValue) ;
		if(!queryNodes.isEmpty()){
			return queryNodes;
		}
		if (topNode == null||topNode.getOrgId()==null){//添加应用第一次选择供应商的逻辑
			/*Org params=new Org();
			params.setOrgLevel(0);
			List<Org> orgList=orgService.findOrgByEntityCriteria(params);
			for (Org org : orgList) {
				TreeNode treeNode =null;
				String type="ORG";
				if (isTopOrg(org)) {
					type="TOPORG";
				}
				treeNode = new TreeNode(String.valueOf(org.getOrgId()),
							String.valueOf(org.getOrgParentId()), org.getOrgName(), true,
							true, true, type, "true",org.getOrgLevel());
				treeNodeList.add(treeNode);
				topNode = (Org) orgService.getOrgById(MyContants.TOP_ORG_ID);
			}*/
			
			topNode=(Org) orgService.getOrgById(MyContants.TOP_ORG_ID);
			String	type="TOPORG";
			TreeNode treeNode = new TreeNode(String.valueOf(topNode.getOrgId()),
							String.valueOf(topNode.getOrgParentId()), topNode.getOrgName(), true,
							true, true, type, "true",topNode.getOrgLevel());
			treeNodeList.add(treeNode);
			//return treeNodeList;
		}
		/*if (isTopOrg(topNode)) {
			TreeNode treeNode=new TreeNode(
					String.valueOf(topNode.getOrgId()), String.valueOf(topNode
							.getOrgParentId()), topNode.getOrgName(), isChecked,
							true, true, "ORG", "true",topNode.getOrgLevel());
			treeNodeList.add(treeNode);	
		}*/
		if(!isChecked){
			//自定义顶级节点
			TreeNode treeNode = new TreeNode(String.valueOf(topNode.getOrgId()), 
					"-1", topNode.getOrgName(), isChecked,
					true, true, "ORG", "false",0,true);
			treeNodeList.add(treeNode);
		}
		
			try {
				List<Org> orgList = orgService.findSubOrg(topNode.getOrgId());
				for (Org suborg : orgList) {
					treeNodeList.add(new TreeNode(
							String.valueOf(suborg.getOrgId()), String.valueOf(suborg
									.getOrgParentId()), suborg.getOrgName(), isChecked,
									true, true, "ORG", "true",suborg.getOrgLevel()));	
				}
				
				List<User> userList = userService.findUserByOrgId(orgId);
				if(userList!=null) {
					for (User user : userList) {
						//委托初始化选中已有的委托人
						isChecked = false;
						if(!StringUtils.isEmpty(isCheckValue)){
							if(isCheckValue.equals(user.getUserId())){
								isChecked = true;
							}
						}
						treeNodeList.add( new TreeNode(String.valueOf(user.getUserId()),
								String.valueOf(user.getOrgId()), user.getUserName(), isChecked,
								true, false, "USER", "true",0));
					}
				}
				
			} catch (Exception e) {
				e.printStackTrace();
			}
		
		return treeNodeList;
	}
	
	
	public List<TreeNode> queryNode(String orgId,String searchUserName,boolean isChecked,String isCheckValue) {
		List<TreeNode> treeNodeList = new ArrayList<TreeNode>();
		Org topNode =null;
		if (StringUtils.isEmpty(orgId)||orgId.equals(MyContants.TOP_ORG_ID)){
			topNode = (Org) orgService.getOrgById(MyContants.TOP_ORG_ID);
		}
		
		if(null != searchUserName && !"".equals(searchUserName.trim())){
			List<User> userList = new ArrayList<User>();
			User query = new User();
			query.setUserName(searchUserName);
			if(MyContants.TOP_ORG_ID.equals(orgId)){
				//by lw 20220119
				//userList = userService.findUserByEntitiyCriteria(query);
			}else{
				query.setOrgId(orgId);
				//userList = userService.findUserByEntitiyCriteria(query);
			}
			if (!userList.isEmpty()) {
				List<Org> orgList=new ArrayList<Org>();
				//去重
				Map<String,String> map = new HashMap<String,String>();
				if(isTopOrg(topNode)){
					map.put(topNode.getOrgId(), topNode.getOrgId());
				}
				for (User user : userList) {
					//排除非中烟的人员
					//if(user.getCompanyId().startsWith("2043")){
						Org org = orgService.getOrgById(user.getOrgId());
						if(null!=org){
							//委托初始化选中已有的委托人
							isChecked = false;
							if(!StringUtils.isEmpty(isCheckValue)){
								if(isCheckValue.equals(user.getUserId())){
									isChecked = true;
								}
							}
							
							TreeNode userNode = new TreeNode(String.valueOf(user.getUserId()),
									String.valueOf(user.getOrgId()), user.getUserName(), isChecked,
									true, false, "USER", "true",0);
							treeNodeList.add(userNode);
							if(!map.containsKey(user.getOrgId())){
//								Org org = orgService.getOrgById(user.getOrgId());
								orgList.add(org);
								map.put(org.getOrgId(), org.getOrgId());
								
								while(!map.containsKey(org.getOrgParentId()) && !MyContants.TOP_ORG_ID.equals( org.getOrgParentId())){
									org = orgService.getOrgById(org.getOrgParentId());
									orgList.add(org);
									map.put(org.getOrgId(), org.getOrgId());
								}
//								if(!map.containsKey(org.getOrgParentId())){
//									Org porg = orgService.getOrgById(org.getOrgParentId());
//									if(null!=porg){
//										orgList.add(porg);
//										map.put(porg.getOrgId(), porg.getOrgId());
//									}
								}
//							}
						}
					//}
				}
				//根据用户姓名或工号查询条件查询包含满足条件的用户所在的所有组织节点，并放入树中
				if(!orgList.isEmpty()){
					for(Org org:orgList){
						addTreeNode(treeNodeList, org, true);
					}
				}
				
			}else{
				treeNodeList.clear();
				
				TreeNode treeNode = new TreeNode(
						String.valueOf(topNode.getOrgId()), String.valueOf(topNode
								.getOrgParentId()), topNode.getOrgName(), isChecked,
						true, false, "TOPORG", "true",topNode.getOrgLevel());
				treeNodeList.add(treeNode);
			}
		}
		return treeNodeList;
	}
	
	
	public List<TreeNode> getUserOrgTree_20150521bak(String orgId, boolean isAssignTreeFlag,String showTreeType,String treeLevelStr) {
		List<TreeNode> treeNodeList = new ArrayList<TreeNode>();
		if (StringUtils.isEmpty(orgId))
			return treeNodeList;
		try {
			Org topNode = (Org) orgService.getOrgById(orgId);
			if (isTopOrg(topNode)) {
				TreeNode treeNode=new TreeNode(
						String.valueOf(topNode.getOrgId()), String.valueOf(topNode
								.getOrgParentId()), topNode.getOrgName(), true,
								true, true, "ORG", "true",topNode.getOrgLevel());
				treeNodeList.add(treeNode);	
			}
			
			List<Org> orgList = orgService.findSubOrg(topNode.getOrgId());
			for (Org suborg : orgList) {
				treeNodeList.add(new TreeNode(
						String.valueOf(suborg.getOrgId()), String.valueOf(suborg
								.getOrgParentId()), suborg.getOrgName(), true,
								true, true, "ORG", "true",suborg.getOrgLevel()));	
			}
			
			List<User> userList = userService.findUserByOrgId(orgId);
			for (User user : userList) {
				treeNodeList.add( new TreeNode(String.valueOf(user.getUserId()),
						String.valueOf(user.getOrgId()), user.getUserName(), true,
						true, false, "USER", "true",0));
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return treeNodeList;
		
	}
	

	/**
	 * 根据menu组装TreeNode对象并添加到treeNodeList中
	 * 
	 * @param treeNodeList
	 *            treeNodeList
	 * @param org
	 *            组织对象
	 * @param isOpenMenu
	 *            是否打开节点
	 */
	private void addTreeNode(List treeNodeList, Org org, boolean isOpenNode) {
		
		List<Org> orgList=orgService.findSubOrg(org.getOrgId());
		long totalCount = orgList!=null?orgList.size():0;
		/**
		 * 判断是否有子节点
		 */
		boolean isChildNode = true;
		if (totalCount <= 0) {
			isChildNode = false;
		}
		TreeNode treeNode = new TreeNode(String.valueOf(org.getOrgId()),
				String.valueOf(org.getOrgParentId()), org.getOrgName(), true,
				isOpenNode, isChildNode, "ORG", "true",org.getOrgLevel());
		treeNodeList.add(treeNode);

	}

	private void addUserTreeNode(List treeNodeList, Org org, boolean isOpenNode) {
		List<User> userList = userService.findUserByOrgId(org.getOrgId());
		for (User user : userList) {
			TreeNode treeNode = new TreeNode(String.valueOf(user.getUserId()),
					String.valueOf(user.getOrgId()), user.getUserName(), true,
					isOpenNode, false, "USER", "true",0);
			treeNodeList.add(treeNode);
		}

	}
	private boolean isTopOrg(Org org){
		if (MyContants.TOP_ORG_ID.equals(org.getOrgId().toString())) {
			return true;
		}
		return false;
	}
	

	public List<TreeNode> getRoleTree(String orgId,String currentAppId,boolean isAssignTreeFlag,String showTreeType,String treeLevelStr,String loginUserId) {
		List<TreeNode> treeNodeList = new ArrayList<TreeNode>();
//		List<Role> roleList = roleService.findAllRole();
		Role query = new Role();
		query.setLoginUserId(loginUserId);
		query.setSortColumns("role_sort");
		query.setRoleAppId(currentAppId);
		List<Role> roleList = roleService.findRolesByParam(query);
		
		for (Role role : roleList) {
			TreeNode treeNode = new TreeNode(String.valueOf(role.getRoleId()),
					role.getRoleId(), role.getRoleName(), true,
					true, false, "ROLE", "true",0);
			treeNodeList.add(treeNode);

		}
		return treeNodeList;

	}

}
