package com.tofly.base.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tofly.base.api.dto.UserInfo;
import com.tofly.base.api.entity.SysMenu;
import com.tofly.base.api.entity.SysRole;
import com.tofly.base.api.entity.SysUser;
import com.tofly.base.entity.Department;
import com.tofly.base.mapper.SysUserMapper;
import com.tofly.base.service.DepartmentService;
import com.tofly.base.service.SysMenuService;
import com.tofly.base.service.SysRoleService;
import com.tofly.base.service.SysUserService;
import com.tofly.common.core.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author Administrator
 * @date 2019/9/6  16:33
 */
@Service
@Slf4j
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {
    @Autowired
    private  SysRoleService sysRoleService;
    @Autowired
    private  SysMenuService sysMenuService;

    @Autowired
    private DepartmentService departmentService;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Override
    public UserInfo getUserInfo(SysUser sysUser) {
        UserInfo userInfo=new UserInfo();
        //加入部门名称
        if(sysUser.getDepartmentId()!=null){
            Department department=departmentService.getOne(Wrappers.<Department>lambdaQuery().
                    eq(Department::getId,sysUser.getDepartmentId()));
            sysUser.setDepartemntName(department.getName());
        }

        userInfo.setSysUser(sysUser);//用户信息

        //设置角色

        List<SysRole> list=sysRoleService.listRolesByUserId(sysUser.getId());
        //List<Map> list=listRolesByUserId(sysUser.getUserId());
        List<Long> roleList=list
                .stream()
                .map(SysRole::getId)
                //.map(m->(Integer)m.get("roleId"))
                .collect(Collectors.toList());

        userInfo.setRoles(roleList.stream().toArray(Long[]::new));//角色信息

        log.info("--------------rolelist:{}",roleList);
        //设置权限
        Set<String> permissions = new HashSet<>();
        roleList.forEach(roleid->{
            log.info("roleid:{}",roleid);
            List<String> permssionsList=sysMenuService.listMenusByRoleId(roleid)
                    .stream()
                    .filter(sysMenu-> StringUtil.isNotEmpty(sysMenu.getPermission()))
                    .map(SysMenu::getPermission)
                    .collect(Collectors.toList());
        });

        userInfo.setPermissions(permissions.stream().toArray(String[]::new));

        return userInfo;
    }

    @Override
    public boolean updateUserInfo(SysUser sysUser) {
        return sysUserMapper.updateUserInfo(sysUser);
    }
}
