package com.njcn.serviceimpl.user;

import com.njcn.mapper.user.PermissionMapper;
import com.njcn.mapper.user.PermissionTreeMapper;
import com.njcn.mapper.user.RoleMapper;
import com.njcn.pojo.commons.ZtreePojo;
import com.njcn.pojo.user.Permission;
import com.njcn.pojo.user.PermissionTree;
import com.njcn.pojo.user.Role;
import com.njcn.service.user.IPermissionService;
import com.njcn.shiro.token.TokenManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.*;

@Service
public class PermissionServiceImpl implements IPermissionService {
	
	@Autowired
	private PermissionMapper permissionMapper;
	
	@Autowired
	private RoleMapper roleMapper;
	
	@Autowired
	private PermissionTreeMapper permissionTreeMapper;
	
	@Override
	public String deleteByIndex(String functionIndex) {
		try {
			Permission permission=new Permission();
			permission.setFunctionIndex(functionIndex);
			permission.setSysType(TokenManager.getSysType());
			Permission list= permissionMapper.selectOne(permission);//根据传过来的index查询资源信息
			if(list!=null){
			    //查询是否还有子节点
				Permission permission2=new Permission();
				permission2.setParentNode(list.getNode());
				permission2.setSysType(TokenManager.getSysType());
				List<Permission> temp=permissionMapper.select(permission2);
				if(temp.isEmpty()){
					permissionMapper.delete(permission);
				}else{
					return "该资源下还有子资源，删除失败";
				}
			}else{
				return "并未找到该资源，删除失败";
			}
		} catch (Exception e) {
			return "删除资源失败";
		}
		return "删除资源成功";
	}
	
	/**
	 * 新增资源
	 */
	@Override
	public String savePermission(String description, String name, String path, Integer first, Integer second) {
		Permission per=new Permission();
		per.setName(name);
		per=permissionMapper.selectOne(per);
		if(null==per){
			Permission temp=new Permission();
			temp.setFunctionIndex(UUID.randomUUID().toString());
			if(first==null){
				first=0;
			}
			if(second==null){
				second=first;
				
			}
			temp.setParentNode(second);
			temp.setDescription(description);
			temp.setName(name);
			temp.setNode(getNextNode(second));
			temp.setPath(path);
			temp.setState(String.valueOf(1));
			temp.setSysType(TokenManager.getSysType());
			temp.setUpdateTime(new Date());
			temp.setUserIndex(TokenManager.getToken().getUserIndex());
			try {
				int flag = permissionMapper.insert(temp);
				return "新增资源成功";
			} catch (Exception e) {
				return "新增资源失败";
			}
		}else{
			return "资源名已存在";
		}
	}
	
	
	/**
	 * 获取父节点下的所有子节点，返回最新的子节点node
	 * */
	public Integer  getNextNode(Integer father){
		List<Permission> lists=new ArrayList<Permission>();
		if(father==0){
			Example example=new Example(Permission.class);
			Example.Criteria criteria = example.createCriteria();
			criteria.andEqualTo("parentNode",father);
			example.setOrderByClause("node desc");
			criteria.andEqualTo("sysType", TokenManager.getSysType());
			lists=permissionMapper.selectByExample(example);
			if(lists.isEmpty()){
				return 1001;
			}else{
				return lists.get(0).getNode()+1;
			}
		}else if(father==1001){
			Example example=new Example(Permission.class);
			Example.Criteria criteria = example.createCriteria();
			criteria.andEqualTo("parentNode",father);
			example.setOrderByClause("node desc");
			criteria.andEqualTo("sysType", TokenManager.getSysType());
			lists=permissionMapper.selectByExample(example);
			if(lists.isEmpty()){
				return 2001;
			}else{
				return lists.get(0).getNode()+1;
			}
		}else{
			Example example=new Example(Permission.class);
			Example.Criteria criteria = example.createCriteria();
			criteria.andNotEqualTo("parentNode", 1001);
			example.setOrderByClause("node desc");
			criteria.andEqualTo("sysType", TokenManager.getSysType());
			lists=permissionMapper.selectByExample(example);
			if(lists.isEmpty()){
				return 3001;
			}else{
				return lists.get(0).getNode()+1;
			}
		}
	}

