/*
 * Author: wangjian
 * 生成ServiceImpl
 */
package com.tofly.base.service.impl;


import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tofly.base.config.FilePathExcel;
import com.tofly.base.dto.ResetUserDTO;
import com.tofly.base.em.CreateWayEM;
import com.tofly.base.em.ExcelExportFileTypeEnum;
import com.tofly.base.em.PasswordEM;
import com.tofly.base.entity.System;
import com.tofly.base.entity.*;
import com.tofly.base.entity.dto.UserDto;
import com.tofly.base.mapper.UserMapper;
import com.tofly.base.service.*;
import com.tofly.base.util.AESUtil;
import com.tofly.base.util.RSAUtils;
import com.tofly.base.vo.UserAddVO;
import com.tofly.base.vo.UserPerssionByMenuVO;
import com.tofly.common.core.constant.CommonConstants;
import com.tofly.common.core.constant.ResponeStatus;
import com.tofly.common.core.constant.SecurityConstants;
import com.tofly.common.core.entity.ResultRespone;
import com.tofly.common.core.util.PasswordUtil;
import com.tofly.common.core.util.StringUtil;
import com.tofly.common.core.util.io.ExcelUtil;
import com.tofly.common.ftp.config.FtpUtil;
import com.tofly.common.oauth.auth.ToflyUser;
import com.tofly.common.oauth.exception.ToflyDeniedException;
import com.tofly.common.oauth.util.SecurityUtils;
import com.tofly.entity.pojo.UserInfo;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;

import org.springframework.data.redis.core.ConvertingCursor;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

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

/**
 * 用户表
 *
 * @author admin
 * @date Thu Oct 10 00:00:00 CST 2019
 */
