package com.ruoyi.project.system.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanValidators;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.framework.aspectj.lang.annotation.DataScope;
import com.ruoyi.project.business.domain.TbAgent;
import com.ruoyi.project.business.domain.TbArea;
import com.ruoyi.project.business.mapper.TbAgentMapper;
import com.ruoyi.project.business.service.ITbAreaService;
import com.ruoyi.project.system.config.RoleKeysProp;
import com.ruoyi.project.system.domain.SysPost;
import com.ruoyi.project.system.domain.SysRole;
import com.ruoyi.project.system.domain.SysUser;
import com.ruoyi.project.system.domain.SysUserPost;
import com.ruoyi.project.system.domain.SysUserRole;
import com.ruoyi.project.system.mapper.SysPostMapper;
import com.ruoyi.project.system.mapper.SysRoleMapper;
import com.ruoyi.project.system.mapper.SysUserMapper;
import com.ruoyi.project.system.mapper.SysUserPostMapper;
import com.ruoyi.project.system.mapper.SysUserRoleMapper;
import com.ruoyi.project.system.service.ISysConfigService;
import com.ruoyi.project.system.service.ISysUserService;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.validation.Validator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

/**
 * 用户 业务层处理
 *
 * @author ruoyi
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {

    private static final Logger log = LoggerFactory.getLogger(SysUserServiceImpl.class);

    @Resource
    protected Validator validator;

    @Resource
    private SysUserMapper userMapper;

    @Resource
    private SysRoleMapper roleMapper;

    @Resource
    private SysPostMapper postMapper;

    @Resource
    private SysUserRoleMapper userRoleMapper;

    @Resource
    private SysUserPostMapper userPostMapper;

    @Resource
    private ISysConfigService configService;

    @Resource
    private ITbAreaService tbAreaService;
    @Resource
    private TbAgentMapper agentMapper;

    public final static Map<String, List<String>> ROLE_KEY2NEXT_KEY_MAP = new ConcurrentHashMap<>();

    @Autowired
    private RoleKeysProp roleKeysProp;

    /**
     * 初始化每一级角色对应的下一级角色（不包括同级）
     */
    @PostConstruct
    private void initRoleKeysProp() {
        List<String> roleLinkKeys = roleKeysProp.getRoleLinkKeys();
        for (int i = 0; i < roleLinkKeys.size() - 1; i++) {
            String key = roleLinkKeys.get(i);
            String nextKey = roleLinkKeys.get(i + 1);
            if (key.contains("|")) {
                String[] split = key.split("\\|");
                ArrayList<String> roles = new ArrayList<>(Arrays.asList(split));
                roles.add(nextKey);
                for (String s : split) {
                    // 排除同级
                    ArrayList<String> temp = new ArrayList<>(roles);
                    temp.remove(s);
                    ROLE_KEY2NEXT_KEY_MAP.put(s, temp);
                }
            } else {
                ROLE_KEY2NEXT_KEY_MAP.put(key, Collections.singletonList(nextKey));
            }
        }
        log.info("ROLE_KEY2NEXT_KEY_MAP: {}", ROLE_KEY2NEXT_KEY_MAP);
    }

    /**
     * 根据条件分页查询用户列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<SysUser> selectUserList(SysUser user) {
        List<SysUser> sysUsers = userMapper.selectUserList(user);

        // List<TbArea> tbAreas = tbAreaService.selectTbAreaList(null);
        // 内存化
        // Map<Long, TbArea> areaId2ItemMap = tbAreas.stream().collect(Collectors.toMap(TbArea::getAreaId, item -> item));

        for (SysUser sysUser : sysUsers) {
            sysUser.setRoleNames(
                sysUser.getRoles().stream().map(SysRole::getRoleName).collect(Collectors.joining(",")));
            // String areaNames = sysUser.getAreaIdList().stream().map(item -> {
            //     TbArea tbArea = areaId2ItemMap.get(item);
            //     return tbArea == null ? null : localAreaNameFun().apply(tbArea);
            // }).collect(Collectors.joining(","));
            // sysUser.setAreaName(areaNames);
        }

        return sysUsers;
    }

    @Override
    public List<SysUser> selectUserListWithoutAdmin(SysUser user) {
        List<SysUser> sysUsers = userMapper.selectUserListWithoutAdmin(user);

        for (SysUser sysUser : sysUsers) {
            sysUser.setRoleNames(sysUser.getRoles().stream().map(SysRole::getRoleName).collect(Collectors.joining(",")));
        }

        return sysUsers;
    }

    /**
     * 根据条件分页查询已分配用户角色列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<SysUser> selectAllocatedList(SysUser user) {
        return userMapper.selectAllocatedList(user);
    }

    /**
     * 根据条件分页查询未分配用户角色列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<SysUser> selectUnallocatedList(SysUser user) {
        return userMapper.selectUnallocatedList(user);
    }

    /**
     * 通过用户名查询用户
     *
     * @param userName 用户名
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserByUserName(String userName) {
        return userMapper.selectUserByUserName(userName);
    }

    /**
     * 通过用户ID查询用户
     *
     * @param userId 用户ID
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserById(Long userId) {
        return userMapper.selectUserById(userId);
    }

    /**
     * 查询用户所属角色组
     *
     * @param userName 用户名
     * @return 结果
     */
    @Override
    public String selectUserRoleGroup(String userName) {
        List<SysRole> list = roleMapper.selectRolesByUserName(userName);
        if (CollectionUtils.isEmpty(list)) {
            return StringUtils.EMPTY;
        }
        return list.stream().map(SysRole::getRoleName).collect(Collectors.joining(","));
    }

    /**
     * 查询用户所属岗位组
     *
     * @param userName 用户名
     * @return 结果
     */
    @Override
    public String selectUserPostGroup(String userName) {
        List<SysPost> list = postMapper.selectPostsByUserName(userName);
        if (CollectionUtils.isEmpty(list)) {
            return StringUtils.EMPTY;
        }
        return list.stream().map(SysPost::getPostName).collect(Collectors.joining(","));
    }

    /**
     * 校验用户名称是否唯一
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public boolean checkUserNameUnique(SysUser user) {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = userMapper.checkUserNameUnique(user.getUserName());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验用户名称是否唯一
     *
     * @param user 用户信息
     * @return
     */
    @Override
    public boolean checkPhoneUnique(SysUser user) {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = userMapper.checkPhoneUnique(user.getPhonenumber());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验email是否唯一
     *
     * @param user 用户信息
     * @return
     */
    @Override
    public boolean checkEmailUnique(SysUser user) {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = userMapper.checkEmailUnique(user.getEmail());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验用户是否允许操作
     *
     * @param user 用户信息
     */
    @Override
    public void checkUserAllowed(SysUser user) {
        if (StringUtils.isNotNull(user.getUserId()) && user.isAdmin()) {
            throw new ServiceException("不允许操作超级管理员用户");
        }
    }

    /**
     * 校验用户是否有数据权限
     *
     * @param userId 用户id
     */
    @Override
    public void checkUserDataScope(Long userId) {
        if (!SysUser.isAdmin(SecurityUtils.getUserId())) {
            SysUser user = new SysUser();
            user.setUserId(userId);
            List<SysUser> users = SpringUtils.getAopProxy(this).selectUserList(user);
            if (StringUtils.isEmpty(users)) {
                throw new ServiceException("没有权限访问用户数据！");
            }
        }
    }

    /**
     * 新增保存用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional
    public int insertUser(SysUser user) {
        // 新增用户信息
        int rows = userMapper.insertUser(user);
        // 新增用户岗位关联
        //insertUserPost(user);
        // 新增用户与角色管理
        insertUserRole(user);
        return rows;
    }

    /**
     * 注册用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public boolean registerUser(SysUser user) {
        return userMapper.insertUser(user) > 0;
    }

    /**
     * 修改保存用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updateUser(SysUser user) {
        Long userId = user.getUserId();
        // 删除用户与角色关联
        userRoleMapper.deleteUserRoleByUserId(userId);
        // 新增用户与角色管理
        insertUserRole(user);
        // 删除用户与岗位关联
        userPostMapper.deleteUserPostByUserId(userId);
        // 新增用户与岗位管理
        insertUserPost(user);
        return userMapper.updateUser(user);
    }

    /**
     * 用户授权角色
     *
     * @param userId  用户ID
     * @param roleIds 角色组
     */
    @Override
    @Transactional
    public void insertUserAuth(Long userId, Long[] roleIds) {
        userRoleMapper.deleteUserRoleByUserId(userId);
        insertUserRole(userId, roleIds);
    }

    /**
     * 修改用户状态
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int updateUserStatus(SysUser user) {
        return userMapper.updateUser(user);
    }

    /**
     * 修改用户基本信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int updateUserProfile(SysUser user) {
        return userMapper.updateUser(user);
    }

    /**
     * 修改用户头像
     *
     * @param userName 用户名
     * @param avatar   头像地址
     * @return 结果
     */
    @Override
    public boolean updateUserAvatar(String userName, String avatar) {
        return userMapper.updateUserAvatar(userName, avatar) > 0;
    }

    /**
     * 重置用户密码
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int resetPwd(SysUser user) {
        return userMapper.updateUser(user);
    }

    /**
     * 重置用户密码
     *
     * @param userName 用户名
     * @param password 密码
     * @return 结果
     */
    @Override
    public int resetUserPwd(String userName, String password) {
        return userMapper.resetUserPwd(userName, password);
    }

    /**
     * 新增用户角色信息
     *
     * @param user 用户对象
     */
    public void insertUserRole(SysUser user) {
        this.insertUserRole(user.getUserId(), user.getRoleIds());
    }

    /**
     * 新增用户岗位信息
     *
     * @param user 用户对象
     */
    public void insertUserPost(SysUser user) {
        Long[] posts = user.getPostIds();
        if (StringUtils.isNotEmpty(posts)) {
            // 新增用户与岗位管理
            List<SysUserPost> list = new ArrayList<SysUserPost>(posts.length);
            for (Long postId : posts) {
                SysUserPost up = new SysUserPost();
                up.setUserId(user.getUserId());
                up.setPostId(postId);
                list.add(up);
            }
            userPostMapper.batchUserPost(list);
        }
    }

    /**
     * 新增用户角色信息
     *
     * @param userId  用户ID
     * @param roleIds 角色组
     */
    public void insertUserRole(Long userId, Long[] roleIds) {
        if (StringUtils.isNotEmpty(roleIds)) {
            // 新增用户与角色管理
            List<SysUserRole> list = new ArrayList<SysUserRole>(roleIds.length);
            for (Long roleId : roleIds) {
                SysUserRole ur = new SysUserRole();
                ur.setUserId(userId);
                ur.setRoleId(roleId);
                list.add(ur);
            }
            userRoleMapper.batchUserRole(list);
        }
    }

    /**
     * 通过用户ID删除用户
     *
     * @param userId 用户ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteUserById(Long userId) {
        // 删除用户与角色关联
        userRoleMapper.deleteUserRoleByUserId(userId);
        // 删除用户与岗位表
        userPostMapper.deleteUserPostByUserId(userId);
        return userMapper.deleteUserById(userId);
    }

    /**
     * 批量删除用户信息
     *
     * @param userIds 需要删除的用户ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteUserByIds(Long[] userIds) {
        for (Long userId : userIds) {
            checkUserAllowed(new SysUser(userId));
            checkUserDataScope(userId);
        }
        // 删除用户与角色关联
        userRoleMapper.deleteUserRole(userIds);
        // 删除用户与岗位关联
        userPostMapper.deleteUserPost(userIds);
        return userMapper.deleteUserByIds(userIds);
    }

    /**
     * 导入用户数据
     *
     * @param userList        用户数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName        操作用户
     * @return 结果
     */
    @Override
    public String importUser(List<SysUser> userList, Boolean isUpdateSupport, String operName) {
        if (StringUtils.isNull(userList) || userList.size() == 0) {
            throw new ServiceException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        String password = configService.selectConfigByKey("sys.user.initPassword");
        for (SysUser user : userList) {
            try {
                // 验证是否存在这个用户
                SysUser u = userMapper.selectUserByUserName(user.getUserName());
                if (StringUtils.isNull(u)) {
                    BeanValidators.validateWithException(validator, user);
                    user.setPassword(SecurityUtils.encryptPassword(password));
                    user.setCreateBy(operName);
                    userMapper.insertUser(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 导入成功");
                } else if (isUpdateSupport) {
                    BeanValidators.validateWithException(validator, user);
                    checkUserAllowed(u);
                    checkUserDataScope(u.getUserId());
                    user.setUserId(u.getUserId());
                    user.setUpdateBy(operName);
                    userMapper.updateUser(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 更新成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、账号 " + user.getUserName() + " 已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、账号 " + user.getUserName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    /**
     * 查询指定区域的销售经理
     *
     * @param roleKey 角色key
     * @param areaId  区域id
     */
    @Override
    public List<SysUser> selectUserByRoleKeyAndAreaId(String roleKey, Long areaId) {
        // 0L 表示总部
        return userMapper.selectUserByRoleKeyAreaIdAgentId(roleKey, areaId, null, 0L, null);
    }

    @Override
    public List<SysUser> selectUserByRoleKeyAndAreaIds(String roleKey, List<Long> areaIds) {
        return userMapper.selectUserByRoleKeyAreaIds(roleKey, areaIds);
    }

    @Override
    public List<SysUser> selectSaleByCurAgent() {
        Long deptId = SecurityUtils.getDeptId();
        if (0L == deptId) {
            return Collections.emptyList();
        }
        // 获取代理商的的销售经理
        TbAgent tbAgent = agentMapper.selectById(deptId);
        SysUser user = userMapper.selectById(tbAgent.getParentSalerId());
        return Collections.singletonList(user);
    }

    @Override
    public List<SysUser> getNextLevelsByCur() {
        // 获取当前用户
        SysUser user = SecurityUtils.getLoginUser().getUser();
        // 如果用户的 代理商 id 为0， 从区域表中获取下级用户；如果不为0，从代理商表中获取下级用户
        Long agentId = user.getDeptId();
        List<SysRole> roles = user.getRoles();
        //String roleKey = roles.get(0).getRoleKey();

        if (CollectionUtil.isEmpty(roles)) {
            throw new ServiceException("用户没有角色");
        }

        // 可用角色集合：当前角色 + 下一级角色
        Set<String> roleCandidate = new HashSet<>();

        // 当前用户拥有的角色
        List<String> roleKeys = roles.stream().map(SysRole::getRoleKey).collect(Collectors.toList());

        for (String roleKey : roleKeys) {
            // 同级和下一级
            roleCandidate.addAll(ROLE_KEY2NEXT_KEY_MAP.get(roleKey));
        }

        // Long areaId = user.getAreaId();
        List<Long> areaIdList = user.getAreaIdList();

        // 同级和下级
        List<SysUser> nextUsers;
        ArrayList<String> roleCandide = new ArrayList<>(roleCandidate);
        if (agentId == 0) {
            List<TbArea> tbAreas = tbAreaService.selectChildAreaList(areaIdList, false, true);
            List<Long> areaIds = tbAreas.stream().map(TbArea::getAreaId).collect(Collectors.toList());
            if (roleKeys.contains("sales_manager")) {
                // 后代区域（注意不只是下级）代理商经理   // TODO 这里的区分可以拿掉？
                nextUsers = userMapper.selectNextUser(roleCandide, areaIds, null, null, 0L, null);
            } else {
                // 后代区域下级角色（关键是下级角色，不一定只在下级区域中）
                nextUsers = userMapper.selectNextUser(roleCandide, areaIds, null, null, null, null);
            }
        } else {
            // 623 反馈：不再同级分配,这里不能使用同一个集合
            List<SysUser> currentAgentStuffs = new ArrayList<>();
            List<SysUser> nextAgentMgns = new ArrayList<>();
            for (String roleKey : roleKeys) {
                if ("agent_manager".equals(roleKey)) {
                    // 所辖销售员
                    currentAgentStuffs = userMapper.selectNextUser(roleCandide, null, null, agentId, null, null);
                } else if ("agent_sales".equals(roleKey)) {
                    // 下级代理商经理
                    nextAgentMgns = userMapper.selectNextUser(roleCandide, null, null, null, agentId, null);
                }
            }
            // 合并两个集合
            nextUsers = Stream.of(currentAgentStuffs, nextAgentMgns).flatMap(List::stream).distinct()
                .collect(Collectors.toList());
        }
        // 排除自己
        nextUsers.removeIf(u -> u.getUserId().equals(user.getUserId()));
        return nextUsers;
    }

    @Override
    public List<SysUser> selectUserByRoleKeyAreaIdAgentId(String roleKey, Long areaId, Long parentAreaId, Long agentId,
        Long parentAgentId) {

        return userMapper.selectUserByRoleKeyAreaIdAgentId(roleKey, areaId, parentAreaId, agentId, parentAgentId);
    }

    @Override
    public List<SysUser> getOwnerList(boolean onlySalesRole) {
        Long deptId = SecurityUtils.getDeptId();
        List<SysUser> result = new ArrayList<>();
        // 兼容原接口，判断是否只查询销售角色
        List<String> roles = onlySalesRole ? Constants.SALE_ROLES : null;
        if (deptId == 0L) {
            List<Long> areaIds = SecurityUtils.getLoginUser().getAreaIdList();
            // 查询所有关联区域：同级或下1级
            List<Long> ids = tbAreaService.selectDeepOneAreaList(areaIds);
            List<SysUser> userList = userMapper.selectAllUserListForOwner(roles);

            // 获取同级区域和下一级区域用户
            for (SysUser sysUser : userList) {
                List<Long> userAreaIds = Arrays.stream(sysUser.getAreaId().split(",")).map(Long::parseLong)
                    .collect(Collectors.toList());
                if (userAreaIds.stream().anyMatch(ids::contains)) {
                    result.add(sysUser);
                }
            }
        } else {
            result = userMapper.selectUserByDeptId(deptId, roles);
        }
        return result;
    }

    @Override
    public List<SysUser> getAllOwnerList(boolean onlySalesRole) {
        return userMapper.selectUserByDeptId(null, onlySalesRole ? Constants.SALE_ROLES : null);
    }

    @Override
    public List<SysUser> getOwnerListByAreaId(Long areaId) {
        Long deptId = SecurityUtils.getDeptId();
        List<SysUser> result = new ArrayList<>();
        if (deptId == 0L) {
            TbArea tbArea = tbAreaService.selectTbAreaByAreaId(areaId);
            List<SysUser> userList = userMapper.selectAllUserListForOwner(Constants.SALE_ROLES);
            if (StringUtils.isNotBlank(tbArea.getPermissionChar())) {
                List<Long> collect = Arrays.stream(tbArea.getPermissionChar().split(",")).filter(
                    org.apache.commons.lang3.StringUtils::isNotBlank).map(Long::valueOf).collect(Collectors.toList());
                // 获取同级区域和下一级区域用户
                for (SysUser sysUser : userList) {
                    List<Long> userAreaIds = Arrays.stream(sysUser.getAreaId().split(",")).map(Long::parseLong)
                        .collect(Collectors.toList());
                    if (userAreaIds.stream().anyMatch(collect::contains)) {
                        result.add(sysUser);
                    }
                }
            }
        }else {
            result = userMapper.selectUserByDeptId(deptId, Constants.SALE_ROLES);
        }
        return result;
    }

    @Override
    public Integer existUserByAgentIds(Long[] agentIds) {
        if (agentIds == null || agentIds.length == 0) {
            return null;
        }
        return userMapper.existUserByAgentIds(agentIds);
    }

    @Override
    public List<SysUser> listByNickNameList(List<String> nickNameList) {
        return userMapper.listByNickNameList(nickNameList);
    }
}
