/**
 * 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.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
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.sys.domain.*;
import com.jeeplus.sys.feign.IUserApi;
import com.jeeplus.sys.mapper.OfficeMapper;
import com.jeeplus.sys.mapper.OtherUserInfoMapper;
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.SnowFlake2;
import com.jeeplus.sys.utils.UserUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;
import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * 用户管理
 *
 * @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;

    @Resource
    private OtherUserInfoMapper otherUserInfoMapper;

    @Autowired
    private OfficeService officeService;

    @Autowired
    private OfficeMapper officeMapper;

    @Autowired
    private SysConfigService sysConfigService;

    @Autowired
    private CertService certService;

    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private RosterCertificateService rosterCertificateService;
    @Autowired
    private RosterContractService rosterContractService;
    @Autowired
    private OtherUserInfoService otherUserInfoService;

    @Autowired
    private RosterBankCardsService rosterBankCardsService;

    public Integer findIdCardOnly(UserOtherInfo otherInfo) throws Exception {
        QueryWrapper<UserOtherInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id_card", otherInfo.getIdCard());
        queryWrapper.eq("del_flag", 0);
        queryWrapper.eq("certificates_type", otherInfo.getCertificatesType());
        // 删除基础信息表
        Integer integer = otherUserInfoMapper.selectCount(queryWrapper);
        return integer;
    }

    public void insertWorkAttachment (WorkAttachmentInfo2 workAttachment, UserDTO userDto){
        userMapper.insertWorkAttachment(workAttachment, userDto);
    }

    /**
     * 根据用户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());
                    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);
            }
        }
        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 ); // 排除已经删除
        return baseMapper.findList ( page, queryWrapper );


    }

    /**
     * 自定义分页检索
     *
     * @param page
     * @param queryWrapper
     * @return
     */
    public IPage <UserDTO> findPageNew(Page <UserDTO> page, QueryWrapper queryWrapper) {
        queryWrapper.eq ( "a.del_flag", CommonConstants.NOT_DELETED ); // 排除已经删除
        queryWrapper.eq ( "sr.name", "总审" ); // 排除已经删除
        return baseMapper.findListNew ( page, queryWrapper );


    }

    /**
     * 自定义分页检索
     *
     * @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 ); // 排除已经删除


        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) {

        UserDTO info = SpringUtil.getBean ( IUserApi.class ).getByToken ( TokenProvider.getCurrentToken() );

        User user = userWrapper.toEntity ( userDTO );
        if(StringUtils.isNotBlank(userDTO.getManageOfficeIds())){
            user.setManageOfficeIds(userDTO.getManageOfficeIds());
        }
        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 ( ) );
            } );
        }
        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(ObjectUtil.isNotEmpty(userDTO.getRosterContractDTO())){
            RosterContractDTO rosterContractDTO = userDTO.getRosterContractDTO();

            RosterContract rosterContract = new RosterContract();
            BeanUtils.copyProperties(rosterContractDTO, rosterContract);

            rosterContract.setCreateById(info.getId());
            rosterContract.setCreateTime(new Date());
            rosterContract.setUpdateById(info.getId());
            rosterContract.setUpdateTime(new Date());

            rosterContract.setBaseId(userDTO.getId());
            rosterContractService.remove(new QueryWrapper<RosterContract>().eq("base_id",userDTO.getId()));
            rosterContractService.saveOrUpdate(rosterContract);
        } else {
            rosterContractService.remove(new QueryWrapper<RosterContract>().eq("base_id",userDTO.getId()));
        }
        //批量导入人员信息处理
        UserOtherInfoDto temporaryOtherInfo = new UserOtherInfoDto();
        //身份证处理
        if(StringUtils.isNotBlank(userDTO.getIdCard())){
            temporaryOtherInfo.setIdCard(userDTO.getIdCard());
            temporaryOtherInfo.setCertificatesType("1");//类型调整为身份证
            temporaryOtherInfo.setWorkerType("1");//员工类型默认正式
        }


        if(null != userDTO.getOnboardingDate()) {
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
            temporaryOtherInfo.setOnboardingDate(sf.format(userDTO.getOnboardingDate()));//员工入职时间
        }
        if (StringUtils.isNotBlank(temporaryOtherInfo.getIdCard()) || StringUtils.isNotBlank(temporaryOtherInfo.getWorkerType()) || StringUtils.isNotBlank(temporaryOtherInfo.getOnboardingDate())) {
            userDTO.setOtherInfoDto(temporaryOtherInfo);
        }
        //保存  银行卡信息、人员资质、员工证书  及  其他个人信息
        //1、保存其他个人信息
        if (null != userDTO.getOtherInfoDto()) {
            UserOtherInfoDto otherInfoDto = userDTO.getOtherInfoDto();
            UserOtherInfo otherInfo = new UserOtherInfo();
            BeanUtils.copyProperties(otherInfoDto, otherInfo);
            if(StringUtils.isNotBlank(userDTO.getId())){
                UserOtherInfo byUserId = otherUserInfoService.getByUserId(userDTO.getId());
                if(null != byUserId && StringUtils.isNotBlank(byUserId.getId())){
                    otherInfo.setId(byUserId.getId());
                }
            }
            otherInfo.setCreateById(info.getId());
            otherInfo.setCreateTime(new Date());
            otherInfo.setUpdateById(info.getId());
            otherInfo.setUpdateTime(new Date());
            otherInfo.setUserInfoId(userDTO.getId());
            otherUserInfoService.saveOrUpdate(otherInfo);
        }
        //2、保存银行卡信息
        if(CollectionUtil.isNotEmpty(userDTO.getRosterBankCardsDTOList())){
            List<String> collect = userDTO.getRosterBankCardsDTOList().stream().map(RosterBankCardsDTO::getId).collect(Collectors.toList());
            rosterBankCardsService.remove(new QueryWrapper<RosterBankCards>().eq("base_id",userDTO.getId()).notIn(CollectionUtil.isNotEmpty(collect),"id",collect));
            userDTO.getRosterBankCardsDTOList().stream().forEach(item->{
                if(ObjectUtil.isNotEmpty(item)&& objectCheckIsNull(item)){
                    RosterBankCards rosterBankCards = new RosterBankCards();
                    BeanUtils.copyProperties(item, rosterBankCards);
                    rosterBankCards.setCreateById(info.getId());
                    rosterBankCards.setCreateTime(new Date());
                    rosterBankCards.setUpdateById(info.getId());
                    rosterBankCards.setUpdateTime(new Date());
                    rosterBankCards.setBaseId(userDTO.getId());
                    rosterBankCardsService.saveOrUpdate(rosterBankCards);
                }
            });
        }else{
            rosterBankCardsService.remove(new QueryWrapper<RosterBankCards>().eq("base_id",userDTO.getId()));
        }
        //3、保存员工证书
        //保存员工证书
        if(CollectionUtil.isNotEmpty(userDTO.getRosterCertificateDTOList())){
            List<String> collect = userDTO.getRosterCertificateDTOList().stream().map(RosterCertificateDTO::getId).collect(Collectors.toList());
            rosterCertificateService.remove(new QueryWrapper<RosterCertificate>().eq("base_id",userDTO.getId()).notIn(CollectionUtil.isNotEmpty(collect),"id",collect));
            userDTO.getRosterCertificateDTOList().stream().forEach(item->{
                if(ObjectUtil.isNotEmpty(item)&& objectCheckIsNull(item)){
                    RosterCertificate rosterCertificate = new RosterCertificate();
                    BeanUtils.copyProperties(item, rosterCertificate);
                    rosterCertificate.setCreateById(info.getId());
                    rosterCertificate.setCreateTime(new Date());
                    rosterCertificate.setUpdateById(info.getId());
                    rosterCertificate.setUpdateTime(new Date());
                    rosterCertificate.setBaseId(userDTO.getId());
                    rosterCertificate.setBaseId(userDTO.getId());
                    rosterCertificateService.saveOrUpdate(rosterCertificate);
                }
            });
        }else{
            rosterCertificateService.remove(new QueryWrapper<RosterCertificate>().eq("base_id",userDTO.getId()));
        }
        //4、保存人员资质
        // 保存花名册关联用户的资质信息
        certService.remove(new QueryWrapper<Cert>().lambda().eq(Cert::getUserId,userDTO.getId()));
        if(ObjectUtil.isNotEmpty(userDTO.getCertDTOList())){
            List<Cert> certList = new ArrayList<>();
            userDTO.getCertDTOList().stream().forEach(i -> {
                Cert cert = CertWrapper.INSTANCE.toEntity(i);
                cert.setUserId(userDTO.getId());
                cert.setId("");
                certList.add(cert);
            });
            if (CollectionUtil.isNotEmpty(certList)) {
                certService.saveBatch(certList);
            }
        }
        User thisUser = this.getOne(new QueryWrapper<User>().lambda().eq(User::getRosterId, userDTO.getId()));
        if (ObjectUtil.isNotEmpty(thisUser)) {
            // 保存花名册关联用户的资质信息
//            certService.remove(new QueryWrapper<Cert>().lambda().eq(Cert::getUserId,user.getId()));
//            if(ObjectUtil.isNotEmpty(userDTO.getCertDTOList())){
//                List<Cert> certList = new ArrayList<>();
//                userDTO.getCertDTOList().stream().forEach(i -> {
//                    Cert cert = CertWrapper.INSTANCE.toEntity(i);
//                    cert.setUserId(user.getId());
//                    cert.setId("");
//                    certList.add(cert);
//                });
//                if (CollectionUtil.isNotEmpty(certList)) {
//                    certService.saveBatch(certList);
//                }
//            }
//            // 保存花名册关联用户的角色
//            userMapper.deleteUserRole(user.getId());  //  删除用户的角色
//            if (CollectionUtil.isNotEmpty(userDTO.getRoleIdList())) {
//                userDTO.getRoleIdList().stream().forEach(i -> {
//                    userMapper.insertUserRole(user.getId(), i);  // 插入用户的角色
//                });
//            }
//            // 保存花名册关联用户的岗位
//            userMapper.deleteUserPost(user.getId());  //  删除用户的岗位
//            if (CollectionUtil.isNotEmpty(userDTO.getPostIdList())) {
//                userDTO.getPostIdList().stream().forEach(i -> {
//                    userMapper.insertUserPost(user.getId(), i);  // 插入用户的岗位
//                });
//            }
//            // 保存花名册关联用户的管理部门
//            UserDTO u = new UserDTO();
//            u.setId(user.getId());
//            userMapper.deleteUserManageOffice(u);  //  删除用户的管理部门 （用户、管理部门关联表）
//            String oIds = "";
//            if (StringUtils.isNotBlank(userDTO.getManageOfficeIds())) {
//                List<String> officeIds= Arrays.asList(userDTO.getManageOfficeIds().split(","));
//                officeIds.stream().forEach(officeId -> {
//                    userMapper.insertUserManageOffice(officeId,user.getId());  // 插入用户的管理部门 （用户、管理部门关联表）
//                });
//                oIds = userDTO.getManageOfficeIds();
//            }
//            userMapper.updateUserManageOffice(oIds, user.getId()); // 修改用户的管理部门 （用户表）
        }
        String id = SnowFlake2.getId();
        //5、保存附件信息
        if (CollectionUtils.isNotEmpty(userDTO.getFiles())) {
            saveFiles(userDTO.getFiles(), userDTO, id);
        }

    }


    public static boolean objectCheckIsNull(Object object) {
        boolean flag = false; //定义返回结果，默认为true

        if (Objects.isNull(object)) {
            flag = false;
        } else {
            Class clazz = (Class) object.getClass(); // 得到类对象
            Field fields[] = clazz.getDeclaredFields(); // 得到所有属性
            for (Field field : fields) {
                if("serialVersionUID".equals(field.getName()) || "BIZ_CODE".equalsIgnoreCase(field.getName())){
                    continue;
                }
                field.setAccessible(true);
                Object fieldValue = null;
                try {
                    fieldValue = field.get(object); //得到属性值
                    Type fieldType = field.getGenericType();//得到属性类型
                    String fieldName = field.getName(); // 得到属性名
                    System.out.println(("属性类型：" + fieldType + ",属性名：" + fieldName + ",属性值：" + fieldValue));
                } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
                if (fieldValue != null && fieldValue != "") {  //只要有一个属性值不为null 就返回false 表示对象不为null
                    flag = true;
                    break;
                }
            }
        }

        return flag;
    }



    public void saveFiles(List<WorkAttachmentDto2> list, UserDTO userDTO, String id) {
        int j = 1;
        for (WorkAttachmentDto2 dto : list) {
            WorkAttachmentInfo2 i = new WorkAttachmentInfo2();
            //包含了url、size、name
            i.setId(UUID.randomUUID().toString().replace("-", ""));
//            i.getCreateBy().setId(userDTO.getId());
            i.setCreateTime(new Date());
//            i.getUpdateBy().setId(userDTO.getId());
            i.setUpdateTime(new Date());
            i.setDelFlag(0);
            i.setUrl(dto.getUrl());
            //文件类型处理
            List<String> strings = Arrays.asList(dto.getName().split("\\."));
            if (org.flowable.editor.language.json.converter.util.CollectionUtils.isNotEmpty(strings)) {
                i.setType(strings.get(1));
            }
            i.setAttachmentId(id);
            i.setAttachmentName(dto.getName());
            i.setAttachmentFlag("userFilesInfo");
            i.setFileSize(dto.getSize());
            i.setSort(j);
            this.insertWorkAttachment(i, userDTO);
            j++;
        }
    }

    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);
    }

    //根据部门查询用户信息
    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);
    }

    /**
     * 签字注师查询用户权限所用
     * @param userDTO
     * @return
     */
    public IPage<UserDTO> findPage3(UserDTO userDTO) {
        Page<UserDTO> page = new Page<>();
        if(null != userDTO && 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 = Lists.newArrayList();
            page.setRecords(list1);
        }
        return page;
    }

    /**
     * 查询签字注师二信息列表
     * @param page
     * @param
     * @return
     */
    public IPage <UserDTO> findPage1(UserDTO dto, Page <UserDTO> page) {
        OfficeDTO officeDTO = dto.getCompanyDTO();
        String companyId = "";
        if (null != officeDTO){
            companyId = officeDTO.getId();
        }
        List <UserDTO> list1 = baseMapper.findList1(dto,companyId);
        // 将List<UserDTO>数据设置到Page对象中
        page.setRecords(list1);
        return  page;
    }



    /**
     * 查询签字注师二信息集合
     * @param page
     * @param
     * @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 ); // 排除已经删除
        return baseMapper.findCertList ( page, queryWrapper );
    }

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

    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 List<WorkAttachmentDto2> getByAttachmentId(String id) {
        return userMapper.getByAttachmentId(id);
    }

    /**
     * 查询当前用户所属部门的部门主任id
     * @return
     */
    public String getDepartmentId() {
        UserDTO userDTO = SpringUtil.getBean(IUserApi.class).getByToken(TokenProvider.getCurrentToken());
        return userMapper.getDepartmentId(userDTO.getId());
    }
}
