package com.vctgo.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.vctgo.common.core.constant.UserConstants;
import com.vctgo.common.core.exception.ServiceException;
import com.vctgo.common.core.text.Convert;
import com.vctgo.common.core.utils.ServletUtils;
import com.vctgo.common.core.utils.SpringUtils;
import com.vctgo.common.core.utils.StrUtils;
import com.vctgo.common.core.utils.bean.BeanValidators;
import com.vctgo.common.core.web.domain.TenantEntity;
import com.vctgo.common.datascope.annotation.DataScope;
import com.vctgo.common.mybatisplus.constant.MybatisPageConstants;
import com.vctgo.common.security.utils.SecurityUtils;
import com.vctgo.system.api.RemoteProfileService;
import com.vctgo.system.api.domain.SysPlatformDept;
import com.vctgo.system.api.domain.SysPlatformRole;
import com.vctgo.system.api.domain.SysPlatformUser;
import com.vctgo.system.api.domain.SysUserTempalte;
import com.vctgo.system.domain.SysPlatformPost;
import com.vctgo.system.domain.SysPlatformUserPost;
import com.vctgo.system.domain.SysPlatformUserRole;
import com.vctgo.system.mapper.*;
import com.vctgo.system.service.ISysConfigService;
import com.vctgo.system.service.ISysPlatformUserService;
import com.vctgo.system.service.SystemCommonService;
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;

import javax.annotation.PostConstruct;
import javax.validation.Validator;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 用户 业务层处理
 *
 * @author vctgo
 */
@Service
public class SysPlatformUserServiceImpl implements ISysPlatformUserService {
    private static final Logger log = LoggerFactory.getLogger(SysUserServiceImpl.class);

    @Autowired
    private SysPlatformUserMapper userMapper;

    @Autowired
    private SysPlatformRoleMapper roleMapper;

    @Autowired
    private SysPlatformPostMapper postMapper;

    @Autowired
    private SysPlatformUserRoleMapper userRoleMapper;

    @Autowired
    private SysPlatformUserPostMapper userPostMapper;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private Validator validator;

    @Autowired
    private SysPlatformDeptMapper sysPlatformDeptMapper;

    @Autowired
    private SystemCommonService systemCommonService;

    @Autowired
    private RemoteProfileService remoteProfileService;

    @PostConstruct
    public void initTenantUser() {
        systemCommonService.loadingSysPlatformUserCache();
    }

    /**
     * 根据条件分页查询用户列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public IPage<SysPlatformUser> selectUserPage(SysPlatformUser user) {
        Page mpPage = new Page(Convert.toLong(ServletUtils.getParameterToInt(MybatisPageConstants.PAGE_NUM), 1L)
                , Convert.toLong(ServletUtils.getParameterToInt(MybatisPageConstants.PAGE_SIZE), 10L));
        return userMapper.selectUserList(mpPage, user);
    }

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

    /**
     * 流程管理获取用户列表
     *
     * @return
     */
    @Override
    public List<SysPlatformDept> processUserList() {
        return sysPlatformDeptMapper.selectUserByDept();
    }

    /**
     * 平台获取流程管理专家列表
     *
     * @return
     */
    @Override
    public List<SysPlatformUser> processExpertList() {
        LambdaQueryWrapper<SysPlatformUser> sysUserWrapper = new LambdaQueryWrapper<>();
        sysUserWrapper.eq(SysPlatformUser::getIsExpert, "1");
        sysUserWrapper.eq(SysUserTempalte::getDelFlag, "0");
        return userMapper.selectList(sysUserWrapper);
    }

    @Override
    public List<SysPlatformUser> userListByTenantIds(String tenantIds) {
        LambdaQueryWrapper<SysPlatformUser> sysUserWrapper = new LambdaQueryWrapper<>();
        sysUserWrapper.in(StrUtils.isNotEmpty(tenantIds), TenantEntity::getTenantId, tenantIds.split(","));
        return userMapper.selectList(sysUserWrapper);
    }

