package com.ruoyi.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.saas.dto.SysUserDTO;
import com.ruoyi.common.core.domain.saas.entity.SysUser;
import com.ruoyi.common.core.domain.saas.vo.SysRoleVO;
import com.ruoyi.common.core.domain.saas.vo.SysUserVO;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.DozerUtils;
import com.ruoyi.common.utils.security.Md5Utils;
import com.ruoyi.platform.mapper.saas.SaaSUserMapper;
import com.ruoyi.platform.service.ISysConfigService;
import com.ruoyi.system.domain.SysUserPost;
import com.ruoyi.system.domain.SysUserRole;
import com.ruoyi.system.domain.vo.SysPostVO;
import com.ruoyi.system.mapper.SysPostMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.ISysRoleService;
import com.ruoyi.system.service.ISysUserPostService;
import com.ruoyi.system.service.ISysUserRoleService;
import com.ruoyi.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;

/**
 *@Description 用户 业务层处理
 *@Author zhushuyong
 *@Date 2021/6/1 11:17
 *@since:
 *@copyright: 版权所有2021 开源组织 gitee(https://gitee.com/jinzheyi)作者：朱述勇<br/>
 *            GitHub(https://github.com/jinzheyi)作者：朱述勇 。
 */
@Slf4j
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {

    @Resource
    private SysUserMapper userMapper;

    @Resource
    private SaaSUserMapper saaSUserMapper;

    @Resource
    private ISysRoleService roleService;

    @Resource
    private SysPostMapper postMapper;

    @Resource
    private ISysUserPostService userPostService;

    @Resource
    private ISysUserRoleService userRoleService;

    @Resource
    private ISysConfigService configService;

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

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

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

    /**
     * 登录时通过用户名，租户id查询用户
     *
     * @param userName 用户名
     * @param tenantId 租户id
     * @return 用户对象信息
     */
    @Override
    public SysUserVO selectUserByLoginNameAndTenantId(String userName, String tenantId) {
        return userMapper.selectUserByLoginNameAndTenantId(userName, tenantId);
    }

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

    /**
     * 批量删除用户信息
     * 
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteUserByIds(String ids) {
        String[] userIds = Convert.toStrArray(ids);
        for (String userId : userIds) {
            checkUserAllowed(SysUserDTO.builder().id(userId).build());
        }
        // 删除用户与角色关联
        userRoleService.remove(new LambdaQueryWrapper<SysUserRole>().in(SysUserRole::getUserId,Arrays.asList(userIds)));
        // 删除用户与岗位关联
        userPostService.remove(new LambdaQueryWrapper<SysUserPost>().in(SysUserPost::getUserId,Arrays.asList(userIds)));
        return userMapper.deleteBatchIds(Arrays.asList(userIds));
    }

    /**
     * 新增保存用户信息
     * 
     * @param userDTO 用户信息
     * @return 结果
     */
    @Override
    @Transactional
    public int insertUser(SysUserDTO userDTO) {
        // 新增用户信息
        SysUser sysUser = DozerUtils.copyProperties(userDTO,SysUser.class);
        int rows = userMapper.insert(sysUser);
        userDTO.setId(sysUser.getId());
        // 新增用户岗位关联
        insertUserPost(userDTO);
        // 新增用户与角色管理
        insertUserRole(userDTO.getId(), userDTO.getRoleIds());
        return rows;
    }

    /**
     * 注册用户信息
     * 
     * @param userDTO 用户信息
     * @return 结果
     */
    @Override
    public boolean registerUser(SysUserDTO userDTO) {
        userDTO.setUserType(UserConstants.REGISTER_USER_TYPE);
        return userMapper.insert(DozerUtils.copyProperties(userDTO,SysUser.class)) > 0;
    }

    /**
     * 修改保存用户信息
     * 
     * @param userDTO 用户信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updateUser(SysUserDTO userDTO) {
        // 删除用户与角色关联
        userRoleService.remove(new LambdaQueryWrapper<SysUserRole>().eq(SysUserRole::getUserId,userDTO.getId()));
        // 新增用户与角色管理
        insertUserRole(userDTO.getId(), userDTO.getRoleIds());
        // 删除用户与岗位表
        userPostService.remove(new LambdaQueryWrapper<SysUserPost>().eq(SysUserPost::getUserId,userDTO.getId()));
        // 新增用户与岗位管理
        insertUserPost(userDTO);
        return userMapper.updateById(DozerUtils.copyProperties(userDTO,SysUser.class));
    }

    /**
     * 修改用户个人详细信息
     * 
     * @param userDTO 用户信息
     * @return 结果
     */
    @Override
    public int updateUserInfo(SysUserDTO userDTO) {
        SysUser sysUser = DozerUtils.copyProperties(userDTO,SysUser.class);
        return userMapper.updateById(sysUser);
    }

    /**
     * 用户授权角色
     * 
     * @param userId 用户ID
     * @param roleIds 角色组
     */
    @Override
    public void insertUserAuth(String userId, String[] roleIds) {
        // 删除用户与角色关联
        userRoleService.remove(new LambdaQueryWrapper<SysUserRole>().eq(SysUserRole::getUserId,userId));
        insertUserRole(userId, roleIds);
    }

    /**
     * 修改用户密码
     * 
     * @param userDTO 用户信息
     * @return 结果
     */
    @Override
    public int resetUserPwd(SysUserDTO userDTO) {
        return updateUserInfo(userDTO);
    }

    /**
     * 新增用户角色信息
     * @param userId 用户id
     * @param roleIds 角色id数组
     */
    public void insertUserRole(String userId, String[] roleIds) {
        if (StringUtils.isNotEmpty(roleIds)) {
            // 新增用户与角色管理
            List<SysUserRole> list = new ArrayList<>();
            for (String roleId : roleIds) {
                list.add(SysUserRole.builder().userId(userId).roleId(roleId).build());
            }
            if (list.size() > 0) {
                userRoleService.saveBatch(BeanUtil.copyToList(list, SysUserRole.class));
            }
        }
    }

    /**
     * 新增用户岗位信息
     * 
     * @param userDTO 用户对象
     */
    public void insertUserPost(SysUserDTO userDTO) {
        String[] posts = userDTO.getPostIds();
        if (StringUtils.isNotEmpty(posts)) {
            // 新增用户与岗位管理
            List<SysUserPost> list = new ArrayList<>();
            for (String postId : posts) {
                list.add(SysUserPost.builder().userId(userDTO.getId()).postId(postId).build());
            }
            if (list.size() > 0) {
                userPostService.saveBatch(BeanUtil.copyToList(list, SysUserPost.class));
            }
        }
    }

    /**
     * 校验登录名称是否唯一
     * 
     * @param loginName 用户名
     * @return 状态信息
     */
    @Override
    public String checkLoginNameUnique(String loginName) {
        long count = userMapper.selectCount(new LambdaQueryWrapper<SysUser>().eq(SysUser::getLoginName,loginName));
        if (count > 0) {
            return UserConstants.USER_NAME_NOT_UNIQUE;
        }
        return UserConstants.USER_NAME_UNIQUE;
    }

    /**
     * 校验手机号码是否唯一
     *
     * @param userDTO 用户信息
     * @return 状态信息
     */
    @Override
    public String checkPhoneUnique(SysUserDTO userDTO) {
        String userId = StringUtils.isIdNull(userDTO.getId());
        Optional<SysUser> info = saaSUserMapper.selectList(Wrappers
                .query(SysUser.builder().phonenumber(userDTO.getPhonenumber()).build())).stream().findFirst();
        if (info.isPresent() && !userId.equals(info.get().getId())) {
            return UserConstants.USER_PHONE_NOT_UNIQUE;
        }
        return UserConstants.USER_PHONE_UNIQUE;
    }

    /**
     * 校验email是否唯一
     *
     * @param userDTO 用户信息
     * @return 状态信息
     */
    @Override
    public String checkEmailUnique(SysUserDTO userDTO) {
        String userId = StringUtils.isIdNull(userDTO.getId());
        Optional<SysUser> info = saaSUserMapper.selectList(Wrappers
                .query(SysUser.builder().email(userDTO.getEmail()).build())).stream().findFirst();
        if (info.isPresent() && !userId.equals(info.get().getId())) {
            return UserConstants.USER_EMAIL_NOT_UNIQUE;
        }
        return UserConstants.USER_EMAIL_UNIQUE;
    }

    /**
     * 校验租户超管用户是否允许操作
     * 
     * @param userDTO 用户信息
     */
    @Override
    public void checkUserAllowed(SysUserDTO userDTO) {
        if (StringUtils.isNotBlank(userDTO.getId()) && this.getById(userDTO.getId()).isAdmin()) {
            throw new BusinessException("不允许操作超级管理员用户");
        }
    }

    /**
     * 查询用户所属角色组
     * 
     * @param user 用户ID
     * @return 结果
     */
    @Override
    public String selectUserRoleGroup(SysUserVO user) {
        List<SysRoleVO> list = roleService.selectRolesByUser(user);
        StringBuilder idsStr = new StringBuilder();
        for (SysRoleVO role : list) {
            idsStr.append(role.getRoleName()).append(",");
        }
        if (StringUtils.isNotEmpty(idsStr.toString())) {
            return idsStr.substring(0, idsStr.length() - 1);
        }
        return idsStr.toString();
    }

    /**
     * 查询用户所属岗位组
     * 
     * @param userId 用户ID
     * @return 结果
     */
    @Override
    public String selectUserPostGroup(String userId) {
        List<SysPostVO> list = postMapper.selectPostsByUserId(userId);
        StringBuilder idsStr = new StringBuilder();
        for (SysPostVO post : list) {
            idsStr.append(post.getPostName()).append(",");
        }
        if (StringUtils.isNotEmpty(idsStr.toString())) {
            return idsStr.substring(0, idsStr.length() - 1);
        }
        return idsStr.toString();
    }

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

    /**
     * 用户状态修改
     * 
     * @param userDTO 用户信息
     * @return 结果
     */
    @Override
    public int changeStatus(SysUserDTO userDTO) {
        return userMapper.updateById(DozerUtils.copyProperties(userDTO,SysUser.class));
    }
}
