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


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.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.google.gson.Gson;
import com.jeeplus.aop.demo.annotation.DemoMode;
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.excel.ExcelOptions;
import com.jeeplus.common.excel.annotation.ExportMode;
import com.jeeplus.common.redis.RedisUtils;
import com.jeeplus.common.utils.ResponseUtil;
import com.jeeplus.core.query.QueryWrapperGenerator;
import com.jeeplus.logging.annotation.ApiLog;
import com.jeeplus.sys.domain.Office;
import com.jeeplus.sys.domain.User;
import com.jeeplus.sys.domain.vo.UserVO;
import com.jeeplus.sys.feign.IUserApi;
import com.jeeplus.sys.service.OfficeService;
import com.jeeplus.sys.service.UserService;
import com.jeeplus.sys.service.dto.OfficeDTO;
import com.jeeplus.sys.service.dto.RoleDTO;
import com.jeeplus.sys.service.dto.UserDTO;
import com.jeeplus.sys.service.dto.UserSignatureScribeDTO;
import com.jeeplus.sys.service.mapstruct.UserWrapper;
import com.jeeplus.sys.utils.*;
import com.jeeplus.sys.utils.excel.UserEasyExcel;
import com.jeeplus.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 用户Controller
 *
 * @author jeeplus
 * @version 2021-8-29
 */
@Api(tags = "用户管理")
@RestController
@RequestMapping("/sys/user")
public class UserController {


    @Autowired
    private UserService userService;

    @Autowired
    private OfficeService officeService;

    @Autowired
    private RedisUtils redisUtils;

    @ApiLog("获取所有的openId信息")
    @GetMapping("/allOpenIds")
    @ApiOperation(value = "判断当前用户是否是管理员")
    public List<String> getAllOpenIds() {
        List<String> openIds = userService.getAllOpenIds();
        return openIds;
    }

    /**
     * 根据ids查询用户基本信息（姓名、手机、角色、部门）
     *
     * @param ids
     * @return
     */
    @ApiLog("根据id查询用户基本信息")
    @GetMapping("queryDetailList")
    @ApiOperation(value = "根据id查询用户基本信息")
    public ResponseEntity<List<UserDTO>> queryDetailList(@RequestParam("ids") String ids) {
        List<UserDTO> list = new ArrayList<>();
        String[] split = ids.split(",");
        for (String id : split) {
            UserDTO userDTO = userService.get(id);
            userDTO.setRoleList(userDTO.getRoleDTOList());
            list.add(userDTO);
        }
        return ResponseEntity.ok(list);
    }

    /**
     * 根据ids查询用户基本信息（姓名、手机、角色、部门）
     *
     * @param id
     * @return
     */
    @ApiLog("根据id查询用户基本信息")
    @GetMapping("queryDetailById")
    @ApiOperation(value = "根据id查询用户基本信息")
    public ResponseEntity<UserDTO> queryDetailById(@RequestParam("id") String id) {
        UserDTO userDTO = userService.get(id);
        userDTO.setRoleList(userDTO.getRoleDTOList());
        return ResponseEntity.ok(userDTO);
    }

    /**
     * 根据id查询用户
     *
     * @param id
     * @return
     */
    @ApiLog("查询用户")
    @GetMapping("queryById")
    @ApiOperation(value = "查询用户")
    public ResponseEntity queryById(@RequestParam("id") String id) {
        UserDTO userDTO = userService.get(id);
        return ResponseEntity.ok(userDTO);
    }

    /**
     * 查询列表
     *
     * @param userDTO
     * @param page
     * @return
     */
    @ApiLog("项目组成员查询用户使用")
    @ApiOperation(value = "项目组成员查询用户使用")
    //@PreAuthorize("hasAuthority('sys:user:list')")
    @GetMapping("memberList")
    public ResponseEntity memberList(UserDTO userDTO, Page<UserDTO> page) throws Exception {

        QueryWrapper<UserDTO> queryWrapper = QueryWrapperGenerator.buildQueryCondition(userDTO, UserDTO.class);
        // 管理员查询不限制
        if (!UserUtils.getCurrentUserDTO().isAdmin()) {
            queryWrapper.isNull("a.is_admin");
            if (ObjectUtil.isNotEmpty(userDTO)) {
                if (ObjectUtil.isNotEmpty(userDTO.getCompanyDTO()) && ObjectUtil.isNotEmpty(userDTO.getOfficeDTO())) {
                    OfficeDTO officeDTO = UserUtils.getCurrentUserDTO().getOfficeDTO();
                    if (StringUtils.isNotBlank(userDTO.getCertType())) {

                    } else {
                        // 当不是精确的部门查询时，再添加下面的筛选条件
                        if ((StringUtils.isNotBlank(userDTO.getCompanyDTO().getId()) && StringUtils.isBlank(userDTO.getOfficeDTO().getId()))
                                || "true".equals(userDTO.getSelectAll())) {
                            // officeDTO.id是空，companyDTO.id不是空的话，说明前端组件点击的集团来进行查询
                            // selectAll为‘true’的话，说明前端没有选择集团或者部门查询，这个时候要展示全部人员
                            // 根据当前用户的部门id找到此部门的ids
                            String ids = officeService.getById(UserUtils.getCurrentUserDTO().getOfficeDTO().getId()).getParentIds();
                            // 根据ids分隔后的index[2],找到当前用户的所属公司id
                            String companyId = null;
                            String[] split = ids.split(",");
                            // split.length大于2，说明当前登录人所属部门是普通部门，展示部分人员信息
                            // 否则，当前登录人所属公共类部门（忘了叫什么类部门了，就是总经办那种部门），展示全部人员信息
                            if (split.length > 2) {
                                companyId = split[2];
                                // 根据公司id,找到此公司下的所有部门
                                List<Office> officeList = officeService.list(new QueryWrapper<Office>().lambda().eq(Office::getParentId, companyId));
                                Set officeIdSet = new HashSet();
                                for (Office office : officeList) {
                                    if (StringUtils.isNotBlank(office.getId())) {
                                        officeIdSet.add(office.getId());
                                    }
                                }
                                List<String> officeIdList = Lists.newArrayList(officeIdSet);
                                // 拿到这些部门的id
                                //List<String> officeIdList = officeList.stream().distinct().map(Office::getId).collect(Collectors.toList());
                                // 拿到所有公有部门的id
                                List<String> officePublicIdList = officeService.list(new LambdaQueryWrapper<Office>().eq(Office::getIsPublic, "1")).stream().map(Office::getId).collect(Collectors.toList());
                                // 拿到直属公司的id
                                officeIdList.add(companyId);
                                // 最后得到的所有部门的id
                                officeIdList.addAll(officePublicIdList);
                                List<String> lastIds = officeIdList.stream().distinct().collect(Collectors.toList());
                                // 添加筛选条件为这些部门的id
                                queryWrapper.in("a.office_id", lastIds);
                            }
                        } else if (StringUtils.isBlank(userDTO.getCompanyDTO().getId()) && StringUtils.isNotBlank(userDTO.getOfficeDTO().getId())) {
                            // officeDTO.id不是空，companyDTO.id是空的话，说明前端组件点击的部门查询
                            queryWrapper.eq("a.office_id", userDTO.getOfficeDTO().getId());
                        }
                    }
                }
            }
        }
        if (ObjectUtil.isNotEmpty(userDTO)) {
            // 当certType传值时，获取拥有此资格证类型的人员
            if (StringUtils.isNotBlank(userDTO.getCertType())) {
                queryWrapper.eq("sc.type", userDTO.getCertType());
            }
            if (userDTO.getTenantDTO() != null && StrUtil.isNotBlank(userDTO.getTenantDTO().getId())) {
                queryWrapper.eq("a.tenant_id", userDTO.getTenantDTO().getId());
            }
        }
        IPage<UserDTO> result = userService.findMemberPage(page, queryWrapper);
        return ResponseEntity.ok(result);
    }

