package cn.com.countrygarden.bi.main.service.personnel.impl;

import cn.com.countrygarden.bi.main.core.Response;
import cn.com.countrygarden.bi.main.core.Result;
import cn.com.countrygarden.bi.main.dao.dup.ManagerCommMapper;
import cn.com.countrygarden.bi.main.dao.dup.TbHsprContractMapper;
import cn.com.countrygarden.bi.main.dao.performance.bdpsndocMapper;
import cn.com.countrygarden.bi.main.dao.personnel.PersonnelAdvisorMapper;
import cn.com.countrygarden.bi.main.dao.personnel.PersonnelCampusevaluationMapper;
import cn.com.countrygarden.bi.main.dao.personnel.PersonnelTagMapper;
import cn.com.countrygarden.bi.main.dao.sys.UserRolesMapper;
import cn.com.countrygarden.bi.main.dao.twerp.hm.ManagerMapForErpMapper;
import cn.com.countrygarden.bi.main.dao.twerp.hm.TbHsprCommunityMapper;
import cn.com.countrygarden.bi.main.dao.wcx.WcxRegionProjectMapper;
import cn.com.countrygarden.bi.main.dto.PersonInfoVO;
import cn.com.countrygarden.bi.main.dto.manager.CommunityInfo;
import cn.com.countrygarden.bi.main.dto.manager.TreeNode;
import cn.com.countrygarden.bi.main.model.AccessToken;
import cn.com.countrygarden.bi.main.model.dup.DupComm;
import cn.com.countrygarden.bi.main.model.dup.DupOrgan;
import cn.com.countrygarden.bi.main.model.dup.ManagerComm;
import cn.com.countrygarden.bi.main.model.sys.UserRoles;
import cn.com.countrygarden.bi.main.service.UserRoleService;
import cn.com.countrygarden.bi.main.service.personnel.PersonnelCommenService;
import cn.com.countrygarden.bi.main.service.twerp.hm.TbSysOrganService;
import cn.com.countrygarden.bi.main.service.wcx.WcxRoleService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;

@Component
public class PersonnelCommenServiceImpl implements PersonnelCommenService {
	
	 @Autowired
	 private UserRoleService userRoleService;
	
	@Autowired
    private ManagerCommMapper managerCommMapper;

	@Autowired
	private UserRolesMapper userRolesMapper;

	@Autowired
	private PersonnelCommenService personnelCommenService;

	@Autowired
	private TbHsprCommunityMapper tbHsprCommunityMapper;
	@Autowired
	private WcxRegionProjectMapper wcxRegionProjectMapper;

	@Autowired
	private TbSysOrganService tbSysOrganService;
	@Autowired
	private WcxRoleService wcxRoleService;

	@Autowired
	private bdpsndocMapper bdpsndocMapper;

	@Autowired
	private PersonnelTagMapper personnelTagMapper;

	@Autowired
	private PersonnelAdvisorMapper personnelAdvisorMapper;

	@Autowired
	private PersonnelCampusevaluationMapper personnelCampusevaluationMapper;

	@Autowired
	private TbHsprContractMapper tbHsprContractMapper;
	
	@Autowired
    private ManagerMapForErpMapper managerMapForErpMapper;
	
	Logger logger= LoggerFactory.getLogger(PersonnelCommenServiceImpl.class);

