package com.ruoyi.platform.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.PlatformDataScope;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.platform.PlatformUser;
import com.ruoyi.common.core.domain.platform.dto.PlatformUserDTO;
import com.ruoyi.common.core.domain.platform.vo.PlatformRoleVO;
import com.ruoyi.common.core.domain.platform.vo.PlatformUserVO;
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.domain.PlatformUserPost;
import com.ruoyi.platform.domain.PlatformUserRole;
import com.ruoyi.platform.domain.vo.PlatformPostVO;
import com.ruoyi.platform.mapper.PlatformPostMapper;
import com.ruoyi.platform.mapper.PlatformUserMapper;
import com.ruoyi.platform.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
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/7/15 11:04
 * @since:
 * @copyright: 版权所有2021 开源组织 gitee(https://gitee.com/jinzheyi)作者：朱述勇<br/>
 * GitHub(https://github.com/jinzheyi)作者：朱述勇 。
 */
@Slf4j
@Service
public class PlatformUserServiceImpl extends ServiceImpl<PlatformUserMapper, PlatformUser> implements IPlatformUserService {

    @Resource
    private PlatformUserMapper userMapper;

    @Autowired
    private IPlatformRoleService roleService;

    @Resource
    private PlatformPostMapper postMapper;

    @Resource
    private IPlatformUserRoleService userRoleService;

    @Resource
    private IPlatformUserPostService userPostService;

    @Resource
    private ISysConfigService configService;

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

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

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

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

    /**
     * 通过登录用户名查询用户
     * @param loginName 登录名
     * @return
     */
    @Override
    public PlatformUserVO selectUserByLoginName(String loginName) {
        return userMapper.selectUserByLoginName(loginName);
    }

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

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

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

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

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

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

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

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

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

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

    /**
     * 校验手机号码是否唯一
     *
     * @param userDTO 用户信息
     * @return 状态信息
     */
    @Override
    public String checkPhoneUnique(PlatformUserDTO userDTO) {
        String userId = StringUtils.isIdNull(userDTO.getId());
        Optional<PlatformUser> info = userMapper.selectList(new LambdaQueryWrapper<PlatformUser>()
                .eq(PlatformUser::getPhonenumber,userDTO.getPhonenumber())).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(PlatformUserDTO userDTO) {
        String userId = StringUtils.isIdNull(userDTO.getId());
        Optional<PlatformUser> info = userMapper.selectList(new LambdaQueryWrapper<PlatformUser>()
                .eq(PlatformUser::getEmail,userDTO.getEmail())).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(PlatformUserDTO userDTO) {
        if (StringUtils.isNotBlank(userDTO.getId()) && this.getById(userDTO.getId()).isAdmin()) {
            throw new BusinessException("不允许操作超级管理员用户");
        }
    }

    /**
     * 查询用户所属角色组
     *
     * @param userId 用户ID
     * @return 结果
     */
    @Override
    public String selectUserRoleGroup(String userId) {
        List<PlatformRoleVO> list = roleService.selectRolesByUserId(userId);
        StringBuilder idsStr = new StringBuilder();
        for (PlatformRoleVO 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<PlatformPostVO> list = postMapper.selectPostsByUserId(userId);
        StringBuilder idsStr = new StringBuilder();
        for (PlatformPostVO 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<PlatformUserDTO> 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 (PlatformUserDTO userDTO : userList) {
            try {
                // 验证是否存在这个用户
                PlatformUser u = userMapper.selectOne(Wrappers.query(PlatformUser.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(PlatformUserDTO userDTO) {
        return userMapper.updateById(DozerUtils.copyProperties(userDTO,PlatformUser.class));
    }
    
}