@Service("userService")
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Value("${user.avatar}")
    private String avatarPath;
    @Value("${aes.key}")
    private String key;
    @Value("${aes.iv}")
    private String iv;
    @Autowired
    private SystemService systemService;
    @Autowired
    private MenuService menuService;
    @Autowired
    private SourceService sourceService;
    @Autowired
    private UserRoleService userRoleService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private DepartmentService departmentService;
    @Autowired
    private UserService userService;
    @Autowired
    private FilePathExcel filePathExcel;
    @Autowired
    private RoleMenuService roleMenuService;
    @Autowired
    private CacheManager cacheManager;
    @Autowired
    private TokenStore tokenStore;
    @Autowired
    private UserMiddleService userMiddleService;
    @Autowired
    private RedisTemplate redisTemplate;
    private static final String PROJECT_OAUTH_ACCESS = SecurityConstants.PROJECT_PREFIX + SecurityConstants.OAUTH_PREFIX + "access:";

    @Override
    public User getUserById(Long id) {
        return baseMapper.getUserById(id);
    }

    @Override
    public List<User> getExistUserListByRole(Long roleId) {
        return baseMapper.getExistUserListByRole(roleId);
    }

    @Override
    public List<User> getNoExistUserListByRole(Long roleId) {
        return baseMapper.getNoExistUserListByRole(roleId);
    }

    @Override
    public List<System> getSystemListByUser(String platform) {
        return systemService.getSystemListByUser(platform);
    }

    @Override
    public List<Menu> getMenuListByUser(String platform) {
        return menuService.getMenuListByUser(platform);
    }

    @Override
    public List<Map> getSourceByUser() {
        return sourceService.getSourceByUser();
    }

    @Override
    public List<Map> getSources(Long departmentId) {
        return baseMapper.getSources(departmentId);
    }

    @Override
    @Transactional
    @SneakyThrows
    public boolean deleteUserByIds(String ids) {
        String[] idss = ids.split(",");

        // 判断当前删除用户id是否包含当前操作人员
        List<String> collect = Arrays.stream(idss).filter(id -> SecurityUtils.getUserId().equals(Long.valueOf(id))).collect(Collectors.toList());
        if (collect.size() > 0) {
            throw new Exception("当前删除用户中包含当前操作对象,不可删除");
        }

        List<Long> list = new ArrayList<>();
        List<Long> userRole = new ArrayList<>();
        for (String id : idss) {
            list.add(Long.valueOf(id));
//            if (checkHandler(Long.valueOf(id))) {
//                throw new Exception("当前用户不能删除其他人创建的用户");
//            }
            List<UserRole> roleMneuList = userRoleService.list(Wrappers.<UserRole>lambdaQuery()
                    .eq(UserRole::getUserId, Long.valueOf(id)));
            if (roleMneuList.size() > 0) {
                userRole.addAll(roleMneuList.stream().map(UserRole::getId).collect(Collectors.toList()));
            }
        }
        if (userRole.size() > 0) {
            userRoleService.removeByIds(userRole);
        }
        userService.removeByIds(list);
        // 清空用户token及redis缓存数据
        this.clearUserListToken(list);

        return true;
    }

    @Override
    @Transactional
    @SneakyThrows
    public boolean updateByIdList(String ids) {
        String[] idss = ids.split(",");
        List<Long> list = new ArrayList<>();
        for (String id : idss) {
            list.add(Long.valueOf(id));
//            if (checkHandlerDisable(Long.valueOf(id))) {
//                throw new Exception("当前用户没有解锁用户的权限");
//            }
        }
        return baseMapper.updateByIdList(list);
    }

    @Override
    @Transactional
    @SneakyThrows
    public boolean updateByIdListToUnlock(String ids) {
        String[] idss = ids.split(",");
        List<Long> list = new ArrayList<>();
        for (String id : idss) {
            list.add(Long.valueOf(id));
//            if (checkHandlerDisable(Long.valueOf(id))) {
//                throw new Exception("当前用户没有解锁用户的权限");
//            }
        }
        return baseMapper.updateByIdListToUnlock(list);
    }

    @Override
    @Transactional
    @SneakyThrows
    public boolean updateByIdStatusFlag(String ids) {
        String[] idss = ids.split(",");
        List<Long> list = new ArrayList<>();
        for (String id : idss) {
            list.add(Long.valueOf(id));
//            if (checkHandlerDisable(Long.valueOf(id))) {
//                throw new Exception("当前用户没有禁用用户的权限");
//            }
        }
        return baseMapper.updateByIdStatusFlag(list);
    }

    @Override
    @Transactional
    @SneakyThrows
    public boolean updateUnStatusFlag(String ids) {
        String[] idss = ids.split(",");
        List<Long> list = new ArrayList<>();
        for (String id : idss) {
            list.add(Long.valueOf(id));
//            if (checkHandlerDisable(Long.valueOf(id))) {
//                throw new Exception("当前用户没有启用用户的权限");
//            }
        }
        return baseMapper.updateUnStatusFlag(list);
    }

    @Override
    public List<User> getDepartmentUsers() {
        Long userId = SecurityUtils.getUserId();
        User user = userService.getUserById(userId);
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("DEPARTMENT_ID", user.getDepartmentId());
        return baseMapper.selectList(wrapper);
    }

    @Override
    public ResultRespone getUserInformatiomByLikeName(String name) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.like("REAL_NAME", name);
        return ResultRespone.success(baseMapper.selectList(wrapper));
    }

    @Override
    public List<User> getDepartmentUsersByIds(Long departmentId) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("DEPARTMENT_ID", departmentId);
        return baseMapper.selectList(wrapper);
    }

    @Override
    public ResultRespone getUserAndDepatmentByPerssion(String ids) throws Exception {
        List<Long> removeId = Arrays.stream(ids.split(",")).map(s -> Long.parseLong(s.trim()))
                .collect(Collectors.toList());
        List<Menu> menu = menuService.listByIds(removeId);
        if (menu == null || menu.size() == 0) {
            throw new ToflyDeniedException("此菜单id不存在");
        }
        List<RoleMenu> lists = new ArrayList<>();
        for (Menu m : menu) {
            List<RoleMenu> list = roleMenuService.getAllRoleId(m.getId());
            lists.addAll(list);
        }
        List<Long> roleId = lists.stream().map(RoleMenu::getRoleId).collect(Collectors.toList());
        List<UserRole> userRoles = userRoleService.list(Wrappers.<UserRole>lambdaQuery().in(UserRole::getRoleId, roleId));
        List<Long> userId = userRoles.stream().map(UserRole::getUserId).collect(Collectors.toList());
        List<User> userList = userService.list(new QueryWrapper<User>().lambda().in(User::getId, userId));
        List<UserPerssionByMenuVO> users = new ArrayList<>();
        for (User u : userList) {
            UserPerssionByMenuVO perssion = new UserPerssionByMenuVO();
            org.apache.commons.beanutils.BeanUtils.copyProperties(perssion, u);
            if (u.getDepartmentId() != null) {
                Department department = departmentService.getById(u.getDepartmentId());
                if (null != department) {
                    perssion.setDepartmentName(department.getName());
                }

            }
            users.add(perssion);
        }
        return ResultRespone.success(users);
    }

    @Override
    public List<Map<String, String>> sysUserReport() {
        return this.baseMapper.sysUserReport();
    }

    //    private boolean checkHandler(String ulevel){