    /**
     * 根据条件分页查询已分配用户角色列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public IPage<SysPlatformUser> selectAllocatedList(SysPlatformUser user) {
        Page mpPage = new Page(Convert.toLong(ServletUtils.getParameterToInt(MybatisPageConstants.PAGE_NUM), 1L)
                , Convert.toLong(ServletUtils.getParameterToInt(MybatisPageConstants.PAGE_SIZE), 10L));
        return userMapper.selectAllocatedList(mpPage, user);
    }

    /**
     * 根据条件分页查询未分配用户角色列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public IPage<SysPlatformUser> selectUnallocatedList(SysPlatformUser user) {
        Page mpPage = new Page(Convert.toLong(ServletUtils.getParameterToInt(MybatisPageConstants.PAGE_NUM), 1L)
                , Convert.toLong(ServletUtils.getParameterToInt(MybatisPageConstants.PAGE_SIZE), 10L));
        return userMapper.selectUnallocatedList(mpPage, user);
    }

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

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

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

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

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

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

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

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

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

    /**
     * 新增保存用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertUser(SysPlatformUser user) {

        // 新增用户信息
        user.setCreateById(SecurityUtils.getUserId());
        int rows = userMapper.insert(user);
        systemCommonService.synchronizedUserInfo(user);

        // 新增用户岗位关联
        if (Objects.nonNull(user.getPostIds()) && 0 != user.getPostIds().length) {
            insertUserPost(user);
        }

        // 新增用户与角色管理
        if (Objects.nonNull(user.getRoleIds()) && 0 != user.getRoleIds().length) {
            insertUserRole(user);
        }
        return rows;
    }

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

    /**
     * 修改保存用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateUser(SysPlatformUser user) {
        // 将新增用户添加到内存中
        systemCommonService.synchronizedUserInfo(user);
        Long userId = user.getUserId();
        // 删除用户与角色关联
        userRoleMapper.deleteUserRoleByUserId(userId);
        // 新增用户与角色管理
        insertUserRole(user);
        // 删除用户与岗位关联
        userPostMapper.deleteUserPostByUserId(userId);
        // 新增用户与岗位管理
        insertUserPost(user);

        //同步"内部资源服务"用户信息
        try {
            remoteProfileService.modifyUserInfo(user);
        }catch (Exception e){
            e.fillInStackTrace();
            log.info("同步“内部资源服务”用户信息失败！");
        }
        //修改用户信息
        return userMapper.updateUser(user);
    }

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

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

    /**
     * 修改用户基本信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int updateUserProfile(SysPlatformUser 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(SysPlatformUser 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 用户对象
     */
    @Override
    public void insertUserRole(SysPlatformUser user) {
        this.insertUserRole(user.getUserId(), user.getRoleIds());
    }

    /**
     * 新增用户岗位信息
     *
     * @param user 用户对象
     */
    public void insertUserPost(SysPlatformUser user) {
        Long[] posts = user.getPostIds();
        if (StrUtils.isNotEmpty(posts)) {
            // 新增用户与岗位管理
            List<SysPlatformUserPost> list = new ArrayList<SysPlatformUserPost>();
            for (Long postId : posts) {
                SysPlatformUserPost up = new SysPlatformUserPost();
                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 (StrUtils.isNotEmpty(roleIds)) {
            // 新增用户与角色管理
            List<SysPlatformUserRole> list = new ArrayList<SysPlatformUserRole>();
            for (Long roleId : roleIds) {
                SysPlatformUserRole ur = new SysPlatformUserRole();
                ur.setUserId(userId);
                ur.setRoleId(roleId);
                list.add(ur);
            }
            userRoleMapper.batchUserRole(list);
        }
    }

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

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

        //删除园所资料内用户
        remoteProfileService.deleteProfileUser(userIds);
        return userMapper.deleteUserByIds(userIds);
    }

    @Override
    public int deleteUserRoleByUserId(Long userId){
        // 删除用户与角色关联
        return userRoleMapper.deleteUserRoleByUserId(userId);
    }

    @Override
    public List<SysPlatformUser> getUserList(String nickName) {
        return userMapper.getUserList(nickName);
    }

    /**
     * 导入用户数据
     *
     * @param userList        用户数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName        操作用户
     * @return 结果
     */
    @Override
    public String importUser(List<SysPlatformUser> userList, Boolean isUpdateSupport, String operName) {
        if (StrUtils.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 (SysPlatformUser user : userList) {
            try {
                // 验证是否存在这个用户
                SysPlatformUser u = userMapper.selectUserByUserName(user.getUserName());
                if (StrUtils.isNull(u)) {
                    BeanValidators.validateWithException(validator, user);
                    user.setPassword(SecurityUtils.encryptPassword(password));
                    user.setCreateBy(operName);
                    userMapper.insert(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();
    }

}