	public Map<String, Object> findRoleInfoMap(String sysUserCode) {
		
		Map<String, Object> map = new HashMap<String, Object>();
		if(null==sysUserCode||sysUserCode.equals("")) {
			map.put("role", "noRole");
			return map;
		}
		List<String> identitys = new ArrayList<String>();
		// 权限处理

		List<UserRoles> sysUserRole = wcxRoleService.selectSysRoleBySysUserCode(sysUserCode);
		for (UserRoles userRoles : sysUserRole) {
			if (userRoles.getRoleCode().equals("gj_admin")) {
				map.clear();
				map.put("gj_admin", "关键人才库_管理员");
				break;

			} else if (userRoles.getRoleCode().equals("gj_Area")) {
				map.put("gj_Area", sysUserCode);

			} else if (userRoles.getRoleCode().equals("gj_jy")) {
				identitys.add("精英");

			} else if (userRoles.getRoleCode().equals("gj_ly")) {
				identitys.add("领域");

			} else if (userRoles.getRoleCode().equals("gj_zy")) {
				identitys.add("卓越");

			} else if (userRoles.getRoleCode().equals("gj_fl")) {
				identitys.add("凤翎");

			} else if (userRoles.getRoleCode().equals("gj_hj")) {
				identitys.add("火箭军");
			}

		}

		if (identitys.size() > 0) {
			map.put("identitys", identitys);
		}

		if (map.size() < 1) {
			map.put("role", "noRole");
		}
		return map;
	}

//	public Map<String,Object> findRole(AccessToken accessToken) {
////		Map<String,Object> map=new HashMap<>();
//	String sysUserCode = accessToken.getUserCode();
//	Map<String, String> map = findRoleInfoMap(sysUserCode);
//
//	List<String> userIds = new ArrayList<>();
//	//-1:没有相应的角色
//	if (map.size() < 1) {
//	    return null;
//		userIds.add("-1");
//		return userIds;
//	}
//	List<String> identitys = new ArrayList<>();
//	for (Object obj : map.keySet()) {
//		String key = (String) obj;
//
//		if (key.equals("gj_admin")) {
//			// 返回为null
//			System.out.println("全部权限");
//			return null;
//			//区域管理员权限
//		} else if (key.equals("gj_Area")) {
//			userIds = bdpsndocMapper.findErpUserCodes(sysUserCode);
//		} else {
//			identitys.add(map.get(key));
//		}
//	}
//	userIds = bdpsndocMapper.findErpUserCodes(sysUserCode);
//	userIds.addAll(personnelTagMapper.findErpUserCode(identitys));
//	HashSet<String> setUserIds=new HashSet<String>(userIds);
//	userIds.clear();
//	userIds.addAll(setUserIds);
//	return map;
//}

	public List<String> findRole(AccessToken accessToken,String userquyu) {
		String sysUserCode = accessToken.getUserCode();
		Map<String, Object> map = findRoleInfoMap(sysUserCode);

		List<String> userIds = new ArrayList<>();
//		if (map.size() < 1) {
//			userIds.add("-1");
//			return userIds;
//		}
		List<String> identitys = new ArrayList<>();
		for (Object obj : map.keySet()) {
			String key = (String) obj;

			if (key.equals("gj_admin")) {
				// 返回为null
				System.out.println("全部权限");
				return null;
			} else if (key.equals("gj_Area")) {
				userIds = bdpsndocMapper.findErpUserCodes(sysUserCode,userquyu);

				return userIds;
			} else if (key.equals("role")) {
				userIds.add("-1");
				return userIds;
			} else {

				List<String> List = (List<String>) map.get("identitys");
				if (List != null && List.size() > 0) {
					for (int i = 0; i < List.size(); i++) {
						System.out.println(List.get(0));
					}
				}

//				identitys.add(map.get(key));
			}

		}
		userIds = bdpsndocMapper.findErpUserCodes(sysUserCode,userquyu);
//		userIds = personnelTagMapper.findErpUserCode(userIds, identitys);
		return userIds;
	}

	@Override
	public Result queryadByUid(String search, AccessToken accessToken) {
		Map<String, Object> rolesMap = personnelCommenService.findRoleInfoMap(accessToken.getUserCode());

//		if(userIds!=null) {
//			if(userIds.size()==0||userIds.get(0).equals("-1")) {
//				//没有匹配的角色或没有查找到数据
//				return Response.response();
//			}		
//		}

//		List<String> liuserquyu = personnelCommenService.findErpRegionByUserCode(accessToken.getUserCode());
//		String userquyu = null;
//		for (int i = 0; i < liuserquyu.size(); i++) {
//			userquyu = liuserquyu.get(i);
//		}
//
//		for (Object obj : rolesMap.keySet()) {
//			String key = (String) obj;
//			if (key.equals("gj_admin")) {
//				userquyu = null;
//				rolesMap.put("identitys", null);
//				break;
//			}
//		}
		
       List<String> userquyu= new ArrayList<>();
		
    	List<DupOrgan> resuaslt=null;
    	for (Object obj : rolesMap.keySet()) {
    		String key = (String) obj;
    		if (key.equals("gj_admin")) {
    			 userquyu=null;
    			 rolesMap.put("identitys", null);
    			 break;
    		}else if (key.equals("role")) {
    			 return null;
			}else if (key.equals("gj_Area")) {
				rolesMap.put("identitys", null);
				
				 resuaslt = personnelCommenService.findDupCommByUserCode(accessToken.getUserCode(),null,true);
				for (int i = 0; i < resuaslt.size(); i++) {
					userquyu.add(resuaslt.get(i).getOrganName());
				}
				
			}
    		
    	}
		
		List<PersonInfoVO> personInfoCodeOrId = personnelCampusevaluationMapper.selectByPersonInfoByCodeOrName(search,
				rolesMap, userquyu);
		List<String> result = new LinkedList<>();
		for (PersonInfoVO psndoc : personInfoCodeOrId) {
			result.add(psndoc.getCode() + " - " + psndoc.getWorkdept() + " - " + psndoc.getName());
		}

		return Response.response(result);
	}