//        if(StringUtil.isEmpty(ulevel)){
//            return false;
//        }
//        String userlevel= SecurityUtils.getUser().getUserLevel();
//        if(Integer.parseInt(userlevel)>=Integer.parseInt(ulevel)){
//            return true;
//        }
//        return false;
//    }

    private boolean checkHandlerDisable(Long userid) {
        if (CommonConstants.SUPER_ADMIN_ULEVEL.equals(SecurityUtils.getUser().getUserLevel())) {
            return false;
        }
        return true;
    }

    private boolean checkHandler(Long userid) {
        if (CommonConstants.SUPER_ADMIN_ULEVEL.equals(SecurityUtils.getUser().getUserLevel())) {
            return false;
        }
        User user = userService.getUserById(userid);
        if (SecurityUtils.getUserId().equals(user.getCreateUser())) {
            return false;
        } else {
//            if (CommonConstants.SUPER_ADMIN_ULEVEL.equals(user.getUserLevel())) {
//                return true;
//            } else {
//                return checkHandler(user.getCreateUser());
//            }
            return true;
        }
    }

    @Override
    public Page<Map> getUserPage(Page page, User user) {
        return page.setRecords(baseMapper.getUserPage(page, user));
    }

    @Override
    @SneakyThrows
    @Transactional
    public String uploadBatchUser(MultipartFile file) {
        if (file == null) {
            throw new ToflyDeniedException("上传文件为空");
        }
        InputStream inputStream = file.getInputStream();
        ExcelUtil userExcel = new ExcelUtil(User.class);
        List<User> listUser = userExcel.importExcel(inputStream);
        List<User> listAllUser = this.list();
        Map<String, User> collect = listAllUser.stream().collect(Collectors.toMap(User::getUsername, m -> m));
        StringBuffer sb = new StringBuffer();
        List<String> collect1 = listUser.stream().filter(k -> collect.get(k.getUsername()) != null)
                .map(User::getUsername).collect(Collectors.toList());
        if (collect1.size() > 0) {
            throw new ToflyDeniedException("数据库已经存在用户名，不能导入" + JSONArray.toJSONString(collect1));
        }
        collect1 = listUser.stream().filter(k -> StringUtil.isEmpty(k.getUsername()) || StringUtil.isEmpty(k.getPassword()))
                .map(User::getUsername).collect(Collectors.toList());
        if (collect1.size() > 0) {
            throw new ToflyDeniedException("用户名或密码存在为空的数据，不能导入" + JSONArray.toJSONString(collect1));
        }

        return "成功导入" + listUser.size() + "条数据";
    }

    @Override
    public List<Map> getUserByMenu(String menuName) {
        return baseMapper.getUserByMenu(menuName);
    }

    @Override
    public Page<Map> getListHistory(Page page, Map map) {
        return page.setRecords(baseMapper.getListHistory(page, map));
    }

    @Override
    public Object insertUser(User user) {
        return baseMapper.insert(user);
    }

    @Override
    public String templateToUpload(MultipartFile file) throws IOException {
        File toFile = null;
        if (file.getSize() <= 0) {
            file = null;
        } else {
            InputStream ins = null;
            ins = file.getInputStream();
            toFile = new File(file.getOriginalFilename());
            inputStreamToFile(ins, toFile);
            ins.close();
        }
        String filePath = filePathExcel + IdWorker.getIdStr() + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        return filePathExcel.getIp() + filePath;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultRespone<Object> resetPassword(ResetUserDTO users) {
        if (CollectionUtils.isEmpty(users.getUsers())) {
            return ResultRespone.failed("重置密码用户不能为空");
        }
        for (User user : users.getUsers()) {
            long id = user.getId();
            String encodePassword = PasswordUtil.passwordEncode(PasswordEM.RESETPASSWORD.getType());
            user.setPwderrtimes(Short.valueOf("0"));
            user.setPassword(encodePassword);
            user.setLockFlag("1");
            user.setFirstlog("1");
            boolean b = userService.updateById(user);
            // 中间表用户同步
            userMiddleService.synchronizeUser(user.getUsername(), PasswordEM.RSA_RESETPASSWORD.getType(), user.getRealName(), "1");
            // 同步营销
            userMiddleService.sendMarketingUser(user.getUsername(), PasswordEM.RSA_RESETPASSWORD.getType(), user.getRealName(), "1");
            if (b) {
                User userById = userService.getUserById(id);
                String username = userById.getUsername();
                updatePwd(username, userById.getId());
            }
        }
        return ResultRespone.success(true);
    }

    @Override
    public Map planTemplate() {
        Map<String, Object> map = new HashMap<>();
        map.put("path", filePathExcel.getExcelmb() + "usermoban.xlsx");
        map.put("name", "用户模版.xlsx");
        return map;
    }

    @Override
    public ResultRespone accountApplication(MultipartFile file, User user, MultipartFile electronicFile) {
        User quser = userService.getOne(Wrappers.<User>lambdaQuery()
                .eq(User::getUsername, user.getUsername()));
        if (quser != null) {
            return ResultRespone.failed("该用户名【" + user.getUsername() + "】已经存在，不能账号申请");
        }
        if (file != null && electronicFile == null) {
            String filename = avatarPath + IdWorker.getIdStr() + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            user.setApplyer(SecurityUtils.getUser().getUsername());
            user.setAvatar(filename);
            user.setCreateType("1");
            user.setPassword(PasswordUtil.passwordEncode(user.getPassword()));
            return ResultRespone.success(userService.save(user));
        } else if (file == null && electronicFile != null) {
            String electronicFilename = avatarPath + IdWorker.getIdStr() + electronicFile.getOriginalFilename().substring(electronicFile.getOriginalFilename().lastIndexOf("."));
            user.setApplyer(SecurityUtils.getUser().getUsername());
            user.setEsignature(electronicFilename);
            user.setCreateType("1");
            user.setPassword(PasswordUtil.passwordEncode(user.getPassword()));
            return ResultRespone.success(userService.save(user));
        } else if (file != null) {
            String filename = avatarPath + IdWorker.getIdStr() + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            String electronicFilename = avatarPath + IdWorker.getIdStr() + electronicFile.getOriginalFilename().substring(electronicFile.getOriginalFilename().lastIndexOf("."));
            user.setApplyer(SecurityUtils.getUser().getUsername());
            user.setAvatar(filename);
            user.setCreateType("1");
            user.setEsignature(electronicFilename);
            user.setPassword(PasswordUtil.passwordEncode(user.getPassword()));
            return ResultRespone.success(userService.save(user));
        } else {
            user.setCreateType("1");
            user.setApplyer(SecurityUtils.getUser().getUsername());
            user.setPassword(PasswordUtil.passwordEncode(user.getPassword()));
            return ResultRespone.success(userService.save(user));
        }
    }

    @Override
    public ResultRespone updateByIdNew(MultipartFile file, User user, String roles) {

        return null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultRespone updatePassword(User user2) {
        Long id = user2.getId();
        User u = userService.getById(id);
        String originalPassword = user2.getOriginalPassword();
        try {
            originalPassword = RSAUtils.priKeyDecryption(originalPassword);
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        boolean flag = bCryptPasswordEncoder.matches(SecurityConstants.BCRYPT + originalPassword, u.getPassword());
        if (!flag) {
            String sha1 = SecureUtil.sha1(originalPassword);
            log.info("sha1加密：{}", sha1);
            boolean matches = bCryptPasswordEncoder.matches(SecurityConstants.BCRYPT + sha1,  u.getPassword());
            if (!matches) {
                return ResultRespone.failed("原始密码不正确");
            }
        }

        String password = user2.getPassword();
        if (StringUtil.isEmpty(password)) {
            return ResultRespone.failed("密码不能为空");
        }
        User user = new User();
        String username = null;
        if (id == null || id == 0L) {
            id = SecurityUtils.getUserId();
            username = SecurityUtils.getUserName();
        } else {
            if (checkHandler(id)) {
                return ResultRespone.failed("当前用户不能修改其他人创建的用户");
            }
        }
        user.setId(id);
        String encodePassword = null;
        try {
            encodePassword = PasswordUtil.passwordEncode(RSAUtils.priKeyDecryption(password));
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        user.setPassword(encodePassword);
        user.setFirstlog("0");
        boolean b = userService.updateById(user);
        // 中间表用户同步
        userMiddleService.synchronizeUser(u.getUsername(), password, u.getRealName(), "1");
        // 同步营销
        userMiddleService.sendMarketingUser(u.getUsername(), password, u.getRealName(), "1");
        if (b) {
            updatePwd(u.getUsername(), u.getId());
        }
        return ResultRespone.success(true);
    }

    @Override
    public ResultRespone saveNew(MultipartFile file, UserRoles user, MultipartFile electronicFile) {
        User quser = userService.getOne(Wrappers.<User>lambdaQuery()
                .eq(User::getUsername, user.getUsername()));
        if (quser != null) {
            return ResultRespone.failed("该用户名【" + user.getUsername() + "】已经存在，不能新增");
        }

        if (CommonConstants.SUPER_ADMIN_ULEVEL.equals(user.getUserLevel())) {
            return ResultRespone.failed("不能创建超级管理员级别的用户");
        }
        if (file != null && electronicFile == null) {
            String filename = avatarPath + IdWorker.getIdStr() + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            boolean b = FtpUtil.uploadFile2Ftp(file, filename);
            if (b) {
                user.setAuditstatus(CreateWayEM.AGREE.getType());
                user.setAvatar(filename);
                user.setCreateType(CreateWayEM.SELF_BUILT.getType());
                return getResultRespone(user);
            } else {
                return ResultRespone.failed("上传到FTP失败");

            }
        } else if (file == null && electronicFile != null) {
            String electronicFilename = avatarPath + IdWorker.getIdStr() + electronicFile.getOriginalFilename().substring(electronicFile.getOriginalFilename().lastIndexOf("."));
            boolean a = FtpUtil.uploadFile2Ftp(electronicFile, electronicFilename);
            if (a) {
                user.setAuditstatus(CreateWayEM.AGREE.getType());
                user.setCreateType(CreateWayEM.SELF_BUILT.getType());
                user.setEsignature(electronicFilename);
                return getResultRespone(user);
            } else {
                return ResultRespone.failed("上传到FTP失败");
            }
        } else if (file != null) {
            String filename = avatarPath + IdWorker.getIdStr() + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            boolean b = FtpUtil.uploadFile2Ftp(file, filename);
            String electronicFilename = avatarPath + IdWorker.getIdStr() + electronicFile.getOriginalFilename().substring(electronicFile.getOriginalFilename().lastIndexOf("."));
            boolean a = FtpUtil.uploadFile2Ftp(electronicFile, electronicFilename);
            user.setAuditstatus(CreateWayEM.AGREE.getType());
            user.setAvatar(filename);
            user.setCreateType(CreateWayEM.SELF_BUILT.getType());
            user.setEsignature(electronicFilename);
            return getResultRespone(user);
        } else {
            user.setAuditstatus(CreateWayEM.AGREE.getType());
            user.setCreateType(CreateWayEM.SELF_BUILT.getType());
            return getResultRespone(user);
        }

    }

    @Override
    public boolean updateByIdNew(MultipartFile file, User user, MultipartFile electronicFile, String roles) {
        User oldUsers = userService.getById(user.getId());
        if (null != file) {
            String filename = avatarPath + IdWorker.getIdStr() + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            FtpUtil.uploadFile2Ftp(file, filename);
            user.setAvatar(filename);
            // 清空以前文件
            if (!StringUtil.isEmpty(oldUsers.getAvatar())) {
                FtpUtil.deleteFile(oldUsers.getAvatar());
            }
        }
        if (null != electronicFile) {
            String electronicFilename = avatarPath + IdWorker.getIdStr() + electronicFile.getOriginalFilename().substring(electronicFile.getOriginalFilename().lastIndexOf("."));
            FtpUtil.uploadFile2Ftp(electronicFile, electronicFilename);
            user.setEsignature(electronicFilename);
            // 清空以前文件
            if (!StringUtil.isEmpty(oldUsers.getEsignature())) {
                FtpUtil.deleteFile(oldUsers.getEsignature());
            }
        }
        // 修改角色getAuxiliaryDispatching
        userRoleService.updateUserRole(user.getId(), roles);
        // 判断密码是否存在(营销调用逻辑)
        String password = user.getPassword();
        if (com.baomidou.mybatisplus.core.toolkit.StringUtils.isNotBlank(password)) {
            // AES解密
            try {
                String s = AESUtil.decryptData(password, key, iv);
                String passwordEncode = PasswordUtil.passwordEncode(s);
                user.setPassword(passwordEncode);
                // 同步用户表
                userMiddleService.synchronizeUser(user.getUsername(), password, user.getRealName(), "");
            } catch (Exception exception) {
                exception.printStackTrace();
            }
        } else {
            // 同步用户中间表
            userMiddleService.synchronizeUser(user.getUsername(), "", user.getRealName(), "");
            // 同步营销用户
            userMiddleService.sendMarketingUser(user.getUsername(), "", user.getRealName(), "");
        }
         if(StringUtil.isNotNull(user.getPhone()) && user.getPhone().equals("null")){
            user.setPhone("");
         }
        if(StringUtil.isNotNull(user.getJob()) && user.getJob().equals("null")){
            user.setJob("");
        }
        if(StringUtil.isNotNull(user.getEmail()) && user.getEmail().equals("null")){
            user.setEmail("");
        }
        if(StringUtil.isNotNull(user.getNote()) && user.getNote().equals("null")){
            user.setNote("");
        }
        if(!oldUsers.getDepartmentId().equals(user.getDepartmentId())){
            List<Long> list = new ArrayList<>();
            list.add(user.getId());
            clearUserListToken(list);
        }

        return userService.updateById(user);
    }

    private ResultRespone getResultRespone(UserRoles user) {
        ResultRespone respone = new ResultRespone();
        String password = user.getPassword();
        if (!StringUtils.isEmpty(password)) {
            // 营销传入  先解密 再加密 赋值为已经第一次登录
            // AES解密
            try {
                String s = AESUtil.decryptData(password, key, iv);
                String passwordEncode = PasswordUtil.passwordEncode(s);
                user.setPassword(passwordEncode);
                userMiddleService.synchronizeUser(user.getUsername(), password, user.getRealName(), "");
                user.setFirstlog("0");
            } catch (Exception exception) {
                exception.printStackTrace();
            }
        } else {
            user.setPassword(PasswordUtil.passwordEncode(PasswordEM.RESETPASSWORD.getType()));
            // 同步用户中间表
            userMiddleService.synchronizeUser(user.getUsername(), PasswordEM.RSA_RESETPASSWORD.getType(), user.getRealName(), "1");
            // 同步营销用户
            userMiddleService.sendMarketingUser(user.getUsername(), PasswordEM.RSA_RESETPASSWORD.getType(), user.getRealName(), "1");
        }


        user.setCreateUser(1L);
        boolean flag = userService.save(user);
        if (StringUtil.isNotEmpty(user.getRoles())) {

            if (flag) {
                boolean b = userRoleService.updateUserRole(user.getId(), user.getRoles());
                respone.setResult(b);
            } else {
                respone.setCode(ResponeStatus.FAIL.getCode());
                respone.setMessage("用户新增失败");
            }
        }
        return respone;
    }

    @Override
    public UserInfo getUserInfo(User sysUser) {
        UserInfo userInfo = new UserInfo();
        //加入部门名称
        if (sysUser.getDepartmentId() != null) {
            Department department = departmentService.getOne(Wrappers.<Department>lambdaQuery().
                    eq(Department::getId, sysUser.getDepartmentId()));
            sysUser.setDepartmentName(department.getName());
        }
        com.tofly.entity.pojo.User user1 = JSONObject.parseObject(JSON.toJSONString(sysUser), com.tofly.entity.pojo.User.class);
        userInfo.setSysUser(user1);//用户信息

        //设置角色

        List<Role> list = roleService.listRolesByUserId(sysUser.getId());
        //List<Map> list=listRolesByUserId(sysUser.getUserId());
        List<Long> roleList = list
                .stream()
                .map(Role::getId)
                //.map(m->(Integer)m.get("roleId"))
                .collect(Collectors.toList());
//        List<String> sysIdList = list
//                .stream()
//                .map(Role::getSysId)
//                .collect(Collectors.toList());

//        userInfo.setRoles(roleList.stream().toArray(Long[]::new));//角色信息

        //设置权限
        Set<String> permissions = new HashSet<>();
        roleList.forEach(roleid -> {
            List<String> permssionsList = menuService.listMenusByRoleId(roleid)
                    .stream()
                    .filter(sysMenu -> StringUtil.isNotEmpty(sysMenu.getPermission()))
                    .map(Menu::getPermission)
                    .collect(Collectors.toList());
        });

        userInfo.setPermissions(permissions.stream().toArray(String[]::new));

        return userInfo;
    }


    //获取流文件
    private static void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void updatePwd(String username, Long userId) {
        String key = "user_details::" + username;
        Boolean delete = redisTemplate.delete(key);
        log.info("用户: " + username + "清除缓存", delete);
    }

    @Override
    public List<Map<String, Object>> getExportData(String dto, String templateFlag) {
        List<Map<String, Object>> returnMap = new ArrayList<>();

        Map<String, Object> parentMap = new HashMap<>(12);
        if (ExcelExportFileTypeEnum.EXPORT_USER_ADD.getFlag().equals(templateFlag)) {
            User user = this.list().get(0);
            UserDto userDto = JSON.parseObject(JSON.toJSONString(user), UserDto.class);
            userDto.setRoleList("表务管理,开发人员");
            List<UserDto> list = new ArrayList<>();
            list.add(userDto);
            parentMap.put("list", list);
        } else {
            User user = new User();
            if (!StringUtils.isEmpty(dto)) {
                user = JSON.parseObject(dto, User.class);
            }
            List<User> userList = this.list(new QueryWrapper<User>().setEntity(user));
            userList.sort(Comparator.comparingLong(User::getId));
            dto = JSONArray.toJSONStringWithDateFormat(userList, "yyyy-MM-dd HH:mm:ss");
            parentMap.put("list", JSONObject.parseArray(dto, Map.class));
        }
        returnMap.add(parentMap);
        return returnMap;
    }

    @Override
    @Transactional
    public Boolean excelDataStorage(List<Object> dataList) {
        List<UserDto> userDtoList = new ArrayList<>();
        for (int i = 0; i < dataList.size(); i++) {
            Object o = dataList.get(i);
            UserDto userDto = JSON.parseObject(JSON.toJSONString(o), UserDto.class);
            userDtoList.add(userDto);
        }

//        List<String> roles = new ArrayList<>();
        // 判断当前插入数据是否满足条件
        List<User> listAllUser = this.list();
        Map<String, User> collect = listAllUser.stream().collect(Collectors.toMap(User::getUsername, m -> m));

        List<String> collect1 = userDtoList.stream().map(UserDto::getUsername)
                .filter(username -> collect.get(username) != null).collect(Collectors.toList());
        if (collect1.size() > 0) {
            throw new ToflyDeniedException("数据库已经存在登录名，不能导入: " + JSONArray.toJSONString(collect1));
        }
        collect1 = userDtoList.stream().map(UserDto::getUsername)
                .filter(StringUtils::isEmpty).collect(Collectors.toList());
        if (collect1.size() > 0) {
            throw new ToflyDeniedException("登录名存在为空的数据，不能导入: " + JSONArray.toJSONString(collect1));
        }
        for (UserDto userDto : userDtoList) {
            User user = new User();
            user.setUsername(userDto.getUsername());
            user.setPhone(userDto.getPhone());
            List<Department> departmentList = departmentService.list(new QueryWrapper<Department>().lambda().eq(Department::getName, userDto.getDepartmentName()));
            if (null != departmentList && departmentList.size() > 0) {
                user.setDepartmentId(departmentList.get(0).getId());
            } else {
                throw new ToflyDeniedException("当前输入部门不存在，不能导入: " + JSONArray.toJSONString(userDto.getDepartmentName()));
            }
            String realName = userDto.getRealName();
            if (StringUtils.isEmpty(realName)) {
                throw new ToflyDeniedException("用户名存在为空的数据，不能导入: " + JSONArray.toJSONString(realName));
            }
            user.setEmail(userDto.getEmail());
            user.setRealName(realName);
            user.setCreateType("0");
            user.setAuditstatus("2");
            user.setJob(userDto.getJob());
            user.setNote(userDto.getNode());
            user.setPassword(PasswordUtil.passwordEncode(PasswordEM.RESETPASSWORD.getType()));
            userService.save(user);
            String r = userDto.getRoleList();
            //分配权限
            if (!StringUtil.isEmpty(r)) {
                String[] role = r.split(",");
                UserRole userRole;
                for (String s : role) {
                    userRole = new UserRole();
                    userRole.setUserId(user.getId());
                    QueryWrapper<Role> wrapper = new QueryWrapper<>();
                    wrapper.eq("ROLE_NAME", s.trim());
                    List<Role> re = roleService.list(wrapper);
                    if (null != re && re.size() > 0) {
                        userRole.setRoleId(re.get(0).getId());
                        userRoleService.save(userRole);

                    } else {
                        throw new ToflyDeniedException("当前输入角色不存在，不能导入: " + s);
                    }

                }
            }

        }
        return true;
    }

    /**
     * 清空用户列表token
     *
     * @param userIdList
     * @return
     */
    private boolean clearUserListToken(List<Long> userIdList) {
        ScanOptions options = ScanOptions.scanOptions().match(PROJECT_OAUTH_ACCESS + "*").build();
        RedisSerializer<String> redisSerializer = (RedisSerializer<String>) redisTemplate.getKeySerializer();
        Cursor cursor = (Cursor) redisTemplate.executeWithStickyConnection(redisConnection -> new ConvertingCursor<>(redisConnection.scan(options), redisSerializer::deserialize));
        assert cursor != null;
        while (cursor.hasNext()) {
            String msg = cursor.next().toString();
            String accessToken = StringUtil.subAfter(msg, PROJECT_OAUTH_ACCESS, true);
            OAuth2AccessToken token = tokenStore.readAccessToken(accessToken);
            OAuth2Authentication oAuth2Auth = tokenStore.readAuthentication(token);
            if (null == oAuth2Auth) {
                continue;
            }
            Authentication authentication = oAuth2Auth.getUserAuthentication();
            if (authentication.getPrincipal() instanceof ToflyUser) {
                ToflyUser user = (ToflyUser) authentication.getPrincipal();
                userIdList.forEach(info -> {
                    if (user.getUserid().intValue() == info.intValue()) {
                        Cache cache = cacheManager.getCache("user_details");
                        assert cache != null;
                        cache.put(authentication.getName(), null);
                        tokenStore.removeAccessToken(token);
                    }
                });

            }
        }
        return true;
    }
}
