package com.njcn.serviceimpl.user;

import com.njcn.enums.RoleEnum;
import com.njcn.enums.RoleGroupEnum;
import com.njcn.mapper.user.RoleGPAssMapper;
import com.njcn.mapper.user.RoleGroupMapper;
import com.njcn.mapper.user.RoleMapper;
import com.njcn.mapper.user.UserMapper;
import com.njcn.pojo.commons.SimpleValue;
import com.njcn.pojo.user.Role;
import com.njcn.pojo.user.RoleGPAss;
import com.njcn.pojo.user.RoleGroup;
import com.njcn.pojo.user.UserSet;
import com.njcn.sso.pojo.user.User;
import com.njcn.service.user.RoleGroupService;
import com.njcn.service.user.RoleService;
import com.njcn.shiro.token.TokenManager;
import com.njcn.utils.PubUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class RoleServiceImpl implements RoleService {
    @Resource
    RoleMapper rm;
    @Autowired
    RoleGroupMapper roleGroupMapper;

    @Autowired
    private RoleGroupService roleGroupService;

    @Autowired
    private RoleGPAssMapper roleGPAssMapper;


    @Override
    public int insertRole(Role role) {
        // TODO Auto-generated method stub
        return rm.insertRole(role);
    }

    @Override
    public int deleteRole(Role role) {
        // TODO Auto-generated method stub
        return rm.deleteRole(role);

    }

    @Override
    public int updateRole(Role role) {
        // TODO Auto-generated method stub
        return rm.updateRole(role);
    }

    @Override
    public List<Role> selectAll() {
        // TODO Auto-generated method stub
        return rm.selectAll();
    }

    @Override
    public Role selectRoleIndex(String roleIndex) {
        // TODO Auto-generated method stub
        return rm.selectRoleIndex(roleIndex);
    }


    @Override
    public int selName(String roleName) {
        // TODO Auto-generated method stub
        return rm.selName(roleName);
    }


    @Override
    public List<Role> queryNameAll(String roleName) {
        // TODO Auto-generated method stub
        return rm.queryNameAll(roleName);
    }


    @Override
    public List<List> getRoleList() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<List> roleList = new ArrayList<List>();
        List<String> roleDescription = new ArrayList<>();
        roleDescription.add(RoleEnum.AUDIT.getEname());
        roleDescription.add(RoleEnum.BUSINESS.getEname());
        roleDescription.add(RoleEnum.CHECK.getEname());
        roleDescription.add(RoleEnum.ROOT.getEname());
        roleDescription.add(RoleEnum.SYSTEM.getEname());
        roleDescription.add(RoleEnum.CASUAL.getEname());
        roleDescription.add(RoleEnum.NORMAL.getEname());
        List<Role> roles = rm.selectAlls(roleDescription);
        if (roles.isEmpty()) {
            return roleList;
        } else {
            for (Role role : roles) {
                List<String> temp = new ArrayList<String>();
                temp.add(role.getRoleName());
                temp.add(role.getRoleDescription());
                temp.add(sdf.format(role.getUpdateTime()));
                temp.add("<button type='button' class='btn btn-danger' style='margin-right:10px;' href='javascript:void(0);' onclick='deleteRoleByIndex(\"" + role.getRoleIndex() + "\")' ><i class='fa fa-trash'></i>删除</button>");
                roleList.add(temp);
            }
        }
        return roleList;
    }


    /**
     * 新增角色
     */
    @Override
    public String saveRole(String roleName, String roleD) {
        //正则判断
        if (!StringUtils.isBlank(roleName)) {
            if (PubUtils.patternRole(roleName)) {
                //角色名不能重复
                Role temp = new Role();
                temp.setRoleName(roleName);
                temp.setState(1);
                temp = rm.selectOne(temp);
                if (null == temp) {
                    Role role = new Role();
                    role.setRoleIndex(UUID.randomUUID().toString());
                    role.setRoleName(roleName);
                    role.setRoleDescription(roleD);
                    role.setState(1);
                    role.setUpdateTime(new Date());
                    User user = TokenManager.getToken();
                    role.setUserIndex(user.getUserIndex());
                    try {
                        int flag = rm.insert(role);
                        return "新增角色成功！";
                    } catch (Exception e) {
                        return "新增角色失败，请稍后再试。";
                    }
                } else {
                    return "角色名已存在";
                }
            } else {
                return "角色名由汉字、数字、字母组成";
            }
        } else {
            return "角色名不可为空";
        }
    }


    @Override
    public String deleteRoleByIndex(String index) {
        //先判断角色是否存在
        Role temp = new Role();
        temp.setRoleIndex(index);
        temp = rm.selectOne(temp);
        if (null == temp) {
            return "该角色不存在，已删除";
        } else {
            try {
                RoleGPAss roleGPAss = new RoleGPAss();
                roleGPAss.setRoleIndex(index);
                roleGPAss.setSysType(TokenManager.getSysType());
                roleGPAss = roleGPAssMapper.selectOne(roleGPAss);
                if(roleGPAss == null){
                    temp.setState(0);
                    rm.updateByPrimaryKey(temp);
                    return "删除角色成功！";
                }else {
                    return "删除角色失败！该角色已被绑定";
                }
            } catch (Exception e) {
                return "删除角色失败，请稍后再试";
            }
        }
    }


    /**
     * 获取分配角色的角色组信息
     */
    @Override
    public List<List> getUserRole() {
        List<List> result = new ArrayList<List>();
        List<RoleGroup> lists = new ArrayList<RoleGroup>();
        List<String> ManagerRolegroup=new ArrayList<>();
        ManagerRolegroup.add(RoleGroupEnum.SYSTEM.getEname());
        ManagerRolegroup.add(RoleGroupEnum.AUDIT.getEname());
        ManagerRolegroup.add(RoleGroupEnum.CHECK.getEname());
        ManagerRolegroup.add(RoleGroupEnum.BUSINESS.getEname());
        ManagerRolegroup.add(RoleGroupEnum.CASUAL.getEname());
        ManagerRolegroup.add(RoleGroupEnum.ROOT.getEname());
        lists = roleGroupMapper.selectAllName(ManagerRolegroup);
        if (lists.isEmpty()) {
            return new ArrayList<List>();
        } else {
            for (RoleGroup user : lists) {
                List<String> temp = new ArrayList<String>();
                temp.add(user.getRolegpDescription());
                temp.add(user.getState() == 1 ? "有效" : "失效");
                //获取当前角色组所拥有的角色
                String roleGpIndex = user.getRoleGpIndex();
                List<Role> roles = new ArrayList<Role>();
                List<String> list = new ArrayList<>();
                list.add(RoleEnum.AUDIT.getEname());
                list.add(RoleEnum.BUSINESS.getEname());
                list.add(RoleEnum.CHECK.getEname());
                list.add(RoleEnum.ROOT.getEname());
                list.add(RoleEnum.SYSTEM.getEname());
                list.add(RoleEnum.CASUAL.getEname());
                list.add(RoleEnum.NORMAL.getEname());
                roles = roleGroupService.getRoleName(roleGpIndex,TokenManager.getSysType(),list);
                if (roles.isEmpty()) {
                    temp.add("暂无角色");
                } else {
                    String roleName = "";
                    for (Role role : roles) {
                        roleName = roleName + role.getRoleDescription() + ",";
                    }
                    roleName = roleName.substring(0, roleName.lastIndexOf(","));
                    temp.add(roleName);
                }
                //操作内容，针对用户分配角色
                temp.add("<button type='button' class='btn themeBGColor' style='margin-right:10px;' href='javascript:void(0);' onclick='destributeRole(\"" + user.getRoleGpIndex() + "\")' ><i class='fa fa-cogs'></i>分配角色</button>");
                result.add(temp);
            }
        }
        return result;
    }


    /**
     * 获取角色用于回显展示
     *
     * @param roleGPIndex
     * @return
     */
    @Override
    public List<SimpleValue> getBackRole(String roleGPIndex) {
        List<SimpleValue> lists = new ArrayList<SimpleValue>();
        //理论上，用户的角色会被缓存在redis中，所以到时候直接从缓存获取
        //现在暂且根据用户索引获取拥有的角色
        RoleGroup rolegp = new RoleGroup();
        rolegp.setRoleGpIndex(roleGPIndex);
        rolegp = roleGroupService.selectOne(rolegp);
        if (null == rolegp) {
            return new ArrayList<SimpleValue>();
        } else {
            //获取所有的角色
            List<String> roleNames = new ArrayList<String>();
            //已有角色
            List<String> hasRoleName = new ArrayList<String>();
            Example example = new Example(Role.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("state", "1");
            List<String> roleDescription = new ArrayList<>();
            roleDescription.add(RoleEnum.AUDIT.getEname());
            roleDescription.add(RoleEnum.BUSINESS.getEname());
            roleDescription.add(RoleEnum.CHECK.getEname());
            roleDescription.add(RoleEnum.ROOT.getEname());
            roleDescription.add(RoleEnum.SYSTEM.getEname());
            roleDescription.add(RoleEnum.CASUAL.getEname());
            roleDescription.add(RoleEnum.NORMAL.getEname());
            List<Role> temp = rm.selectAlls(roleDescription);
            if (!temp.isEmpty()) {
                for (Role role : temp) {
                    roleNames.add(role.getRoleDescription() + "," + role.getRoleIndex());
                }
                List<Role> roles = new ArrayList<Role>();
                List<String> list = new ArrayList<>();
                list.add(RoleEnum.AUDIT.getEname());
                list.add(RoleEnum.BUSINESS.getEname());
                list.add(RoleEnum.CHECK.getEname());
                list.add(RoleEnum.ROOT.getEname());
                list.add(RoleEnum.SYSTEM.getEname());
                list.add(RoleEnum.CASUAL.getEname());
                list.add(RoleEnum.NORMAL.getEname());
                roles = roleGroupService.getRoleName(roleGPIndex,TokenManager.getSysType(),list);
                if (roles.isEmpty()) {
                    //判断为该角色组没有绑定角色
                    for (String roleName : roleNames) {
                        String[] back = roleName.split(",");
                        SimpleValue sim = new SimpleValue();
                        sim.setCheckbox("false");
                        sim.setName(back[0]);
                        sim.setIndex(back[1]);
                        lists.add(sim);
                    }
                    return lists;
                } else {
                    //筛选出已经绑定的角色
                    for (Role role : roles) {
                        hasRoleName.add(role.getRoleDescription() + "," + role.getRoleIndex());
                    }
                    Collection exists = new ArrayList<String>(roleNames);
                    exists.removeAll(hasRoleName);
                    //用户当前没有的，非重复元素
                    for (Object object : exists) {
                        String tempS = (String) object;
                        String[] back = tempS.split(",");
                        SimpleValue sim = new SimpleValue();
                        sim.setCheckbox("false");
                        sim.setName(back[0]);
                        sim.setIndex(back[1]);
                        lists.add(sim);
                    }
                    //用户当前已经绑定的元素
                    for (Role role : roles) {
                        SimpleValue sim = new SimpleValue();
                        sim.setCheckbox("true");
                        sim.setName(role.getRoleDescription());
                        sim.setIndex(role.getRoleIndex());
                        lists.add(sim);
                    }
                    return lists;
                }
            } else {
                return new ArrayList<SimpleValue>();
            }
        }
    }


    @Override
    public String disRole(String roleGPIndex, String roleIndex) {
//        roleIndex = roleIndex.substring(0, roleIndex.lastIndexOf(","));
        //因为【正式用户】是必备，且页面没有提供勾选，所以需要单独提供出来
        Role roleTemp = new Role();
        roleTemp.setRoleName("normal");
        roleTemp=rm.selectOne(roleTemp);
        if(null!=roleTemp){
            roleIndex=roleIndex+roleTemp.getRoleIndex();
        }
        String[] roleIndexs = roleIndex.split(",");
        RoleGroup rolegp = new RoleGroup();
        rolegp.setRoleGpIndex(roleGPIndex);
        rolegp = roleGroupService.selectOne(rolegp);
        if (null == rolegp) {
            return "角色组不存在，请稍后再试";
        } else {
            roleGroupService.deleteByGpIndex(roleGPIndex,TokenManager.getSysType());
            //在循环插入用户与角色的中间关系表数据
            for (String index : roleIndexs) {
                //判断角色是否存在，不存在则跳过
                Role role=rm.selectRoleIndex(index);
                if(null==role){
                    continue;
                }
                roleGroupService.addASS(roleGPIndex, index,TokenManager.getSysType());
            }
        }
        return "分配角色成功";
    }

    /**
     * 根据角色组索引获取所有角色
     */
    @Override
    public List<Role> selectByRoleGpIndex(String roleGpIndex) {
        List<Role> roles = new ArrayList<Role>();
        List<String> list = new ArrayList<>();
        list.add(RoleEnum.AUDIT.getEname());
        list.add(RoleEnum.BUSINESS.getEname());
        list.add(RoleEnum.CHECK.getEname());
        list.add(RoleEnum.ROOT.getEname());
        list.add(RoleEnum.SYSTEM.getEname());
        list.add(RoleEnum.CASUAL.getEname());
        list.add(RoleEnum.NORMAL.getEname());
        roles = roleGroupService.getRoleName(roleGpIndex,TokenManager.getSysType(),list);
        if (roles.isEmpty()) {
            return new ArrayList<Role>();
        } else {
            return roles;
        }
    }


}