	public Result findRoleregionName(AccessToken accessToken) {
		// 根据登录账号进行数据过滤
		Map<String, Object> rolesMap = personnelCommenService.findRoleInfoMap(accessToken.getUserCode());
		for (Object obj : rolesMap.keySet()) {
			String key = (String) obj;
			if (key.equals("gj_admin")) {
				return Response.response(wcxRegionProjectMapper.findAllRoleOrganCode("all"));
			} else if (key.equals("role")) {
				return null;
			} else if (key.equals("gj_Area")) {
				List<String> liuserquyu = personnelCommenService.findErpRegionByUserCode(accessToken.getUserCode());
				String userquyu = null;
				if (liuserquyu.size() > 0) {
					userquyu = liuserquyu.get(0);
				}

				return Response.response(wcxRegionProjectMapper.findAllRoleOrganCode(userquyu));
			}else if(key.equals("identitys")) {
				return Response.response(wcxRegionProjectMapper.findAllRoleOrganCode("all"));
			}
		}
		return null;

	}

	

	@Override
	public String findboolean(AccessToken accessToken, String userid, String identitys,String userquyu) {
		String sysUserCode = accessToken.getUserCode();
		Map<String, Object> map = findRoleInfoMap(sysUserCode);

		List<String> userIds = new ArrayList<>();
//		if (map.size() < 1) {
//			userIds.add("-1");
//			return userIds;
//		}
//		
		for (Object obj : map.keySet()) {
			String key = (String) obj;

			if (key.equals("gj_admin")) {
				// 返回为null
				System.out.println("全部权限");
				return "gj_admin";
			} else if (key.equals("gj_Area")) {
				if (userid != null) {
					userIds = bdpsndocMapper.findErpUserCodes(userid,userquyu);
					if (userIds != null && userIds.size() > 0) {
						//for (int i = 0; i < userIds.size(); i++) {
						//if (userIds.get(i).equals(userid)) {
								return "gj_Area";
							//}
						//}
					}
				}

			} else if (key.equals("role")) {
				return "role";
			} else if(key.equals("identitys")){
				
				if (identitys != null){
				
					List<String> List = (List<String>) map.get("identitys");
					if (List != null && List.size() > 0) {
						for (int i = 0; i < List.size(); i++) {
							if (List.get(i).equals(identitys)) {
								return "identitys";
							}
						}
					}
				

			}

			}
		}
		return "0";
	}

	@Override
	public List<String> findErpRegionByUserCode(String userCode) {
		List<String> tbHsp = tbHsprContractMapper.findErpRegionByUserquyu(userCode);

		return tbHsp;
	}