	/**
	 * 获取所有角色信息，状态为1（正常）的
	 */
	@Override
	public List<List> getRolePermission() {
		List<List> lists= new ArrayList<List>();
		Example example=new Example(Role.class);
		Example.Criteria criteria = example.createCriteria();
		criteria.andEqualTo("state", 1);
		criteria.andEqualTo("sysType", TokenManager.getSysType());
		List<Role> roles = roleMapper.selectByExample(example);
		if(roles.isEmpty()){
			return new ArrayList<List>();
		}else{
			for (Role role : roles) {
				List<String> temp=new ArrayList<String>();
				temp.add(role.getRoleName());
				temp.add(role.getRoleDescription());
				temp.add("<a href='javascript:void(0);' onclick='viewPermission(\""+role.getRoleIndex()+"\")'><font style='color:blue'>查看资源</font></a>");
				temp.add("<button  class='btn  btn-edit themeBGColor' style='margin-right:10px;' href='javascript:void(0);' onclick='destributePermission(\""+role.getRoleIndex()+"\")' ><i class='fa fa-sitemap'></i>资源分配</button>");
				lists.add(temp);
			}
			return lists;
		}
	}

	@Override
	public List<Permission> quarrAll(Integer nodeIndex, Integer parentIndex, String sysType) {
		return permissionMapper.quarrAll(nodeIndex,parentIndex,sysType);
	}

	/**
	 * 根据角色索引，获取其拥有的资源
	 * @param roleIndex
	 * @return
	 */
	@Override
	public List<ZtreePojo> getPermissions(String roleIndex) {
		return getBindedPermission(roleIndex);
	}
	
	private List<ZtreePojo> getBindedPermission(String roleIndex){
		List<ZtreePojo> litsZ=new ArrayList<ZtreePojo>();
		List<ZtreePojo> sup=new ArrayList<ZtreePojo>();
		//根据角色索引获取所有的资源
		List<Permission> lists=new ArrayList<Permission>();
		String sysType=TokenManager.getSysType();
		lists=permissionMapper.queryPermissionByRoleIndex(roleIndex,sysType);
		if(lists.isEmpty()){
			return new ArrayList<ZtreePojo>();
		}else{
			//清洗数据。区分一级页面、二级资源
			for (Permission permission : lists) {
				//该资源为页面级别资源，其下的所有子资源都必须获取出来
				Integer parentNode = permission.getParentNode();
				ZtreePojo zp=new ZtreePojo();
				if(parentNode==0){
					//先加入父树内容
					zp.setId(permission.getNode());           //设置
					zp.setPId(permission.getParentNode());
					zp.setName(permission.getName());
					zp.setOpen(true);
					zp.setChecked(true);
					zp.setIndex(permission.getFunctionIndex());
					litsZ.add(zp);
					//再加入所有子树内容
					List<Permission> list=new ArrayList<Permission>();
					int node=permission.getNode();
					list=permissionMapper.queryPermissionByTwoIndex(roleIndex, sysType, node);
					if(!list.isEmpty()){
						for (Permission p2 : list) {
							ZtreePojo zpson=new ZtreePojo();
							zpson.setId(p2.getNode());              //用户
							zpson.setPId(p2.getParentNode());
							zpson.setName(p2.getName());
							zpson.setOpen(true);
							zpson.setChecked(true);
							zpson.setIndex(p2.getFunctionIndex());
							litsZ.add(zpson);
							
							List<Permission> list3=new ArrayList<Permission>();
							int node1=p2.getNode();
							list3=permissionMapper.queryPermissionByTwoIndex(roleIndex, sysType, node1);
							if(!list3.isEmpty()){
								for (Permission p3 : list3) {
									ZtreePojo zpson1=new ZtreePojo();
									zpson1.setId(p3.getNode());
									zpson1.setPId(p3.getParentNode());
									zpson1.setName(p3.getName());
									zpson1.setOpen(true);
									zpson1.setChecked(true);
									zpson1.setIndex(p3.getFunctionIndex());
									litsZ.add(zpson1);
								}
							}
						}
					}
				}
				
			}
		}
		if(!sup.isEmpty()){
			litsZ.addAll(sup);
		}
		return litsZ;
	}
	
	
	/**
	 * 判断子资源在获取的集合中是否存在页面资源
	 */
	private boolean isContain(List<Permission> per,int parentNode){
		boolean flag=false;
		for (Permission permission : per) {
			int node = permission.getNode();
			if(node==parentNode){
				flag=true;
				break;
			}
		}
		return flag;
	}
	
	/**
	 * 判断集合中是否已经存在
	 */
	private boolean isContains(List<ZtreePojo> per,int node){
		boolean flag=false;
		for (ZtreePojo permission : per) {
			int id = permission.getId();
			if(id==node){
				flag=true;
				break;
			}
		}
		return flag;
	}

