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

import cn.com.countrygarden.bi.main.core.AbstractService;
import cn.com.countrygarden.bi.main.core.Response;
import cn.com.countrygarden.bi.main.core.Result;
import cn.com.countrygarden.bi.main.dao.sys.RoleFunctionsMapper;
import cn.com.countrygarden.bi.main.dao.sys.RoleMapper;
import cn.com.countrygarden.bi.main.dao.sys.RoleMenusMapper;
import cn.com.countrygarden.bi.main.dao.sys.UserRolesMapper;
import cn.com.countrygarden.bi.main.exception.ServiceException;
import cn.com.countrygarden.bi.main.model.PageData;
import cn.com.countrygarden.bi.main.model.sys.*;
import cn.com.countrygarden.bi.main.service.RoleService;
import cn.com.countrygarden.bi.main.service.UserRoleService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageRowBounds;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Condition;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Pattern;

/**
 * package: cn.com.countrygarden.bi.main.service.impl
 * describe:
 * creat_user: lsl
 * creat_date: 2018/6/7
 * creat_time: 21:57
 **/
@Service
@Transactional
public class RoleServiceImpl extends AbstractService<Role> implements RoleService {

    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private RoleMenusMapper roleMenusMapper;
    @Autowired
    private RoleFunctionsMapper roleFunctionsMapper;
    @Autowired
    private UserRolesMapper userRolesMapper;
    @Autowired
    private UserRoleService userRoleService;
    @Override
    public Result queryRoleInfo(Role role, int page, int size) {
        Page<Role> objects = PageHelper.startPage(page, size);
        Condition condition = new Condition(Function.class);
        Example.Criteria criteria = condition.createCriteria();
        condition.setOrderByClause(" created_date DESC");
        if(StringUtils.isNotBlank(role.getCode())){
            criteria.andLike("code",String.format("%%%s%%",role.getCode()));
        }
        if(StringUtils.isNotBlank(role.getName())){
            criteria.andLike("name",String.format("%%%s%%",role.getName()));
        }
        roleMapper.selectByCondition(condition);
        PageData pageData = new PageData(objects);
        pageData.setData(objects.getResult());
        return Response.response(pageData);
    }
    
    @Override
    public Result queryRoleInfo(Role role, String userCode, int page, int size) {
    	PageRowBounds pageRowBounds = new PageRowBounds(page,size);
    	 Integer isAdmin = roleMapper.checkIsAdmin(userCode);
    	 List<Role> totalList = null;
    	 if(isAdmin > 0) {
    		 totalList = roleMapper.getUserRoleList(role,null,pageRowBounds);
    	 }else {
    		 totalList = roleMapper.getUserRoleList(role,userCode,pageRowBounds);
    	 }
    	 PageData pageList = new PageData(totalList, pageRowBounds);
    	 return Response.response(pageList);
    }
    
    @Override
    public boolean checkRoleCodeExist(String code) {
        Role role=new Role();
        role.setCode(code);
        int count = roleMapper.selectCount(role);
        return count>0;
    }

    @Override
    public Result addRoleOrMenusAndFunctions(Role role, String menusIds, String functionIds) {
        int count = roleMapper.insert(role);
        if(count!=1){
            throw new ServiceException("系统异常，角色数据新增异常！");
        }
        String[] menuAry = menusIds.split(",");
        String[] funAry = functionIds.split(",");
        List<RoleMenus> roleMenusList=new LinkedList<>();
        for (String menuCode : menuAry) {
            RoleMenus roleMenus=new RoleMenus();
            roleMenus.setMenuCode(menuCode);
            roleMenus.setRoleCode(role.getCode());
            roleMenus.setCreatedBy(role.getCreatedBy());
            roleMenus.setCreatedDate(new Date());
            roleMenusList.add(roleMenus);
        }
        List<RoleFunctions> roleFunctionsList=new LinkedList<>();
        for (String funCode : funAry) {
            RoleFunctions functions1=new RoleFunctions();
            functions1.setFunctionCode(funCode);
            functions1.setRoleCode(role.getCode());
            functions1.setCreatedBy(role.getCreatedBy());
            functions1.setCreatedDate(new Date());
            roleFunctionsList.add(functions1);
        }
        roleMenusMapper.insertList(roleMenusList);
        roleFunctionsMapper.insertList(roleFunctionsList);
        return Response.response();
    }
    
    @Override
    public Result addRoleOrMenusAndFunctions(Role role, String userCode, String menusIds, String functionIds) {
        int count = roleMapper.insert(role);
        if(count!=1){
            throw new ServiceException("系统异常，角色数据新增异常！");
        }
        if(!this.checkIsAdmin(userCode)) {
        	throw new ServiceException("系统异常，你没有管理员权限进行操作");
        }
        String[] menuAry = menusIds.split(",");
        String[] funAry = functionIds.split(",");
        List<RoleMenus> roleMenusList=new LinkedList<>();
        for (String menuCode : menuAry) {
            RoleMenus roleMenus=new RoleMenus();
            roleMenus.setMenuCode(menuCode);
            roleMenus.setRoleCode(role.getCode());
            roleMenus.setCreatedBy(role.getCreatedBy());
            roleMenus.setCreatedDate(new Date());
            roleMenusList.add(roleMenus);
        }
        List<RoleFunctions> roleFunctionsList=new LinkedList<>();
        for (String funCode : funAry) {
            RoleFunctions functions1=new RoleFunctions();
            functions1.setFunctionCode(funCode);
            functions1.setRoleCode(role.getCode());
            functions1.setCreatedBy(role.getCreatedBy());
            functions1.setCreatedDate(new Date());
            roleFunctionsList.add(functions1);
        }
        roleMenusMapper.insertList(roleMenusList);
        roleFunctionsMapper.insertList(roleFunctionsList);
        return Response.response();
    }
    