    /**
     * 查询列表
     *
     * @param userDTO
     * @param page
     * @return
     */
    @ApiLog("用户数据列表")
    @ApiOperation(value = "用户数据列表")
    //@PreAuthorize("hasAuthority('sys:user:list')")
    @GetMapping("list")
    public ResponseEntity list(UserDTO userDTO, Page<UserDTO> page) throws Exception {
//        QueryWrapper <UserDTO> queryWrapper = QueryWrapperGenerator.buildQueryCondition ( userDTO, UserDTO.class );
//        if ( userDTO.getTenantDTO ( ) != null && StrUtil.isNotBlank ( userDTO.getTenantDTO ( ).getId ( ) ) ) {
//            queryWrapper.eq ( "a.tenant_id", userDTO.getTenantDTO ( ).getId ( ) );
//        }
//        IPage <UserDTO> result = userService.findPage ( page, queryWrapper );
//        return ResponseEntity.ok ( result );

        QueryWrapper<UserDTO> queryWrapper = QueryWrapperGenerator.buildQueryCondition(userDTO, UserDTO.class);
        // 管理员查询不限制
        Boolean isAdmin = false;
        UserDTO currentUserDTO = UserUtils.getCurrentUserDTO();
        if (currentUserDTO != null && CollectionUtil.isNotEmpty(currentUserDTO.getRoleDTOList())) {
            for (RoleDTO roleDTO : currentUserDTO.getRoleDTOList()) {
                if (roleDTO.getEnName().equals("sys")) {
                    isAdmin = true;
                    break;
                }
            }
        }
        if (!isAdmin) {
            queryWrapper.isNull("a.is_admin");
            if (ObjectUtil.isNotEmpty(userDTO)) {
                if (ObjectUtil.isNotEmpty(userDTO.getCompanyDTO()) && ObjectUtil.isNotEmpty(userDTO.getOfficeDTO())) {
                    String id = UserUtils.getCurrentUserDTO().getCompanyDTO().getId();
                    if (StringUtils.isNotBlank(userDTO.getCertType())) {
                        //获取当前登陆人是否事中审公司人员
                        /*if(officeDTO.getParentIds().contains("1615171302381182978")){

                        }*/
                    } else {
                        // 当不是精确的部门查询时，再添加下面的筛选条件
                        if ((StringUtils.isNotBlank(userDTO.getCompanyDTO().getId()) && StringUtils.isBlank(userDTO.getOfficeDTO().getId()))
                                || "true".equals(userDTO.getSelectAll())) {
                            // officeDTO.id是空，companyDTO.id不是空的话，说明前端组件点击的集团来进行查询
                            // selectAll为‘true’的话，说明前端没有选择集团或者部门查询，这个时候要展示全部人员
                            // 根据当前用户的部门id找到此部门的ids
                            String ids = officeService.getById(UserUtils.getCurrentUserDTO().getOfficeDTO().getId()).getParentIds();
                            // 根据ids分隔后的index[2],找到当前用户的所属公司id
                            String companyId = null;
                            String[] split = ids.split(",");
                            // split.length大于2，说明当前登录人所属部门是普通部门，展示部分人员信息
                            // 否则，当前登录人所属公共类部门（忘了叫什么类部门了，就是总经办那种部门），展示全部人员信息
                            if (split.length > 2) {
                                companyId = split[2];
                                // 根据公司id,找到此公司下的所有部门
                                List<Office> officeList = officeService.list(new QueryWrapper<Office>().lambda().eq(Office::getParentId, companyId));
                                Set officeIdSet = new HashSet();
                                for (Office office : officeList) {
                                    if (StringUtils.isNotBlank(office.getId())) {
                                        officeIdSet.add(office.getId());
                                    }
                                }
                                List<String> officeIdList = Lists.newArrayList(officeIdSet);
                                // 拿到这些部门的id
                                //List<String> officeIdList = officeList.stream().distinct().map(Office::getId).collect(Collectors.toList());
                                // 拿到所有公有部门的id
                                List<String> officePublicIdList = officeService.list(new LambdaQueryWrapper<Office>().eq(Office::getIsPublic, "1")).stream().map(Office::getId).collect(Collectors.toList());
                                // 拿到直属公司的id
                                officeIdList.add(companyId);
                                // 最后得到的所有部门的id
                                officeIdList.addAll(officePublicIdList);
                                List<String> lastIds = officeIdList.stream().distinct().collect(Collectors.toList());
                                // 添加筛选条件为这些部门的id
                                queryWrapper.in("a.office_id", lastIds);
                            }
                        } else if (StringUtils.isBlank(userDTO.getCompanyDTO().getId()) && StringUtils.isNotBlank(userDTO.getOfficeDTO().getId())) {
                            // officeDTO.id不是空，companyDTO.id是空的话，说明前端组件点击的部门查询
                            queryWrapper.eq("a.office_id", userDTO.getOfficeDTO().getId());
                        }
                    }
                }
            }
        }
        if (ObjectUtil.isNotEmpty(userDTO)) {
            // 当certType传值时，获取拥有此资格证类型的人员
            if (StringUtils.isNotBlank(userDTO.getCertType())) {
                queryWrapper.orderByDesc("a.company_id");
                queryWrapper.orderByAsc("a.office_id");
                queryWrapper.orderByDesc("a.name");
                //获取当前登录人信息
                UserDTO loginUserDTO = UserUtils.getCurrentUserDTO();
                //如果当前登录人是中审的管理咨询部人员，则注会列表中添加该部门选择项
                if (null != loginUserDTO && null != loginUserDTO.getOfficeDTO()) {
                    OfficeDTO officeDTO = loginUserDTO.getOfficeDTO();
                    if (StringUtils.isNotBlank(officeDTO.getId())) {
                        if ("1602840084816138241".equals(officeDTO.getId())) {
                            queryWrapper.and(
                                    wrapper -> wrapper.eq("sc.type", userDTO.getCertType()).or().eq("a.office_id", "1602840084816138241")
                            );
                            //queryWrapper.eq("sc.type",userDTO.getCertType()).or().eq("a.office_id","1602840084816138241");
                        } else {
                            queryWrapper.eq("sc.type", userDTO.getCertType());
                        }
                    } else {
                        queryWrapper.eq("sc.type", userDTO.getCertType());
                    }
                } else {
                    queryWrapper.eq("sc.type", userDTO.getCertType());
                }

            }
            if (userDTO.getTenantDTO() != null && StrUtil.isNotBlank(userDTO.getTenantDTO().getId())) {
                queryWrapper.eq("a.tenant_id", userDTO.getTenantDTO().getId());
            }
        }
        IPage<UserDTO> result = userService.findPage(page, queryWrapper);
        IPage<UserDTO> result2 = userService.findPage3(userDTO);
        //判断 如果是签字注师筛选，则获取签字注师的被选择次数
        if (StringUtils.isNotBlank(userDTO.getCertType()) && "6".equals(userDTO.getCertType())) {
            List<UserDTO> userList = result.getRecords();
            List<UserDTO> user2List = result2.getRecords();
            List<String> idList = Lists.newArrayList();
            for (UserDTO dto : user2List) {
                idList.add(dto.getId());
            }
            for (UserDTO info : userList) {
                if (idList.size() > 0) {
                    if (idList.contains(info.getId())) {
                        info.setAccountantUserFlag(0);
                    } else {
                        info.setAccountantUserFlag(1);
                    }
                } else {
                    if ("潘中".equals(info.getName())) {
                        info.setAccountantUserFlag(0);
                    } else {
                        info.setAccountantUserFlag(1);
                    }
                }
                /*if("潘中".equals(info.getName())){
                    info.setAccountantUserFlag(0);
                }else{
                    info.setAccountantUserFlag(1);
                }*/
                Integer accountantUserCount = userService.getAccountantUserCount(info.getId());
                info.setAccountantUserCount(accountantUserCount);
            }
        }
        return ResponseEntity.ok(result);
    }

    /**
     * 查询列表
     *
     * @param userDTO
     * @param page
     * @return
     */
    @ApiLog("用户数据列表")
    @ApiOperation(value = "用户数据列表")
    @GetMapping("allUserList")
    public ResponseEntity allUserList(UserDTO userDTO, Page<UserDTO> page) throws Exception {

        QueryWrapper<UserDTO> queryWrapper = QueryWrapperGenerator.buildQueryCondition(userDTO, UserDTO.class);
        // 管理员查询不限制
//        if (!UserUtils.getCurrentUserDTO().isAdmin()) {
//            if (ObjectUtil.isNotEmpty(userDTO)){
//                if (ObjectUtil.isNotEmpty(userDTO.getCompanyDTO()) && ObjectUtil.isNotEmpty(userDTO.getOfficeDTO())) {
//                    String id = UserUtils.getCurrentUserDTO().getCompanyDTO().getId();
//                    if (StringUtils.isNotBlank(userDTO.getCertType())) {
//                        //获取当前登陆人是否事中审公司人员
//                        /*if(officeDTO.getParentIds().contains("1615171302381182978")){
//
//                        }*/
//                    }else{
//                        // 当不是精确的部门查询时，再添加下面的筛选条件
//                        if ((StringUtils.isNotBlank(userDTO.getCompanyDTO().getId()) && StringUtils.isBlank(userDTO.getOfficeDTO().getId()))
//                                || "true".equals(userDTO.getSelectAll())) {
//                            // officeDTO.id是空，companyDTO.id不是空的话，说明前端组件点击的集团来进行查询
//                            // selectAll为‘true’的话，说明前端没有选择集团或者部门查询，这个时候要展示全部人员
//                            // 根据当前用户的部门id找到此部门的ids
//                            String ids = officeService.getById(UserUtils.getCurrentUserDTO().getOfficeDTO().getId()).getParentIds();
//                            // 根据ids分隔后的index[2],找到当前用户的所属公司id
//                            String companyId = null;
//                            String[] split = ids.split(",");
//                            // split.length大于2，说明当前登录人所属部门是普通部门，展示部分人员信息
//                            // 否则，当前登录人所属公共类部门（忘了叫什么类部门了，就是总经办那种部门），展示全部人员信息
//                            if(split.length>2){
//                                companyId = split[2];
//                                // 根据公司id,找到此公司下的所有部门
//                                List<Office> officeList = officeService.list(new QueryWrapper<Office>().lambda().eq(Office::getParentId, companyId));
//                                Set officeIdSet = new HashSet();
//                                for (Office office : officeList) {
//                                    if(StringUtils.isNotBlank(office.getId())){
//                                        officeIdSet.add(office.getId());
//                                    }
//                                }
//                                List<String> officeIdList = Lists.newArrayList(officeIdSet);
//                                // 拿到这些部门的id
//                                //List<String> officeIdList = officeList.stream().distinct().map(Office::getId).collect(Collectors.toList());
//                                // 拿到所有公有部门的id
//                                List<String> officePublicIdList = officeService.list(new LambdaQueryWrapper<Office>().eq(Office::getIsPublic,"1")).stream().map(Office::getId).collect(Collectors.toList());
//                                // 拿到直属公司的id
//                                officeIdList.add(companyId);
//                                // 最后得到的所有部门的id
//                                officeIdList.addAll(officePublicIdList);
//                                List<String> lastIds = officeIdList.stream().distinct().collect(Collectors.toList());
//                                // 添加筛选条件为这些部门的id
//                                queryWrapper.in("a.office_id",lastIds);
//                            }
//                        } else if(StringUtils.isBlank(userDTO.getCompanyDTO().getId()) && StringUtils.isNotBlank(userDTO.getOfficeDTO().getId())) {
//                            // officeDTO.id不是空，companyDTO.id是空的话，说明前端组件点击的部门查询
//                            queryWrapper.eq("a.office_id",userDTO.getOfficeDTO().getId());
//                        }
//                    }
//                }
//            }
//        }
        if (ObjectUtil.isNotEmpty(userDTO)) {
            // 当certType传值时，获取拥有此资格证类型的人员
            if (StringUtils.isNotBlank(userDTO.getCertType())) {

                //获取当前登录人信息
                UserDTO loginUserDTO = UserUtils.getCurrentUserDTO();
                //如果当前登录人是中审的管理咨询部人员，则注会列表中添加该部门选择项
                if (null != loginUserDTO && null != loginUserDTO.getOfficeDTO()) {
                    OfficeDTO officeDTO = loginUserDTO.getOfficeDTO();
                    if (StringUtils.isNotBlank(officeDTO.getId())) {
                        if ("1602840084816138241".equals(officeDTO.getId())) {
                            queryWrapper.and(
                                    wrapper -> wrapper.eq("sc.type", userDTO.getCertType()).or().eq("a.office_id", "1602840084816138241")
                            );
                            //queryWrapper.eq("sc.type",userDTO.getCertType()).or().eq("a.office_id","1602840084816138241");
                        } else {
                            queryWrapper.eq("sc.type", userDTO.getCertType());
                        }
                    } else {
                        queryWrapper.eq("sc.type", userDTO.getCertType());
                    }
                } else {
                    queryWrapper.eq("sc.type", userDTO.getCertType());
                }

            }
            if (userDTO.getTenantDTO() != null && StrUtil.isNotBlank(userDTO.getTenantDTO().getId())) {
                queryWrapper.eq("a.tenant_id", userDTO.getTenantDTO().getId());
            }
        }
        IPage<UserDTO> result = userService.findPage(page, queryWrapper);
//        IPage<UserDTO> result2 = userService.findPage3(userDTO);
//        //判断 如果是签字注师筛选，则获取签字注师的被选择次数
//        if(StringUtils.isNotBlank(userDTO.getCertType()) && "6".equals(userDTO.getCertType())){
//            List<UserDTO> userList = result.getRecords();
//            List<UserDTO> user2List = result2.getRecords();
//            List<String> idList = Lists.newArrayList();
//            for (UserDTO dto : user2List) {
//                idList.add(dto.getId());
//            }
//            for (UserDTO info : userList) {
//                if(idList.size()>0){
//                    if(idList.contains(info.getId())){
//                        info.setAccountantUserFlag(0);
//                    }else{
//                        info.setAccountantUserFlag(1);
//                    }
//                }else{
//                    if("潘中".equals(info.getName())){
//                        info.setAccountantUserFlag(0);
//                    }else{
//                        info.setAccountantUserFlag(1);
//                    }
//                }
//                /*if("潘中".equals(info.getName())){
//                    info.setAccountantUserFlag(0);
//                }else{
//                    info.setAccountantUserFlag(1);
//                }*/
//                Integer accountantUserCount = userService.getAccountantUserCount(info.getId());
//                info.setAccountantUserCount(accountantUserCount);
//            }
//        }
        return ResponseEntity.ok(result);
    }


