package com.ruoyi.system.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.base.MPJBaseServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanValidators;
import com.ruoyi.common.utils.sign.PasswdUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.system.domain.SysAuthUser;
import com.ruoyi.system.domain.SysPost;
import com.ruoyi.system.domain.SysUserPost;
import com.ruoyi.system.domain.SysUserRole;
import com.ruoyi.system.mapper.*;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysUserService;
import org.apache.poi.ss.formula.functions.T;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.validation.Validator;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户 业务层处理
 *
 * @author ruoyi
 */
@Service
public class SysUserServiceImpl extends MPJBaseServiceImpl<SysUserMapper, SysUser> implements ISysUserService {
    private static final Logger log = LoggerFactory.getLogger(SysUserServiceImpl.class);

    @Resource
    private SysRoleMapper roleMapper;

    @Resource
    private SysPostMapper postMapper;

    @Resource
    private SysUserRoleMapper userRoleMapper;

    @Resource
    private SysUserPostMapper userPostMapper;

    @Resource
    private SysDeptMapper deptMapper;

    @Resource
    private ISysConfigService configService;

    @Resource
    protected Validator validator;

    @Resource
    private SysAuthUserMapper authUserMapper;

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

        MPJLambdaWrapper<SysUser> selectUserList = new MPJLambdaWrapper<SysUser>("u")
                .selectAll(SysUser.class)
                .selectAssociation(SysDept.class, SysUser::getDept)
                .selectCollection(SysRole.class, SysUser::getRoles)
                .leftJoin(SysDept.class, "d", SysDept::getDeptId, SysUser::getDeptId)
                .leftJoin(SysUserRole.class, "ur", SysUserRole::getUserId, SysUser::getUserId)
                .leftJoin(SysRole.class, "r", SysRole::getRoleId, SysUserRole::getRoleId)
                .eq(StringUtils.isNotLongNull(user.getUserId()), SysUser::getUserId, user.getUserId())
                .like(StringUtils.isNotBlank(user.getUserName()), SysUser::getUserName, user.getUserName())
                .eq(StringUtils.isNotBlank(user.getStatus()), SysUser::getStatus, user.getStatus())
                .eq(StringUtils.isNotBlank(user.getPhonenumber()), SysUser::getPhonenumber, user.getPhonenumber())
                .apply(StringUtils.isNotNull(user.getParams().get("beginTime")),
                        "date_format(u.create_time,'%y%m%d') >= date_format('" + user.getParams().get("beginTime") + "','%y%m%d')")
                .apply(StringUtils.isNotNull(user.getParams().get("endTime")),
                        "date_format(u.create_time,'%y%m%d') <= date_format('" + user.getParams().get("endTime") + "','%y%m%d')")
                .and(StringUtils.isNotLongNull(user.getDeptId()),
                        i -> i.eq(SysUser::getDeptId, user.getDeptId()).or().inSql(SysUser::getDeptId, "SELECT dept_id FROM sys_dept WHERE FIND_IN_SET('"+user.getDeptId()+"',ancestors)"))
                .apply(StringUtils.isNotBlank((String) user.getParams().get("dataScope")), (String) user.getParams().get("dataScope"));

