/**
 * Copyright &copy; 2021-2026 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.sys.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.jeeplus.common.SecurityUtils;
import com.jeeplus.common.TokenProvider;
import com.jeeplus.common.constant.CacheNames;
import com.jeeplus.common.constant.CommonConstants;
import com.jeeplus.common.redis.RedisUtils;
import com.jeeplus.common.utils.RequestUtils;
import com.jeeplus.core.query.QueryWrapperGenerator;
import com.jeeplus.flowable.feign.IHumanApi;
import com.jeeplus.sys.domain.*;
import com.jeeplus.sys.feign.IDictApi;
import com.jeeplus.sys.feign.IUserApi;
import com.jeeplus.sys.mapper.OfficeMapper;
import com.jeeplus.sys.mapper.UserSignatureInfoMapper;
import com.jeeplus.sys.mapper.UserMapper;
import com.jeeplus.sys.service.dto.*;
import com.jeeplus.sys.service.mapstruct.CertWrapper;
import com.jeeplus.sys.service.mapstruct.UserWrapper;
import com.jeeplus.sys.utils.UserUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 用户管理
 *
 * @author jeeplus
 * @version 2021-09-05
 */
@Service
@Transactional
public class UserService extends ServiceImpl<UserMapper, User> {

    // 通过 -?[0-9]+(\\\\.[0-9]+)? 进行匹配是否为数字
    private static Pattern pattern = Pattern.compile("-?[0-9]+(\\\\.[0-9]+)?");

    @Autowired
    private UserWrapper userWrapper;

    @Resource
    private UserMapper userMapper;

    @Autowired
    private OfficeService officeService;

    @Autowired
    private OfficeMapper officeMapper;

    @Autowired
    private UserSignatureInfoMapper userSignatureInfoMapper;

    @Autowired
    private SysConfigService sysConfigService;

    @Autowired
    private CertService certService;

    @Autowired
    private RedisUtils redisUtils;

    public UserDTO getByOpenId(String openId) {
        return baseMapper.getByOpenId(openId);
    }

    public UserDTO getByDdId(String ddId) {
        return baseMapper.getByDdId(ddId);
    }

    public UserDTO getByDdIdAndTenantId(String ddId, String tenantId) {
        return baseMapper.getByDdIdAndTenantId(ddId, tenantId);
    }

    public List<String> getAllOpenIds() {
        return baseMapper.getAllOpenIds();
    }

    public List<String> getOpenIdsByIds(List<String> ids) {
        return baseMapper.getOpenIdsByIds(ids);
    }

    public List<String> getNamesByIds(List<String> ids) {
        return baseMapper.getNamesByIds(ids);
    }



    /**
     * 根据用户id 查询该用户会计报告的签字注师被选择次数
     *
     * @param userId
     * @return
     */
    public Integer getAccountantUserCount(String userId) {
        Calendar cal = Calendar.getInstance();
        String yearStr = String.valueOf(cal.get(Calendar.YEAR));
        yearStr = yearStr + "-";
        return userMapper.getAccountantUserCount(userId, yearStr);
    }

    public List<CertDTO> getCertListByUserId() {
        return userMapper.getCertListByUserId();
    }

    //	保存人员执业资质
    public void saveCertList(UserDTO userDTO) {
        if (ObjectUtil.isNotEmpty(userDTO)) {
            if (CollectionUtil.isNotEmpty(userDTO.getCertDTOList())) {
                List<String> ids = userDTO.getCertDTOList().stream().filter(item -> {
                    if (StringUtils.isNotBlank(item.getId())) {
                        return true;
                    }
                    return false;
                }).map(CertDTO::getId).collect(Collectors.toList());
                if (CollectionUtil.isNotEmpty(ids)) {
                    certService.remove(new QueryWrapper<Cert>().lambda().eq(Cert::getUserId, userDTO.getId()).notIn(Cert::getId, ids));
                } else {
                    certService.remove(new QueryWrapper<Cert>().lambda().eq(Cert::getUserId, userDTO.getId()));
                }
                userDTO.getCertDTOList().stream().forEach(item -> {
                    Cert cert = CertWrapper.INSTANCE.toEntity(item);
                    cert.setUserId(userDTO.getId());
                    cert.setStatus("5");//管理员添加资质，状态直接为5
                    certService.saveOrUpdate(cert);
                });
            } else {
                certService.remove(new QueryWrapper<Cert>().lambda().eq(Cert::getUserId, userDTO.getId()));
            }
        }
    }


