package com.usky.system.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.usky.common.core.bean.CommonPage;
import com.usky.common.core.exception.BusinessException;
import com.usky.common.core.util.BeanMapperUtils;
import com.usky.common.core.util.StringUtils;
import com.usky.common.mybatis.core.AbstractCrudService;
import com.usky.common.security.utils.SecurityUtils;
import com.usky.system.domain.*;
import com.usky.system.domain.constants.UserConstants;
import com.usky.system.mapper.*;
import com.usky.system.model.LoginUser;
import com.usky.system.service.ISysConfigService;
import com.usky.system.service.ISysDeptService;
import com.usky.system.service.ISysUserService;
import com.usky.system.service.SysUserTenantService;
import com.usky.system.service.vo.SysUserNewVO;
import com.usky.system.service.vo.UserPostVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

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

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private SysRoleMapper roleMapper;

    @Autowired
    private SysPostMapper postMapper;

    @Autowired
    private SysUserRoleMapper userRoleMapper;

    @Autowired
    private SysUserPostMapper userPostMapper;


    @Autowired
    private SysPermissionService sysPermissionService;

    @Autowired
    private ISysConfigService iSysConfigService;

    @Autowired
    private SysUserTenantService sysUserTenantService;

    @Autowired
    private ISysDeptService deptService;


    /**
     * 根据条件分页查询用户列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    public List<SysUser> selectUserList(SysUser user) {

        user.setTenantId(SecurityUtils.getTenantId());
        user.setUserType("00");
        return userMapper.selectUserList(user);
    }

    @Override
    public List<SysUser> platAccountlist(SysUser user) {

        return userMapper.selectUserList(user);
    }

    /**
     * 新增保存平台账户信息
     *
     * @param user 平台账户信息
     * @return 结果
     */
    @Override
    @Transactional
    public int insertPlatAccount(SysUser user) {

        if (UserConstants.NOT_UNIQUE.equals(this.checkUserNameUnique(user.getUserName(),0)))
        {
            throw new BusinessException( "新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        }
        if(UserConstants.NOT_UNIQUE.equals(this.checkPhoneUnique1(user.getPhonenumber(),0))){
            throw new BusinessException("新增手机号'" + user.getPhonenumber() + "'失败，手机号已存在");
        }
        if(UserConstants.NOT_UNIQUE.equals(this.checkEmailUnique1(user.getEmail(),0))){
            throw new BusinessException( "新增邮箱'" + user.getEmail() + "'失败，邮箱已存在");
        }
//        user.setUserType("00");
//        user.setTenantId(SecurityUtils.getTenantId());
        user.setDeptId(deptService.deptListByTenant(user.getTenantId()).get(0).getDeptId());

        user.setCreateBy(SecurityUtils.getUsername());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));

        // 新增用户信息
        int rows = userMapper.insertUser(user);
        SysUserTenant sysUserTenant = new SysUserTenant();
        sysUserTenant.setUserId(user.getUserId());
        sysUserTenant.setIsDefault(false);
        sysUserTenant.setTenantId(user.getTenantId());
        sysUserTenantService.save(sysUserTenant);
        // 新增用户岗位关联
        insertUserPost(user);
        // 新增用户与角色管理
        insertUserRole(user);
        return rows;
    }

    /**
     * 根据条件分页查询用户列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    public List<SysUser> selectDUserList(SysUser user) {
        user.setTenantId(SecurityUtils.getTenantId());
        user.setUserType("00");
        user.setStatus("0");
        return userMapper.selectUserList(user);
    }

    /**
     * 用户列表-新
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    public List<SysUserNewVO> dUserList(SysUser user) {
        user.setTenantId(SecurityUtils.getTenantId());
        user.setUserType("00");
        List<SysUserNewVO> sysUserNewVOS = new ArrayList<>();
        List<SysUser> sysUsers = userMapper.selectUserList(user);
        List<Long> userIds = new ArrayList<>();
        if (!sysUsers.isEmpty()) {
            for (SysUser sysUser : sysUsers) {
                SysUserNewVO sysUserNewVO = new SysUserNewVO();
                try {
                    BeanUtils.copyProperties(sysUser, sysUserNewVO);
                } catch (BeansException e) {
                    throw new BusinessException("dUserList方法，获取用户列表信息异常" + e);
                }
                userIds.add(sysUser.getUserId());
                sysUserNewVOS.add(sysUserNewVO);
            }
            Map<Long, String> userIdToPostMap = userPostMapper.getUserPost(userIds).stream()
                    .collect(Collectors.toMap(UserPostVo::getUserId, UserPostVo::getPostName));
            sysUserNewVOS.forEach(sysUserNewVO -> sysUserNewVO.setPost(userIdToPostMap.get(sysUserNewVO.getUserId())));
        }
        return sysUserNewVOS;
    }

    /**
     * 根据条件分页查询已分配用户角色列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    public List<SysUser> selectAllocatedList(SysUser user) {
        user.setTenantId(SecurityUtils.getTenantId());
        return userMapper.selectAllocatedList(user);
    }

    /**
     * 根据条件分页查询未分配用户角色列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    public List<SysUser> selectUnallocatedList(SysUser user) {
        user.setTenantId(SecurityUtils.getTenantId());
        return userMapper.selectUnallocatedList(user);
    }

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

    @Override
    public SysUser selectUserByUserNameOne(String userName, Integer tenantId) {
        return userMapper.selectUserByUserNameOne(userName, tenantId);
    }

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

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

    /**
     * 查询用户所属角色组
     *
     * @param userName 用户名
     * @return 结果
     */
    @Override
    public String selectUserRoleGroup(String userName) {
        Integer tenantId = SecurityUtils.getTenantId();
        List<SysRole> list = roleMapper.selectRolesByUserName(userName, tenantId);
        StringBuffer idsStr = new StringBuffer();
        for (SysRole role : list) {
            idsStr.append(role.getRoleName()).append(",");
        }
        if (StringUtils.isNotBlank(idsStr.toString())) {
            return idsStr.substring(0, idsStr.length() - 1);
        }
        return idsStr.toString();
    }

    /**
     * 查询用户所属岗位组
     *
     * @param userName 用户名
     * @return 结果
     */
    @Override
    public String selectUserPostGroup(String userName) {
        Integer tenantId = SecurityUtils.getTenantId();
        List<SysPost> list = postMapper.selectPostsByUserName(userName, tenantId);
        StringBuffer idsStr = new StringBuffer();
        for (SysPost post : list) {
            idsStr.append(post.getPostName()).append(",");
        }
        if (StringUtils.isNotEmpty(idsStr.toString())) {
            return idsStr.substring(0, idsStr.length() - 1);
        }
        return idsStr.toString();
    }

    /**
     * 校验用户名称是否唯一
     *
     * @param userName 用户名称
     * @return 结果
     */
    @Override
    public String checkUserNameUnique(String userName, Integer tenantId) {
        int count = userMapper.checkUserNameUnique(userName, tenantId);
        if (count > 0) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

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

    @Override
    public String checkPhoneUnique1(String phone, Integer tenantId) {
        int count = userMapper.checkPhoneUnique1(phone, tenantId);
        if (count > 0) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

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

    /**
     * 校验email是否唯一
     *
     * @param email 用户邮箱
     * @param tenantId 租户ID
     * @return
     */
    @Override
    public String checkEmailUnique1(String email, Integer tenantId) {
        int count = userMapper.checkEmailUnique1(email, tenantId);
        if (count > 0) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

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

    /**
     * 新增保存用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional
    public int insertUser(SysUser user) {
        // 新增用户信息
        int rows = userMapper.insertUser(user);
        SysUserTenant sysUserTenant = new SysUserTenant();
        sysUserTenant.setUserId(user.getUserId());
        sysUserTenant.setIsDefault(true);
        sysUserTenant.setTenantId(user.getTenantId());
        sysUserTenantService.save(sysUserTenant);
        // 新增用户岗位关联
        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,SecurityUtils.getTenantId());
        // 新增用户与角色管理
        insertUserRole(user);
        // 删除用户与岗位关联
        userPostMapper.deleteUserPostByUserId(userId);
        // 新增用户与岗位管理
        insertUserPost(user);
        return userMapper.updateUser(user);
    }

    /**
     * 修改保存运维管理系统-平台账号信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updatePlatAccount(SysUser user) {
        return userMapper.updateUser(user);
    }

    /**
     * 用户授权角色
     *
     * @param userId  用户ID
     * @param roleIds 角色组
     */
    @Override
    @Transactional
    public void insertUserAuth(Long userId, Long[] roleIds) {
        userRoleMapper.deleteUserRoleByUserId(userId, SecurityUtils.getTenantId());
        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) {
        Long[] roles = user.getRoleIds();
        if (Objects.nonNull(roles)) {
            // 新增用户与角色管理
            List<SysUserRole> list = new ArrayList<SysUserRole>();
            for (Long roleId : roles) {
                SysUserRole ur = new SysUserRole();
                ur.setUserId(user.getUserId());
                ur.setRoleId(roleId);
                ur.setTenantId(SecurityUtils.getTenantId());
                list.add(ur);
            }
            if (list.size() > 0) {
                userRoleMapper.batchUserRole(list);
            }
        }
    }

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

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

    /**
     * 通过用户ID删除用户
     *
     * @param userId 用户ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteUserById(Long userId) {
        // 删除用户与角色关联
        userRoleMapper.deleteUserRoleByUserId(userId, SecurityUtils.getTenantId());
        // 删除用户与岗位表
        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));
        }
        // 删除用户与角色关联
        userRoleMapper.deleteUserRole(userIds, SecurityUtils.getTenantId());
        // 删除用户与岗位关联
        userPostMapper.deleteUserPost(userIds);
        return userMapper.deleteUserByIds(userIds);
    }

    @Override
    @Transactional
    public int deleteUserByPwd(Long userId, String password) {
        checkUserAllowed(new SysUser(userId));
        SysUser user = this.selectUserById(userId);
        if (user.getPassword().equals(password)) {
            // 删除用户与角色关联
            userRoleMapper.deleteUserRoleByUserId(userId, SecurityUtils.getTenantId());
            // 删除用户与岗位表
            userPostMapper.deleteUserPostByUserId(userId);
            return userMapper.deleteUserById(userId);
        } else {
            throw new BusinessException("密码错误");
        }
    }


    @Override
    public LoginUser getUserInfo(String username) {
        SysUser sysUser = this.selectUserByUserName(username);
        if (Objects.isNull(sysUser)) {
            throw new BusinessException("用户信息/密码不存在");
        }
        // 角色集合
        Set<String> roles = sysPermissionService.getRolePermission(sysUser);
        // 权限集合
        Set<String> permissions = sysPermissionService.getMenuPermission(sysUser);
        LoginUser SysUser = new LoginUser();
        SysUserVO sysUserVO = BeanMapperUtils.map(sysUser, SysUserVO.class);
        SysUser.setSysUser(sysUserVO);
        SysUser.setRoles(roles);
        SysUser.setPermissions(permissions);
        return SysUser;
    }

    @Override
    public LoginUser getUserInfoOne(String username, Integer tenantId) {
        SysUser sysUser = this.selectUserByUserNameOne(username, tenantId);
        if (Objects.isNull(sysUser)) {
            throw new BusinessException("用户信息/密码不存在");
        }
        // 角色集合
        Set<String> roles = sysPermissionService.getRolePermission(sysUser);
        // 权限集合
        Set<String> permissions = sysPermissionService.getMenuPermission(sysUser);
        LoginUser SysUser = new LoginUser();
        SysUserVO sysUserVO = BeanMapperUtils.map(sysUser, SysUserVO.class);
        SysUser.setSysUser(sysUserVO);
        SysUser.setRoles(roles);
        SysUser.setPermissions(permissions);
        return SysUser;
    }

    @Override
    public SysUser getAppUserInfo(String username, Integer tenantId, String phone, String method) {
        SysUser sysUser = new SysUser();
        if (!StringUtils.isBlank(username)) {
            if (!StringUtils.isBlank(method) && method.equals("switch")){
                sysUser = userMapper.selectUserTenantData1(username, tenantId);
                if(sysUser != null){
                    sysUser.setTenantId(tenantId);
                }
            }else {
                sysUser = userMapper.selectUserTenantData(username, tenantId);
            }
        } else if (!StringUtils.isBlank(phone)) {
            if (!StringUtils.isBlank(method) && method.equals("switch")){
                sysUser = userMapper.selectUserTenantDataOne1(tenantId, phone);
                if(sysUser != null){
                    sysUser.setTenantId(tenantId);
                }
            }else {
                sysUser = userMapper.selectUserTenantDataOne(tenantId, phone);
            }
        }
        if (Objects.isNull(sysUser)) {
            if (!StringUtils.isBlank(method) && method.equals("switch")){
                sysUser = userMapper.selectUserTenantDataOne1(tenantId, username);
                if(sysUser != null){
                    sysUser.setTenantId(tenantId);
                }
            }else {
                sysUser = userMapper.selectUserTenantDataOne(tenantId, username);
            }
            if (Objects.isNull(sysUser)) {
                throw new BusinessException("用户信息未注册");
            }
        }
        List<SysRole> sysRoles = roleMapper.selectRolePermissionByUserId(sysUser.getUserId());
        List<SysRoleVO> collect = sysRoles.stream().map(sysRole -> {
            SysRoleVO sysRoleVO = new SysRoleVO();
            BeanUtils.copyProperties(sysRole, sysRoleVO);
            return sysRoleVO;
        }).collect(Collectors.toList());
        sysUser.setRoles(collect);
        return sysUser;
    }


    @Override
    public Boolean register(SysUser sysUser) {
        String username = sysUser.getUserName();
        if (!("true".equals(iSysConfigService.selectConfigByKey("sys.account.registerUser")))) {
            throw new BusinessException("当前系统没有开启注册功能！");
        }
        if (UserConstants.NOT_UNIQUE.equals(this.checkUserNameUnique(username, SecurityUtils.getTenantId()))) {
            throw new BusinessException("保存用户'" + username + "'失败，注册账号已存在");
        }
        return this.registerUser(sysUser);
    }

    /**
     * 租户管理-管理员配置-新增
     *
     * @param user
     * @return
     */
    @Override
    public int addUser(SysUser user) {
        // 新增用户信息
        int rows = userMapper.insertUser(user);
        return rows;
    }

    @Override
    public int updateUserData(SysUser user) {
        return userMapper.updateUser(user);
    }


    @Override
    public int resetUserPwdOne(Long userId, String password) {
        return userMapper.resetUserPwdOne(userId, password);
    }


    @Override
    public CommonPage<SysUser> userList(Integer tenantId, Integer page, Integer size, long userId, String nickName) {
        List<SysUser> list1 = userMapper.getUserData(tenantId, null, null, userId, nickName);
        int total = 0;
        if (list1.size() > 0) {
            total = list1.size();
        }
        Integer current = null;
        if (page != null && size > 0) {
            current = (page - 1) * size;
        }
        List<SysUser> list = userMapper.getUserData(tenantId, current, size, userId, nickName);
        return new CommonPage<>(list, total, size, page);
    }


    public List<SysUser> userList() {
        // LoginUser loginUser = SecurityUtils.getLoginUser();
        // String userType = null;
        // if (loginUser != null && !"".equals(loginUser)) {
        //     userType = loginUser.getSysUser().getUserType();
        // }
        String userName = null;
        // if ("00".equals(userType)) {
        //     userName = SecurityUtils.getUsername();
        // }
        List<SysUser> list = userMapper.userList(SecurityUtils.getTenantId(), userName);
        return list;
    }

    public List<SysUser> userByIdList(List<Integer> userIds) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        String userType = null;
        if (loginUser != null && !"".equals(loginUser)) {
            userType = loginUser.getSysUser().getUserType();
        }
        String userName = null;
        if ("00".equals(userType)) {
            userName = SecurityUtils.getUsername();
        }
        List<SysUser> list = userMapper.userList(SecurityUtils.getTenantId(), userName);
        return list;
    }

    public List<SysUser> userAllList() {
        List<SysUser> list = userMapper.userAllList();
        return list;
    }

    public List<SysUser> selectUserOne(String phonenumber,String userName,String email) {
        LambdaQueryWrapper<SysUser> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.select(SysUser::getUserName,SysUser::getUserId,SysUser::getNickName,SysUser::getPhonenumber,SysUser::getEmail)
                .eq(StringUtils.isNotBlank(phonenumber),SysUser::getPhonenumber,phonenumber)
                .eq(StringUtils.isNotBlank(userName),SysUser::getUserName,userName)
                .eq(StringUtils.isNotBlank(email),SysUser::getEmail,email)
                .eq(SysUser::getDelFlag,0);
        return this.list(queryWrapper);
    }
}
