package com.dayou.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.dayou.bo.LeaderRatioBO;
import com.dayou.bo.LoginCacheUserBO;
import com.dayou.bo.PrivilegeTreeBO;
import com.dayou.bo.SimpleParentModel;
import com.dayou.common.*;
import com.dayou.condition.LoginCondition;
import com.dayou.constants.JwtConstants;
import com.dayou.dto.LoginDTO;
import com.dayou.dto.SimplePostModel;
import com.dayou.dto.UpdatePasswordDTO;
import com.dayou.dto.UserBaseDetailDTO;
import com.dayou.entity.*;
import com.dayou.exception.ErrorCode;
import com.dayou.mapper.BrokeragePostRatioMapper;
import com.dayou.mapper.UserMapper;
import com.dayou.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dayou.utils.*;
import com.dayou.vo.DepartmentUserVO;
import com.dayou.vo.IdNameVO;
import com.dayou.vo.UserVO;
import com.google.common.collect.Maps;
import com.google.common.cache.Cache;
import com.google.common.collect.Sets;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import io.jsonwebtoken.Claims;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;

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

import org.springframework.transaction.annotation.Transactional;
import com.dayou.enums.BatchTaskTypeEnum;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import static com.dayou.common.Constants.*;
import static com.dayou.exception.ErrorCode.*;

/**
 * <p>
 * 基础用户 服务实现类
 * </p>
 *
 * @author wucl
 * @since 2022-11-29
 */
