package com.yida.data.auth.manager;

import cc.mrbird.febs.common.redis.service.RedisService;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yida.data.auth.mapper.EduUserLogoMapper;
import com.yida.data.auth.mapper.MenuMapper;
import com.yida.data.auth.mapper.RoleMapper;
import com.yida.data.auth.mapper.UserMapper;
import com.yida.data.auth.mapper.UserMenuMapper;
import com.yida.data.auth.mapper.UserRoleMapper;
import com.yida.data.common.core.entity.constant.CachePrefixConstant;
import com.yida.data.common.core.entity.constant.FebsConstant;
import com.yida.data.common.core.entity.constant.StringConstant;
import com.yida.data.common.core.entity.system.Dept;
import com.yida.data.common.core.entity.system.EduUserLogo;
import com.yida.data.common.core.entity.system.Menu;
import com.yida.data.common.core.entity.system.Role;
import com.yida.data.common.core.entity.system.SystemUser;
import com.yida.data.common.core.entity.system.SystemUserMenu;
import com.yida.data.common.core.entity.system.UserRole;
import com.yida.data.common.service.CommonService;
import com.yida.data.user.feign.RemoteTeacherService;
import java.util.List;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * 用户业务逻辑
 *
 * @author MrBird
 */
@Slf4j
@Service
@RequiredArgsConstructor
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
public class UserManager {

    private final UserMapper userMapper;
    private final EduUserLogoMapper eduUserLogoMapper;
    private final MenuMapper menuMapper;
    private final RoleMapper roleMapper;
    private final UserRoleMapper userRoleMapper;
    private final UserMenuMapper userMenuMapper;
    private final RemoteTeacherService remoteTeacherService;
    private final RedisService redisService;
    private final CommonService commonService;

    /**
     * 通过用户名查询用户信息
     *
     * @param username 用户名
     * @return 用户
     */
    public SystemUser findByName(String username) {
        Object deptO = redisService.hget(CachePrefixConstant.USER_LOGIN_DEPT, username);
        SystemUser user = userMapper.findByName(username);
        if (user != null) {
            if (deptO != null) {
                Long deptId = Long.valueOf(deptO.toString());
                Dept dept = commonService.getDept(deptId);
                user.setDeptId(dept.getDeptId());
                user.setDeptName(dept.getDeptName());
                user.setDeptType(dept.getDeptType());
            }
            user.setUserLogo(
                eduUserLogoMapper.selectOne(Wrappers.<EduUserLogo>lambdaQuery().eq(EduUserLogo::getUserId, user.getUserId())));
        }
        return user;
    }

    /**
     * 通过用户名查询用户权限串
     *
     * @param username 用户名
     * @return 权限
     */
    public List<String> findUserPermissions(String username) {
        // 获取角色权限
        List<String> menus = menuMapper.findUserPermissions(username);
        // 获取用户权限
        List<SystemUserMenu> userPermissions = userMenuMapper.findUserPermissions(username);
        // 过滤
        if (CollUtil.isNotEmpty(userPermissions)) {
            menus.addAll(
                userPermissions.stream().filter(x -> x.getType() == 0).map(SystemUserMenu::getPerms).filter(StrUtil::isNotBlank)
                    .collect(Collectors.toList()));
            List<String> excludePerms = userPermissions.stream().filter(x -> x.getType() == 1).map(SystemUserMenu::getPerms)
                .filter(StrUtil::isNotBlank).collect(Collectors.toList());
            if (CollUtil.isNotEmpty(excludePerms)) {
                menus = menus.stream().filter(x -> !excludePerms.contains(x)).collect(Collectors.toList());
            }
        }
        // 只返回串
        return menus;
    }

    /**
     * 注册用户
     *
     * @param username username
     * @param password password
     * @return SystemUser SystemUser
     */
    @Transactional(rollbackFor = Exception.class)
    public SystemUser registUser(String username, String password) {
        SystemUser systemUser = new SystemUser();
        systemUser.setUsername(username);
        systemUser.setPassword(password);
        systemUser.setStatus(SystemUser.STATUS_VALID);
        systemUser.setSex(SystemUser.SEX_UNKNOW);
        systemUser.setAvatar(SystemUser.DEFAULT_AVATAR);
        systemUser.setDescription("注册用户");
        userMapper.insert(systemUser);

        UserRole userRole = new UserRole();
        userRole.setUserId(systemUser.getUserId());
        // 注册用户角色 ID
        userRole.setRoleId(FebsConstant.REGISTER_ROLE_ID);
        userRoleMapper.insert(userRole);
        return systemUser;
    }

    /**
     * 注册用户
     */
    @Transactional(rollbackFor = Exception.class)
    public SystemUser registUser(SystemUser systemUser) {
        systemUser.setStatus(SystemUser.STATUS_VALID);
        userMapper.insert(systemUser);
        UserRole userRole = new UserRole();
        userRole.setUserId(systemUser.getUserId());
        if (systemUser.getRoleId() != null) {
            // 注册用户角色 ID
            userRole.setRoleId(Long.valueOf(systemUser.getRoleId()));
            userRoleMapper.insert(userRole);
        } else if (StrUtil.isNotBlank(systemUser.getRoleName())) {
            Role role = roleMapper.selectOne(Wrappers.<Role>lambdaQuery().eq(Role::getRoleName, systemUser.getRoleName()));
            userRole.setRoleId(role.getRoleId());
            userRoleMapper.insert(userRole);
        }
        return systemUser;
    }

    /**
     * 添加角色
     */
    public void addRole(Long userId, Long roleId) {
        UserRole userRole = new UserRole();
        userRole.setRoleId(roleId);
        userRole.setUserId(userId);
        userRoleMapper.insert(userRole);
    }

    /**
     * 查询主角色code字符串
     *
     * @param mainDeptId 主部门id
     * @return java.lang.String
     * @author ZYJ
     * @date 2022/1/14 10:36
     */
    public String findMainRole(Long mainDeptId) {
        // 查询主角色code
        List<String> rolePerms = userMapper.findMainRole(mainDeptId);
        return rolePerms.stream().filter(StringUtils::isNotBlank).distinct().collect(Collectors.joining(StringConstant.COMMA));
    }
}