    /**
     * 根据角色英文名称查询角色下人员信息
     *
     * @param enName 角色英文名称
     * @return
     */
    public List<UserDTO> getUserInfoByEnName(String enName) {
        return userMapper.getUserInfoByEnName(enName);
    }


    /**
     * 根据登录名获取用户
     *
     * @param name
     * @return
     */
    public UserDTO getUserByName(String name) {
        UserDTO userDTO = userMapper.getUserByName(name);
        return userDTO;
    }

    /**
     * 获取用户
     *
     * @param id
     * @return
     */
    public UserDTO get(String id) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("a.id", id);
        queryWrapper.eq("a.del_flag", CommonConstants.NOT_DELETED); // 排除已经删除
        UserDTO userDTO = baseMapper.get(queryWrapper);
        //根据用户id查询其管理部门
        if (null != userDTO && StringUtils.isNotBlank(userDTO.getId())) {
            String manageOfficeIdsById = baseMapper.getManageOfficeIdsById(userDTO.getId());
            if (StringUtils.isNotBlank(manageOfficeIdsById)) {
                userDTO.setManageOfficeIds(manageOfficeIdsById);
                //获取当前人管理的部门id
                List<String> manageOfficeIdList = Arrays.asList(userDTO.getManageOfficeIds().split(","));
                //查询这些部门信息
                List<String> officeNameList = officeService.getOfficeNameByIds(manageOfficeIdList);
                userDTO.setManageOfficeNameList(officeNameList);
            }
            // user表中没有身份证信息，通过入职那边查询
            String idCard = SpringUtil.getBean(IHumanApi.class).findIdCardByUserId(userDTO.getId());
            if(StringUtils.isNotBlank(idCard)){
                userDTO.setIdCard(idCard);
            }
        }
        return userDTO;
    }

    /**
     * 获取用户
     *
     * @param id
     * @return
     */
    public UserDTO getFlowAbleById(String id) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("a.id", id);
        queryWrapper.eq("a.del_flag", CommonConstants.NOT_DELETED); // 排除已经删除
        return userMapper.getFlowAbleById(queryWrapper);
    }

    /**
     * 根据登录名获取用户
     *
     * @param loginName
     * @return
     */
    public UserDTO getUserByLoginName(String loginName, String tenantId) {
        UserDTO userDTO = (UserDTO) RedisUtils.getInstance().get(CacheNames.USER_CACHE_LOGIN_NAME, tenantId + ":" + loginName);
        if (userDTO == null) {
            QueryWrapper queryWrapper = new QueryWrapper();
            //判断是否是用手机号登录
            Matcher m = pattern.matcher(loginName);
            if (m.matches()) {
                queryWrapper.eq("a.mobile", loginName);
            } else {
                queryWrapper.eq("a.login_name", loginName);
            }

            queryWrapper.eq("a.del_flag", CommonConstants.NOT_DELETED);

            String domain = RequestUtils.getHeader("domain");
            if (domain.contains("ydddl")) {
                tenantId = "";
            }

            if (StringUtils.isNotBlank(tenantId)) {
                queryWrapper.eq("a.tenant_id", tenantId);
            }

            userDTO = baseMapper.get(queryWrapper);
            RedisUtils.getInstance().set(CacheNames.USER_CACHE_LOGIN_NAME, tenantId + ":" + loginName, userDTO);
        }

        return userDTO;
    }

    /**
     * 根据登录名获取用户
     *
     * @param loginName
     * @return
     */
    public UserDTO getByLoginNameNotTenantId(String loginName) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("a.login_name", loginName);
        queryWrapper.eq("a.del_flag", CommonConstants.NOT_DELETED);
        UserDTO userDTO = baseMapper.get(queryWrapper);
        return userDTO;
    }


    /**
     * 自定义分页检索
     *
     * @param page
     * @param queryWrapper
     * @return
     */
    public IPage<UserDTO> findPage(Page<UserDTO> page, QueryWrapper queryWrapper) {
        queryWrapper.eq("a.del_flag", CommonConstants.NOT_DELETED); // 排除已经删除
        IPage<UserDTO> list = baseMapper.findList(page, queryWrapper);
        for (UserDTO record : list.getRecords()) {
            if (CollectionUtil.isNotEmpty(record.getRoleDTOList())) {
                StringBuilder names = new StringBuilder();

                for (RoleDTO roleDTO : record.getRoleDTOList()) {
                    if (names.length() > 0) {
                        names.append(",");  // 只有在已有内容的情况下才添加逗号
                    }
                    names.append(roleDTO.getName());
                }
                record.setRole(names.toString());
            }
            if (CollectionUtil.isNotEmpty(record.getPostDTOList())) {
                StringBuilder names = new StringBuilder();

                for (PostDTO postDTO : record.getPostDTOList()) {
                    if (names.length() > 0) {
                        names.append(",");  // 只有在已有内容的情况下才添加逗号
                    }
                    names.append(postDTO.getName());
                }
                record.setPost(names.toString());
            }
        }
        return list;
    }

    /**
     * 签字注师用户查询
     *
     * @param page
     * @param queryWrapper
     * @return
     */
    public IPage<UserDTO> findUserList(Page<UserDTO> page, QueryWrapper queryWrapper) {
        queryWrapper.eq("a.del_flag", CommonConstants.NOT_DELETED); // 排除已经删除
        IPage<UserDTO> list = baseMapper.findUserList(page, queryWrapper);
        for (UserDTO record : list.getRecords()) {
            if (CollectionUtil.isNotEmpty(record.getRoleDTOList())) {
                StringBuilder names = new StringBuilder();

                for (RoleDTO roleDTO : record.getRoleDTOList()) {
                    if (names.length() > 0) {
                        names.append(",");  // 只有在已有内容的情况下才添加逗号
                    }
                    names.append(roleDTO.getName());
                }
                record.setRole(names.toString());
            }
            if (CollectionUtil.isNotEmpty(record.getPostDTOList())) {
                StringBuilder names = new StringBuilder();

                for (PostDTO postDTO : record.getPostDTOList()) {
                    if (names.length() > 0) {
                        names.append(",");  // 只有在已有内容的情况下才添加逗号
                    }
                    names.append(postDTO.getName());
                }
                record.setPost(names.toString());
            }
        }
        return list;
    }




    /**
     * 自定义分页检索
     *
     * @param page
     * @param queryWrapper
     * @return
     */
    public IPage<UserDTO> findMemberPage(Page<UserDTO> page, QueryWrapper queryWrapper) {
        queryWrapper.eq("a.del_flag", CommonConstants.NOT_DELETED); // 排除已经删除
        if (!SecurityUtils.getCurrentUserDTO().isAdmin()) {
            //根据当前人的所属公司查该公司下的所有人员信息
            UserDTO userDTO = SpringUtil.getBean(IUserApi.class).getByToken(TokenProvider.getCurrentToken());
            queryWrapper.eq("a.company_id", userDTO.getCompanyDTO().getId());

        }
        return baseMapper.findList(page, queryWrapper);


    }


    /**
     * 自定义分页检索
     *
     * @param page
     * @param queryWrapper
     * @return
     */
    public IPage<UserDTO> userFindPage(Page<UserDTO> page, QueryWrapper queryWrapper) {
        queryWrapper.eq("a.del_flag", CommonConstants.NOT_DELETED); // 排除已经删除
        queryWrapper.orderByDesc("a.id");

        return baseMapper.userFindPage(page, queryWrapper);

    }


    public IPage<UserDTO> findPage2(Page<UserDTO> page, QueryWrapper queryWrapper) {
        queryWrapper.eq("a.del_flag", CommonConstants.NOT_DELETED); // 排除已经删除
        return baseMapper.findList2(page, queryWrapper);


    }

    /**
     * 查询角色下关联的用户
     *
     * @param page
     * @param queryWrapper
     * @return
     */
    public IPage<UserDTO> findPageByRole(Page<UserDTO> page, QueryWrapper queryWrapper) {
        queryWrapper.eq("a.del_flag", CommonConstants.NOT_DELETED); //排除已经删除
        return baseMapper.findListByRole(page, queryWrapper);


    }

    /**
     * 查询角色下关联的用户
     *
     * @param roleId
     * @return
     */
    public List<UserDTO> findListByRoleId(String roleId) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("a.del_flag", CommonConstants.NOT_DELETED); //排除已经删除
        queryWrapper.eq("r.id", roleId);

        Page<UserDTO> page = new Page<>();
        page.setSize(-1);
        return baseMapper.findListByRole(page, queryWrapper).getRecords();
    }

    /**
     * 查询岗位下关联的用户
     *
     * @param postId
     * @return
     */
    public List<UserDTO> findListByPostId(String postId) {
        return baseMapper.findListByPostId(postId);
    }


    /**
     * 查询岗位下关联的用户
     *
     * @param postId
     * @return
     */
    public List<UserDTO> findListFlowAbleByPostId(String postId) {
        return baseMapper.findListFlowAbleByPostId(postId);
    }


    /**
     * 保存或者更新用户
     *
     * @param userDTO
     */
    public void saveOrUpdate(UserDTO userDTO) {
        User user = userWrapper.toEntity(userDTO);
        if (StringUtils.isNotBlank(userDTO.getOpenId())) {
            user.setOpenId(userDTO.getOpenId());
        }
        if (StringUtils.isNotBlank(userDTO.getManageOfficeIds())) {
            user.setManageOfficeIds(userDTO.getManageOfficeIds());
        }
        user.setDdId(userDTO.getDdId());
        if (StringUtils.isNotBlank(userDTO.getNo())) {
            user.setNo(userDTO.getNo());
        }
        super.saveOrUpdate(user);
        if (StrUtil.isBlank(userDTO.getId())) {
            userDTO.setId(user.getId());
        }
        // 更新用户与角色关联
        baseMapper.deleteUserRole(userDTO.getId());
        if (userDTO.getRoleDTOList() != null) {
            userDTO.getRoleDTOList().forEach(roleDTO -> {
                baseMapper.insertUserRole(userDTO.getId(), roleDTO.getId());
            });
        } else {
            throw new RuntimeException(userDTO.getLoginName() + "没有设置角色！");
        }
        // 更新用户与岗位联系
        baseMapper.deleteUserPost(userDTO.getId());
        if (userDTO.getPostDTOList() != null) {
            userDTO.getPostDTOList().forEach(postDTO -> {
                baseMapper.insertUserPost(userDTO.getId(), postDTO.getId());
            });
            syncUserSignatureTwoInfo(userDTO.getId());
        }
        UserUtils.deleteCache(userDTO);
        //判断redis中是否有这个key
        if (redisUtils.hasKey("user:cache:user:all:info")) {
            //先清除redis中的数据
            redisUtils.delete(CacheNames.USER_CACHE_USER_ALL_INFO, "user:cache:user:all:info");
            //获取全部的人员信息
            List<UserDTO> allUserInfo = userMapper.getAllUserInfo();
            //再次将人员信息存入到redis中
            redisUtils.set(CacheNames.USER_CACHE_USER_ALL_INFO, "user:cache:user:all:info", allUserInfo);
        } else {
            //获取全部的人员信息
            List<UserDTO> allUserInfo = userMapper.getAllUserInfo();
            //再次将人员信息存入到redis中
            redisUtils.set(CacheNames.USER_CACHE_USER_ALL_INFO, "user:cache:user:all:info", allUserInfo);
        }
        /**
         * 更新用户管理部门
         */
        if (StringUtils.isNotBlank(user.getManageOfficeIds())) {
            //查询该用户在sys_user_manage_office中是否有数据
            List<UserManageOffice> userManageOffices = userMapper.getManageOffices(userDTO.getId());
            if (CollectionUtil.isNotEmpty(userManageOffices)) {
                //将原本的数据进行删除
                userMapper.deleteByUserId(user.getId());
            }
            //将用户管理部门新增进用户管理部门表中
            if (user.getManageOfficeIds().contains(",")) {
                String[] split = user.getManageOfficeIds().split(",");
                for (String s : split) {
                    userMapper.insertUserManageOffice(userDTO.getId(), s);
                }
            } else {
                userMapper.insertUserManageOffice(userDTO.getId(), userDTO.getManageOfficeIds());
            }
        } else {
            userMapper.deleteByUserId(user.getId());
        }

    }


    public void deleteUser(UserDTO userDTO) {
        baseMapper.deleteUserRole(userDTO.getId());
        baseMapper.deleteUserPost(userDTO.getId());
        super.removeById(userDTO.getId());
        UserUtils.deleteCache(userDTO);
    }

    /**
     * 单一登录判断，是否允许登录
     *
     * @return
     */
    public boolean isEnableLogin(String tenantId, String loginName) {
        SysConfig sysConfig = sysConfigService.getById("1");
        if (sysConfig.getMultiAccountLogin().equals(CommonConstants.NO)) { // 不允许一个账号多个客户端登录
            if (sysConfig.getSingleLoginType().equals("1")) { // 后登陆踢出先登录

                UserUtils.getOnlineUsers().forEach(userDTO -> {
                    if (tenantId.equals(userDTO.getTenantDTO().getId()) && loginName.equals(userDTO.getLoginName())) {
                        RedisUtils.getInstance().set(CacheNames.USER_CACHE_TOKEN, userDTO.getToken(), "kickOut");
                        RedisUtils.getInstance().delete(CacheNames.USER_CACHE_ONLINE_USERS, userDTO.getToken());
                    }
                });

            } else { // 已经登陆禁止再登录
                int size = UserUtils.getOnlineUsers().stream().filter(userDTO ->
                        tenantId.equals(userDTO.getTenantDTO().getId()) && loginName.equals(userDTO.getLoginName())
                ).collect(Collectors.toList()).size();
                if (size > 0) {
                    return false;
                }
                ;
            }
        }
        return true;
    }

    /**
     * 根据部门id获取 部门 以及 子部门 下的所有用户信息
     *
     * @param officeId
     * @return
     */
    public List<User> getUserByOfficeAll(String officeId) {
        List<Office> officeList = officeMapper.selectList(new QueryWrapper<Office>().lambda().eq(Office::getParentId, officeId));
        List<String> officeIdList = officeList.stream().distinct().map(Office::getId).collect(Collectors.toList());
        while (true) {
            List<String> ids = new ArrayList<>();
            officeIdList.stream().forEach(item -> {
                List<Office> officeList1 = officeMapper.selectList(new QueryWrapper<Office>().lambda().eq(Office::getParentId, item));
                officeList1.stream().forEach(i -> {
                    officeList.add(i);
                    ids.add(i.getId());
                });
            });
            if (CollectionUtil.isNotEmpty(ids)) {
                officeIdList = ids;
            } else {
                break;
            }
        }
        List<String> officeIds = officeList.stream().distinct().filter(item -> {
            if (StringUtils.isNotBlank(item.getId())) {
                return true;
            }
            return false;
        }).map(Office::getId).collect(Collectors.toList());
        officeIds.add(officeId);
        return this.list(new QueryWrapper<User>().lambda().in(User::getOfficeId, officeIds));
    }

    /**
     * 根据用户name获取用户id
     *
     * @param name
     * @return
     */
    public String getUserIdByName(String name) {
        return userMapper.getUserIdByName(name);
    }

    /**
     * 根据用户name获取用户id
     *
     * @param name
     * @return
     */
    public String getUserIdByUserName(String name) {
        return userMapper.getUserIdByUserName(name);
    }

    //根据部门查询用户信息
    public List<OfficeDTO> getUserByOffice(List<String> officeIds, String type) {
        return userMapper.getUserByOffice(officeIds, type);
    }

    /**
     * 修改用户更新密码状态信息
     *
     * @param userDTO
     */
    public void updateUserUpPassword(UserDTO userDTO) {
        baseMapper.updateUserUpPassword(userDTO);
    }

    public List<User> selectListByName(String name) {
        return userMapper.selectListByName(name);
    }

    public List<User> findListByLikeName(String name) {
        return userMapper.findListByLikeName(name);
    }



    /**
     * 签字注师查询用户权限所用
     *
     * @param userDTO
     * @return
     */
    public IPage<UserDTO> findPage3(UserDTO userDTO) {
        Page<UserDTO> page = new Page<>();
        if (null != userDTO) {
            if (null != userDTO.getOfficeDTO() && StringUtils.isNotBlank(userDTO.getOfficeDTO().getId())) {

                List<UserDTO> list1 = baseMapper.findList3(userDTO.getOfficeDTO().getId(), userDTO.getLoginName());
                page.setRecords(list1);
            } else {
                List<UserDTO> list1 = baseMapper.findList3("", userDTO.getLoginName());
                page.setRecords(list1);
            }
        } else {
            List<UserDTO> list1 = Lists.newArrayList();
            page.setRecords(list1);
        }
        return page;
    }

    /**
     * 查询签字注师二信息列表
     *
     * @param page
     * @param
     * @return
     */
    public IPage<UserDTO> findPage1(UserDTO dto, Page<UserDTO> page) {
        QueryWrapper<UserDTO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("post.NAME","签字注师2");
        queryWrapper.eq("post.del_flag ","0");
        queryWrapper.eq("sc.type","6");
        if(StringUtils.isNotBlank(dto.getCompanyDTO().getId())){
            queryWrapper.eq("a.company_id",dto.getCompanyDTO().getId());
        }
        IPage<UserDTO> list1 = baseMapper.findUserList2(page, queryWrapper);
        //List<UserDTO> list1 = baseMapper.findList1(dto, companyId);
        return list1;
    }

    /**
     *根据签字注师id查询签章份数
     *
     * @param
     * @return
     */
    public UserDTO findCountById(String userId) {
        QueryWrapper<UserDTO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("a.id",userId);
        UserDTO result = baseMapper.findCountById(queryWrapper);
        Integer accountantUserCount = getAccountantUserCount(result.getId());
        result.setAccountantUserCount(accountantUserCount);
        return result;
    }


    /**
     *添加默认的签字注师1，100次可签章份数
     *
     * @param
     * @return
     */
    public void addDefaultSignatureCount(String userId) {
        UserSignatureInfo info = userSignatureInfoMapper.findById(userId);
        if(info == null){
            UserSignatureInfo userSignatureInfo = new UserSignatureInfo();
            userSignatureInfo.setSignatureCount("100");
            userSignatureInfo.setUserId(userId);
            userSignatureInfo.setCreateById("1");
            userSignatureInfo.setUpdateById("1");
            userSignatureInfoMapper.insert(userSignatureInfo);
        }
    }


    /**
     *同步签字注师2的签章信息
     */
    public void syncUserSignatureTwoInfo(String userId) {
        UserDTO userDTO = baseMapper.findUserList(
                new Page<>(1, 1),
                new QueryWrapper<UserDTO>()
                        .eq("a.del_flag", CommonConstants.NOT_DELETED)
                        .eq("sc.type", "6")
                        .eq("a.id", userId)
        ).getRecords().stream().findFirst().orElse(null);

        if (userDTO == null) {
            return;
        }
        String post = userDTO.getPost();
        String count = userDTO.getSignatureCount();
        if ("签字注师2".equals(post) && !"9999".equals(count)) {
            updateSignatureCount(userId, "9999");
            return;
        }
        if (!"签字注师2".equals(post) && "9999".equals(count)) {
            updateSignatureCount(userId, "100");
        }
    }


    /**
     * 查询签字注师二信息集合
     *
     * @param dto
     * @return
     */
    public List<UserDTO> getSignatureAnnotator2List(UserDTO dto) {
        OfficeDTO officeDTO = dto.getCompanyDTO();
        String companyId = "";
        if (null != officeDTO) {
            companyId = officeDTO.getId();
        }
        List<UserDTO> signatureAnnotator2List = baseMapper.findList1(dto, companyId);
        return signatureAnnotator2List;
    }

    public Boolean isUpdatePassword(String userId) {
        String updatePassword = userMapper.isUpdatePassword(userId);
        if (StringUtils.isNotBlank(updatePassword)) {
            if ("1".equals(updatePassword)) {
                // 密码已经修改过
                return true;
            }
        }
        return false;
    }

    /**
     * 岗位分页检索
     *
     * @param
     * @param
     * @return
     */
    public List<String> findOffId() {
        UserDTO dto = new UserDTO();
        OfficeDTO officeDTO = dto.getCompanyDTO();
        String companyId = "";
        if (null != officeDTO) {
            companyId = officeDTO.getId();
        }
        List<UserDTO> list1 = baseMapper.findList1(dto, companyId);
        List<String> list = new ArrayList<>();
        list1.forEach(li -> {
            list.add(li.getOfficeDTO().getId());
        });
        list1.forEach(li -> {
            list.add(li.getCompanyDTO().getId());
        });
        return list;
    }

    /**
     * 岗位分页检索
     *
     * @param
     * @param
     * @return
     */
    public List<String> findAllOffId() {
        UserDTO dto = new UserDTO();
        OfficeDTO officeDTO = dto.getCompanyDTO();
        String companyId = "";
        if (null != officeDTO) {
            companyId = officeDTO.getId();
        }
        List<UserDTO> list1 = baseMapper.findAllList(dto, companyId);
        List<String> list = new ArrayList<>();
        list1.forEach(li -> {
            list.add(li.getOfficeDTO().getId());
        });
        list1.forEach(li -> {
            list.add(li.getCompanyDTO().getId());
        });
        return list;
    }

    /**
     * 获取所有的用户数据
     *
     * @return
     */
    public List<UserDTO> getAllUserInfo() {
        List<UserDTO> allUserInfo = userMapper.getAllUserInfo();
        return allUserInfo;
    }

    /**
     * 获取所有的用户数据
     *
     * @return
     */
    public List<UserDTO> getAllUserInfoByTentId() {
        List<UserDTO> allUserInfo = userMapper.getAllUserInfoByTentId("10001", "10003");
        return allUserInfo;
    }

    /**
     * 查询出拥有权限的用户的部门id
     *
     * @return
     */
    public List<String> hasUser() {
        List<String> hasUser = userMapper.getHasUser();
        List<String> hasUserFather = userMapper.getHasUserFather();
        hasUser.addAll(hasUserFather);

        //获取当前登录人信息
        UserDTO userDTO = UserUtils.getCurrentUserDTO();
        //如果当前登录人是中审的管理咨询部人员，则注会列表中添加该部门选择项
        if (null != userDTO && null != userDTO.getOfficeDTO()) {
            OfficeDTO officeDTO = userDTO.getOfficeDTO();
            if (StringUtils.isNotBlank(officeDTO.getId())) {
                if ("1602840084816138241".equals(officeDTO.getId())) {
                    hasUser.add("1602840084816138241");
                    hasUser.add("1615171302381182978");
                }
            }
        }

        return hasUser;
    }

    public IPage<UserDTO> findCertPage(Page<UserDTO> page, QueryWrapper<UserDTO> queryWrapper) {
        queryWrapper.eq("a.del_flag", CommonConstants.NOT_DELETED); // 排除已经删除
        //queryWrapper.and(qw -> qw.eq("sc.status", "5").or().isNull("sc.status"));
        return baseMapper.findCertList(page, queryWrapper);
    }

    /**
     * 修改用户邮箱
     *
     * @param id
     * @param userEmail
     * @return
     */
    public void updateEmail(String id, String userEmail) {
        userMapper.updateEmail(id, userEmail);
    }

    /**
     * 修改用户是否允许登录状态
     *
     * @param id
     * @param loginFlag
     * @return
     */
    public void updateLoginFlag(String id, String loginFlag) {
        userMapper.updateLoginFlag(id, loginFlag);
    }

    public Integer selectCountByMobile(String mobile) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("mobile", mobile);
        queryWrapper.eq("del_flag", 0);
        // 删除基础信息表
        Integer integer = userMapper.selectCount(queryWrapper);
        return integer;
    }

    /**
     * 根据id获取用户过滤掉tenantId
     *
     * @param id
     * @return
     */
    public UserDTO getByIdNoTenantId(String id) {
        return userMapper.getByIdNoTenantId(id);
    }

    /**
     * 根据id修改用户的del_flag及登录的login_flag
     *
     * @param id
     */
    public void updateDelFlagById(String id) {
        userMapper.updateDelFlagById(id);
    }

    /**
     * 根据用户id查询是否存在“部门主任”岗位
     *
     * @param id
     * @return
     */
    public Integer getUserPostCountById(String id) {
        return userMapper.getUserPostCountById(id);
    }

    public String getMobileById(String id) {
        return userMapper.getMobileById(id);
    }

    public UserDTO getByLoginNameNoTen(String loginName) {
        return userMapper.getByLoginNameNoTen(loginName);
    }

    /**
     * 获取所有的用户信息
     *
     * @return
     */
    public List<UserDTO> getAllUserInfoNoTenId() {
        List<UserDTO> allUserInfo = userMapper.getAllUserInfoNoTenId();
        return allUserInfo;
    }

    /**
     * 修改用户信息
     *
     * @param dto
     */
    public void updateUserById(UserDTO dto) {
        userMapper.updateUserById(dto);
    }

    /**
     * 根据手机号获取用户信息
     *
     * @param mobilePhone
     * @return
     */
    public UserDTO getByMobile(String mobilePhone) {
        return userMapper.getByMobile(mobilePhone);
    }

    public UserDTO selectByMobile(String mobilePhone) {
        return userMapper.selectByMobile(mobilePhone);
    }

    public String getManageOfficeIdsById(String id) {
        return userMapper.getManageOfficeIdsById(id);
    }


    /**
     * 根据登录名和对应租户id查询登陆人员信息
     * @param loginNanme
     * @param tenantId
     * @return
     */
    public List <UserDTO> getOnLineUserList(String loginNanme, String tenantId) {
        UserDTO userDTO= userMapper.getByLoginName(loginNanme,tenantId);
        if (StringUtils.isBlank(tenantId)) {
            tenantId = "10000";
        }
        if(null != userDTO){
            Stream<UserDTO> list = UserUtils.getOnlineUsers ( ).stream ( );
            if ( StrUtil.isNotEmpty ( userDTO.getLoginName ( ) ) ) {
                list = list.filter ( user -> user.getLoginName ( ).contains ( userDTO.getLoginName ( ) ) );

            }
            if ( StrUtil.isNotEmpty ( userDTO.getName ( ) ) ) {
                list = list.filter ( user -> user.getName ( ).contains ( userDTO.getName ( ) ) );
            }
            if ( !CommonConstants.DEFAULT_TENANT_ID.equals ( tenantId ) ) { // 非平台租户只显示租户内在线用户

                String finalTenantId = tenantId;
                list = list.filter (user -> user.getTenantDTO ( ).getId ( ).contains (finalTenantId) );

            }
            List <UserDTO> users = list.collect ( Collectors.toList ( ) );

            return users;
        }

        List <UserDTO> users = Lists.newArrayList();
        return users;

    }
    /**
     * 根据登录名和对应租户id查询登陆人员信息
     * @param tenantId
     * @return
     */
    public List <UserDTO> modifyReportEditFlag( String tenantId) {
        String reportEditFlags = SpringUtil.getBean ( IDictApi.class ).getDictListMapByDict ("report_edit_flag");
        Map<String,Object> paymentStatusValueDTOs = JSON.parseObject(reportEditFlags, new TypeReference<Map<String,Object>>() {});

        for (String key : paymentStatusValueDTOs.keySet()) {
            if("1".equals(key)){
                SpringUtil.getBean ( IDictApi.class ).updateDictValue ("open", "0");
                break;
            }else if("0".equals(key)){
                SpringUtil.getBean ( IDictApi.class ).updateDictValue ("open", "1");
                break;
            }
        }

        if (StringUtils.isBlank(tenantId)) {
            tenantId = "10000";
        }
        redisUtils.delPattern ( "sys:cache:dictMap:*" );


        Stream<UserDTO> list = UserUtils.getOnlineUsers ( ).stream ( );
        if ( !CommonConstants.DEFAULT_TENANT_ID.equals ( tenantId ) ) { // 非平台租户只显示租户内在线用户
            String finalTenantId = tenantId;
            list = list.filter (user -> user.getTenantDTO ( ).getId ( ).contains (finalTenantId) );

        }
        List <UserDTO> users = list.collect ( Collectors.toList ( ) );
        if(null == users){
            users = Lists.newArrayList();
        }
        return users;
    }

    /**
     * 修改注会的可签章份数
     */
    public void updateSignatureCount(String id, String signatureCount) {
        UserSignatureInfo info = userSignatureInfoMapper.findById(id);
        if(info == null){
            UserSignatureInfo userSignatureInfo = new UserSignatureInfo();
            userSignatureInfo.setSignatureCount(signatureCount);
            userSignatureInfo.setUserId(id);
            userSignatureInfo.setCreateById("1");
            userSignatureInfo.setUpdateById("1");
            userSignatureInfoMapper.insert(userSignatureInfo);
        }else{
            userSignatureInfoMapper.update(
                    null,
                    new UpdateWrapper<UserSignatureInfo>()
                            .set("signature_count", signatureCount)
                            .eq("user_id", id)
            );
        }



    }
}