@DS("mbs")
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    private static final List<String> userExcelTitles = new ArrayList();

    static {
        userExcelTitles.add("姓名");
        userExcelTitles.add("身份证号");
        userExcelTitles.add("手机号码");
        userExcelTitles.add("用户性别 男/女");
        userExcelTitles.add("员工类型");
        userExcelTitles.add("出生日期");
        userExcelTitles.add("民族");
        userExcelTitles.add("政治面貌");
        userExcelTitles.add("籍贯");
        userExcelTitles.add("家庭住址");
        userExcelTitles.add("入职日期");
        userExcelTitles.add("备注");
    }

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private IUserPostService userPostService;

    @Autowired
    @Qualifier("loginCache")
    private Cache<Long, LoginCacheUserBO> cache;

    @Autowired
    private IPostPrivilegeService postPrivilegeService;

    @Autowired
    private IMenuService menuService;

    @Autowired
    private IPostService postService;
    
    @Autowired
    private BrokeragePostRatioMapper brokeragePostRatioMapper;

    @Autowired
    private ISortedDepartmentService sortedDepartmentService;


    @Override
    @SuppressWarnings("unchecked")
    public Page<User> selectPage(Page page, User user) {
        return this.page(page, new QueryWrapper<User>(user));
    }


    @Override
    public UserVO detail(Long id) {
        return userMapper.detail(id);
    }

    @Override
    public Boolean add(User user) {
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user,userVO);
        return this.xSave(userVO);
    }

    @Override
    public Boolean update(User user) {
        return this.updateById(user);
    }

    @Override
    public Boolean delete(Long id) {
        //逻辑删除
        return this.removeById(id);
    }

    @Override
    public XSSFWorkbook generateImportTemplate() {
        XSSFWorkbook wb = new XSSFWorkbook();
        //创建固定列的表头
        createExcelTitle(wb);
        return wb;
    }

    private void createExcelTitle(XSSFWorkbook wb) {
        Sheet sheet = wb.createSheet("基础用户导入模板");
        Row row = sheet.createRow(0);
        CellStyle style = wb.createCellStyle();
        Cell cell = null;
        for (int i = 0; i < userExcelTitles.size(); i++) {
            cell = row.createCell(i);
            cell.setCellStyle(style);
            cell.setCellValue(userExcelTitles.get(i));
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void importExcel(MultipartFile file) {
        ExcelUtil.importExcel(User.class, new ExcelUtil.ImportListener<User>() {
            @Override
            public Boolean handleOneRecord(User user) {
                return add(user);
            }

            @Override
            public void afterImport(ExcelUtil.BatchImportResult batchImportResult) {

            }
        }, file, BatchTaskTypeEnum.DEFAULT, ExcelUtil.BatchImportStrategy.ROLL_BACK);
    }

    @Override
    public XSSFWorkbook exportExcel(User user) {
        XSSFWorkbook wb = ExcelUtil.export(User.class,
                (page, userReq) -> selectPage(page, userReq),
                user);
        return wb;
    }

    @Override
    public LoginDTO login(LoginCondition loginCondition, HttpServletRequest request) {
        String account = loginCondition.getAccount();
        String pwd = loginCondition.getPwd();

        User user = checkUserLogin(account, pwd);

//        if (user.getEnable().equals(Boolean.FALSE)) {
//            ErrorCode.throwBusinessException(USER_DISABLE);
//        }

        Long userId = user.getId();

        Map<String, Object> claims = Maps.newHashMap();
        String token = JwtTokenUtil.doGenerateToken(claims, String.valueOf(userId));
        //缓存用户信息
        cacheLoginInfo(user, token);
        //将userId存入HttpSession中用于Websocket中获取

        HttpSession session = request.getSession();
        session.setAttribute(USER_ID, userId);

        return LoginDTO.builder()
                .token(token)
                .build();
    }

    @Override
    public UserBaseDetailDTO baseInfo(String token) {
        Claims claims = JwtTokenUtil.getClaimFromToken(token, JwtConstants.SECRET);
        Long id = Long.valueOf(claims.getSubject());
        return getUserBaseInfo(id);
    }

    private UserBaseDetailDTO getUserBaseInfo(Long userId) {
        UserBaseDetailDTO userBaseDetailDTO = new UserBaseDetailDTO();
        User user = getById(userId);
        if (user != null) {
            BeanUtils.copyProperties(user,userBaseDetailDTO);
        }

        List<SimplePostModel> postList = userPostService.getPostList(userId);
        userBaseDetailDTO.setPostList(postList);

        Set<Long> postIds = postList.stream().map(SimpleListModel::getId).collect(Collectors.toSet());

        List<SimpleParentModel> departmentList = postService.getDepartmentList(postIds);
        userBaseDetailDTO.setDepartmentList(departmentList);

        LoginCacheUserBO loginCacheUserBO = cache.getIfPresent(userId);
        userBaseDetailDTO.setLoginCacheUserBO(loginCacheUserBO);
        return userBaseDetailDTO;
    }
    private User checkUserLogin(String account, String pwd) {

        //先验证账号
        List<User> users = userMapper.selectList(new LambdaQueryWrapper<User>()
                .eq(User::getStaffNo,account).eq(BaseEntity::getDeleted,false));

        if (CollectionUtils.isEmpty(users)) {
            //如果账号未查询到，再用姓名尝试
            users = userMapper.selectList(new LambdaQueryWrapper<User>()
                    .eq(User::getName,account).eq(BaseEntity::getDeleted,false));

            if (users.size() > 1) {
                ErrorCode.throwBusinessException(CUSTOM_ERROR,"存在多个姓名相同的用户，请使用工号登录。");
            }

        }

        if (CollectionUtils.isEmpty(users)){
            ErrorCode.throwBusinessException(PWD_ERROR);
        }

        User user = users.get(0);
        Long userId = user.getId();
        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<User>()
                .eq(User::getId, userId)
                .eq(User::getPassword, pwd)
                .eq(User::getDeleted, false);

        User xUser = this.getOne(userLambdaQueryWrapper);
        if (xUser == null) {
            ErrorCode.throwBusinessException(PWD_ERROR);
        }
        return xUser;
    }

    private void cacheLoginInfo(User user, String token) {
        LoginCacheUserBO loginCacheUserBO = new LoginCacheUserBO();
        UserBaseDetailDTO userBaseDetailDTO = this.baseInfo(token);
        Set<PrivilegeTreeBO> privilegeList = this.privilegesList(token);

        loginCacheUserBO.setId(user.getId());
        loginCacheUserBO.setName(userBaseDetailDTO.getName());
        loginCacheUserBO.setPostList(userBaseDetailDTO.getPostList());
        loginCacheUserBO.setPrivilegeList(privilegeList);
        loginCacheUserBO.setDepartmentList(userBaseDetailDTO.getDepartmentList());

        loginCacheUserBO.setAccount(StringUtils.isNotBlank(user.getStaffNo()) ? user.getStaffNo() : user.getMobile());
        cache.put(user.getId(), loginCacheUserBO);

        LoginContext.setLoginCacheUserBO(loginCacheUserBO);
    }

    @Override
    public Set<PrivilegeTreeBO> privilegesList(String token) {
        Set<PrivilegeTreeBO> privilegesSet = Sets.newHashSet();
        UserBaseDetailDTO userBaseDetailDTO = this.baseInfo(token);
        List<SimplePostModel> postList = userBaseDetailDTO.getPostList();
        if (CollectionUtils.isNotEmpty(postList)) {
            //用户可能有多个岗位，每个岗位都有各自的权限，需要对权限进行合并
            for (SimpleListModel simleListModel : postList) {
                Long postId = simleListModel.getId();
                LambdaQueryWrapper<PostPrivilege> postPrivilegeLambdaQueryWrapper =
                        new LambdaQueryWrapper<PostPrivilege>()
                                .eq(PostPrivilege::getPostId, postId)
                                .eq(PostPrivilege::getDeleted, false);
                PostPrivilege postPrivilege = postPrivilegeService.getOne(postPrivilegeLambdaQueryWrapper);
                if (postPrivilege != null) {
                    String privilegeTree = postPrivilege.getPermissionTree();
                    if (StringUtils.isNotBlank(privilegeTree)) {
                        //将权限树转换为平铺列表
                        Gson gson = new Gson();
                        List<PrivilegeTreeBO> results = gson.fromJson(privilegeTree,
                                new TypeToken<List<PrivilegeTreeBO>>() {
                                }.getType());
                        List<PrivilegeTreeBO> tiledList = (List<PrivilegeTreeBO>) TreeUtil.treeTile(results);
                        tiledList = tiledList.stream().filter(PrivilegeTreeBO::getChecked).collect(Collectors.toList());
                        //去重
                        for (PrivilegeTreeBO bo : tiledList) {
                            if (privilegesSet.contains(bo)) {
                                PrivilegeTreeBO existBo =
                                        privilegesSet.stream().filter(b -> b.getId().equals(bo.getId())).findFirst().get();

                                if (existBo.getChecked() == null || (existBo.getChecked() != null && !existBo.getChecked())) {
                                    existBo.setChecked(bo.getChecked());
                                }
                            }
                        }
                        privilegesSet.addAll(tiledList);
                    }

                }
            }
            Set<Long> checkedMenuIds = privilegesSet.stream().filter(p -> p.getChecked()).map(PrivilegeTreeBO::getId).collect(Collectors.toSet());

            //同步菜单
            privilegesSet = new HashSet<>(menuService.syncMenu(privilegesSet));
            privilegesSet = privilegesSet.stream().filter(p -> checkedMenuIds.contains(p.getId())).collect(Collectors.toSet());
        }
        return privilegesSet;
    }

    @Override
    public Set<PrivilegeTreeBO> privilegesTree(String token) {
        Set<PrivilegeTreeBO> mergePrivilegeTree = this.privilegesList(token);
        List<PrivilegeTreeBO> trees = (List<PrivilegeTreeBO>) TreeUtil.buildTree(mergePrivilegeTree);
        Set<PrivilegeTreeBO> results = Sets.newTreeSet((o1, o2) -> {
            int num = o1.getOrderNum() - o2.getOrderNum();
            return num == 0 ? 1 : num;
        });
        results.addAll(trees);
        return results;
    }

    @Override
    public void saveOrUpdateById(User user) {
        userMapper.saveOrUpdateById(user);
    }

    @Override
    public Page<UserVO> xPage(Page page, UserVO userVO) {
        Page<UserVO> result = userMapper.xPage(page,userVO);
        return result;
    }

    @Transactional
    @Override
    public Boolean xUpdate(UserVO user) {
        this.update(user);
        userPostService.remove(new LambdaQueryWrapper<UserPost>().eq(UserPost::getUserId,user.getId()));
        List<IdNameVO> vos = user.getUserPosts();
        Set<Long> postIds = vos.stream().map(IdNameVO::getId).collect(Collectors.toSet());
        if (CollectionUtils.isNotEmpty(postIds)){
            userPostService.checkMultiPostInMarketDepartment(postIds);
        }
        Set<UserPost> xUserPosts = vos.stream().map(x -> {
            UserPost userPost = new UserPost();
            userPost.setUserId(user.getId());
            userPost.setPostId(x.getId());
            return userPost;
        }).collect(Collectors.toSet());
        return userPostService.saveBatch(xUserPosts);
    }

    @Transactional
    @Override
    public Boolean xSave(UserVO user) {
        //生成员工工号，生成规则：公司前缀+入职年份+身份证号码后三位
        int year = user.getHireDate().getYear();
        user.setStaffNo(STAFF_NO_PREFIX + year + user.getIdNo().substring(15,18));
        user.setPassword(DigestUtils.getMD5String(DEFAULT_PASSWORD));
        user.setSettlePassword(DigestUtils.getMD5String(DEFAULT_PASSWORD));
        this.save(user);
        List<IdNameVO> userPosts = user.getUserPosts();
        Set<Long> postIds = userPosts.stream().map(IdNameVO::getId).collect(Collectors.toSet());
        if (CollectionUtils.isNotEmpty(postIds)){
            userPostService.checkMultiPostInMarketDepartment(postIds);
        }
        if (CollectionUtils.isNotEmpty(userPosts)){
            Set<UserPost> xUserPosts = userPosts.stream().map(x -> {
                UserPost userPost = new UserPost();
                userPost.setUserId(user.getId());
                userPost.setPostId(x.getId());
                return userPost;
            }).collect(Collectors.toSet());
            return userPostService.saveBatch(xUserPosts);
        }
        return Boolean.TRUE;
    }

    @Override
    public Boolean restPassword(Long id) {
        return this.update(new LambdaUpdateWrapper<User>()
                .set(User::getPassword,DigestUtils.getMD5String(DEFAULT_PASSWORD))
                .set(User::getPasswordState,Boolean.TRUE)
                .eq(BaseEntity::getId,id));
    }

    @Override
    public Boolean updatePassword(UpdatePasswordDTO passwordDTO) {
        if (!StrUtil.equals(passwordDTO.getCurrentPassword(),passwordDTO.getRepeatPassword())){
            ErrorCode.throwBusinessException(ErrorCode.PASSWORD_DIFFERENT);
        }
        User user = this.getById(LoginContext.getUserId());

        if (!StrUtil.equals(user.getPassword(),passwordDTO.getOriginalPassword())){
            ErrorCode.throwBusinessException(ErrorCode.PASSWORD_ERROR);
        }

        boolean update = this.update(new LambdaUpdateWrapper<User>()
                .set(User::getPassword, passwordDTO.getCurrentPassword())
                        .set(User::getPasswordState,Boolean.FALSE)
                .eq(BaseEntity::getId, user.getId()));
        return update;
    }

    /**
     * 获取登录人下属员工集合
     * @param userId
     * @return培育
     */
    @Override
    public Set<Long> getJuniorUserId(Long userId) {
        Set<Long> juniorUser = new HashSet<>();
        Set<Long> juniorPost = new HashSet<>();
                //当前登录人拥有的岗位集合
        Set<Long> postIds = userPostService.getPostList(userId).stream().map(SimpleListModel::getId).collect(Collectors.toSet());
        if (CollectionUtils.isNotEmpty(postIds)){
            //获取登录人岗位的下属岗位
            juniorPost = findJuniorPost(postIds,juniorPost);

            if (CollectionUtils.isNotEmpty(juniorPost)){
                //获取下属岗位的员工
                juniorUser = userPostService.getPostUserId(juniorPost);
            }
        }
        return juniorUser;
    }

    @Override
    public Set<LeaderRatioBO> getLeaderRatioBO(Long userId) {
        Set<Long> parentPostIds = new HashSet<>();
        Set<LeaderRatioBO> leaderRatioBOS = new HashSet<>();
        List<SimplePostModel> postList = userPostService.getPostList(userId);
        for (SimplePostModel simplePostModel :postList){
            parentPostIds.addAll(getLeaderPostInDepartment(simplePostModel.getId(), simplePostModel.getDepartmentId(), parentPostIds));
        }
        if (CollectionUtils.isNotEmpty(parentPostIds)){
            //需要排除当前userId,因为领导有可能设置成自己
            leaderRatioBOS = brokeragePostRatioMapper.getLeadersRatio(parentPostIds,userId);

        }
        return leaderRatioBOS;
    }

    public Set<Long> getLeaderPostInDepartment(Long postId,Long departmentId,Set<Long> parentPostIds){
        Post post = postService.getById(postId);
        if (post.getParentId()!=null){
            Post postParent = postService.getById(post.getParentId());
            if (postParent.getDepartmentId().equals(departmentId)){
                parentPostIds.add(postParent.getId());
                getLeaderPostInDepartment(postParent.getId(),departmentId,parentPostIds);
            }
        }
        return parentPostIds;
    }

    @Override
    public Set<Long> getDepartmentIdByUserId(Long userId) {
        return userMapper.getDepartmentIdByUserId(userId);
    }

    @Override
    public List<User> simplePostName(String postName) {
        List<User> list = userMapper.simplePostName(postName);
        return list;
    }

    @Override
    public List<UserVO> listPostName(String postName) {
        List<UserVO> list = userMapper.listPostName(postName);
        return list;
    }

    @Override
    public Set<LeaderRatioBO> getLeaderRatioBO(Set<Long> leaderIds) {
        Set<LeaderRatioBO> set = brokeragePostRatioMapper.getLeaderRatioBO(leaderIds);
        return set;
    }

    @Override
    public Set<LeaderRatioBO> marketManagerRatioBO() {
        Set<LeaderRatioBO> set = brokeragePostRatioMapper.marketManagerRatioBO();
        return set;
    }

    @Override
    public List<IdNameVO> usersByDepartment(String departmentName) {
        List<IdNameVO> list = userMapper.usersByDepartment(departmentName);
        return list;
    }

    @Override
    public Boolean resetSettlePassword(Long id) {
        return this.update(new LambdaUpdateWrapper<User>()
                .set(User::getSettlePassword,DigestUtils.getMD5String(DEFAULT_PASSWORD))
                .eq(BaseEntity::getId,id));
    }

    @Override
    public Boolean updateSettlePassword(UpdatePasswordDTO passwordDTO) {
        if (!StrUtil.equals(passwordDTO.getCurrentPassword(),passwordDTO.getRepeatPassword())){
            ErrorCode.throwBusinessException(ErrorCode.PASSWORD_DIFFERENT);
        }
        User user = this.getById(LoginContext.getUserId());

        if (!StrUtil.equals(user.getSettlePassword(),passwordDTO.getOriginalPassword())){
            ErrorCode.throwBusinessException(ErrorCode.PASSWORD_ERROR);
        }

        boolean update = this.update(new LambdaUpdateWrapper<User>()
                .set(User::getSettlePassword, passwordDTO.getCurrentPassword())
                .eq(BaseEntity::getId, user.getId()));
        return update;
    }

    @Override
    public Boolean validSettlePassword(String settlePassword) {
        User user = this.getById(LoginContext.getUserId());
        if (!StrUtil.equals(user.getSettlePassword(),settlePassword)){
            ErrorCode.throwBusinessException(ErrorCode.SETTLE_PASSWORD_ERROR);
        }
        return Boolean.TRUE;
    }

    @Override
    public List<IdNameVO> usersByDepartments(List<String> departmentNames) {
        List<IdNameVO> idNameVOS = userMapper.usersByDepartments(departmentNames);
        return idNameVOS;
    }

    @Override
    public Long getLeaderByCurrentUser() {
        LoginCacheUserBO loginCacheUserBO = LoginContext.getLoginCacheUserBO();
        List<SimplePostModel> postList = loginCacheUserBO.getPostList();
        Set<Long> collect = postList.stream().map(SimplePostModel::getDepartmentId).collect(Collectors.toSet());
        if (collect.size()!=1){
            return null;
        }
        for (SimplePostModel simplePostModel : postList){
            //上级岗位id
            Long parentId = simplePostModel.getParentId();
            if (parentId!=null){
                //上级岗位所属部门id
                Long departmentId = postService.getOne(new LambdaQueryWrapper<Post>().select(Post::getDepartmentId).eq(BaseEntity::getId, parentId)
                        .eq(BaseEntity::getDeleted, Boolean.FALSE)).getDepartmentId();
                if (simplePostModel.getDepartmentId().equals(departmentId)){
                    List<UserPost> list = userPostService.list(new LambdaQueryWrapper<UserPost>().eq(UserPost::getPostId, parentId)
                            .eq(BaseEntity::getDeleted, Boolean.FALSE));
                    if (CollectionUtils.isNotEmpty(list) && list.size()==1){
                        return list.get(0).getUserId();
                    }
                }else {
                    return loginCacheUserBO.getId();
                }
            }
        }
        return null;
    }

    @Override
    public List<User> byDepartmentId(Long id) {
        if (id==null){
           ErrorCode.throwBusinessException(CUSTOM_ERROR,"获取部门员工失败。");
        }
        return  userMapper.byDepartmentId(id);
    }

    @Override
    public List<PullDownModel> allotDepartmentUsers(String businessType) {
        Set<Long> departmentIds = sortedDepartmentService.list(new LambdaQueryWrapper<SortedDepartment>()
            .select(SortedDepartment::getDepartmentId)
            .eq(SortedDepartment::getBusinessType, businessType).eq(BaseEntity::getDeleted, Boolean.FALSE))
            .stream().map(SortedDepartment::getDepartmentId).collect(Collectors.toSet());
        if (CollectionUtils.isNotEmpty(departmentIds)){
            return userMapper.allotDepartmentUsers(departmentIds);
        }
        return null;
    }

    @Override
    public List<User> infoPostName(String postName) {
        List<User> list = userMapper.infoPostName(postName);
        return list;
    }

    @Override
    public List<DepartmentUserVO> departmentUsers() {
        LoginCacheUserBO loginCacheUserBO = LoginContext.getLoginCacheUserBO();
        List<SimpleParentModel> departmentList = loginCacheUserBO.getDepartmentList();
        List<DepartmentUserVO> collect = departmentList.stream().map(x -> {
            DepartmentUserVO departmentUserVO = new DepartmentUserVO();
            departmentUserVO.setName(x.getName());
            List<User> users = userMapper.byDepartmentId(x.getId());
            departmentUserVO.setUsers(BeanUtil.copyToList(users, IdNameVO.class));
            return departmentUserVO;
        }).collect(Collectors.toList());
        return collect;
    }

    /**
     * 获取资产评估师用户
     * @return List<User>
     */
    @Override
    public List<User> byAssetEvaluator() {
        return userMapper.byAssetEvaluator();
    }

    /**
     * 根据部门名称获取部门及其下辖部门人员
     * @param depName 部门
     * @return List<User>
     */
    @Override
    public List<User> byDepartmentName(String depName) {
        return userMapper.byDepartmentName(depName);
    }

    @Override
    public Boolean notRemind() {
        Long currentUserId = LoginContext.getCurrentUserId();
        return this.update(new LambdaUpdateWrapper<User>().set(User::getPasswordState,false).eq(BaseEntity::getId,currentUserId));
    }

    /**
     * 递归查询下级岗位
     * @param postIds
     * @param juniorPost
     * @return
     */
    private Set<Long> findJuniorPost(Set<Long> postIds,Set<Long> juniorPost){
        Set<Long> collect = postService.list(new LambdaQueryWrapper<Post>().select(BaseEntity::getId)
                .in(Post::getParentId, postIds).eq(BaseEntity::getDeleted, Boolean.FALSE)).stream().map(BaseEntity::getId).collect(Collectors.toSet());
        if (CollectionUtils.isEmpty(collect)){
            return juniorPost;
        }else {
            juniorPost.addAll(collect);
            findJuniorPost(collect,juniorPost);
        }
        return juniorPost;
    }
}
