/*
 * Author: wangjian
 * 生成ServiceImpl
 */
package com.tofly.base.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tofly.base.entity.User;
import com.tofly.base.entity.UserRole;
import com.tofly.base.entity.System;
import com.tofly.base.entity.*;
import com.tofly.base.mapper.RoleMapper;
import com.tofly.base.service.*;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 角色信息表
 *
 * @author admin
 * @date Thu Oct 10 00:00:00 CST 2019
 */
@Service("roleService")
@Slf4j
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    @Autowired
    private MenuService menuService;

    @Autowired
    private UserService userService;

    @Autowired
    private RoleMenuService roleMenuService;

    @Autowired
    private SystemService systemService;

    @Autowired
    private UserRoleService userRoleService;

    @Override
    public List<Menu> getMenuListByRole(Long roleId) {
        return menuService.getMenuListByRole(roleId);
    }

    @Override
    public List<User> getExistUserListByRole(Long roleId) {
        return userService.getExistUserListByRole(roleId);
    }

    @Override
    public List<User> getNoExistUserListByRole(Long roleId) {
        return userService.getNoExistUserListByRole(roleId);
    }

    @Override
    @Transactional
    public String deleteRolesByIds(String ids) {
        String[] idss=ids.split(",");
        List<Long> list=new ArrayList();
        boolean flag=true;
        StringBuffer sb=new StringBuffer();

        List<Long> roleMenus=new ArrayList<>(),userRoles=new ArrayList<>();
        for(String id:idss){
            list.add(Long.valueOf(id));

            //查询用户是否还存在该角色
            List<UserRole> sourceList=userRoleService.list(Wrappers.<UserRole>lambdaQuery()
                    .eq(UserRole::getRoleId,Long.valueOf(id)));

            if(sourceList.size()>0){
                flag=false;
                sb.append("id:").append(id).append(",该角色还存在").append(sourceList.size())
                        .append("个用户正在使用。");
                continue;
            }

            List<RoleMenu> roleMneuList=roleMenuService.list(Wrappers.<RoleMenu>lambdaQuery()
            .eq(RoleMenu::getRoleId,Long.valueOf(id)));
            roleMenus.addAll(roleMneuList.stream().map(RoleMenu::getId).collect(Collectors.toList()));
        }
        if(flag){

            if(roleMenus.size()>0){
                roleMenuService.removeByIds(roleMenus);
            }
            this.removeByIds(list);
            return null;
        }else {
            return "还存在用户使用，不能删除："+sb.toString();
        }
    }

    @Override
    @SneakyThrows
    public List<Map> listMenuByRoleId(Long roleId) {
        List<System> systemList=systemService.list(Wrappers.<System>lambdaQuery().orderByAsc(System::getSort));
        List<Map> reList=new ArrayList<>();
        Map m=new HashMap(),map;
        m.put("roleId",roleId);
        for(System system:systemList){
            map = BeanUtils.describe(system);
            m.put("systemId",system.getId());
            map.put("funs",baseMapper.listMenuByRoleId(m));
            reList.add(map);
        };

        return reList;
    }

    @Override
    public Boolean selectByRoleName(Long roleId, String name) {
        QueryWrapper<Role> role = new QueryWrapper<>();
        role.eq("ROLE_NAME",name);
        Role r = baseMapper.selectOne(role);
        if (r != null && roleId != null && !Objects.equals(r.getId(), roleId)){
            return false;
        }
        return r == null || roleId != null;
    }

    @Override
    public List<Role> listRolesByUserId(Long userId) {
        return baseMapper.listRolesByUserId(userId);
    }

}