    @Override
    public Result queryDataById(Integer id) {
        return Response.response(roleMapper.selectDataByPrimaryKey(id));
    }


    @Override
    public Result del(Integer id) {
        Role role = roleMapper.selectByPrimaryKey(id);
        if(role==null){
            throw new ServiceException("系统异常，角色不存在！");
        }
        UserRoles userRole=new UserRoles();
        userRole.setRoleCode(role.getCode());
        int i = userRolesMapper.selectCount(userRole);
        if(i>0){
            throw new ServiceException("系统异常，角色存在关联用户，删除会造成影响！");
        }
        RoleMenus roleMenus=new RoleMenus();
        roleMenus.setRoleCode(role.getCode());
        roleMenusMapper.delete(roleMenus);

        RoleFunctions func=new RoleFunctions();
        func.setRoleCode(role.getCode());
        roleFunctionsMapper.delete(func);

        roleMapper.deleteByPrimaryKey(role.getId());
        return Response.response();
    }

    @Override
    public boolean isExistRoleCode(String roleCode, String userCode){
        Condition condition=new Condition(UserRoles.class);
        condition.createCriteria()
                .andEqualTo("userCode",userCode)
                .andEqualTo("roleCode",roleCode);
        int count = userRolesMapper.selectCountByCondition(condition);
        return count>0;
    }


    @Override
    public Result edit(Role role, String menusIds, String functionIds) {
        if(StringUtils.isBlank(role.getCode())||role.getId()==null){
            throw new ServiceException("系统异常，接口参数错误！");
        }
        int count = roleMapper.updateByPrimaryKey(role);
        if(count==-1){
            throw new ServiceException("系统异常，角色数据新增异常！");
        }
//      清空授权数据
        Condition con=new Condition(RoleMenus.class);
        con.createCriteria().andEqualTo("roleCode",role.getCode());
        roleMenusMapper.deleteByCondition(con);
        Condition con1=new Condition(RoleFunctions.class);
        con1.createCriteria().andEqualTo("roleCode",role.getCode());
        roleFunctionsMapper.deleteByCondition(con1);
//      授权
        String[] menuAry = menusIds.split(",");
        String[] funAry = functionIds.split(",");
        List<RoleMenus> roleMenusList=new LinkedList<>();
        for (String menuCode : menuAry) {
            RoleMenus roleMenus=new RoleMenus();
            roleMenus.setMenuCode(menuCode);
            roleMenus.setRoleCode(role.getCode());
            roleMenus.setCreatedBy(role.getCreatedBy());
            roleMenus.setCreatedDate(new Date());
            roleMenusList.add(roleMenus);
        }
        List<RoleFunctions> roleFunctionsList=new LinkedList<>();
        for (String funCode : funAry) {
            RoleFunctions functions1=new RoleFunctions();
            functions1.setFunctionCode(funCode);
            functions1.setRoleCode(role.getCode());
            functions1.setCreatedBy(role.getCreatedBy());
            functions1.setCreatedDate(new Date());
            roleFunctionsList.add(functions1);
        }
        roleMenusMapper.insertList(roleMenusList);
        roleFunctionsMapper.insertList(roleFunctionsList);
        return Response.response();
    }

	@Override
	public boolean whiteUrlFiter(String userCode, String requestUrl) {
        //通过用户code 获取用户所有角色
        if (StringUtils.isBlank(userCode)) {
            throw new ServiceException("无法获取当前用户信息");
        }
        List<UserRoles> userRolesList = userRolesMapper.searchByUserCode(userCode);
        if (userRolesList == null || userRolesList.isEmpty()) {
            throw new ServiceException("当前未分配角色");
        }
        if (requestUrl.contains("/api/user/logout")) {
            return true;
        }

        List<UserWhiteUrl> userWhiteUrlList = new ArrayList<UserWhiteUrl>();
        List<UserWhiteUrl> tempuserWhiteUrlList = null;
        for (UserRoles userRole : userRolesList) {
            tempuserWhiteUrlList = userRoleService.getUserWhiteUrlByUserCode(userRole.getRoleCode());
            if (tempuserWhiteUrlList != null && !tempuserWhiteUrlList.isEmpty()) {
                userWhiteUrlList.addAll(tempuserWhiteUrlList);
            }
        }
        //域名匹配
        for (UserWhiteUrl whiteUrl : userWhiteUrlList) {
            if (!StringUtils.isBlank(whiteUrl.getWhiteUrl())) {
                //多个白名单允许已逗号切割
                for (String url : whiteUrl.getWhiteUrl().split(",")) {
                    if (StringUtils.isBlank(url)) {
                        continue;
                    }
                    //切割以后做一些约定符号的转换
                    String pattern = "^(https?):\\/\\/([\\w\\-]+(\\.[\\w\\-]+)*\\/)*[\\w\\-]+(\\.[\\w\\-]+)*(:[0-9]*)?\\/" + url + "(\\/.*)?";
                    //替换掉第一个斜杠
                    if (Pattern.matches(pattern, requestUrl)) {
                        return true;
                    }
                }
            }
        }
//        throw new ServiceException("很抱歉，你未被授权访问当前链接");
return true;
    }
	
	@Override
	public boolean checkIsAdmin(String userCode) {
		//查询是否是超级管理员
		Integer count = roleMapper.checkIsAdmin(userCode);
		if(count != null && count >0) {
			return true;
		}else {
			//查询当前人员是否有操作权限
			count = roleMapper.checkIsConsoleAdmin(userCode);
			if(count != null && count > 0) {
				return true;
			}
		}
		throw new ServiceException("很抱歉，你没有权限进行当前操作");
	}
}