        if (StringUtils.isNotNull(pageDomain)){
            Page<SysUser> page =new Page<>();
            page.setSize(pageDomain.getPageSize());
            page.setCurrent(pageDomain.getPageNum());
            page.setOptimizeJoinOfCountSql(true);
            return (T) selectJoinListPage(page,SysUser.class, selectUserList);
        }else {
            return (T) selectJoinList(SysUser.class, selectUserList);
        }
    }

    /**
     * 根据条件分页查询已分配用户角色列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<SysUser> selectAllocatedList(SysUser user) {
        MPJLambdaWrapper<SysUser> selectAllocatedList = new MPJLambdaWrapper<SysUser>("u")
                .distinct()
                .selectAll(SysUser.class)
                .leftJoin(SysDept.class, "d", SysDept::getDeptId, SysUser::getDeptId)
                .leftJoin(SysUserRole.class, "ur", SysUserRole::getUserId, SysUser::getUserId)
                .leftJoin(SysRole.class, "r", SysRole::getRoleId, SysUserRole::getRoleId)
                .eq(SysRole::getRoleId, user.getRoleId())
                .like(StringUtils.isNotBlank(user.getUserName()), SysUser::getUserName, user.getUserName())
                .like(StringUtils.isNotBlank(user.getPhonenumber()), SysUser::getPhonenumber, user.getPhonenumber())
                .apply(StringUtils.isNotBlank((String) user.getParams().get("dataScope")),
                        (String) user.getParams().get("dataScope"));
        return selectJoinList(SysUser.class, selectAllocatedList);
    }

    /**
     * 根据条件分页查询未分配用户角色列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<SysUser> selectUnallocatedList(SysUser user) {
        MPJLambdaWrapper<SysUser> noRoleUserIds = new MPJLambdaWrapper<SysUser>("u")
                .innerJoin(SysUserRole.class, "ur", SysUserRole::getUserId, SysUser::getUserId)
                .eq(SysUserRole::getRoleId, user.getRoleId());
        List<SysUser> noRoleSysUserIds = selectJoinList(SysUser.class, noRoleUserIds);
        MPJLambdaWrapper<SysUser> selectUnallocatedList = new MPJLambdaWrapper<SysUser>("u")
                .selectAll(SysUser.class)
                .leftJoin(SysDept.class, "d", SysDept::getDeptId, SysUser::getDeptId)
                .leftJoin(SysUserRole.class, "ur", SysUserRole::getUserId, SysUser::getUserId)
                .leftJoin(SysRole.class, "r", SysRole::getRoleId, SysUserRole::getRoleId)
                .and(i -> i.ne(SysUser::getRoleId, user.getRoleId()).or().isNull(SysRole::getRoleId))
                .notIn(SysUser::getUserId, noRoleSysUserIds.stream().map(SysUser::getUserId).collect(Collectors.toList()))
                .like(StringUtils.isNotBlank(user.getUserName()), SysUser::getUserName, user.getUserName())
                .like(StringUtils.isNotBlank(user.getPhonenumber()), SysUser::getPhonenumber, user.getPhonenumber())
                .apply(StringUtils.isNotBlank((String) user.getParams().get("dataScope")),
                        (String) user.getParams().get("dataScope"));
        return selectJoinList(SysUser.class, selectUnallocatedList);
    }

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

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

    private SysUser getOneByIdOrUserName(String userName, Long userId) {
        MPJLambdaWrapper<SysUser> getOneByIdOrUserName = new MPJLambdaWrapper<SysUser>("u")
                .selectAll(SysUser.class)
                .selectAssociation(SysDept.class, SysUser::getDept)
                .selectCollection(SysRole.class, SysUser::getRoles)
                .leftJoin(SysDept.class, "d", SysDept::getDeptId, SysUser::getDeptId)
                .leftJoin(SysUserRole.class, "ur", SysUserRole::getUserId, SysUser::getUserId)
                .leftJoin(SysRole.class, "r", SysRole::getRoleId, SysUserRole::getRoleId)
                .eq(StringUtils.isNotLongNull(userId), SysUser::getUserId, userId)
                .eq(StringUtils.isNotBlank(userName), SysUser::getUserName, userName)
                .last("limit 1");
        return selectJoinOne(SysUser.class, getOneByIdOrUserName);
    }

    /**
     * 查询用户所属角色组
     *
     * @param userName 用户名
     * @return 结果
     */
    @Override
    public String selectUserRoleGroup(String userName) {
        MPJLambdaWrapper<SysRole> selectRolePermissionByUserName = new MPJLambdaWrapper<SysRole>("r")
                .selectAll(SysRole.class)
                .leftJoin(SysUserRole.class, "ur", SysUserRole::getRoleId, SysRole::getRoleId)
                .leftJoin(SysUser.class, "u", SysUser::getUserId, SysUserRole::getUserId)
                .leftJoin(SysDept.class, "d", SysDept::getDeptId, SysUser::getDeptId)
                .eq(SysUser::getUserName, userName);
        List<SysRole> list = roleMapper.selectJoinList(SysRole.class, selectRolePermissionByUserName);
        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) {
        MPJLambdaWrapper<SysPost> selectPostsByUserName = new MPJLambdaWrapper<SysPost>("p")
                .selectAll(SysPost.class)
                .leftJoin(SysUserPost.class, "up", SysUserPost::getPostId, SysPost::getPostId)
                .leftJoin(SysUser.class, "u", SysUser::getUserId, SysUserPost::getUserId)
                .eq(SysUser::getUserName, userName);
        List<SysPost> list = postMapper.selectJoinList(SysPost.class, selectPostsByUserName);
        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 = getOne(new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getUserName, user.getUserName())
                .last("limit 1"));
        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 = getOne(new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getPhonenumber,user.getPhonenumber())
                .last("limit 1"));
        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 = getOne(new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getEmail,user.getEmail())
                .last("limit 1"));
        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(Long.parseLong((String) StpUtil.getLoginId()))) {
            SysUser user = new SysUser();
            user.setUserId(userId);
            List<SysUser> users = SpringUtils.getAopProxy(this).selectUserList(user,null);
            if (StringUtils.isEmpty(users)) {
                throw new ServiceException("没有权限访问用户数据！");
            }
        }
    }

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

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

    /**
     * 修改保存用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional
    public boolean updateUser(SysUser user) {
        Long userId = user.getUserId();
        // 删除用户与角色关联
        userRoleMapper.delete(new LambdaQueryWrapper<SysUserRole>()
                .eq(SysUserRole::getUserId,userId));
        // 新增用户与角色管理
        insertUserRole(user);
        // 删除用户与岗位关联
        userPostMapper.delete(new LambdaQueryWrapper<SysUserPost>()
                .eq(SysUserPost::getUserId,userId));
        // 新增用户与岗位管理
        insertUserPost(user);
        return updateById(user);
    }

    /**
     * 用户授权角色
     *
     * @param userId  用户ID
     * @param roleIds 角色组
     */
    @Override
    @Transactional
    public void insertUserAuth(Long userId, Long[] roleIds) {
        userRoleMapper.delete(new LambdaQueryWrapper<SysUserRole>()
                .eq(SysUserRole::getUserId,userId));
        insertUserRole(userId, roleIds);
    }

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

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

    /**
     * 修改用户头像
     *
     * @param userName 用户名
     * @param avatar   头像地址
     * @return 结果
     */
    @Override
    public boolean updateUserAvatar(String userName, String avatar) {
        return update(new LambdaUpdateWrapper<SysUser>()
                .set(SysUser::getAvatar, avatar)
                .eq(SysUser::getUserName,userName));
    }

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

    /**
     * 重置用户密码
     *
     * @param userName 用户名
     * @param password 密码
     * @return 结果
     */
    @Override
    public boolean resetUserPwd(String userName, String password) {
        return update(new LambdaUpdateWrapper<SysUser>()
                .set(SysUser::getPassword, password)
                .eq(SysUser::getUserName,userName));
    }

    /**
     * 新增用户角色信息
     *
     * @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)) {
            // 新增用户与岗位管理
            for (Long postId : posts) {
                SysUserPost up = new SysUserPost();
                up.setUserId(user.getUserId());
                up.setPostId(postId);
                userPostMapper.insert(up);
            }
        }
    }

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

    /**
     * 通过用户ID删除用户
     *
     * @param userId 用户ID
     * @return 结果
     */
    @Override
    @Transactional
    public boolean deleteUserById(Long userId) {
        // 删除用户与角色关联
        userRoleMapper.delete(new LambdaQueryWrapper<SysUserRole>()
                .eq(SysUserRole::getUserId,userId));
        // 删除用户与岗位关联
        userPostMapper.delete(new LambdaQueryWrapper<SysUserPost>()
                .eq(SysUserPost::getUserId,userId));
        return removeById(userId);
    }

    /**
     * 批量删除用户信息
     *
     * @param userIds 需要删除的用户ID
     * @return 结果
     */
    @Override
    @Transactional
    public boolean deleteUserByIds(Long[] userIds) {
        for (Long userId : userIds) {
            checkUserAllowed(new SysUser(userId));
            checkUserDataScope(userId);
            // 删除用户与角色关联
            userRoleMapper.delete(new LambdaQueryWrapper<SysUserRole>()
                    .eq(SysUserRole::getUserId,userId));
            // 删除用户与岗位关联
            userPostMapper.delete(new LambdaQueryWrapper<SysUserPost>()
                    .eq(SysUserPost::getUserId,userId));
        }
        return removeBatchByIds(Arrays.asList(userIds));
    }

    /**
     * 导入用户数据
     *
     * @param userList        用户数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName        操作用户
     * @return 结果
     */
    @Override
    @Transactional
    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 = getOneByIdOrUserName(user.getUserName(),null);
                if (StringUtils.isNull(u)) {
                    BeanValidators.validateWithException(validator, user);
                    user.setPassword(PasswdUtils.encryptPassword(password));
                    user.setCreateBy(operName);
                    save(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);
                    updateById(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() + " 导入失败：";
                if(e instanceof DuplicateKeyException){
                    failureMsg.append(msg + "用户编号已经存在！");
                }else {
                    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();
    }

    /**
     * 通过userId与来源查询第三方列表
     * @param userId
     * @return
     */
    @Override
    public List<SysAuthUser> selectAuthUserByUserId(Long userId){
        LambdaQueryWrapper<SysAuthUser> list = new LambdaQueryWrapper<SysAuthUser>()
                .eq(SysAuthUser::getUserId, userId);
        return authUserMapper.selectList(list);
    }
    /**
     * 通过第三方uuid与来源查询用户id
     * @param uuid
     * @param source
     * @return
     */
    @Override
    public Long selectUserIdByUuid(String uuid,String source){
        LambdaQueryWrapper<SysAuthUser> one = new LambdaQueryWrapper<SysAuthUser>()
                .eq(SysAuthUser::getUuid, uuid)
                .eq(SysAuthUser::getSource, source)
                .last("limit 1");
        try {
            return authUserMapper.selectOne(one).getUserId();
        }catch (NullPointerException e){
            return null;
        }
    }

    /**
     * 绑定第三方登录用户
     * @param authUser
     */
    public void bindSysUser(SysAuthUser authUser) throws ServiceException{
        LambdaQueryWrapper<SysAuthUser> repeatUserId = new LambdaQueryWrapper<SysAuthUser>()
                .eq(SysAuthUser::getUserId, authUser.getUserId())
                .eq(SysAuthUser::getSource, authUser.getSource());
        Long bLong = authUserMapper.selectCount(repeatUserId);
        if (null != bLong && bLong >0){
            throw new ServiceException("当前账号已经被绑定了，请解绑后重试！");
        }
        authUserMapper.insert(authUser);
    }

    /**
     * 查询第三方登录用户
     * @param userId
     */
    @Override
    public List<SysAuthUser> selectAuthUser(long userId){
        LambdaQueryWrapper<SysAuthUser> list = new LambdaQueryWrapper<SysAuthUser>()
                .eq(SysAuthUser::getUserId, userId);
        return authUserMapper.selectList(list);
    }
    /**
     * 查询第三方登录用户
     * @param authId
     */
    @Override
    public int deleteAuthUser(Long authId){
        return authUserMapper.deleteById(authId);
    }
}
