package com.gyee.frame.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.gyee.frame.common.base.BaseService;
import com.gyee.frame.common.support.ConvertUtil;
import com.gyee.frame.mapper.auto.TvuePermissionMapper;
import com.gyee.frame.mapper.auto.TvuePermissionRoleMapper;
import com.gyee.frame.mapper.custom.PermissionVueDao;
import com.gyee.frame.model.auto.TvuePermission;
import com.gyee.frame.model.auto.TvuePermissionExample;
import com.gyee.frame.model.auto.TvuePermissionRole;
import com.gyee.frame.model.auto.TvuePermissionRoleExample;
import com.gyee.frame.model.custom.BootstrapTree;
import com.gyee.frame.model.custom.Tablepar;
import com.gyee.frame.util.SnowflakeIdWorker;
import com.gyee.frame.util.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class VuePermissionService implements BaseService<TvuePermission, TvuePermissionExample>{
	
	//权限mapper
	@Resource
	private TvuePermissionMapper tvuePermissionMapper;
	
	//权限自定义dao
	@Resource
	private PermissionVueDao permissionVueDao;
	//权限角色关联表
	@Resource
	private TvuePermissionRoleMapper tvuePermissionRoleMapper;
	
	/**
	 * 分页查询
	 * @return
	 */
	 public PageInfo<TvuePermission> list(Tablepar tablepar, String searchText){
	        TvuePermissionExample testExample=new TvuePermissionExample();
	        testExample.setOrderByClause("order_num  is null  ASC,order_num  ASC");
	        if(searchText!=null&&!"".equals(searchText)){
	        	testExample.createCriteria().andNameLike("%"+searchText+"%");
	        }

	        PageHelper.startPage(tablepar.getPageNum(), tablepar.getPageSize());
	        List<TvuePermission> list= tvuePermissionMapper.selectByExample(testExample);
	        PageInfo<TvuePermission> pageInfo = new PageInfo<TvuePermission>(list);
	        return  pageInfo;
	 }
	 
	 public List<TvuePermission> list2(String searchText){
	        TvuePermissionExample testExample=new TvuePermissionExample();
	        testExample.setOrderByClause("order_num  ASC,order_num  ASC");
	        if(searchText!=null&&!"".equals(searchText)){
	        	testExample.createCriteria().andNameLike("%"+searchText+"%");
	        }
	        List<TvuePermission> list= tvuePermissionMapper.selectByExample(testExample);
	        return  list;
	 }

	
	@Override
	public int deleteByPrimaryKey(String ids) {
		//转成集合
		List<String> lista=ConvertUtil.toListStrArray(ids);
		
		
		//判断角色是否删除去除
		TvuePermissionRoleExample permissionRoleExample=new TvuePermissionRoleExample();
		permissionRoleExample.createCriteria().andPermissionIdIn(lista);
		List<TvuePermissionRole> tvuePermissionRoles=tvuePermissionRoleMapper.selectByExample(permissionRoleExample);
		if(tvuePermissionRoles.size()>0) {//有角色外键
			return -2;
		}
		
		//判断是否有子集
		TvuePermissionExample example=new TvuePermissionExample();
		example.createCriteria().andIdIn(lista);
		List<TvuePermission> tsysPermissions = tvuePermissionMapper.selectByExample(example);
		boolean lag=false;
		for (TvuePermission tvuePermission : tsysPermissions) {
			if(tvuePermission.getChildCount()>0) {
				lag=true;
			}
		}
		if(lag) {//有子集 无法删除
			return -1;
		}else {//删除操作
			int i=tvuePermissionMapper.deleteByExample(example);
			if(i>0) {//删除成功
				return 1;
			}else {//删除失败
				return 0;
			}
			
		}
	}


	
	@Override
	public int insertSelective(TvuePermission record) {
		//添加雪花主键id
		record.setId(SnowflakeIdWorker.getUUID());
		//判断为目录的时候添加父id为0
		if(record!=null&&record.getType()==0){
			record.setPid("1");
		}
		//默认设置不跳转
		if(record.getIsBlank()==null) {
			record.setIsBlank(0);
		}
		return tvuePermissionMapper.insertSelective(record);
	}

	@Override
	public TvuePermission selectByPrimaryKey(String id) {
		
		return tvuePermissionMapper.selectByPrimaryKey(id);
	}

	
	@Override
	public int updateByPrimaryKeySelective(TvuePermission record) {
		//默认设置不跳转
		if(record.getIsBlank()==null) {
			record.setIsBlank(0);
		}
		return tvuePermissionMapper.updateByPrimaryKeySelective(record);
	}
	
	public int updateByPrimaryKey(TvuePermission record) {
		//默认设置不跳转
		if(record.getIsBlank()==null) {
			record.setIsBlank(0);
		}
		return tvuePermissionMapper.updateByPrimaryKey(record);
	}

	
	@Override
	public int updateByExampleSelective(TvuePermission record, TvuePermissionExample example) {
		//默认设置不跳转
		if(record.getIsBlank()==null) {
			record.setIsBlank(0);
		}
		return tvuePermissionMapper.updateByExampleSelective(record, example);
	}

	
	@Override
	public int updateByExample(TvuePermission record, TvuePermissionExample example) {
		//默认设置不跳转
		if(record.getIsBlank()==null) {
			record.setIsBlank(0);
		}
		return tvuePermissionMapper.updateByExample(record, example);
	}

	@Override
	public List<TvuePermission> selectByExample(TvuePermissionExample example) {
		
		return tvuePermissionMapper.selectByExample(example);
	}

	
	@Override
	public long countByExample(TvuePermissionExample example) {
		
		return tvuePermissionMapper.countByExample(example);
	}

	
	@Override
	public int deleteByExample(TvuePermissionExample example) {
		
		return tvuePermissionMapper.deleteByExample(example);
	}
	
	/**
	 * 检查权限名字
	 * @return
	 */
	public int checkNameUnique(TvuePermission tvuePermission){
		TvuePermissionExample example=new TvuePermissionExample();
		example.createCriteria().andNameEqualTo(tvuePermission.getName());
		List<TvuePermission> list=tvuePermissionMapper.selectByExample(example);
		return list.size();
	}

	/**
	 * 检查权限URL
	 * @return
	 */
	public int checkURLUnique(TvuePermission tvuePermission){
		TvuePermissionExample example=new TvuePermissionExample();
		example.createCriteria().andUrlEqualTo(tvuePermission.getUrl());
		List<TvuePermission> list=tvuePermissionMapper.selectByExample(example);
		return list.size();
	}

	/**
	 * 检查权限perms字段
	 * @return
	 */
	public int checkPermsUnique(TvuePermission tvuePermission){
		TvuePermissionExample example=new TvuePermissionExample();
		example.createCriteria().andPermsEqualTo(tvuePermission.getPerms());
		List<TvuePermission> list=tvuePermissionMapper.selectByExample(example);
		return list.size();
	}
	
	
	/**
	 * 根据父id 以及类型查询权限子集
	 * @param pid
	 * @return
	 */
	public List<TvuePermission> queryPid(String pid, int type){
		TvuePermissionExample example=new TvuePermissionExample();
		example.createCriteria().andPidEqualTo(pid).andTypeEqualTo(type);
		return tvuePermissionMapper.selectByExample(example);
	}
	
	/**
	 * 获取转换成bootstarp的权限数据
	 * @return
	 */
	public BootstrapTree getbooBootstrapTreePerm(String userid){
		List<BootstrapTree> treeList = new ArrayList<BootstrapTree>();
		List<TvuePermission> menuList =  getall(userid);
		treeList = getbooBootstrapTreePerm(menuList,"0");
		if(treeList!=null&&treeList.size()==1) {
			return treeList.get(0);
		}
		return new BootstrapTree("菜单", "fa fa-home", "", "-1","###",0,treeList,"",0);
	}
	
	
	
	/**
	 * 获取树
	 * @param menuList
	 * @param parentId
	 * @return
	 */
	private static List<BootstrapTree> getbooBootstrapTreePerm(List<TvuePermission> menuList, String parentId){
		List<BootstrapTree> treeList = new ArrayList<>();
		List<BootstrapTree> childList = null;
		for(TvuePermission p : menuList) {
			p.setPid(p.getPid()==null||p.getPid().trim().equals("")?"0":p.getPid());
			if(p.getPid().trim().equals(parentId)) {
				if(p.getChildCount()!=null&&p.getChildCount()>0) {
					childList = getbooBootstrapTreePerm(menuList, String.valueOf(p.getId()));
				}
				BootstrapTree bootstrapTree = new BootstrapTree(p.getName(), p.getIcon(), "", String.valueOf(p.getId()), p.getUrl(),p.getIsBlank(),childList,p.getPerms(),p.getVisible());
				treeList.add(bootstrapTree);
				childList = null;
			}
		}
		return treeList.size() >0 ? treeList : null;
	}
	
	/**
	 * 根据用户id获取用户角色如果用户为null 获取所有权限
	 * @return
	 */
	public List<TvuePermission> getall(String userid){
		if(StringUtils.isEmpty(userid)) {
			TvuePermissionExample example = new TvuePermissionExample();
			example.setOrderByClause("order_num asc");
			return  tvuePermissionMapper.selectByExample(example);
		}
		return  permissionVueDao.findByAdminUserId(userid);
	}
	
	
	
	
	
	/**
	 * 判断权限是否有权限
	 * @param myTsysPermissions
	 * @param sysPermission
	 */
	public Boolean ifpermissions(List<TvuePermission> myTsysPermissions, BootstrapTree sysPermission){
		for (TvuePermission mytsysPermission : myTsysPermissions) {
			if(sysPermission.getId().equals(mytsysPermission.getId())){
				return true;
			}
		}
		return false;
	}
	
	
	/**
	 * 获取角色已有的Bootstarp权限
	 * @return
	 */
	public BootstrapTree getCheckPrem(String roleid) {
		Map<String, Object> map = new HashMap<String, Object>();
		//设置选中
		map.put("checked", true);
		//设置展开
		//map.put("expanded", true);
		// 获取角色的权限
		List<TvuePermission> myTsysPermissions = permissionVueDao.queryRoleId(roleid);
		// 获取所有的权限
		BootstrapTree sysPermissions = getbooBootstrapTreePerm(null);
		iterationCheckPre(sysPermissions, myTsysPermissions, map);
		return sysPermissions;

	}
	
	/**
	 * 循环迭代获取所有权限
	 * @param pboostrapTree
	 * @param myTsysPermissions
	 * @param map
	 */
	public void iterationCheckPre(BootstrapTree pboostrapTree, List<TvuePermission> myTsysPermissions, Map<String, Object> map) {
		if(null!=pboostrapTree) {
			if (ifpermissions(myTsysPermissions, pboostrapTree)) {
				pboostrapTree.setState(map);
			}
			List<BootstrapTree> bootstrapTreeList = pboostrapTree.getNodes();
			if(null!=bootstrapTreeList&&!bootstrapTreeList.isEmpty()) {
				for(BootstrapTree bootstrapTree : bootstrapTreeList) {
					if (ifpermissions(myTsysPermissions, bootstrapTree)) {// 菜单栏设置
						bootstrapTree.setState(map);
					}
					//检查子节点
					iterationCheckPre(bootstrapTree, myTsysPermissions, map);
				}
			}
		}
	}
	
	/**
	 * 根据权限字段查询是否存在
	 * @param perms
	 * @return
	 * @author gyee
	 * @Date 2019年9月1日 上午2:06:31
	 */
	public Boolean queryLikePerms(String perms){
		TvuePermissionExample example=new TvuePermissionExample();
		example.createCriteria().andPermsLike("%gen:"+perms+"%");
		List<TvuePermission> list= tvuePermissionMapper.selectByExample(example);
        return list.size() > 0;
    }
	
	
}