    @ApiLog("根据用户id获取被选次数")
    @ApiOperation(value = "根据用户id获取被选次数")
    //@PreAuthorize("hasAuthority('sys:user:list')")
    @GetMapping("getCount")
    public ResponseEntity getCount(String id) {
        UserDTO userDTO = userService.get(id);
        List<UserDTO> signatureAnnotator2List = userService.getSignatureAnnotator2List(new UserDTO());
        for (UserDTO dto : signatureAnnotator2List) {

            if (userDTO.getId().equals(dto.getId())) {
                userDTO.setAccountantUserFlag(0);
                break;
            } else {
                userDTO.setAccountantUserFlag(1);
                // break;
            }
        }
        /*if (userDTO.getName().equals("潘中")){
            userDTO.setAccountantUserFlag(0);
        }else{
            userDTO.setAccountantUserFlag(1);
        }*/
        userDTO.setAccountantUserCount(userService.getAccountantUserCount(id));
        return ResponseEntity.ok(userDTO);
    }

    /**
     * 查询列表
     *
     * @param userDTO
     * @param page
     * @return
     */
    @ApiLog("用户数据列表")
    @ApiOperation(value = "用户数据列表")
    //@PreAuthorize("hasAuthority('sys:user:list')")
    @GetMapping("userList")
    public ResponseEntity userList(UserDTO userDTO, Page<UserDTO> page) throws Exception {

        QueryWrapper<UserDTO> queryWrapper = QueryWrapperGenerator.buildQueryCondition(userDTO, UserDTO.class);
        // 管理员查询不限制
        if (!UserUtils.getCurrentUserDTO().isAdmin()) {
            queryWrapper.isNull("a.is_admin");
            if (ObjectUtil.isNotEmpty(userDTO)) {
                if (ObjectUtil.isNotEmpty(userDTO.getCompanyDTO()) && ObjectUtil.isNotEmpty(userDTO.getOfficeDTO())) {
                    //OfficeDTO officeDTO = UserUtils.getCurrentUserDTO().getOfficeDTO();
                    if (StringUtils.isNotBlank(userDTO.getCertType())) {
                        //获取当前登陆人是否事中审公司人员
                        /*if(officeDTO.getParentIds().contains("1615171302381182978")){

                        }*/
                    } else {
                        // 当不是精确的部门查询时，再添加下面的筛选条件
                        if ((StringUtils.isNotBlank(userDTO.getCompanyDTO().getId()) && StringUtils.isBlank(userDTO.getOfficeDTO().getId()))
                                || "true".equals(userDTO.getSelectAll())) {
                            // officeDTO.id是空，companyDTO.id不是空的话，说明前端组件点击的集团来进行查询
                            // selectAll为‘true’的话，说明前端没有选择集团或者部门查询，这个时候要展示全部人员
                            // 根据当前用户的部门id找到此部门的ids
                            Office byId = officeService.getById(UserUtils.getCurrentUserDTO().getOfficeDTO().getId());
                            if (null != byId) {
                                String ids = officeService.getById(byId).getParentIds();
                                // 根据ids分隔后的index[2],找到当前用户的所属公司id
                                String companyId = null;
                                String[] split = ids.split(",");
                                // split.length大于2，说明当前登录人所属部门是普通部门，展示部分人员信息
                                // 否则，当前登录人所属公共类部门（忘了叫什么类部门了，就是总经办那种部门），展示全部人员信息
                                if (split.length > 2) {
                                    companyId = split[2];
                                    // 根据公司id,找到此公司下的所有部门
                                    List<Office> officeList = officeService.list(new QueryWrapper<Office>().lambda().eq(Office::getParentId, companyId));
                                    Set officeIdSet = new HashSet();
                                    for (Office office : officeList) {
                                        if (StringUtils.isNotBlank(office.getId())) {
                                            officeIdSet.add(office.getId());
                                        }
                                    }
                                    List<String> officeIdList = Lists.newArrayList(officeIdSet);
                                    // 拿到这些部门的id
                                    //List<String> officeIdList = officeList.stream().distinct().map(Office::getId).collect(Collectors.toList());
                                    // 拿到所有公有部门的id
                                    List<String> officePublicIdList = officeService.list(new LambdaQueryWrapper<Office>().eq(Office::getIsPublic, "1")).stream().map(Office::getId).collect(Collectors.toList());
                                    // 拿到直属公司的id
                                    officeIdList.add(companyId);
                                    // 最后得到的所有部门的id
                                    officeIdList.addAll(officePublicIdList);
                                    List<String> lastIds = officeIdList.stream().distinct().collect(Collectors.toList());
                                    // 添加筛选条件为这些部门的id
                                    queryWrapper.in("a.office_id", lastIds);
                                }
                            }
                        } else if (StringUtils.isBlank(userDTO.getCompanyDTO().getId()) && StringUtils.isNotBlank(userDTO.getOfficeDTO().getId())) {
                            // officeDTO.id不是空，companyDTO.id是空的话，说明前端组件点击的部门查询
                            queryWrapper.eq("a.office_id", userDTO.getOfficeDTO().getId());
                        }
                    }
                }
            }
        }
        if (ObjectUtil.isNotEmpty(userDTO)) {
            // 当certType传值时，获取拥有此资格证类型的人员
            if (StringUtils.isNotBlank(userDTO.getCertType())) {
                queryWrapper.eq("sc.type", userDTO.getCertType());
            }
        }
        IPage<UserDTO> result = userService.userFindPage(page, queryWrapper);
        return ResponseEntity.ok(result);
    }