	@Override
	public List<ZtreePojo> destributePermission(String roleIndex) {
		List<ZtreePojo> litsZ=new ArrayList<ZtreePojo>();
		List<ZtreePojo> sup=new ArrayList<ZtreePojo>();
		//首先获取出该角色已经绑定的资源
		List<ZtreePojo> bindedPermission = getBindedPermission(roleIndex);
		//再查找出所有的资源（state为1正常的资源）
		Example example=new Example(Permission.class);
		Example.Criteria criteria = example.createCriteria();
		criteria.andEqualTo("state", 1);
		criteria.andEqualTo("sysType", TokenManager.getSysType());
		List<Permission> perListTemp=permissionMapper.selectByExample(example);
		for (Permission permission : perListTemp) {
			ZtreePojo zp=new ZtreePojo();
			zp.setId(permission.getNode());
			zp.setChecked(false);
			zp.setIndex(permission.getFunctionIndex());
			zp.setName(permission.getName());
			zp.setOpen(true);
			zp.setPId(permission.getParentNode());
			litsZ.add(zp);
		}
		//如果一个资源都没绑定，则放回全部的资源
		if(bindedPermission.isEmpty()){
			return litsZ;
		}else{
		//用户已经绑定部分资源，则需要清洗数据
			for (ZtreePojo zp : litsZ) {
				for (ZtreePojo zpb : bindedPermission) {
					if(zpb.getIndex().equalsIgnoreCase(zp.getIndex())){
						zp.setChecked(zpb.isChecked());
					}
				}
			}
		}
		return litsZ;
	}

	/**
	 * 根据角色索引，重新分配资源
	 * @param roleIndex
	 * @param permissionIndex
	 * @return
	 */
	@Override
	public String disPer(String roleIndex, String permissionIndex) {
		permissionIndex=permissionIndex.substring(0, permissionIndex.lastIndexOf(","));
		String[] pIndex = permissionIndex.split(",");
		List<String> list= Arrays.asList(pIndex);
		List<String> list2= new ArrayList<String>();
		//先获取已经关联的资源索引
		try {
			List<String> bindIndex=permissionMapper.queryPermissionsByRoleIndex(roleIndex);
			//清洗数据 筛选出相同的数据、已绑定中有，现在没有（删除）、已绑定无，现在有（新增）
			if(bindIndex.isEmpty()){
				for (String string : list) {
					permissionMapper.addByIndex(roleIndex,string);
				}
				
			}else{
				List<String> has=new ArrayList<String>();
				for (String s1 : list) {
					list2.add(s1);
					for (String s2 : bindIndex) {
						if(s1.equalsIgnoreCase(s2)){
							has.add(s2);
						}
					}
				}
				//两个集合清除已有的
				for (String string : has) {
					list2.remove(string);
				}
				for (String string : has) {
					bindIndex.remove(string);
				}
				//删除
				if(!bindIndex.isEmpty()){
					for (String string : bindIndex) {
						permissionMapper.removeByIndex(roleIndex,string);
					}
				}
				//新增
				if(!list2.isEmpty()){
					for (String string : list2) {
						permissionMapper.addByIndex(roleIndex,string);
					}
				}
			}
		} catch (Exception e) {
			return "重新分配资源失败";
		}
		return "重新分配资源成功";
	}