	@Override
	public List<DupOrgan> findDupCommByUserCode(String userCode, String organCode, boolean isManager) {
		Map<String, String> paramter = new HashMap<String, String>();
        paramter.put("userCode", userCode);
        paramter.put("organCode", organCode);       
        paramter.put("isManager", isManager + "");

        Map<String, String> managerCommMap = new HashMap<String, String>();
        Integer count = userRoleService.countByUserCodeAndRoleCode(userCode,"gj_admin");
        if(count>0){
            List<DupOrgan> result =managerMapForErpMapper.queryAllRegion();
            for (DupOrgan organ : result) {
                List<DupComm> comms=managerMapForErpMapper.queryAllComm(organ.getOrganCode());
                organ.setComms(comms);
            }
            return  result;
        }
        if (isManager) {
            List<ManagerComm> managerCommList = managerCommMapper.selectAll();
            for (ManagerComm mComm : managerCommList) {
                managerCommMap.put(mComm.getErpCommId(), mComm.getErpCommId());
            }
        }
        List<DupOrgan> result = new ArrayList<DupOrgan>();
        List<TreeNode> companyTree = getCommTree(userCode);
        if(!CollectionUtils.isEmpty(companyTree)&&!CollectionUtils.isEmpty(companyTree.get(0).getChildren())){
            for (TreeNode compList : companyTree) {
                List<TreeNode> regionList = compList.getChildren();
                for (int i = 0; i < regionList.size(); i++) {
                    TreeNode treeNode = regionList.get(i);
                    DupOrgan organ = new DupOrgan();
                    organ.setOrganCode(treeNode.getId());
                    organ.setOrganName(treeNode.getLabel());
                    List<DupComm> comms = new ArrayList<>();
                    if (treeNode.getChildren() == null) {
                        result.add(organ);
                        continue;
                    }
                    for (TreeNode node : treeNode.getChildren()) {
                        DupComm comm = new DupComm();
                        comm.setCommId(node.getId());
                        comm.setCommName(node.getLabel());
                        comm.setNcSystemNumber(node.getNcSystemNumber());
                        if (!isManager || managerCommMap.get(comm.getCommId()) != null) {
                            comms.add(comm);
                        }
                    }
                    organ.setComms(comms);
                    result.add(organ);
                }
            }
        }

        return uniqueData(result);

	}
	 public List<TreeNode> getCommTree(String userCode) {
	        List<TreeNode> tree = new LinkedList<>();
	        List<CommunityInfo> communityInfoList = managerMapForErpMapper.queryCommInfo(null);
	        List<Integer> commIds = managerMapForErpMapper.queryCommId(userCode);
	      //  System.out.println("区域集："+ (CollectionUtils.isEmpty(communityInfoList)?"":JSON.toJSONString(communityInfoList)));
	       // System.out.println("已有区域集："+ commIds);

	        TreeNode tempCompany = new TreeNode();
	        TreeNode tempOrgan = new TreeNode();
	        for (CommunityInfo info : communityInfoList) {
	            logger.info(info.getCommID()+"");
	            TreeNode communityTreeNode = new TreeNode(info.getCommID().toString(), info.getCommName());
	            communityTreeNode.setNcSystemNumber(info.getNcSystemNumber());
	            for (Integer id : commIds) {

	                if (id==info.getCommID()||info.getCommID().equals(id)) {
	                    if (info.getCompanyCode().equals(tempCompany.getId())) {
	                        if (info.getOrganCode().equals(tempOrgan.getId())) {
	                            // 同一（城市）公司，同一区域，不同项目
	                            tempCompany.getChildren().get(tempCompany.getChildren().size() - 1)
	                                    .getChildren().add(communityTreeNode);
	                        } else {
	                            // 同一（城市）公司，不同区域
	                            tempOrgan = new TreeNode(info.getOrganCode(), info.getOrganName(), new LinkedList<>());
	                            tempOrgan.getChildren().add(communityTreeNode);
	                            tempCompany.getChildren().add(tempOrgan);
	                        }
	                    } else {
	                        // 将（城市）公司临时变量加入结果列表中，排除第一次循环
	                        if (!StringUtils.isEmpty(tempCompany.getId())) {
	                            tree.add(tempCompany);
	                        }

	                        // 从当前记录获取（城市）公司的编码和名称、区域的编码和名称、项目的ID和名称，并保存在临时变量中
	                        tempOrgan = new TreeNode(info.getOrganCode(), info.getOrganName(), new LinkedList<>());
	                        tempOrgan.getChildren().add(communityTreeNode);
	                        tempCompany = new TreeNode(info.getCompanyCode(), info.getCompanyName(), new LinkedList<>());
	                        tempCompany.getChildren().add(tempOrgan);
	                    }
	                }
	            }
	        }
	        // 最后一个（城市）公司临时变量也需加入到结果列表中
	        tree.add(tempCompany);

	        return tree;
	    }
	 
	 private List<DupOrgan> uniqueData(List<DupOrgan> result) {
	        List<DupOrgan> data=new ArrayList<>();
	        Map<String,DupOrgan> organMap=new HashMap<>();
	       // System.out.println("区域权限："+ (CollectionUtils.isEmpty(result)?"":JSON.toJSONString(result)));
	        for (DupOrgan organ : result) {
	            if(organMap.containsKey(organ.getOrganCode())){
	                List<DupComm> comms = organMap.get(organ.getOrganCode()).getComms();
	                if(CollectionUtils.isEmpty(comms)){
	                    comms=new ArrayList<>();
	                }
	                if(!CollectionUtils.isEmpty(organ.getComms())){
	                    comms.addAll(organ.getComms());
	                }
	                organMap.get(organ.getOrganCode()).setComms(comms);
	            }else{
	                organMap.put(organ.getOrganCode(),organ);
	            }
	        }
	        for (String s:organMap.keySet()){
	            data.add(organMap.get(s));
	        }

	       // System.out.println("区域权限："+ (CollectionUtils.isEmpty(data)?"":JSON.toJSONString(data)));
	        return data;
	    }

}