    /**
     * 签字注师列表查询
     *
     * @param userDTO
     * @param page
     * @return
     */
    @ApiLog("签字注师列表查询")
    @ApiOperation(value = "签字注师列表查询")
    //@PreAuthorize("hasAuthority('sys:user:list')")
    @GetMapping("findUserList")
    public ResponseEntity findUserList(UserDTO userDTO, Page<UserDTO> page) throws Exception {
        QueryWrapper<UserDTO> queryWrapper = QueryWrapperGenerator.buildQueryCondition(userDTO, UserDTO.class);
        // 管理员查询不限制
        Boolean isAdmin = false;
        UserDTO currentUserDTO = UserUtils.getCurrentUserDTO();
        if (currentUserDTO != null && CollectionUtil.isNotEmpty(currentUserDTO.getRoleDTOList())) {
            for (RoleDTO roleDTO : currentUserDTO.getRoleDTOList()) {
                if (roleDTO.getEnName().equals("sys")) {
                    isAdmin = true;
                    break;
                }
            }
        }
        if (!isAdmin) {
            queryWrapper.isNull("a.is_admin");
            if (ObjectUtil.isNotEmpty(userDTO)) {
                if (ObjectUtil.isNotEmpty(userDTO.getCompanyDTO()) && ObjectUtil.isNotEmpty(userDTO.getOfficeDTO())) {
                    String id = UserUtils.getCurrentUserDTO().getCompanyDTO().getId();
                    if (StringUtils.isNotBlank(userDTO.getCertType())) {
                        //获取当前登陆人是否事中审公司人员
                        /*if(officeDTO.getParentIds().contains("1615171302381182978")){

                        }*/
                    } else {
                        // 当不是精确的部门查询时，再添加下面的筛选条件
                        if ((StringUtils.isNotBlank(userDTO.getCompanyDTO().getId()) && StringUtils.isBlank(userDTO.getOfficeDTO().getId()))
                                || "true".equals(userDTO.getSelectAll())) {
                            // officeDTO.id是空，companyDTO.id不是空的话，说明前端组件点击的集团来进行查询
                            // selectAll为‘true’的话，说明前端没有选择集团或者部门查询，这个时候要展示全部人员
                            // 根据当前用户的部门id找到此部门的ids
                            String ids = officeService.getById(UserUtils.getCurrentUserDTO().getOfficeDTO().getId()).getParentIds();
                            // 根据ids分隔后的index[2],找到当前用户的所属公司id
                            String companyId = null;
                            String[] split = ids.split(",");
                            // split.length大于2，说明当前登录人所属部门是普通部门，展示部分人员信息
                            // 否则，当前登录人所属公共类部门（忘了叫什么类部门了，就是总经办那种部门），展示全部人员信息
                            if (split.length > 2) {
                                companyId = split[2];
                                // 根据公司id,找到此公司下的所有部门
                                List<Office> officeList = officeService.list(new QueryWrapper<Office>().lambda().eq(Office::getParentId, companyId));
                                Set officeIdSet = new HashSet();
                                for (Office office : officeList) {
                                    if (StringUtils.isNotBlank(office.getId())) {
                                        officeIdSet.add(office.getId());
                                    }
                                }
                                List<String> officeIdList = Lists.newArrayList(officeIdSet);
                                // 拿到所有公有部门的id
                                List<String> officePublicIdList = officeService.list(new LambdaQueryWrapper<Office>().eq(Office::getIsPublic, "1")).stream().map(Office::getId).collect(Collectors.toList());
                                // 拿到直属公司的id
                                officeIdList.add(companyId);
                                // 最后得到的所有部门的id
                                officeIdList.addAll(officePublicIdList);
                                List<String> lastIds = officeIdList.stream().distinct().collect(Collectors.toList());
                                // 添加筛选条件为这些部门的id
                                queryWrapper.in("a.office_id", lastIds);
                            }
                        } else if (StringUtils.isBlank(userDTO.getCompanyDTO().getId()) && StringUtils.isNotBlank(userDTO.getOfficeDTO().getId())) {
                            // officeDTO.id不是空，companyDTO.id是空的话，说明前端组件点击的部门查询
                            queryWrapper.eq("a.office_id", userDTO.getOfficeDTO().getId());
                        }
                    }
                }
            }
        }
        if (ObjectUtil.isNotEmpty(userDTO)) {
            // 当certType传值时，获取拥有此资格证类型的人员
            if (StringUtils.isNotBlank(userDTO.getCertType())) {
                queryWrapper.orderByAsc("post2.name");
                //获取当前登录人信息
                UserDTO loginUserDTO = UserUtils.getCurrentUserDTO();
                //如果当前登录人是中审的管理咨询部人员，则注会列表中添加该部门选择项
                if (null != loginUserDTO && null != loginUserDTO.getOfficeDTO()) {
                    OfficeDTO officeDTO = loginUserDTO.getOfficeDTO();
                    if (StringUtils.isNotBlank(officeDTO.getId())) {
                        if ("1602840084816138241".equals(officeDTO.getId())) {
                            queryWrapper.and(
                                    wrapper -> wrapper.eq("sc.type", userDTO.getCertType()).or().eq("a.office_id", "1602840084816138241")
                            );
                            //queryWrapper.eq("sc.type",userDTO.getCertType()).or().eq("a.office_id","1602840084816138241");
                        } else {
                            queryWrapper.eq("sc.type", userDTO.getCertType());
                        }
                    } else {
                        queryWrapper.eq("sc.type", userDTO.getCertType());
                    }
                } else {
                    queryWrapper.eq("sc.type", userDTO.getCertType());
                }

            }
            if (userDTO.getTenantDTO() != null && StrUtil.isNotBlank(userDTO.getTenantDTO().getId())) {
                queryWrapper.eq("a.tenant_id", userDTO.getTenantDTO().getId());
            }
        }
        IPage<UserDTO> result = userService.findUserList(page, queryWrapper);
        IPage<UserDTO> result2 = userService.findPage3(userDTO);
        //判断 如果是签字注师筛选，则获取签字注师的被选择次数
        if (StringUtils.isNotBlank(userDTO.getCertType()) && "6".equals(userDTO.getCertType())) {
            List<UserDTO> userList = result.getRecords();
            List<UserDTO> user2List = result2.getRecords();
            List<String> idList = Lists.newArrayList();
            for (UserDTO dto : user2List) {
                idList.add(dto.getId());
            }
            for (UserDTO info : userList) {
                if (idList.size() > 0) {
                    if (idList.contains(info.getId())) {
                        info.setAccountantUserFlag(0);
                    } else {
                        info.setAccountantUserFlag(1);
                    }
                } else {
                    if ("潘中".equals(info.getName())) {
                        info.setAccountantUserFlag(0);
                    } else {
                        info.setAccountantUserFlag(1);
                    }
                }
                /*if("潘中".equals(info.getName())){
                    info.setAccountantUserFlag(0);
                }else{
                    info.setAccountantUserFlag(1);
                }*/
                Integer accountantUserCount = userService.getAccountantUserCount(info.getId());
                info.setAccountantUserCount(accountantUserCount);
            }
        }
        return ResponseEntity.ok(result);
    }


    @GetMapping("list2")
    public ResponseEntity list2(UserDTO userDTO, Page<UserDTO> page) throws Exception {
        if (ObjectUtil.isNotEmpty(userDTO.getOfficeDTO().getId()) || ObjectUtil.isNotEmpty(userDTO.getLoginName())) {
            IPage<UserDTO> result = userService.findPage3(userDTO);
            //判断 如果是签字注师筛选，则获取签字注师的被选择次数
            if (StringUtils.isNotBlank(userDTO.getCertType()) && "6".equals(userDTO.getCertType())) {
                List<UserDTO> userList = result.getRecords();
                for (UserDTO info : userList) {
                    //if ("潘中".equals(info.getName())) {
                    info.setAccountantUserFlag(0);
                    /*} else {
                        info.setAccountantUserFlag(1);
                    }*/
                    Integer accountantUserCount = userService.getAccountantUserCount(info.getId());
                    info.setAccountantUserCount(accountantUserCount);
                }
            }
            result.setTotal(result.getRecords().size());
            return ResponseEntity.ok(result);

        } else {
            IPage<UserDTO> result = userService.findPage1(userDTO, page);
            //判断 如果是签字注师筛选，则获取签字注师的被选择次数
            if (StringUtils.isNotBlank(userDTO.getCertType()) && "6".equals(userDTO.getCertType())) {
                List<UserDTO> userList = result.getRecords();
                for (UserDTO info : userList) {
//                    if ("潘中".equals(info.getName())) {
//                        info.setAccountantUserFlag(0);
//                    } else {
//                        info.setAccountantUserFlag(1);
//                    }
                    info.setAccountantUserFlag(0);
                    Integer accountantUserCount = userService.getAccountantUserCount(info.getId());
                    info.setAccountantUserCount(accountantUserCount);
                }
            }
            return ResponseEntity.ok(result);
        }
    }

//    /**
//     * 查询列表(排除admin)
//     *
//     * @param userDTO
//     * @param page
//     * @return
//     */
//    @ApiLog("用户数据列表")
//    @ApiOperation(value = "用户数据列表")
//    @PreAuthorize("hasAuthority('sys:user:list')")
//    @GetMapping("list2")
//    public ResponseEntity list2(UserDTO userDTO, Page <UserDTO> page) throws Exception {
//        QueryWrapper <UserDTO> queryWrapper = QueryWrapperGenerator.buildQueryCondition ( userDTO, UserDTO.class );
//        if ( userDTO.getTenantDTO ( ) != null && StrUtil.isNotBlank ( userDTO.getTenantDTO ( ).getId ( ) ) ) {
//            queryWrapper.eq ( "a.tenant_id", userDTO.getTenantDTO ( ).getId ( ) );
//        }
//        IPage <UserDTO> result = userService.findPage2 ( page, queryWrapper );
//        return ResponseEntity.ok ( result );
//    }

    /**
     * 保存人员执业资质
     *
     * @param userDTO
     * @return
     */
    @DemoMode
    @ApiLog("保存人员执业资质")
    @PreAuthorize("hasAnyAuthority('sys:user:add', 'sys:user:edit')")
    @ApiOperation(value = "保存人员执业资质")
    @PostMapping("saveCertList")
    public ResponseEntity saveCertList(@Valid @RequestBody UserDTO userDTO) {
        userService.saveCertList(userDTO);
        return ResponseEntity.ok("保存成功!");
    }

    /**
     * 保存用户
     *
     * @param userDTO
     * @return
     */
    @DemoMode
    @ApiLog("保存用户")
    @PreAuthorize("hasAnyAuthority('sys:user:add', 'sys:user:edit')")
    @ApiOperation(value = "保存用户")
    @PostMapping("save")
    public ResponseEntity save(@Valid @RequestBody UserDTO userDTO) {
        // 如果新密码为空，则不更换密码
        if (StrUtil.isNotBlank(userDTO.getNewPassword())) {
            userDTO.setPassword(SecurityUtils.encryptPassword(userDTO.getNewPassword()));
            userDTO.setUpPassword("0");
        }
        if (!UserUtils.isCheckLoginName(userDTO.getOldLoginName(), userDTO.getLoginName(), userDTO.getTenantDTO().getId())) {
            return ResponseEntity.badRequest().body("保存用户'" + userDTO.getLoginName() + "'失败，登录名已存在!");
        }
        // 保存用户信息
        userService.saveOrUpdate(userDTO);
        //清除用户缓存
        List<UserDTO> onLineUserList = SpringUtil.getBean(IUserApi.class).getOnLineUserList(userDTO.getLoginName(), "");
        for (UserDTO dto : onLineUserList) {
            SpringUtil.getBean(IUserApi.class).clearCache ( dto );
            redisUtils.delete ( CacheNames.USER_CACHE_TOKEN, dto.getToken() );
            redisUtils.delete ( CacheNames.USER_CACHE_ONLINE_USERS, dto.getToken() );
        }
//        return ResponseEntity.ok ( "保存用户'" + userDTO.getLoginName ( ) + "'成功!" );
        return ResponseUtil.newInstance().add("userId", userDTO.getId()).ok("保存用户'" + userDTO.getLoginName() + "'成功!");
    }

    /**
     * 用户信息显示编辑保存
     *
     * @param userDTO
     * @return
     */
    @DemoMode
    @ApiLog("修改个人资料")
    @ApiOperation(value = "修改个人资料")
    @PostMapping("saveInfo")
    public ResponseEntity saveInfo(@RequestBody UserDTO userDTO) {
        userService.updateById(UserWrapper.INSTANCE.toEntity(userDTO));
        UserUtils.deleteCache(UserUtils.getCurrentUserDTO());

        UserDTO newestUserDTO = UserUtils.getCurrentUserDTO();
        if (StrUtil.isNotBlank(userDTO.getOldPassword()) && StrUtil.isNotBlank(userDTO.getNewPassword())) {
            if (SecurityUtils.validatePassword(userDTO.getOldPassword(), newestUserDTO.getPassword())) {
                User user = new User(newestUserDTO.getId());
                user.setPassword(SecurityUtils.encryptPassword(userDTO.getNewPassword()));
                user.setUpPassword("1");
                userService.updateById(user);
                UserUtils.deleteCache(userDTO);
                return ResponseEntity.ok("修改密码成功！");
            } else {
                return ResponseEntity.badRequest().body("修改密码失败，旧密码错误！");
            }
        }

        return ResponseEntity.ok("修改个人资料成功!");
    }