	@Override
	public List<PermissionTree> getTreeData() {
		List<PermissionTree> list = new ArrayList<>();

		Map<Integer, Integer> value = new HashMap<Integer, Integer>();
		int p = 1000;
		List<PermissionTree> one = permissionTreeMapper.getfirstData(TokenManager.getSysType());
		
		if (one.isEmpty()) {
			PermissionTree dt = new PermissionTree();
			dt.setId(100);
			dt.setNodeType(0);
			dt.setpId(0);
			dt.setPpId(0);
			dt.setName("资源列表");
			dt.setRdIndex("0");
			list.add(dt);
			return list;
		}
		
		PermissionTree dt = new PermissionTree();
		dt.setId(100);
		dt.setNodeType(0);
		dt.setpId(0);
		dt.setPpId(0);
		dt.setName("资源列表");
		dt.setRdIndex("0");
		list.add(dt);
		
		List<Integer> first = new ArrayList<>();
		
		for (int i=0;i<one.size();i++) {
			first.add(one.get(i).getNodeIndex());
			PermissionTree dto = new PermissionTree();
			dto.setId(++p);
			dto.setName(one.get(i).getName());
			dto.setpId(100);
			dto.setPpId(100);
			dto.setNodeIndex(one.get(i).getNodeIndex());
			dto.setNodeType(1);
			dto.setRdIndex(one.get(i).getRdIndex());
			list.add(dto);
			value.put(one.get(i).getNodeIndex(), p);
		}
		
		List<PermissionTree> two = permissionTreeMapper.getsecondData(first,TokenManager.getSysType());
		if (two.isEmpty()) {
			return list;
		}
		
		Map<Integer, Integer> value1 = new HashMap<Integer, Integer>();
		List<Integer> second = new ArrayList<>();
		int p1 = 2000;
		for (int i=0;i<two.size();i++) {
			second.add(two.get(i).getNodeIndex());
			PermissionTree dto = new PermissionTree();
			dto.setId(++p1);
			dto.setName(two.get(i).getName());
			dto.setpId(value.get(two.get(i).getpId()));
			dto.setPpId(two.get(i).getpId());
			dto.setNodeIndex(two.get(i).getNodeIndex());
			dto.setNodeType(2);
			dto.setRdIndex(two.get(i).getRdIndex());
			list.add(dto);
			value1.put(two.get(i).getNodeIndex(), p1);
		}
		
		List<PermissionTree> three = permissionTreeMapper.getsecondData(second,TokenManager.getSysType());
		if (three == null) {
			return list;
		}
		
		int p2 = 3000;
		for (int i=0;i<three.size();i++) {
			PermissionTree dto = new PermissionTree();
			dto.setId(++p1);
			dto.setName(three.get(i).getName());
			dto.setpId(value1.get(three.get(i).getpId()));
			dto.setPpId(three.get(i).getpId());
			dto.setNodeIndex(three.get(i).getNodeIndex());
			dto.setNodeType(3);
			dto.setRdIndex(three.get(i).getRdIndex());
			list.add(dto);
		}
		return list;
	}

	@Override
	public List<List> getAllData() {
        List<List> result = new ArrayList<>();
		Permission permission=new Permission();
		permission.setSysType(TokenManager.getSysType());
		List<Permission> one = permissionMapper.select(permission);
		
		for(int i=0;i<one.size();i++){
			List<String> tmp=new ArrayList<String>();
			tmp.add(one.get(i).getName());
			tmp.add(one.get(i).getPath());
			tmp.add(one.get(i).getDescription());
			int parentnode = one.get(i).getParentNode();
			if(parentnode == 0){
				tmp.add("无");
			}else{
				Permission rpt = new Permission();
				rpt.setNode(parentnode);
				rpt.setSysType(TokenManager.getSysType());
				rpt = permissionMapper.selectOne(rpt);
				if(rpt != null){
					tmp.add(rpt.getName());
				}
			}
			
			tmp.add(
					"<button type='button' class='btn  btn-danger' style='margin-right:10px;font-size: 12px;padding:1px 12px;' href='javascript:void(0);' onclick='deletePermission(\""+one.get(i).getFunctionIndex()+"\")' ><i class='fa fa-trash'></i>删除</button>"
			        );
			
			result.add(tmp);
		}
		return result;
	}

	@Override
	public List<List> getData(Integer index) {
        List<List> result = new ArrayList<>();
		
//        Permission tmp = new Permission();
//		tmp.setNode(index);
//		tmp.setSysType(TokenManager.getSysType());
		List<Permission> one = quarrAll(index,index,TokenManager.getSysType());
		
		for(int i=0;i<one.size();i++){
			List<String> tm=new ArrayList<String>();
			tm.add(one.get(i).getName());
			tm.add(one.get(i).getPath());
			tm.add(one.get(i).getDescription());
			int parentnode = one.get(i).getParentNode();
			if(parentnode == 0){
				tm.add("无");
			}else{
				Permission rpt = new Permission();
				rpt.setNode(parentnode);
				rpt.setSysType(TokenManager.getSysType());
				rpt = permissionMapper.selectOne(rpt);
				if(rpt != null){
					tm.add(rpt.getName());
				}
			}
			
			tm.add(
					"<button type='button' class='btn  btn-danger' style='margin-right:10px;font-size: 12px;padding:1px 12px; ' href='javascript:void(0);' onclick='deletePermission(\""+one.get(i).getFunctionIndex()+"\")' ><i class='fa fa-trash'></i>删除</button>"
			        );
			
			result.add(tm);
		}
		return result;
	}
}