    /**
     * 批量删除用户
     */
    @DemoMode
    @ApiLog("删除用户")
    @ApiOperation(value = "删除用户")
    @PreAuthorize("hasAuthority('sys:user:del')")
    @DeleteMapping("delete")
    public ResponseEntity delete(String ids) {
        String idArray[] = ids.split(",");
        StringBuffer msg = new StringBuffer();
        boolean success = true;
        for (String id : idArray) {
            UserDTO userDTO = userService.get(id);
            if (UserUtils.getCurrentUserDTO().getId().equals(userDTO.getId())) {
                success = false;
                msg.append("[" + userDTO.getLoginName() + "]删除失败，不允许删除当前用户!<br/>");
            } else if (userDTO.isAdmin()) {
                success = false;
                msg.append("[" + userDTO.getLoginName() + "]删除失败，不允许删除平台管理员!<br/>");//删除用户失败, 不允许删除平台管理员用户
            } else {
                msg.append("[" + userDTO.getLoginName() + "]删除成功!<br/>");
                userService.deleteUser(userDTO);//删除用户成功
            }
        }
        if (success) {
            return ResponseEntity.ok(msg.toString());
        } else {
            return ResponseEntity.badRequest().body(msg.toString());
        }
    }

    /**
     * 导出用户数据
     *
     * @param userDTO
     * @param page
     * @param response
     * @throws Exception
     */
    @ApiLog("导出用户数据")
    @PreAuthorize("hasAnyAuthority('sys:user:export')")
    @GetMapping("export")
    @ApiOperation(value = "导出用户excel")
    public void exportFile(UserDTO userDTO, Page<UserDTO> page, ExcelOptions options, HttpServletResponse response) throws Exception {
        String fileName = options.getFilename();
        QueryWrapper<UserDTO> queryWrapper = QueryWrapperGenerator.buildQueryCondition(userDTO, UserDTO.class);
        if (userDTO.getTenantDTO() != null && StrUtil.isNotBlank(userDTO.getTenantDTO().getId())) {
            queryWrapper.eq("a.tenant_id", userDTO.getTenantDTO().getId());
        }
        List<UserDTO> result;
        if (ExportMode.current.equals(options.getMode())) {
            result = userService.findPage(page, queryWrapper).getRecords();
        } else if (ExportMode.selected.equals(options.getMode())) {
            queryWrapper.in("a.id", options.getSelectIds());
            result = userService.findPage(page, queryWrapper).getRecords();
        } else {
            page.setSize(-1);
            page.setCurrent(0);
            result = userService.findPage(page, queryWrapper).getRecords();
        }
        List<String> exportFields = options.getExportFields();
        exportFields.add("mobile");//手机号
        exportFields.add("role");//角色
        exportFields.add("post");//岗位

        UserEasyExcel.newInstance().exportExcel(result, options.getSheetName(), UserDTO.class, fileName, options.getExportFields(), response);
    }

    /**
     * 导出用户数据
     *
     * @param userDTO
     * @param page
     * @param response
     * @throws Exception
     */
    @ApiLog("导出用户数据")
    @GetMapping("exportSignatureScribeFile")
    @ApiOperation(value = "导出用户excel")
    public void exportSignatureScribeFile(UserDTO userDTO, Page<UserDTO> page, ExcelOptions options, HttpServletResponse response) throws Exception {
        String fileName = options.getFilename();
        QueryWrapper<UserDTO> queryWrapper = QueryWrapperGenerator.buildQueryCondition(userDTO, UserDTO.class);
        userDTO.setCertType("6");
        if (StringUtils.isNotBlank(userDTO.getCertType())) {
            queryWrapper.orderByDesc("a.company_id");
            queryWrapper.orderByAsc("a.office_id");
            queryWrapper.orderByDesc("a.name");
            //获取当前登录人信息
            UserDTO loginUserDTO = UserUtils.getCurrentUserDTO();
            //如果当前登录人是中审的管理咨询部人员，则注会列表中添加该部门选择项
            if (null != loginUserDTO && null != loginUserDTO.getOfficeDTO()) {
                OfficeDTO officeDTO = loginUserDTO.getOfficeDTO();
                if (StringUtils.isNotBlank(officeDTO.getId())) {
                    if ("1602840084816138241".equals(officeDTO.getId())) {
                        queryWrapper.and(
                                wrapper -> wrapper.eq("sc.type", userDTO.getCertType()).or().eq("a.office_id", "1602840084816138241")
                        );
                    } else {
                        queryWrapper.eq("sc.type", userDTO.getCertType());
                    }
                } else {
                    queryWrapper.eq("sc.type", userDTO.getCertType());
                }
            } else {
                queryWrapper.eq("sc.type", userDTO.getCertType());
            }

        }

        if (userDTO.getTenantDTO() != null && StrUtil.isNotBlank(userDTO.getTenantDTO().getId())) {
            queryWrapper.eq("a.tenant_id", userDTO.getTenantDTO().getId());
        }
        List<UserDTO> result;
        if (ExportMode.current.equals(options.getMode())) {
            result = userService.findPage(page, queryWrapper).getRecords();
        } else if (ExportMode.selected.equals(options.getMode())) {
            queryWrapper.in("a.id", options.getSelectIds());
            result = userService.findPage(page, queryWrapper).getRecords();
        } else {
            page.setSize(-1);
            page.setCurrent(0);
            result = userService.findPage(page, queryWrapper).getRecords();
        }

        IPage<UserDTO> result2 = userService.findPage3(userDTO);
        //判断 如果是签字注师筛选，则获取签字注师的被选择次数
        if (StringUtils.isNotBlank(userDTO.getCertType()) && "6".equals(userDTO.getCertType())) {
            List<UserDTO> userList = result;
            List<UserDTO> user2List = result2.getRecords();
            List<String> idList = Lists.newArrayList();
            for (UserDTO dto : user2List) {
                idList.add(dto.getId());
            }
            for (UserDTO info : userList) {
                if (idList.size() > 0) {
                    if (idList.contains(info.getId())) {
                        info.setAccountantUserFlag(0);
                    } else {
                        info.setAccountantUserFlag(1);
                    }
                } else {
                    if ("潘中".equals(info.getName())) {
                        info.setAccountantUserFlag(0);
                    } else {
                        info.setAccountantUserFlag(1);
                    }
                }
                Integer accountantUserCount = userService.getAccountantUserCount(info.getId());
                info.setAccountantUserCount(accountantUserCount);
            }
        }

        UserEasyExcel.newInstance().exportExcel(result, options.getSheetName(), UserSignatureScribeDTO.class, fileName, options.getExportFields(), response);
    }

    /**
     * 导入用户数据
     *
     * @return
     */
    @DemoMode
    @PreAuthorize("hasAnyAuthority('sys:user:import')")
    @PostMapping("import")
    @ApiOperation(value = "导入用户excel")
    public ResponseEntity importFile(MultipartFile file) throws IOException {
        String result = UserEasyExcel.newInstance(userService, UserWrapper.INSTANCE).importExcel(file, UserDTO.class);
        List<UserDTO> allUserInfo = userService.getAllUserInfo();
        if (redisUtils.hasKey("user:cache:user:all:info")) {
            //先清除redis中的数据
            redisUtils.delete(CacheNames.USER_CACHE_USER_ALL_INFO, "user:cache:user:all:info");
            //再次将人员信息存入到redis中
            redisUtils.set(CacheNames.USER_CACHE_USER_ALL_INFO, "user:cache:user:all:info", allUserInfo);
        } else {
            //将人员信息存入到redis中
            redisUtils.set(CacheNames.USER_CACHE_USER_ALL_INFO, "user:cache:user:all:info", allUserInfo);
        }
        return ResponseEntity.ok(result);
    }

    /**
     * 下载导入用户数据模板
     *
     * @param response
     * @return
     */
    @PreAuthorize("hasAnyAuthority('sys:user:import')")
    @GetMapping("import/template")
    @ApiOperation(value = "下载模板")
    public void importFileTemplate(HttpServletResponse response) throws IOException {
        String fileName = "用户数据导入模板.xlsx";
        List<UserDTO> list = Lists.newArrayList();
        list.add(UserUtils.getCurrentUserDTO());
        UserEasyExcel.newInstance().exportExcel(list, "用户数据", UserDTO.class, fileName, null, response);
    }


    /**
     * 返回用户信息
     *
     * @return
     */
    @ApiLog("获取当前用户信息")
    @GetMapping("info")
    @ApiOperation(value = "获取当前用户信息")
    public ResponseEntity infoData() {
        return ResponseUtil.newInstance()
                .add("role", UserUtils.getRoleDTOList())
                .add("user", UserUtils.getCurrentUserDTO())
                .add("currentTenantId", TenantUtils.getTenantId())
                .ok("获取个人信息成功!");
    }

    /**
     * 修改密码
     *
     * @param oldPassword
     * @param newPassword
     * @return
     */
    @DemoMode
    @ApiLog("修改密码")
    @PostMapping("/savePwd")
    public ResponseEntity savePwd(String oldPassword, String newPassword) {
        UserDTO userDTO = UserUtils.getCurrentUserDTO();
        if (StrUtil.isNotBlank(oldPassword) && StrUtil.isNotBlank(newPassword)) {
            if (SecurityUtils.validatePassword(oldPassword, userDTO.getPassword())) {
                User user = new User(userDTO.getId());
                user.setPassword(SecurityUtils.encryptPassword(newPassword));
                user.setUpPassword("1");
                user.setUpdatePasswordDate(new Date());
                userService.updateById(user);
                UserUtils.deleteCache(userDTO);
                return ResponseEntity.ok("修改密码成功！");
            } else {
                return ResponseEntity.badRequest().body("修改密码失败，旧密码错误！");
            }
        }
        return ResponseEntity.badRequest().body("参数错误！");
    }

    /**
     * 重置密码
     *
     * @param id
     * @return
     */
    @DemoMode
    @ApiLog("重置密码")
    @PostMapping("/resetPwd")
    public ResponseEntity resetPwd(String id) {
        if(StringUtils.isNotBlank(id)){
            User user = new User(id);
            if(StringUtils.isNotBlank(user.getId())){
                UserDTO userDTO =  SpringUtil.getBean(IUserApi.class).getById(user.getId());
                user.setPassword(SecurityUtils.encryptPassword("123456"));
                user.setUpPassword("1");
                user.setUpdatePasswordDate(new Date());
                userService.updateById(user);
                UserUtils.deleteCache(userDTO);
                return ResponseEntity.ok("重置密码成功！");
            }else{
                return ResponseEntity.badRequest().body("参数错误！");
            }
        }
        return ResponseEntity.badRequest().body("参数错误！");
    }

    /**
     * 修改密码(超过90天未修改密码)
     *
     * @param oldPassword
     * @param newPassword
     * @return
     */
    @DemoMode
    @ApiLog("修改密码(超过90天未修改密码)")
    @PostMapping("/saveExceedPwd")
    public ResponseEntity saveExceedPwd(String oldPassword, String newPassword) {
        UserDTO userDTO = UserUtils.getCurrentUserDTO();
        if (StrUtil.isNotBlank(oldPassword) && StrUtil.isNotBlank(newPassword)) {
            if (SecurityUtils.validatePassword(oldPassword, userDTO.getPassword())) {
                User user = new User(userDTO.getId());
                user.setPassword(SecurityUtils.encryptPassword(newPassword));
                user.setUpPassword("1");
                user.setUpdatePasswordDate(new Date());
                userService.updateById(user);
                UserUtils.deleteCache(userDTO);
                return ResponseEntity.ok("修改密码成功！");
            } else {
                return ResponseEntity.badRequest().body("修改密码失败，旧密码错误！");
            }
        }
        return ResponseEntity.badRequest().body("参数错误！");
    }

    /**
     * 手机端-修改密码
     *
     * @return
     */
    @DemoMode
    @ApiLog("手机端-修改密码")
    @PostMapping("/savePwdByPhone")
    public ResponseEntity savePwdByPhone(@Valid @RequestBody UserVO userVO) {
        UserDTO userDTO = userService.get(userVO.getUserId());
        if (StrUtil.isNotBlank(userVO.getOldPassword()) && StrUtil.isNotBlank(userVO.getNewPassword())) {
            if (SecurityUtils.validatePassword(userVO.getOldPassword(), userDTO.getPassword())) {
                User user = new User(userDTO.getId());
                user.setPassword(SecurityUtils.encryptPassword(userVO.getNewPassword()));
                user.setUpPassword("1");
                userService.updateById(user);
                UserUtils.deleteCache(userDTO);
                return ResponseEntity.ok("修改密码成功！");
            } else {
                return ResponseEntity.badRequest().body("修改密码失败，旧密码错误！");
            }
        }
        return ResponseEntity.badRequest().body("参数错误！");
    }

    /**
     * 获取菜单
     *
     * @return
     */
    @ApiLog("获取用户菜单")
    @GetMapping("getMenus")
    public ResponseEntity getMenus() {

//        return ResponseUtil.newInstance ()
//                .add ("dictList",  DictUtils.getDictMap()) //获取字典
//                .add("permissions", UserUtils.getPermissions())
//                .add ("menuList", MenuUtils.getMenuVOs () ).ok ();
        /**
         * 修改的原因，在某些性能很差的服务器上该方法的执行速度可以提升十几倍。当然在性能优良的服务器上，两种方式耗时几无区别。
         */
        Map map = new HashMap();
        map.put("dictList", DictUtils.getDictMap()); //获取字典
        map.put("permissions", UserUtils.getPermissions());
        map.put("menuList", MenuUtils.getMenuVOs());
        String res = new Gson().toJson(map);
        return ResponseEntity.ok(res);
    }

    /**
     * 获取机构JSON数据。
     *
     * @param officeName 部门名称
     * @param extId      排除的ID
     * @param type       类型（1：公司；2：部门）
     * @param showAll    是否显示不可用数据 1 显示 0 隐藏
     * @return
     */
    @ApiLog("获取部门用户数据")
    @GetMapping("treeUserDataAllOffice")
    public ResponseEntity treeUserDataAllOffice(@RequestParam(required = false) String officeName, @RequestParam(required = false) String extId, @RequestParam(required = false) String type, @RequestParam(required = false, defaultValue = CommonConstants.NO) String showAll) {
        List<OfficeDTO> list = officeService.getOfficeAllByOfficeName(officeName);
        if (list.size() > 0) {
            List<String> officeIds = Lists.newArrayList();
            for (OfficeDTO info : list) {
                info.setTypeFlag(true);
                officeIds.add(info.getId());
            }
            //根据部门查询对应部门下的所有数据
            List<OfficeDTO> officeDTOList = userService.getUserByOffice(officeIds, type);
            list.addAll(officeDTOList);
        }
        List rootTree = officeService.getRootTree(list, extId, type, showAll, "1");
        return ResponseEntity.ok(rootTree);
    }

    /**
     * 获取评估机构JSON数据。
     *
     * @param officeName 部门名称
     * @param extId      排除的ID
     * @param type       类型（1：公司；2：部门）
     * @param showAll    是否显示不可用数据 1 显示 0 隐藏
     * @return
     */
    @ApiLog("获取评估部门用户数据")
    @GetMapping("treeUserDataAccessOffice")
    public ResponseEntity treeUserDataAccessOffice(@RequestParam(required = false) String officeName, @RequestParam(required = false) String extId, @RequestParam(required = false) String type, @RequestParam(required = false, defaultValue = CommonConstants.NO) String showAll) {
        officeName = "评估部";
        List<OfficeDTO> list = officeService.getOfficeAllByOfficeName(officeName);
        if (list.size() > 0) {
            List<String> officeIds = Lists.newArrayList();
            for (OfficeDTO info : list) {
                info.setTypeFlag(true);
                officeIds.add(info.getId());
            }
            //根据部门查询对应部门下的所有数据
            List<OfficeDTO> officeDTOList = userService.getUserByOffice(officeIds, type);
            list.addAll(officeDTOList);
        }
        List rootTree = officeService.getAccessRootTree(list, extId, type, showAll, "1");
        return ResponseEntity.ok(rootTree);
    }

    /**
     * 获取财务机构JSON数据。
     *
     * @param officeName 部门名称
     * @param extId      排除的ID
     * @param type       类型（1：公司；2：部门）
     * @param showAll    是否显示不可用数据 1 显示 0 隐藏
     * @return
     */
    @ApiLog("获取财务部门用户数据")
    @GetMapping("treeUserDataFinanceOffice")
    public ResponseEntity treeUserDataFinanceOffice(@RequestParam(required = false) String officeName, @RequestParam(required = false) String extId, @RequestParam(required = false) String type, @RequestParam(required = false, defaultValue = CommonConstants.NO) String showAll) {
        officeName = "兴光会计师事务所";
        List<OfficeDTO> list = officeService.getOfficeAllByOfficeName(officeName);
        if (list.size() > 0) {
            List<String> officeIds = Lists.newArrayList();
            for (OfficeDTO info : list) {
                info.setTypeFlag(true);
                officeIds.add(info.getId());
            }
            //根据部门查询对应部门下的所有数据
            List<OfficeDTO> officeDTOList = userService.getUserByOffice(officeIds, type);
            list.addAll(officeDTOList);
        }
        List rootTree = officeService.getFinanceRootTree(list, extId, type, showAll, "1");
        return ResponseEntity.ok(rootTree);
    }

    /**
     * 判断当前用户是否是管理员
     *
     * @return
     */
    @ApiLog("判断当前用户是否是管理员")
    @GetMapping("isAdmin")
    @ApiOperation(value = "判断当前用户是否是管理员")
    public Boolean isAdmin() {
        UserDTO currentUserDTO = UserUtils.getCurrentUserDTO();
        return "admin".equals(currentUserDTO.getLoginName()) || UserUtils.getCurrentUserDTO().isAdmin();
    }

    /**
     * 判断当前用户是否是会计所长
     */
    @ApiLog("判断当前用户是否是会计所长")
    @GetMapping("isKjsz")
    @ApiOperation(value = "判断当前用户是否是会计所长")
    public boolean isKjsz() {
        UserDTO currentUserDTO = UserUtils.getCurrentUserDTO();
        for (RoleDTO roleDTO : currentUserDTO.getRoleDTOList()) {
            if (ObjectUtils.isNotEmpty(roleDTO)) {
                if ("kjsz".equals(roleDTO.getEnName())) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 判断当前用户是否是专家
     */
    @ApiLog("判断当前用户角色是否是专家")
    @GetMapping("isZj")
    @ApiOperation(value = "判断当前用户角色是否是专家")
    public boolean isZj() {
        UserDTO currentUserDTO = UserUtils.getCurrentUserDTO();
        for (RoleDTO roleDTO : currentUserDTO.getRoleDTOList()) {
            if (ObjectUtils.isNotEmpty(roleDTO)) {
                if ("dgsbx".equals(roleDTO.getEnName())) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 判断当前用户是否是多公司报销(部门主任)
     */
    @ApiLog("判断当前用户是否是多公司报销(部门主任)")
    @GetMapping("isDgsbxBmzr")
    @ApiOperation(value = "判断当前用户是否是多公司报销(部门主任)")
    public boolean isDgsbxBmzr() {
        UserDTO currentUserDTO = UserUtils.getCurrentUserDTO();
        for (RoleDTO roleDTO : currentUserDTO.getRoleDTOList()) {
            if (ObjectUtils.isNotEmpty(roleDTO)) {
                if ("dgsbx_bmzr".equals(roleDTO.getEnName())) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 判断当前用户是否是总经办人员
     */
    @ApiLog("判断当前用户是否是总经办人员")
    @GetMapping("isZjbry")
    @ApiOperation(value = "判断当前用户是否是总经办人员")
    public boolean isZjbry() {
        UserDTO currentUserDTO = UserUtils.getCurrentUserDTO();
        for (RoleDTO roleDTO : currentUserDTO.getRoleDTOList()) {
            if (ObjectUtils.isNotEmpty(roleDTO)) {
                if ("zjbry".equals(roleDTO.getEnName()) || "zjbbx".equals(roleDTO.getEnName()) || "zsbxqxld".equals(roleDTO.getEnName())) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 判断当前用户是否是总经办人员
     */
    @ApiLog("判断当前用户是否是苏州分公司智永祥部门人员")
    @GetMapping("isSzZyx")
    @ApiOperation(value = "判断当前用户是否是苏州分公司智永祥部门人员")
    public boolean isSzZyx() {
        UserDTO currentUserDTO = UserUtils.getCurrentUserDTO();
        for (RoleDTO roleDTO : currentUserDTO.getRoleDTOList()) {
            if (ObjectUtils.isNotEmpty(roleDTO)) {
                if ("zsbxszzyx".equals(roleDTO.getEnName())) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 判断当前用户是否是盛所部门主任
     */
    @ApiLog("判断当前用户是否是盛所部门主任")
    @GetMapping("isSs")
    @ApiOperation(value = "判断当前用户是否是盛所部门主任")
    public boolean isSs() {
        UserDTO currentUserDTO = UserUtils.getCurrentUserDTO();
        for (RoleDTO roleDTO : currentUserDTO.getRoleDTOList()) {
            if (ObjectUtils.isNotEmpty(roleDTO)) {
                if ("ssbmzr".equals(roleDTO.getEnName())) {
                    return true;
                }
            }
        }
        return false;
    }


    /**
     * 判断当前用户是否是中审报告归档管理员
     */
    @ApiLog("判断当前用户是否是中审报告归档管理员")
    @GetMapping("isBggdgly")
    @ApiOperation(value = "判断当前用户是否是中审报告归档管理员")
    public boolean isBggdgly() {
        UserDTO currentUserDTO = UserUtils.getCurrentUserDTO();
        for (RoleDTO roleDTO : currentUserDTO.getRoleDTOList()) {
            if (ObjectUtils.isNotEmpty(roleDTO)) {
                if ("zsbggdgly".equals(roleDTO.getEnName())) {
                    return true;
                }
            }
        }
        return false;
    }


    /**
     * 通过手机号获取验证码（忘记密码）
     *
     * @param mobile 手机号码
     * @return
     */
    @ApiOperation(value = "通过手机号获取验证码（忘记密码）")
    @GetMapping(value = "/getPhoneCode")
    public ResponseEntity<HashMap<String, Object>> getPhoneCode(@RequestParam("mobile") String mobile) {
        HashMap<String, Object> j = new HashMap<String, Object>();
        //验证该手机号是否已经进行注册
        User user = userService.getOne(new LambdaQueryWrapper<User>().eq(User::getMobile, mobile));
        if (ObjectUtil.isNotEmpty(user)) {
            //生成四位随机验证码
            String randomCode = String.valueOf((int) (Math.random() * 9000 + 1000));
            System.out.println(randomCode);
//            redisUtils.setEx(mobile+ "resetPassword", randomCode, 300, TimeUnit.SECONDS);
            HashMap<String, Object> result = null;
            try {
                //调用工具类返回结果
                result = ALiYunSmsUtil.updatePasswordSendSms(mobile, randomCode);
                Integer statusCode = (Integer) result.get("statusCode");
                if (200 == statusCode) {
                    j.put("success", true);
                    j.put("message", "短信发送成功!");
                    //存放验证码
                    //以手机号+为key 五分钟为时效 将验证码进行短期存储
                    redisUtils.setEx(mobile + "resetPassword", randomCode, 300, TimeUnit.SECONDS);
                }else if(10001 == statusCode){
                    j.put("success", false);
                    String message = (String) result.get("message");
                    //j.setMsg("短信发送失败，错误代码："+result+"，请联系管理员。");
                    j.put("message",message);
                    j.put("ErrorXml",result);
                }else if(10002 == statusCode){
                    j.put("success", false);
                    j.put("message","账户短信量余额不足，请联系管理员进行充值!");
                    j.put("ErrorXml",result);
                }else if(10003 == statusCode){
                    j.put("success", false);
                    j.put("message","手机号获取验证码次数已达每日上限!");
                    j.put("ErrorXml",result);
                }else{
                    j.put("success", false);
                    j.put("message","短信发送失败，错误代码：101，请联系管理员!");
                    j.put("ErrorXml",result);
                }
            } catch (Exception e) {
                e.printStackTrace();
                j.put("success", false);
                j.put("message", "短信发送失败!");
            }
        } else {
            j.put("success", false);
            j.put("message", "当前手机号未注册!请联系管理员");
        }
        return ResponseEntity.ok(j);
    }

    /**
     * 修改密码
     *
     * @param mobile
     * @param code
     * @param newPassword
     * @return
     */
    @GetMapping(value = "/saveNewPassword")
    @ApiOperation(value = "保存新密码")
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity<HashMap<String, Object>> saveNewPassword(@RequestParam("mobile") String mobile,
                                                                   @RequestParam("code") String code,
                                                                   @RequestParam("newPassword") String newPassword) {
        HashMap<String, Object> j = new HashMap<String, Object>();
        User user1 = userService.getOne(new LambdaQueryWrapper<User>().eq(User::getMobile, mobile));
        // 判断当前页面输入的验证码是否与redis中存储的验证码匹配
        String redisCode = (String) redisUtils.get(mobile + "resetPassword");
        if (org.apache.commons.lang3.StringUtils.isNotBlank(redisCode)) {
            if (redisCode.equals(code)) {
                // 进行密码修改操作
                User user = userService.getOne(new LambdaQueryWrapper<User>().eq(User::getMobile, mobile));
                if (ObjectUtil.isNotEmpty(user)) {
                    if (org.apache.commons.lang3.StringUtils.isNotBlank(newPassword)) {
                        user.setPassword(SecurityUtils.encryptPassword(newPassword));
                        user.setUpPassword("1");
                        userService.updateById(user); // 修改密码
                        redisUtils.delete(mobile + "resetPassword"); // 删除redis中的key
                        redisUtils.delete(CacheNames.USER_CACHE_LOGIN_NAME, user1.getTenantId() + ":" + mobile);
                        j.put("success", true);
                        j.put("message", "密码修改成功!");
                    } else {
                        j.put("success", false);
                        j.put("message", "请输入有效密码!");
                    }
                } else {
                    j.put("success", false);
                    j.put("message", "当前手机号未注册!");
                }
            } else {
                j.put("success", false);
                j.put("message", "验证码输入不正确!");
            }
        } else {
            j.put("success", false);
            j.put("message", "当前手机验证码已失效，请重新发送验证码!");
        }
        return ResponseEntity.ok(j);
    }

    /**
     * 获取当前用户是否已经修改过密码
     *
     * @return
     */
    @ApiLog("获取当前用户是否已经修改过密码")
    @GetMapping("isUpdatePassword")
    @ApiOperation(value = "获取当前用户是否已经修改过密码")
    public ResponseEntity<Boolean> isUpdatePassword() {
        // 返回结果  true为以修改  false为未修改
        UserDTO userDTO = UserUtils.getCurrentUserDTO();
        Boolean updatePassword = userService.isUpdatePassword(userDTO.getId());
        return ResponseEntity.ok(updatePassword);
    }


    /**
     * 获取财务机构JSON数据(会计,总经办)。
     *
     * @param tenantId 部门id
     * @param extId    排除的ID
     * @param type     类型（1：公司；2：部门）
     * @param showAll  是否显示不可用数据 1 显示 0 隐藏
     * @return
     */
    @ApiLog("获取财务部门用户数据")
    @GetMapping("treeFinanceOffice")
    public ResponseEntity treeFinanceOffice(@RequestParam(required = false) String tenantId, @RequestParam(required = false) String extId, @RequestParam(required = false) String type, @RequestParam(required = false, defaultValue = CommonConstants.NO) String showAll) {
        UserDTO userDTO = UserUtils.getCurrentUserDTO();
        String id = userDTO.getTenantDTO().getId();
        if (id.equals("10005")) {
            String officeName = "兴光会计师事务所";
            List<OfficeDTO> list = officeService.getOfficeAllByOfficeName(officeName);
            if (list.size() > 0) {
                List<String> officeIds = Lists.newArrayList();
                for (OfficeDTO info : list) {
                    info.setTypeFlag(true);
                    officeIds.add(info.getId());
                }
                //根据部门查询对应部门下的所有数据
                List<OfficeDTO> officeDTOList = userService.getUserByOffice(officeIds, type);
                list.addAll(officeDTOList);
            }
            String officeName2 = "兴光项目公司";
            List<OfficeDTO> list2 = officeService.getOfficeAllByOfficeName(officeName2);
            if (list2.size() > 0) {
                List<String> officeIds = Lists.newArrayList();
                for (OfficeDTO info : list2) {
                    info.setTypeFlag(true);
                    officeIds.add(info.getId());
                }
                //根据部门查询对应部门下的所有数据
                List<OfficeDTO> officeDTOList = userService.getUserByOffice(officeIds, type);
                list2.addAll(officeDTOList);
            }
            List<OfficeDTO> objects1 = new ArrayList<>();
            objects1.addAll(list);
            objects1.addAll(list2);
            List rootTree = officeService.getFinanceTree(objects1, extId, type, showAll, "1");
            return ResponseEntity.ok(rootTree);
        } else if (id.equals("10002")) {
            String officeName = "兴光会计师事务所";
            List<OfficeDTO> list = officeService.getOfficeAllByOfficeName(officeName);
            if (list.size() > 0) {
                List<String> officeIds = Lists.newArrayList();
                for (OfficeDTO info : list) {
                    info.setTypeFlag(true);
                    officeIds.add(info.getId());
                }
                //根据部门查询对应部门下的所有数据
                List<OfficeDTO> officeDTOList = userService.getUserByOffice(officeIds, type);
                list.addAll(officeDTOList);
            }
            String officeName1 = "综合管理公司";
            List<OfficeDTO> list1 = officeService.getOfficeAllByOfficeName(officeName1);
            if (list1.size() > 0) {
                List<String> officeIds = Lists.newArrayList();
                for (OfficeDTO info : list1) {
                    info.setTypeFlag(true);
                    officeIds.add(info.getId());
                }
                //根据部门查询对应部门下的所有数据
                List<OfficeDTO> officeDTOList = userService.getUserByOffice(officeIds, type);
                list1.addAll(officeDTOList);
            }
            List<OfficeDTO> objects = new ArrayList<>();
            objects.addAll(list);
            objects.addAll(list1);
            List rootTree = officeService.getFinanceTree(objects, extId, type, showAll, "1");
            return ResponseEntity.ok(rootTree);

        } else if (id.equals("10006")) {
            String officeName = "兴光会计师事务所";
            List<OfficeDTO> list = officeService.getOfficeAllByOfficeName(officeName);
            if (list.size() > 0) {
                List<String> officeIds = Lists.newArrayList();
                for (OfficeDTO info : list) {
                    info.setTypeFlag(true);
                    officeIds.add(info.getId());
                }
                //根据部门查询对应部门下的所有数据
                List<OfficeDTO> officeDTOList = userService.getUserByOffice(officeIds, type);
                list.addAll(officeDTOList);
            }
            String officeName1 = "苏州分公司";
            List<OfficeDTO> list1 = officeService.getOfficeAllByOfficeName(officeName1);
            if (list1.size() > 0) {
                List<String> officeIds = Lists.newArrayList();
                for (OfficeDTO info : list1) {
                    info.setTypeFlag(true);
                    officeIds.add(info.getId());
                }
                //根据部门查询对应部门下的所有数据
                List<OfficeDTO> officeDTOList = userService.getUserByOffice(officeIds, type);
                list1.addAll(officeDTOList);
            }
            List<OfficeDTO> objects = new ArrayList<>();
            objects.addAll(list);
            objects.addAll(list1);
            List rootTree = officeService.getFinanceTree(objects, extId, type, showAll, "1");
            return ResponseEntity.ok(rootTree);

        } else if (id.equals("10004")) {
            String officeName = "兴光会计师事务所";
            List<OfficeDTO> list = officeService.getOfficeAllByOfficeName(officeName);
            if (list.size() > 0) {
                List<String> officeIds = Lists.newArrayList();
                for (OfficeDTO info : list) {
                    info.setTypeFlag(true);
                    officeIds.add(info.getId());
                }
                //根据部门查询对应部门下的所有数据
                List<OfficeDTO> officeDTOList = userService.getUserByOffice(officeIds, type);
                list.addAll(officeDTOList);
            }
            String officeName1 = "中审江苏分所";
            List<OfficeDTO> list1 = officeService.getOfficeAllByOfficeName(officeName1);
            if (list1.size() > 0) {
                List<String> officeIds = Lists.newArrayList();
                for (OfficeDTO info : list1) {
                    info.setTypeFlag(true);
                    officeIds.add(info.getId());
                }
                //根据部门查询对应部门下的所有数据
                List<OfficeDTO> officeDTOList = userService.getUserByOffice(officeIds, type);
                list1.addAll(officeDTOList);
            }
            List<OfficeDTO> objects = new ArrayList<>();
            objects.addAll(list);
            objects.addAll(list1);
            List rootTree = officeService.getFinanceTree(objects, extId, type, showAll, "1");
            return ResponseEntity.ok(rootTree);

        } else {
            String officeName = "兴光会计师事务所";
            List<OfficeDTO> list = officeService.getOfficeAllByOfficeName(officeName);
            if (list.size() > 0) {
                List<String> officeIds = Lists.newArrayList();
                for (OfficeDTO info : list) {
                    info.setTypeFlag(true);
                    officeIds.add(info.getId());
                }
                //根据部门查询对应部门下的所有数据
                List<OfficeDTO> officeDTOList = userService.getUserByOffice(officeIds, type);
                list.addAll(officeDTOList);
            }
            List rootTree = officeService.getFinanceRootTree(list, extId, type, showAll, "1");
            return ResponseEntity.ok(rootTree);
        }
    }


    /**
     * 查询资质用户列表
     */
    @ApiLog("查询资质用户列表")
    @ApiOperation(value = "查询资质用户列表")
    //@PreAuthorize("hasAuthority('sys:user:list')")
    @GetMapping("certList")
    public ResponseEntity certList(UserDTO userDTO, Page<UserDTO> page) throws Exception {
        QueryWrapper<UserDTO> queryWrapper = QueryWrapperGenerator.buildQueryCondition(userDTO, UserDTO.class);
        // 管理员查询不限制
        if (!UserUtils.getCurrentUserDTO().isAdmin()) {
            queryWrapper.isNull("a.is_admin");
            if (ObjectUtil.isNotEmpty(userDTO)) {
                if (ObjectUtil.isNotEmpty(userDTO.getCompanyDTO()) && ObjectUtil.isNotEmpty(userDTO.getOfficeDTO())) {
                    String id = UserUtils.getCurrentUserDTO().getCompanyDTO().getId();
                    //判断当前登录人是否是综合管理公司人员
                    if (id.equals("1680778353809350658")) {

                    } else {
                        //如果不是综合管理公司人员
                        queryWrapper.eq("a.company_id", id);
                    }
                    if (StringUtils.isNotBlank(userDTO.getCertType())) {
                        //获取当前登陆人是否事中审公司人员
                        /*if(officeDTO.getParentIds().contains("1615171302381182978")){

                        }*/
                    } else {
                        // 当不是精确的部门查询时，再添加下面的筛选条件
                        if ((StringUtils.isNotBlank(userDTO.getCompanyDTO().getId()) && StringUtils.isBlank(userDTO.getOfficeDTO().getId()))
                                || "true".equals(userDTO.getSelectAll())) {
                            // officeDTO.id是空，companyDTO.id不是空的话，说明前端组件点击的集团来进行查询
                            // selectAll为‘true’的话，说明前端没有选择集团或者部门查询，这个时候要展示全部人员
                            // 根据当前用户的部门id找到此部门的ids
                            String ids = officeService.getById(UserUtils.getCurrentUserDTO().getOfficeDTO().getId()).getParentIds();
                            // 根据ids分隔后的index[2],找到当前用户的所属公司id
                            String companyId = null;
                            String[] split = ids.split(",");
                            // split.length大于2，说明当前登录人所属部门是普通部门，展示部分人员信息
                            // 否则，当前登录人所属公共类部门（忘了叫什么类部门了，就是总经办那种部门），展示全部人员信息
                            if (split.length > 2) {
                                companyId = split[2];
                                // 根据公司id,找到此公司下的所有部门
                                List<Office> officeList = officeService.list(new QueryWrapper<Office>().lambda().eq(Office::getParentId, companyId));
                                Set officeIdSet = new HashSet();
                                for (Office office : officeList) {
                                    if (StringUtils.isNotBlank(office.getId())) {
                                        officeIdSet.add(office.getId());
                                    }
                                }
                                List<String> officeIdList = Lists.newArrayList(officeIdSet);
                                // 拿到这些部门的id
                                //List<String> officeIdList = officeList.stream().distinct().map(Office::getId).collect(Collectors.toList());
                                // 拿到所有公有部门的id
                                List<String> officePublicIdList = officeService.list(new LambdaQueryWrapper<Office>().eq(Office::getIsPublic, "1")).stream().map(Office::getId).collect(Collectors.toList());
                                // 拿到直属公司的id
                                officeIdList.add(companyId);
                                // 最后得到的所有部门的id
                                officeIdList.addAll(officePublicIdList);
                                List<String> lastIds = officeIdList.stream().distinct().collect(Collectors.toList());
                                // 添加筛选条件为这些部门的id
                                queryWrapper.in("a.office_id", lastIds);
                            }
                        } else if (StringUtils.isBlank(userDTO.getCompanyDTO().getId()) && StringUtils.isNotBlank(userDTO.getOfficeDTO().getId())) {
                            // officeDTO.id不是空，companyDTO.id是空的话，说明前端组件点击的部门查询
                            queryWrapper.eq("a.office_id", userDTO.getOfficeDTO().getId());
                        }
                    }
                }
            }
        }
        if (ObjectUtil.isNotEmpty(userDTO)) {
            // 当certType传值时，获取拥有此资格证类型的人员
            if (StringUtils.isNotBlank(userDTO.getCertType())) {
                queryWrapper.eq("sc.type", userDTO.getCertType());
            }
            if (userDTO.getTenantDTO() != null && StrUtil.isNotBlank(userDTO.getTenantDTO().getId())) {
                queryWrapper.eq("a.tenant_id", userDTO.getTenantDTO().getId());
            }
        }
        IPage<UserDTO> result = userService.findCertPage(page, queryWrapper);
        //判断 如果是签字注师筛选，则获取签字注师的被选择次数
        if (StringUtils.isNotBlank(userDTO.getCertType()) && "6".equals(userDTO.getCertType())) {
            List<UserDTO> userList = result.getRecords();
            for (UserDTO info : userList) {
                if ("潘中".equals(info.getName())) {
                    info.setAccountantUserFlag(0);
                } else {
                    info.setAccountantUserFlag(1);
                }
                Integer accountantUserCount = userService.getAccountantUserCount(info.getId());
                info.setAccountantUserCount(accountantUserCount);
            }
        }
        return ResponseEntity.ok(result);
    }


    /**
     * 修改用户邮箱
     */
    @ApiLog("修改用户邮箱")
    @PostMapping("updateEmail")
    public String updateEmail(String id, String userEmail) {
        userService.updateEmail(id, userEmail);
        return "修改成功";
    }

    /**
     * 修改用户邮箱
     */
    @ApiLog("修改用户邮箱")
    @PostMapping("updateEmailApp")
    public String updateEmailApp(@RequestBody User user) {
        userService.updateEmail(user.getId(), user.getEmail());
        return "修改成功";
    }

    /**
     * 根据用户id获取电话号码
     */
    @ApiLog("根据用户id获取电话号码")
    @PostMapping("getMobileById")
    public String getMobileById(String id) {
        return userService.getMobileById(id);
    }


    /**
     * 清除用户缓存
     *
     * @param id
     * @return
     */
    @ApiLog("清除用户缓存")
    @GetMapping("removeRedis")
    public String removeRedis(String id) {
        if (StringUtils.isNotBlank(id)) {
            UserDTO userDTO = userService.get(id);
            if (null != userDTO) {
                RedisUtils.getInstance().set(CacheNames.USER_CACHE_LOGIN_CODE + userDTO.getLoginName(), 0);
                RedisUtils.getInstance().set(CacheNames.USER_CACHE_LOGIN_CODE + userDTO.getMobile(), 0);
                UserUtils.deleteCache(userDTO);
            }
        }
        return "清除登录缓存成功";
    }

    /**
     * 修改用户是否允许登录
     */
    @ApiLog("修改用户是否允许登录")
    @PostMapping("updateLoginFlag")
    public String updateLoginFlag(@RequestBody User user) {
        userService.updateLoginFlag(user.getId(), user.getLoginFlag());
        return "修改成功";
    }

    /**
     * 修改注会的可签章份数
     */
    @ApiLog("修改注会的可签章份数")
    @PostMapping("updateSignatureCount")
    public String updateSignatureCount(@RequestBody UserDTO userDTO) {
        userService.updateSignatureCount(userDTO.getId(), userDTO.getSignatureCount());
        return "修改成功";
    }

    /**
     * 根据签字注师id查询签章份数
     *
     * @param id
     * @return
     */
    @ApiLog("根据签字注师id查询签章份数")
    @GetMapping("findCountById")
    public ResponseEntity findCountById(String id) {
        UserDTO dto = userService.findCountById(id);
        return ResponseEntity.ok(dto);
    }


}
