package com.diagbot.facade;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.diagbot.client.AuthServiceClient;
import com.diagbot.client.DiagbotmanClient;
import com.diagbot.dto.AuthenticationDTO;
import com.diagbot.dto.CustomerDTO;
import com.diagbot.dto.ExportKemaDTO;
import com.diagbot.dto.ExportOrganizationDTO;
import com.diagbot.dto.ExportUserInfoDTO;
import com.diagbot.dto.ExportVerifiedDTO;
import com.diagbot.dto.GetConsoleUserInfoDTO;
import com.diagbot.dto.JwtDTO;
import com.diagbot.dto.LoginDTO;
import com.diagbot.dto.OrganizationDTO;
import com.diagbot.dto.RespDTO;
import com.diagbot.dto.UserAllDTO;
import com.diagbot.dto.UserAndProdutDTO;
import com.diagbot.dto.UserInfoDTO;
import com.diagbot.dto.UserInfoExportDTO;
import com.diagbot.dto.UserLoginDTO;
import com.diagbot.dto.UserOrgDTO;
import com.diagbot.dto.UserOrgizationProductDTO;
import com.diagbot.entity.JWT;
import com.diagbot.entity.JwtStore;
import com.diagbot.entity.Organization;
import com.diagbot.entity.User;
import com.diagbot.entity.UserAuthentication;
import com.diagbot.entity.UserOrganization;
import com.diagbot.entity.UserRole;
import com.diagbot.entity.wrapper.MenuWrapper;
import com.diagbot.enums.AuthHandleEnum;
import com.diagbot.enums.AuthStatusEnum;
import com.diagbot.enums.ConstantEnum;
import com.diagbot.enums.IsDeleteEnum;
import com.diagbot.enums.OrganizationTypeEnum;
import com.diagbot.enums.RejectEnum;
import com.diagbot.enums.StatusEnum;
import com.diagbot.enums.VisibleIdTypeEnum;
import com.diagbot.exception.CommonErrorCode;
import com.diagbot.exception.CommonException;
import com.diagbot.exception.ServiceErrorCode;
import com.diagbot.idc.VisibleIdCreater;
import com.diagbot.service.impl.UserServiceImpl;
import com.diagbot.util.BeanUtil;
import com.diagbot.util.DateUtil;
import com.diagbot.util.EntityUtil;
import com.diagbot.util.ExportBeanExcelUtil;
import com.diagbot.util.GsonUtil;
import com.diagbot.util.ListUtil;
import com.diagbot.util.RegexValidateUtil;
import com.diagbot.util.StringUtil;
import com.diagbot.util.UserUtils;
import com.diagbot.vo.AmendOrgVO;
import com.diagbot.vo.AmendUserInfoVO;
import com.diagbot.vo.BaseIdVO;
import com.diagbot.vo.ImgVerVerVO;
import com.diagbot.vo.OrganizationVO;
import com.diagbot.vo.PersonVO;
import com.diagbot.vo.UserAndOrganizationVO;
import com.diagbot.vo.UserExportVO;
import com.diagbot.vo.UserInfoAuditVO;
import com.diagbot.vo.UserInfoOrganizationsVO;
import com.diagbot.vo.UserSaveVO;
import com.diagbot.vo.UsernameVO;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: 用户业务层
 * @author: gaodm
 * @time: 2018/8/6 9:00
 */
@Component
public class UserFacade extends UserServiceImpl {

    private static final String CACHE_NAME = "UserInfo";

    @Autowired
    AuthServiceClient authServiceClient;
    @Autowired
    VerFacade verFacade;
    @Autowired
    OrganizationFacade organizationFacade;
    @Autowired
    UserOrganizationFacade userOrganizationFacade;
    @Autowired
    UserRoleFacade userRoleFacade;
    @Autowired
    MenuFacade menuFacade;
    @Autowired
    UserAuthenticationFacade userAuthenticationFacade;
    @Autowired
    PermissionFacade permissionFacade;
    @Autowired
    DiagbotmanClient diagbotmanClient;
    @Autowired
    private VisibleIdCreater visibleIdCreater;
    @Autowired
    private TokenFacade tokenFacade;


    /**
     * 注册
     *
     * @param userSaveVO 参数
     * @return 用户信息
     */
    public Boolean createUser(UserSaveVO userSaveVO) {
        User user = new User();
        BeanUtil.copyProperties(userSaveVO, user);
        user.setGmtCreate(new Date());
        ImgVerVerVO imgVerVerVO = new ImgVerVerVO();
        BeanUtil.copyProperties(userSaveVO, imgVerVerVO);
        User bean = findByName(user.getUsername());
        if (bean != null) {
            throw new CommonException(ServiceErrorCode.USER_EXIST);
        }
        if (!RegexValidateUtil.checkMobileNumber(userSaveVO.getUsername())) {
            throw new CommonException(CommonErrorCode.SERVER_IS_ERROR, "请输入正确的手机号");
        }

        verFacade.verifyImgVerification(imgVerVerVO); //保存时再次校验图形验证码，主要是为了防止跳过前端校验直接调用接口

        PasswordEncoder passwordEncoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
        String entryPassword = passwordEncoder.encode(user.getPassword());
        user.setPassword(entryPassword);
        user.setPhone(userSaveVO.getUsername());
        this.save(user);

        // 机构相关业务
        doOrganization(userSaveVO, user);

        //权限相关业务
        doPermisson(userSaveVO, user);

        //用户认证业务
        //doUserAuthentication(userSaveVO, user);
        return true;
    }


    /**
     * 校验用户(手机号）未注册
     *
     * @param usernameVO 参数
     * @return 返回状态
     */
    public Boolean verifyNoUser(UsernameVO usernameVO) {
        String username = usernameVO.getUsername();
        if (StringUtil.isEmpty(username)) {
            throw new CommonException(CommonErrorCode.SERVER_IS_ERROR, "请输入手机号");
        }
        if (!RegexValidateUtil.checkMobileNumber(username)) {
            throw new CommonException(CommonErrorCode.SERVER_IS_ERROR, "请输入正确的手机号");
        }
        User bean = findByName(username);
        if (bean != null) {
            throw new CommonException(CommonErrorCode.SERVER_IS_ERROR, "该手机已注册");
        }
        return true;
    }


    /**
     * 校验用户(手机号）已注册
     *
     * @param usernameVO 参数
     * @return 返回状态
     */
    public Boolean verifyExistUser(UsernameVO usernameVO) {
        String username = usernameVO.getUsername();
        if (StringUtil.isEmpty(username)) {
            throw new CommonException(CommonErrorCode.SERVER_IS_ERROR, "请输入手机号");
        }
        if (!RegexValidateUtil.checkMobileNumber(username)) {
            throw new CommonException(CommonErrorCode.SERVER_IS_ERROR, "请输入正确的手机号");
        }
        User bean = findByName(username);
        if (bean == null) {
            throw new CommonException(CommonErrorCode.SERVER_IS_ERROR, "该手机未注册");
        }
        return true;
    }

    /**
     * @param page       分页参数
     * @param userSaveVO 参数
     * @return 用户列表
     */
    public RespDTO<IPage<User>> index(Page page, UserSaveVO userSaveVO) {
        User user = new User();
        BeanUtil.copyProperties(userSaveVO, user);
        IPage<User> res = this.indexPage(page, user);
        return RespDTO.onSuc(res);
    }


    /**
     * 添加一条默认用户认证信息
     *
     * @param userSaveVO 参数
     * @param user       参数
     */
    public void doUserAuthentication(UserSaveVO userSaveVO, User user) {
        UserAuthentication ua = new UserAuthentication();
        ua.setGmtCreate(new Date());
        ua.setUserId(user.getId());
        userAuthenticationFacade.save(ua);
    }


    /**
     * 如果机构已存在，只要添加用户与机构的映射即可;如果机构不存在，先添加机构信息
     *
     * @param userSaveVO 参数
     * @param user       参数
     */
    public void doPermisson(UserSaveVO userSaveVO, User user) {
        UserRole userRole = new UserRole();
        userRole.setUserId(user.getId());
        userRole.setRoleId(1L);
        userRole.setGmtCreate(new Date());
        userRoleFacade.save(userRole);
    }


    /**
     * 如果机构已存在，只要添加用户与机构的映射即可;如果机构不存在，先添加机构信息
     *
     * @param userSaveVO 参数
     * @param user       参数
     */
    public void doOrganization(UserSaveVO userSaveVO, User user) {
        Map<String, Object> paramMap = new HashMap<>();
        String name = userSaveVO.getOrganization();
        paramMap.put("name", name);
        paramMap.put("is_deleted", IsDeleteEnum.N.getKey());
        Long orgId = 0L;
        List<Organization> list = organizationFacade.selectByMap(paramMap);
        if (ListUtil.isEmpty(list)) {
            Organization org = new Organization();
            org.setName(name);
            org.setGmtCreate(new Date());
            organizationFacade.save(org);
            orgId = org.getId();
        } else {
            orgId = list.get(0).getId();
            //查询机构下是否已存在用户信息，如已存在，就抛异常,需求核实2018.10.16
            Map paramMap1 = new HashMap();
            paramMap1.put("organization_id", orgId);
            paramMap1.put("is_deleted", IsDeleteEnum.N.getKey());
            List<UserOrganization> res1 = userOrganizationFacade.selectByMap(paramMap1);
            if (ListUtil.isNotEmpty(res1)) {
                throw new CommonException(CommonErrorCode.SERVER_IS_ERROR, "该机构下已存在用户，不能再添加别的用户");
            }
        }

        UserOrganization userOrganization = new UserOrganization();
        userOrganization.setUserId(user.getId());
        userOrganization.setOrganizationId(orgId);
        userOrganization.setGmtCreate(new Date());
        userOrganizationFacade.save(userOrganization);
    }

    /**
     * 根据用户名获取用户信息
     *
     * @param username 用户名
     * @return 用户信息
     */
    //@Cacheable(value = "UserName", key = "'username:'+#p0")
    public User getUserInfo(String username) {
        return this.findByName(username);
    }


    /**
     * 登录
     *
     * @return 登录相关信息
     */
    public LoginDTO getUserOrgMenu() {
        LoginDTO data = new LoginDTO();

        Long userId = Long.parseLong(UserUtils.getCurrentPrincipleID());
        User user = this.getById(userId);
        if (user == null) {
            throw new CommonException(CommonErrorCode.SERVER_IS_ERROR,
                    "用户不存在【" + userId + "】");
        }
        //添加用户
        UserLoginDTO userLoginDTO = new UserLoginDTO();
        BeanUtil.copyProperties(user, userLoginDTO);
        data.setUserLoginDTO(userLoginDTO);

        //添加机构信息
        Organization org = organizationFacade.getByUserId(user.getId());
        data.setOrganization(org);
        //添加菜单信息
        List<MenuWrapper> menuList = menuFacade.getByRole(user.getId());
        Map<Long, List<MenuWrapper>> menuMap = EntityUtil.makeEntityListMap(menuList, "parentId");
        List<MenuWrapper> menuRes = menuMap.get(-1L);
        for (MenuWrapper bean : menuRes) {
            getSonMenu(bean, menuMap);
        }
        data.setMenuWrappers(menuRes);
        return data;
    }


    /**
     * 获取朗通后台个人信息
     *
     * @return 获取个人信息
     */
    public UserLoginDTO getPersonInfo() {
        Long userId = Long.parseLong(UserUtils.getCurrentPrincipleID());
        User user = this.getById(userId);
        if (user == null) {
            throw new CommonException(CommonErrorCode.SERVER_IS_ERROR,
                    "用户不存在【" + userId + "】");
        }
        UserLoginDTO userLoginDTO = new UserLoginDTO();
        BeanUtil.copyProperties(user, userLoginDTO);
        return userLoginDTO;
    }


    /**
     * 修改朗通后台个人信息
     */
    public void updatePersonInfo(PersonVO personVO) {
        if (!RegexValidateUtil.checkMobileNumber(personVO.getPhone())) {
            throw new CommonException(CommonErrorCode.SERVER_IS_ERROR,
                    "请输入正确的手机号");
        }
        Long userId = Long.parseLong(UserUtils.getCurrentPrincipleID());
        User user = this.getById(userId);
        if (user == null) {
            throw new CommonException(CommonErrorCode.SERVER_IS_ERROR,
                    "用户不存在【" + userId + "】");
        }
        user.setGmtModified(DateUtil.now());
        user.setPhone(personVO.getPhone());
        user.setLinkman(personVO.getLinkman());
        user.setDept(personVO.getDept());
        user.setPosition(personVO.getPosition());
        user.setEmail(personVO.getEmail());
        this.updateById(user);
    }

    /**
     * 获取jwt
     *
     * @param username 用户名
     * @param password 密码
     * @return jwt
     */
    public JwtDTO getJwt(String username, String password) {
        JwtDTO data = new JwtDTO();
        if (StringUtil.isBlank(username)) {
            throw new CommonException(CommonErrorCode.PARAM_IS_NULL,
                    "请输入手机号");
        }
        if (StringUtil.isBlank(password)) {
            throw new CommonException(CommonErrorCode.PARAM_IS_NULL,
                    "请输入密码");
        }
        User user = this.findByName(username);
        if (null == user) {
            throw new CommonException(ServiceErrorCode.USER_NOT_FOUND);
        }
        PasswordEncoder passwordEncoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
        if (!passwordEncoder.matches(password, user.getPassword())) {
            throw new CommonException(ServiceErrorCode.USER_PASSWORD_ERROR);
        }
        JWT jwt = authServiceClient.getToken("Basic dWFhLXNlcnZpY2U6MTIzNDU2", "password", username, password);
        if (null == jwt) {
            throw new CommonException(ServiceErrorCode.GET_TOKEN_FAIL);
        }
        data.setAccessToken(jwt.getAccess_token());
        data.setRefreshToken(jwt.getRefresh_token());
        data.setType(user.getType());
        data.setTypeCn(ConstantEnum.getName(user.getType()));//返回中文
        //token存入redis
        JwtStore jwtStore = new JwtStore();
        jwtStore.setAccessToken(jwt.getAccess_token());
        jwtStore.setRefreshToken(jwt.getRefresh_token());
        tokenFacade.createToken(jwtStore);
        return data;
    }

    /**
     * 刷新jwt
     *
     * @param refreshToken
     * @return jwt
     */
    public JwtDTO refreshJwt(String refreshToken) {
        JwtDTO data = new JwtDTO();
        if (StringUtil.isBlank(refreshToken)) {
            throw new CommonException(CommonErrorCode.PARAM_IS_NULL,
                    "刷新令牌不能为空");
        }

        //验证刷新令牌有效性
        if (!tokenFacade.verifyToken(refreshToken, 2)) {
            throw new CommonException(CommonErrorCode.TOKEN_PAST);
        }

        JWT jwt = authServiceClient.refreshToken("Basic dWFhLXNlcnZpY2U6MTIzNDU2", "refresh_token", refreshToken);
        if (null == jwt) {
            throw new CommonException(ServiceErrorCode.GET_TOKEN_FAIL);
        }
        data.setAccessToken(jwt.getAccess_token());
        data.setRefreshToken(jwt.getRefresh_token());
        //token存入redis
        JwtStore jwtStore = new JwtStore();
        jwtStore.setAccessToken(jwt.getAccess_token());
        jwtStore.setRefreshToken(jwt.getRefresh_token());
        tokenFacade.createToken(jwtStore);
        return data;
    }


    /**
     * 验证jwt
     *
     * @param token
     * @return jwt
     */
    public OAuth2AccessToken checkToken(String token) {
        if (StringUtil.isBlank(token)) {
            throw new CommonException(CommonErrorCode.PARAM_IS_NULL,
                    "令牌不能为空");
        }

        OAuth2AccessToken jwt = authServiceClient.checkToken("Basic dWFhLXNlcnZpY2U6MTIzNDU2", token);
        if (null == jwt) {
            throw new CommonException(ServiceErrorCode.GET_TOKEN_FAIL);
        }
        return jwt;
    }


    /**
     * 递归获取菜单结构
     *
     * @param menu    当前菜单
     * @param menuMap 菜单集
     * @return 菜单结构
     */
    public List<MenuWrapper> getSonMenu(MenuWrapper menu, Map<Long, List<MenuWrapper>> menuMap) {
        List<MenuWrapper> res = new ArrayList<>();
        List<MenuWrapper> list = menuMap.get(menu.getId());
        if (ListUtil.isNotEmpty(list)) {
            menu.setSubMenuList(list);
            for (MenuWrapper bean : list) {
                getSonMenu(bean, menuMap);
            }
        }
        return res;
    }

    /**
     * 递归获取菜单结构
     *
     * @param menuList 菜单参数
     */
    public void getMenuStruct(List<MenuWrapper> menuList) {
        for (MenuWrapper m : menuList) {
            m.setSubMenuList(recursion(m));
        }
    }


    /**
     * 递归查询菜单信息
     *
     * @param m 参数
     * @return 菜单信息
     */
    public List<MenuWrapper> recursion(MenuWrapper m) {
        List<MenuWrapper> subMenu = menuFacade.getSubMenuById(m.getId());
        for (MenuWrapper sub : subMenu) {
            sub.setSubMenuList(recursion(sub));
        }
        return subMenu;
    }


    /**
     * 获取用户相关信息和机构信息
     *
     * @param userIds 用户ids
     * @return 用户相关信息和机构信息
     */
    public Map<Long, UserOrgDTO> getUserAndOrg(List<Long> userIds) {
        Map<Long, UserOrgDTO> data = new HashMap();
        if (ListUtil.isEmpty(userIds)) {
            return data;
        }
        List<UserOrgDTO> list = this.getUserOrgByIds(userIds);
        //        for(UserOrgDTO bean : list) {
        //            data.put(bean.getUserId(), bean);
        //        }
        data = EntityUtil.makeEntityMap(list, "userId");
        return data;
    }


    /**
     * 重置密码
     *
     * @param username     用户名
     * @param password     重置密码
     * @param diffPassword 是否与上次密码不同标识
     * @return 重置密码是否成功
     */
    public RespDTO resetPassword(String username, String password, String diffPassword) {
        if (StringUtil.isBlank(username)) {
            throw new CommonException(CommonErrorCode.PARAM_IS_NULL,
                    "请输入手机号");
        }
        if (StringUtil.isBlank(password)) {
            throw new CommonException(CommonErrorCode.PARAM_IS_NULL,
                    "请输入密码");
        }
        User user = this.findByName(username);
        if (null == user) {
            throw new CommonException(ServiceErrorCode.USER_NOT_FOUND);
        }
        PasswordEncoder passwordEncoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
        if (!StringUtil.isBlank(diffPassword) && "Y".equals(diffPassword)) {
            if (passwordEncoder.matches(password, user.getPassword())) {
                throw new CommonException(CommonErrorCode.PARAM_IS_ERROR, "原密码和新密码不能相同");
            }
        }
        String entryPassword = passwordEncoder.encode(password);
        user.setPassword(entryPassword);
        user.setGmtModified(new Date());
        this.updateById(user);
        return RespDTO.onSuc(true);
    }


    /**
     * 修改密码
     *
     * @param password       原密码
     * @param modifyPassword 新密码
     * @return 修改密码是否成功
     */
    public Boolean modifyPassword(String password, String modifyPassword) {
        if (StringUtil.isBlank(password)) {
            throw new CommonException(CommonErrorCode.PARAM_IS_NULL,
                    "请输入密码");
        }
        if (StringUtil.isBlank(modifyPassword)) {
            throw new CommonException(CommonErrorCode.PARAM_IS_NULL,
                    "请输入新密码");
        }
        if (password.equals(modifyPassword)) {
            throw new CommonException(CommonErrorCode.PARAM_IS_NULL,
                    "原密码和新密码不能相同");
        }
        Long userId = Long.parseLong(UserUtils.getCurrentPrincipleID());
        User user = this.getById(userId);
        if (user == null) {
            throw new CommonException(CommonErrorCode.SERVER_IS_ERROR,
                    "用户不存在【" + userId + "】");
        }

        PasswordEncoder passwordEncoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
        if (!passwordEncoder.matches(password, user.getPassword())) {
            throw new CommonException(CommonErrorCode.PARAM_IS_ERROR, "原密码错误");
        }

        String entryPassword = passwordEncoder.encode(modifyPassword);
        user.setPassword(entryPassword);
        user.setGmtModified(new Date());
        this.updateById(user);
        return true;
    }

    //---------------缓存演示开始-------------------------------------

    /**
     * 新建用户
     *
     * @param user 新建用户信息输入参数
     * @return 用户信息
     */
    //@CachePut(value = CACHE_NAME, key = "'user:'+#p0['id']")
    public User saveUser(User user) {
        PasswordEncoder passwordEncoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
        String entryPassword = passwordEncoder.encode(user.getPassword());
        user.setPassword(entryPassword);
        user.setGmtCreate(new Date());
        user.setCreator(UserUtils.getCurrentPrincipleID());
        super.save(user);
        return user;
    }

    /**
     * 更新用户信息
     *
     * @param user 更新用户信息输入参数
     * @return 用户信息
     */
    //@CachePut(value = CACHE_NAME, key = "'user:'+#p0['id']")
    public User updateUser(User user) {
        PasswordEncoder passwordEncoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
        String entryPassword = passwordEncoder.encode(user.getPassword());
        user.setPassword(entryPassword);
        user.setGmtModified(new Date());
        user.setModifier(UserUtils.getCurrentPrincipleID());
        super.updateById(user);
        return user;
    }

    /**
     * 根据用户ID获取用户信息
     *
     * @param id 用户ID
     * @return 用户信息
     */
    @Override
    //@Cacheable(value = CACHE_NAME, key = "'user:'+#p0")
    public User getById(Serializable id) {
        return super.getById(id);
    }

    /**
     * 根据用户ID删除用户(物理删除)
     *
     * @param id 用户ID
     * @return 是否成功
     */
    @Override
    //@CacheEvict(value = CACHE_NAME, key = "'user:'+#p0")
    public boolean removeById(Serializable id) {
        return super.removeById(id);
    }

    /**
     * 获取控制台用户信息
     *
     * @return 用户信息
     */
    public GetConsoleUserInfoDTO getConsoleUserInfo() {
        Long userId = Long.parseLong(UserUtils.getCurrentPrincipleID());
        User user = this.getById(userId);
        Organization organization = organizationFacade.getByUserId(userId);
        QueryWrapper<UserAuthentication> qw = new QueryWrapper<>();
        qw.eq("user_id", userId).
                eq("is_deleted", IsDeleteEnum.N.getKey());
        UserAuthentication userAuthentication = userAuthenticationFacade.getOne(qw);

        GetConsoleUserInfoDTO getConsoleUserInfoDTO = new GetConsoleUserInfoDTO();
        getConsoleUserInfoDTO.setUserName(user.getUsername());
        getConsoleUserInfoDTO.setOrganizationName(organization.getName());
        getConsoleUserInfoDTO.setUserStatus(AuthStatusEnum.getName(userAuthentication.getStatus()));

        //        getConsoleUserInfoDTO.setUser(user);
        //        getConsoleUserInfoDTO.setOrganization(organization);
        //        getConsoleUserInfoDTO.setUserAuthentication(userAuthentication);

        return getConsoleUserInfoDTO;
    }
    //---------------缓存演示结束-------------------------------------


    /**
     * 远程调用，根据机构名称获取用户信息
     *
     * @param orgName 机构信息
     * @return 用户ids
     */
    public List<Long> getUserByOrgNameFac(String orgName) {
        List<Long> userIdList = new ArrayList<>();
        if (StringUtil.isEmpty(orgName)) {
            return userIdList;
        }
        List<User> userList = this.getUserByOrgName(orgName);
        for (User bean : userList) {
            userIdList.add(bean.getId());
        }
        return userIdList;
    }

    /**
     * @param userExportVO
     * @return 导出Excel文件
     */
    public void export(UserExportVO userExportVO, HttpServletResponse response) {
        Map<String, Object> userMap = new HashMap<String, Object>();
        userMap.put("startTime", userExportVO.getStartTime());
        userMap.put("endTime", userExportVO.getEndTime());
        userMap.put("authStatus", userExportVO.getAuthStatus());
        userMap.put("orgName", userExportVO.getOrgName());
        userMap.put("userName", userExportVO.getUserName());
        List<UserInfoDTO> datas = dependentuserInfoByTime(userMap);
        GsonUtil.toJson(datas);
        List<String> listName = new ArrayList<>();

        listName.add("用户id");
        listName.add("记录创建时间");
        listName.add("手机号");
        listName.add("联系人");
        listName.add("邮箱");
        listName.add("机构ID");
        listName.add("机构名称");
        listName.add("机构属性");
        listName.add("负责人");
        listName.add("机构地址");
        listName.add("上级机构id");
        listName.add("下属机构数量");
        listName.add("岗位信息");
        listName.add("是否通过认证 ");
        listName.add("状态");

        List<String> listId = new ArrayList<>();
        listId.add("userId");//用户ID
        listId.add("userGmtCreate");//记录创建时间
        listId.add("userName");// 用户名
        listId.add("linkman");//联系人
        listId.add("email");// 邮箱
        listId.add("orgId");//机构ID
        //listId.add("orgGmtCreate");//记录创建时间
        listId.add("orgName");//机构名称
        listId.add("orgType");//机构属性
        listId.add("orgPrincipal");//负责人
        listId.add("orgAddress");//机构地址
        listId.add("orgParentId");//上级机构id
        listId.add("orgSubNum");//下属机构数量
        listId.add("position");//岗位信息
        listId.add("autIsReject");//是否通过认证 N:未通过，Y:已通过
        listId.add("authStatus");//认证状态

        List<UserInfoExportDTO> list = new ArrayList<>();
        for (int i = 0; i < datas.size(); i++) {
            UserInfoDTO userInfo = datas.get(i);
            list.add(new UserInfoExportDTO(String.valueOf(userInfo.getUserId()),
                    DateUtil.formatDate(userInfo.getUserGmtCreate()),
                    userInfo.getUserName(),
                    userInfo.getLinkman(),
                    userInfo.getEmail(),
                    String.valueOf(userInfo.getOrgId()),
                    userInfo.getOrgName(),
                    OrganizationTypeEnum.getName(userInfo.getOrgType()),
                    userInfo.getOrgPrincipal(),
                    userInfo.getOrgAddress(),
                    String.valueOf(userInfo.getOrgParentId()),
                    String.valueOf(userInfo.getOrgSubNum()),
                    userInfo.getPosition(),
                    String.valueOf(userInfo.getAutIsReject()),
                    AuthStatusEnum.getName(userInfo.getAuthStatus())));
        }
        //response.setContentType("text/html;charset=UTF-8");
/*        String filePath = userExportVO.getFilePath();//文件路径
        String fileName = userExportVO.getFileName();//文件名
        ExportBeanExcelUtil ex = new ExportBeanExcelUtil();
        RespDTO resul = ex.exportExcel("测试POI导出EXCEL文档", listName, listId, list, filePath, fileName);*/
        response.setContentType("text/html;charset=UTF-8");
        ExportBeanExcelUtil ex = new ExportBeanExcelUtil();
        ex.exportExcelNew("用户信息详情", listName, listId, list, response);
    }

    /**
     * @param userInfoOrganizationsVO
     * @return 修改用户信息和机构信息
     */
    public RespDTO<UserInfoOrganizationsVO> updateUserInfoAlls(UserInfoOrganizationsVO userInfoOrganizationsVO) {
        Map<String, Object> userMap = new HashMap<String, Object>();
        userMap.put("modifier", UserUtils.getCurrentPrincipleID());
        userMap.put("gmtModified", DateUtil.now());
        userMap.put("email", userInfoOrganizationsVO.getEmail());
        userMap.put("principal", userInfoOrganizationsVO.getPrincipal());
        userMap.put("address", userInfoOrganizationsVO.getAddress());
        userMap.put("type", userInfoOrganizationsVO.getType());
        userMap.put("position", userInfoOrganizationsVO.getPosition());
        userMap.put("userId", userInfoOrganizationsVO.getUserId());
        userMap.put("orgId", userInfoOrganizationsVO.getOrgId());
        userMap.put("orgSubNum", userInfoOrganizationsVO.getOrgSubNum());
        boolean res = updateUserInfoAll(userMap);
        if (!res) {
            throw new CommonException(CommonErrorCode.UPDATE_INFO_FAIL);
        }
        return RespDTO.onSuc(res);
    }

    /**
     * @param userInfoAuditVO
     * @return 审核用户信息和机构信息
     */
    public RespDTO<Boolean> auditUserInfoAlls(UserInfoAuditVO userInfoAuditVO, int ByType) {
        Map<String, Object> auditMap = new HashMap<String, Object>();
        auditMap.put("orderNum", userInfoAuditVO.getOrderNum());
        auditMap.put("userId", userInfoAuditVO.getUserId());
        auditMap.put("modifier", UserUtils.getCurrentPrincipleID());
        auditMap.put("gmtModified", DateUtil.now());
        auditMap.put("certificationDate", DateUtil.now());
        User userDate = getById(userInfoAuditVO.getUserId());
        if (!userDate.getAuthStatus().equals(2)) {
            return RespDTO.onError("该用户已被操作");
        }
        if (ByType == 1) {
            auditMap.put("isReject", RejectEnum.PASS.getKey());
        }
        if (ByType == 2) {
            auditMap.put("isReject", RejectEnum.NO_PASS.getKey());
        }
        auditMap.put("rejectComment", userInfoAuditVO.getRejectComment());
        auditMap.put("rejectType", userInfoAuditVO.getRejectType());
        auditMap.put("status", AuthHandleEnum.Handled.getKey());//已处理
        if (ByType == 1) {
            auditMap.put("authStatus", 1);
        }
        if (ByType == 2) {
            auditMap.put("authStatus", 0);
        }
        // TODO 审核前先验证该用户的的认证状态
        boolean res = auditUserInfoAll(auditMap);
        if (!res) {
            throw new CommonException(CommonErrorCode.UPDATE_INFO_FAIL);
        }
        return RespDTO.onSuc(res);
    }

    /**
     * 添加机构信息
     *
     * @param organizationVO
     * @return
     */
    public RespDTO<Boolean> addOrganizations(OrganizationVO organizationVO) {

        String organizationName = organizationVO.getOrganizationName();
        List<Organization> organizationList = organizationFacade.findOrganizationAll(organizationName);
        if (ListUtil.isNotEmpty(organizationList)) {
            throw new CommonException(CommonErrorCode.NOT_EXISTS, "该机构存在");
        }
        Organization organization = new Organization();
        organization.setName(organizationVO.getOrganizationName());
        organization.setType(organizationVO.getType());
        organization.setPrincipal(organizationVO.getPrincipal());
        organization.setSubNum(organizationVO.getSubNum());
        organization.setAddress(organizationVO.getAddress());
        organization.setGmtCreate(DateUtil.now());
        organization.setModifier(UserUtils.getCurrentPrincipleID());

        boolean res = organizationFacade.save(organization);

        // System.out.println(GsonUtil.toJson(organization));
        if (!res) {
            throw new CommonException(CommonErrorCode.UPDATE_INFO_FAIL);
        }
        return RespDTO.onSuc(res);
    }

    /**
     * 添加用户信息和机构信息管理员
     *
     * @param userAndOrganizationVO
     * @return
     */
    public RespDTO<Boolean> addUserInfos(UserAndOrganizationVO userAndOrganizationVO) {
        // TODO 先查找机构，获取机构id,再注册用户,返回用户id, 取到用户id和 机构id ,查询用户机构关联表，在进行绑定
        // User user = new User();
        // 验证用户是否存在
        String username = userAndOrganizationVO.getUserName();
        User userData = getUserInfo(username);
        // System.out.println(user);
        if (userData != null) {
            throw new CommonException(CommonErrorCode.IS_EXISTS, "该用户已存在");
        }
        // 验证机构是否被绑定
        UserOrganization userORG = new UserOrganization();
        userORG.setOrganizationId(userAndOrganizationVO.getOrganizationId());

        List<UserOrganization> userOrganizationData = userOrganizationFacade.getAgencyPersonnel(userORG);
        if (ListUtil.isNotEmpty(userOrganizationData)) {
            throw new CommonException(CommonErrorCode.IS_EXISTS, "该机构绑定了用户");
        }

        User user = new User();
        user.setCreator(UserUtils.getCurrentPrincipleID());//创建id
        user.setUsername(userAndOrganizationVO.getUserName());//用户账号
        String password = DigestUtils.md5Hex(userAndOrganizationVO.getPassWord());
        //System.out.println(password);
        PasswordEncoder passwordEncoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
        String entryPassword = passwordEncoder.encode(password);
        user.setPassword(entryPassword);//用户密码
        user.setLinkman(userAndOrganizationVO.getLinkman());//用户名
        user.setGmtCreate(DateUtil.now());//创建时间
        user.setPosition(userAndOrganizationVO.getPosition());// 岗位信息
        user.setEmail(userAndOrganizationVO.getEmail());//邮箱
        user.setPassauthTime(DateUtil.now());//认证通过时间
        user.setAuthStatus(AuthStatusEnum.Authorized.getKey());// 认证状态（0：未认证，1：已认证，2：认证中）
        save(user);

        Long userId = user.getId();
        // 生成用户信息的认证单号
        UserAuthentication userAuthentication = new UserAuthentication();
        userAuthentication.setCreator(UserUtils.getCurrentPrincipleID());// 创建人Id
        userAuthentication.setGmtCreate(DateUtil.now());// 记录创建时间
        userAuthentication.setOrderNum(visibleIdCreater.getNextId(VisibleIdTypeEnum.IS_AUTH.getKey()).toString());
        userAuthentication.setUserId(userId);// 用户id
        userAuthentication.setIsReject(RejectEnum.PASS.getKey());//是否通过认证 0:未通过，1:已通过 ,默认为null
        userAuthentication.setStatus(1);//处理状态（0：待处理，1：已处理）
        userAuthentication.setRemark("admin");
        userAuthenticationFacade.save(userAuthentication);

        // 用户信息和机构信息的绑定
        UserOrganization userOrganization = new UserOrganization();
        userOrganization.setCreator(UserUtils.getCurrentPrincipleID());//
        // 创建人Id
        userOrganization.setGmtCreate(DateUtil.now());
        userOrganization.setOrganizationId(userAndOrganizationVO.getOrganizationId());// 机构id
        userOrganization.setUserId(userId);// 用户id

        userOrganizationFacade.save(userOrganization);

        UserRole userRole = new UserRole();
        userRole.setUserId(user.getId());
        userRole.setRoleId(1L);
        userRole.setGmtCreate(new Date());
        userRole.setCreator(UserUtils.getCurrentPrincipleID());
        userRoleFacade.save(userRole);
        return RespDTO.onSuc(true);
    }


    /**
     * 删除用户信息和机构信息
     *
     * @param baseIdVO 参数
     * @return 删除用户信息和机构信息
     */
    public RespDTO<Boolean> updateDeleteds(BaseIdVO baseIdVO) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("userId", baseIdVO.getId());
        map.put("modifier", UserUtils.getCurrentPrincipleID());
        map.put("gmtModified", DateUtil.now());
        User userDate = getById(baseIdVO.getId());
        if (userDate.getIsDeleted().equals("Y")) {
            return RespDTO.onError("该用户已不存在");
        }
        //客户中心-查询用户续费数量
        RespDTO<Integer> renewalSums = diagbotmanClient.getUserWaitingRenewal(baseIdVO.getId());
        if (renewalSums == null || !"0".equals(renewalSums.code)) {
            throw new CommonException(CommonErrorCode.SERVER_IS_ERROR,
                    "获取用户续费数量信息失败");
        }
        int renewalSum = renewalSums.data;
        //System.out.println("========renewalSu====="+renewalSum);
        if (renewalSum > 0) {
            return RespDTO.onError("该用户无法删除，请先处理产品申请信息");
        }
        //查询用户是否有待审核的产品数量
        RespDTO<Integer> auditSums = diagbotmanClient.getOrderByUserToAudit(baseIdVO.getId());
        if (auditSums == null || !"0".equals(auditSums.code)) {
            throw new CommonException(CommonErrorCode.SERVER_IS_ERROR,
                    "审核的产品数量失败");
        }
        int auditSum = auditSums.data;
        //System.out.println("=========auditSumauditSum===="+auditSum);
        if (auditSum > 0) {
            return RespDTO.onError("该用户存在产品申请单，请先审核");
        }
        List<Long> userIds = new ArrayList<>();
        userIds.add(baseIdVO.getId());
        RespDTO<List<UserAndProdutDTO>> InformationData = diagbotmanClient.getInformationAvailableAll(userIds);

        if (InformationData == null || !"0".equals(InformationData.code)) {
            throw new CommonException(CommonErrorCode.SERVER_IS_ERROR,
                    "获取所有开通信息失败");
        }
        //获取该用户开通的产品信息的状态
        List<UserAndProdutDTO> dataList = InformationData.data;
        for (UserAndProdutDTO InformationDataNew : dataList) {
            Integer serviceStatus = InformationDataNew.getServiceStatus();
            if (serviceStatus.equals(StatusEnum.Enable.getKey())) {
                return RespDTO.onError("请先停用所有产品");
            }
        }
        boolean res = updateDeleted(map);
        if (!res) {
            throw new CommonException(CommonErrorCode.UPDATE_INFO_FAIL);
        }
        //删除用户成功后把token也删除
        tokenFacade.deleteToken(String.valueOf(baseIdVO.getId()));
        return RespDTO.onSuc(res);
    }

    /**
     * @param page
     * @param orgName
     * @param authStatus
     * @return 分页查询用户信息和机构信息开通产品
     */
/*    public RespDTO<IPage<UserInfoDTO>> getUserOrganProductAlls(Page page, String orgName, Integer authStatus) {

        UserInfoDTO userInfo = new UserInfoDTO();
        userInfo.setOrgName(orgName);
        userInfo.setAuthStatus(authStatus);
        IPage<UserInfoDTO> user = selectUserInfoListPage(page, userInfo);
        List<UserInfoDTO> userData = user.getRecords();
        List<Long> userIds = new ArrayList<>();
        for (UserInfoDTO userInfoDTO : userData) {
            Long userInfoId = userInfoDTO.getUserId();
            userIds.add(userInfoId);
        }
        RespDTO<List<UserAndProdutUDTO>> InformationData = diagbotmanClient.getInformationAvailableAll(userIds);

        if (InformationData == null || !"0".equals(InformationData.code)) {
            throw new CommonException(CommonErrorCode.SERVER_IS_ERROR,
                    "获取所有开通信息失败");
        }
        Map<Long, List<UserAndProdutUDTO>> map = new HashMap<>();
        //获取所有用户开通的产品信息
        List<UserAndProdutUDTO> dataList = InformationData.data;
        map = EntityUtil.makeEntityListMap(dataList, "userId");
        if (map.size() > 0) {
            for (UserInfoDTO userInfoDTO : userData) {
                List<UserAndProdutUDTO> userAndProdutUDTO = map.get(userInfoDTO.getUserId());
                if (ListUtil.isNotEmpty(userAndProdutUDTO)) {
                    userInfoDTO.setUserAndProdutUDTO(userAndProdutUDTO);
                }
            }
        }

        System.out.println("====================" + GsonUtil.toJson(userData));
        user.setRecords(userData);
        return RespDTO.onSuc(user);
    }*/

    /**
     * 1.分页查询注册用户信息接口 queryUserInformation
     *
     * @param page
     * @param userName
     * @param authStatus
     * @return
     */
    public RespDTO<IPage<UserAllDTO>> queryUserInformations(Page page, String userName, Integer authStatus, String startTime, String endTime) {
        CustomerDTO userInfo = new CustomerDTO();
        if (userName != null && userName.length() != 0) {
            userInfo.setUserName(userName);
        }
        if (authStatus != null) {
            userInfo.setAuthStatus(authStatus);
        }
        if (startTime != null && startTime.length() != 0) {
            userInfo.setStartTime(startTime);
        }
        if (endTime != null && endTime.length() != 0) {
            userInfo.setEndTime(endTime);
        }

        return RespDTO.onSuc(queryUserInformation(page, userInfo));
    }

    /**
     * 2.分页查询机构信息接口 queryMechanismInformation
     *
     * @param page
     * @param orgName
     * @return
     */
    public RespDTO<IPage<OrganizationDTO>> queryMechanismInformations(Page page, String orgName, String startTime, String endTime) {
        CustomerDTO userInfo = new CustomerDTO();
        if (orgName != null && orgName.length() != 0) {
            userInfo.setOrgName(orgName);
        }
        if (startTime != null && startTime.length() != 0) {
            userInfo.setStartTime(startTime);
        }
        if (endTime != null && endTime.length() != 0) {
            userInfo.setEndTime(endTime);
        }
        return RespDTO.onSuc(queryMechanismInformation(page, userInfo));
    }

    /**
     * 3.分页查询已认证用户信息和机构信息及开通产品接口 queryVerifiedUserOrganizationProduct
     *
     * @param page
     * @param orgName
     * @param userName
     * @return
     */
    public RespDTO<IPage<UserOrgizationProductDTO>> queryVerifiedUserOrganizationProducts(Page page, String orgName, String userName, String startTime, String endTime) {
        CustomerDTO userInfo = new CustomerDTO();
        if (userName != null && userName.length() != 0) {
            userInfo.setUserName(userName);
        }
        if (orgName != null && orgName.length() != 0) {
            userInfo.setOrgName(orgName);
        }
        if (startTime != null && startTime.length() != 0) {
            userInfo.setStartTime(startTime);
        }
        if (endTime != null && endTime.length() != 0) {
            userInfo.setEndTime(endTime);
        }

        IPage<UserOrgizationProductDTO> user = queryVerifiedUserOrganizationProduct(page, userInfo);
        List<UserOrgizationProductDTO> userData = user.getRecords();
        List<Long> userIds = new ArrayList<>();
        for (UserOrgizationProductDTO userInfoDTO : userData) {
            Long userInfoId = userInfoDTO.getUserId();
            userIds.add(userInfoId);
        }
        if (userIds.size() > 0) {


            RespDTO<List<UserAndProdutDTO>> InformationData = diagbotmanClient.getInformationAvailableAll(userIds);

            if (InformationData == null || !"0".equals(InformationData.code)) {
                throw new CommonException(CommonErrorCode.SERVER_IS_ERROR,
                        "获取所有开通信息失败");
            }
            Map<Long, List<UserAndProdutDTO>> map = new HashMap<>();
            //获取所有用户开通的产品信息
            List<UserAndProdutDTO> dataList = InformationData.data;
            map = EntityUtil.makeEntityListMap(dataList, "userId");
            if (map.size() > 0) {
                for (UserOrgizationProductDTO userInfoDTO : userData) {
                    List<UserAndProdutDTO> userAndProdutUDTO = map.get(userInfoDTO.getUserId());
                    if (ListUtil.isNotEmpty(userAndProdutUDTO)) {
                        userInfoDTO.setUserAndProdutUDTO(userAndProdutUDTO);
                    }
                }
            }
        }
        //System.out.println("====================" + GsonUtil.toJson(userData));
        user.setRecords(userData);
        return RespDTO.onSuc(user);
    }

    /**
     * 4.分页查询认证中的用户信息接口 queryAuthentication
     *
     * @param page
     * @param orgName
     * @param userName
     * @return
     */
    public RespDTO<IPage<AuthenticationDTO>> queryAuthentications(Page page, String orgName, String userName, String startTime, String endTime) {
        CustomerDTO userInfo = new CustomerDTO();
        if (userName != null && userName.length() != 0) {
            userInfo.setUserName(userName);
        }
        if (orgName != null && orgName.length() != 0) {
            userInfo.setOrgName(orgName);
        }
        if (startTime != null && startTime.length() != 0) {
            userInfo.setStartTime(startTime);
        }
        if (endTime != null && endTime.length() != 0) {
            userInfo.setEndTime(endTime);
        }
        userInfo.setAuthStatus(2);//认证中。。。
        userInfo.setStatus(0);//待处理
        return RespDTO.onSuc(queryAuthentication(page, userInfo));
    }

    /**
     * 导出用户信息
     *
     * @param userExportVO
     * @param response
     */
    public void exportUserInfo(UserExportVO userExportVO, HttpServletResponse response) {
        Map<String, Object> userMap = new HashMap<String, Object>();
        userMap.put("startTime", userExportVO.getStartTime());
        userMap.put("endTime", userExportVO.getEndTime());
        userMap.put("authStatus", userExportVO.getAuthStatus());
        userMap.put("orgName", userExportVO.getOrgName());
        userMap.put("userName", userExportVO.getUserName());
        List<UserInfoDTO> datas = dependentuserInfoByTime(userMap);

        GsonUtil.toJson(datas);
        List<String> listName = new ArrayList<>();

        listName.add("编号");
        listName.add("注册时间");
        listName.add("联系人");
        listName.add("状态");
        listName.add("手机号");
        listName.add("邮箱");
        listName.add("机构名称");


        List<String> listId = new ArrayList<>();
        listId.add("userId");//用户ID
        listId.add("userGmtCreate");//记录创建时间
        listId.add("linkman");//联系人
        listId.add("authStatus");//认证状态
        listId.add("userName");// 用户名
        listId.add("email");// 邮箱
        listId.add("orgName");//机构名称


        List<ExportUserInfoDTO> list = new ArrayList<>();
        for (int i = 0; i < datas.size(); i++) {
            UserInfoDTO userInfo = datas.get(i);
            list.add(new ExportUserInfoDTO(String.valueOf(i + 1),
                    DateUtil.formatDateTime(userInfo.getUserGmtCreate()),
                    userInfo.getLinkman(),
                    AuthStatusEnum.getName(userInfo.getAuthStatus()),
                    userInfo.getUserName(),
                    userInfo.getEmail(),
                    userInfo.getOrgName()));

        }
        response.setContentType("text/html;charset=UTF-8");
        ExportBeanExcelUtil ex = new ExportBeanExcelUtil();
        ex.exportExcelNew("注册用户信息", listName, listId, list, response);

    }

    //导出机构信息数据
    public void exportOrganization(UserExportVO userExportVO, HttpServletResponse response) {
        Map<String, Object> userMap = new HashMap<String, Object>();
        userMap.put("startTime", userExportVO.getStartTime());
        userMap.put("endTime", userExportVO.getEndTime());
        /*userMap.put("autStatus",userExportVO.getAutStatus());*/
        userMap.put("orgName", userExportVO.getOrgName());
        /*userMap.put("userName",userExportVO.getUserName());*/
        List<UserInfoDTO> datas = exportOrganizations(userMap);
        GsonUtil.toJson(datas);
        List<String> listName = new ArrayList<>();


        listName.add("编号");
        listName.add("注册时间");
        listName.add("注册机构");
        listName.add("机构负责人");
        listName.add("机构属性");
        listName.add("机构地址");
        listName.add("超管名称");

        List<String> listId = new ArrayList<>();

        listId.add("orgId");//机构ID
        listId.add("orgGmtCreate");//记录创建时间
        listId.add("orgName");//机构名称
        listId.add("orgPrincipal");//负责人
        listId.add("orgType");//机构属性
        listId.add("orgAddress");//机构地址
        listId.add("linkman");// 用户名

        List<ExportOrganizationDTO> list = new ArrayList<>();
        for (int i = 0; i < datas.size(); i++) {
            UserInfoDTO userInfo = datas.get(i);
            list.add(new ExportOrganizationDTO(
                    String.valueOf(i + 1),
                    DateUtil.formatDateTime(userInfo.getOrgGmtCreate()),
                    userInfo.getOrgName(),
                    userInfo.getOrgPrincipal(),
                    OrganizationTypeEnum.getName(userInfo.getOrgType()),
                    userInfo.getOrgAddress(),
                    userInfo.getLinkman()));
        }
        response.setContentType("text/html;charset=UTF-8");
        ExportBeanExcelUtil ex = new ExportBeanExcelUtil();
        ex.exportExcelNew("机构信息详情", listName, listId, list, response);

    }

    //导出认证中数据
    public void exportKema(UserExportVO userExportVO, HttpServletResponse response) {
        Map<String, Object> userMap = new HashMap<String, Object>();
        userMap.put("startTime", userExportVO.getStartTime());
        userMap.put("endTime", userExportVO.getEndTime());
        userMap.put("authStatus", 2);//认证状态: 0 未认证，1 已认证，2 认证中
        userMap.put("status", 0);//处理状态（0：待处理，1：已处理）
        userMap.put("orgName", userExportVO.getOrgName());
        userMap.put("userName", userExportVO.getUserName());
        List<AuthenticationDTO> datas = exportKema(userMap);
        GsonUtil.toJson(datas);
        List<String> listName = new ArrayList<>();

        listName.add("编号");
        listName.add("注册时间");
        listName.add("认证单号");
        listName.add("超管名称");
        listName.add("所在机构");
        listName.add("岗位名称");
        listName.add("手机号");
        listName.add("邮箱");
        listName.add("状态");

        List<String> listId = new ArrayList<>();
        listId.add("userId");//用户ID
        listId.add("autGmtCreate");//记录创建时间
        listId.add("orderNum");
        listId.add("linkman");//联系人
        listId.add("orgName");//机构名称
        listId.add("position");//岗位信息
        listId.add("userName");// 用户名
        listId.add("email");// 邮箱
        listId.add("authStatus");//认证状态

        List<ExportKemaDTO> list = new ArrayList<>();
        for (int i = 0; i < datas.size(); i++) {
            AuthenticationDTO userInfo = datas.get(i);
            list.add(new ExportKemaDTO(String.valueOf(i + 1),
                    DateUtil.formatDateTime(userInfo.getAutGmtCreate()),
                    userInfo.getOrderNum(),
                    userInfo.getLinkman(),
                    userInfo.getOrgName(),
                    userInfo.getPosition(),
                    userInfo.getUserName(),
                    userInfo.getEmail(),
                    AuthStatusEnum.getName(userInfo.getAuthStatus())));
        }

        response.setContentType("text/html;charset=UTF-8");
        ExportBeanExcelUtil ex = new ExportBeanExcelUtil();
        ex.exportExcelNew("认证用户信息详情", listName, listId, list, response);
    }

    //导出已认证数据
    public void exportVerified(UserExportVO userExportVO, HttpServletResponse response) {
        Map<String, Object> userMap = new HashMap<String, Object>();
        userMap.put("startTime", userExportVO.getStartTime());
        userMap.put("endTime", userExportVO.getEndTime());
        userMap.put("authStatus", 1);
        userMap.put("orgName", userExportVO.getOrgName());
        userMap.put("userName", userExportVO.getUserName());
        List<UserInfoDTO> datas = exportVerified(userMap);
        GsonUtil.toJson(datas);
        List<String> listName = new ArrayList<>();

        listName.add("编号");
        listName.add("注册时间");
        listName.add("审核通过时间");
        listName.add("超管名称");
        listName.add("所在机构");
        listName.add("岗位名称");
        listName.add("手机号");
        listName.add("邮箱");
        listName.add("状态");

        List<String> listId = new ArrayList<>();
        listId.add("userId");//用户ID
        listId.add("userGmtCreate");//记录创建时间
        listId.add("passauthTime");
        listId.add("linkman");//联系人
        listId.add("orgName");//机构名称
        listId.add("position");//岗位信息
        listId.add("userName");// 用户名
        listId.add("email");// 邮箱
        listId.add("authStatus");//认证状态

        List<ExportVerifiedDTO> list = new ArrayList<>();
        for (int i = 0; i < datas.size(); i++) {
            UserInfoDTO userInfo = datas.get(i);
            list.add(new ExportVerifiedDTO(String.valueOf(i + 1),
                    DateUtil.formatDateTime(userInfo.getUserGmtCreate()),
                    DateUtil.formatDateTime(userInfo.getPassauthTime()),
                    userInfo.getLinkman(),
                    userInfo.getOrgName(),
                    userInfo.getPosition(),
                    userInfo.getUserName(),
                    userInfo.getEmail(),
                    AuthStatusEnum.getName(userInfo.getAuthStatus())));
        }
        response.setContentType("text/html;charset=UTF-8");
        ExportBeanExcelUtil ex = new ExportBeanExcelUtil();
        ex.exportExcelNew("已认证用户信息", listName, listId, list, response);

    }

    //超管修改用户信息接口
    public RespDTO<Boolean> updateUserInfos(AmendUserInfoVO amendUserInfoVO) {
        Map<String, Object> amendUserInfo = new HashMap<String, Object>();
        amendUserInfo.put("modifier", UserUtils.getCurrentPrincipleID());
        amendUserInfo.put("gmtModified", DateUtil.now());
        amendUserInfo.put("email", amendUserInfoVO.getEmail());
        amendUserInfo.put("userId", amendUserInfoVO.getUserId());
        amendUserInfo.put("position", amendUserInfoVO.getPosition());
        amendUserInfo.put("linkman", amendUserInfoVO.getLinkman());
        User userDate = getById(amendUserInfoVO.getUserId());
        if (userDate.getIsDeleted().equals("Y")) {
            return RespDTO.onError("该用户已不存在");
        }
        boolean res = updateUserInfo(amendUserInfo);
        if (!res) {
            throw new CommonException(CommonErrorCode.UPDATE_INFO_FAIL);
        }
        return RespDTO.onSuc(res);
    }

    //超管修改机构信息
    public RespDTO<Boolean> updateOrganizations(AmendOrgVO amendOrgVO) {
        Map<String, Object> amendOrg = new HashMap<String, Object>();
        amendOrg.put("modifier", UserUtils.getCurrentPrincipleID());
        amendOrg.put("gmtModified", DateUtil.now());
        amendOrg.put("address", amendOrgVO.getOrgAddress());
        amendOrg.put("type", amendOrgVO.getOrgType());
        amendOrg.put("orgId", amendOrgVO.getOrgId());
        amendOrg.put("orgSubNum", amendOrgVO.getOrgSubNum());
        boolean res = updateOrganizations(amendOrg);
        if (!res) {
            throw new CommonException(CommonErrorCode.UPDATE_INFO_FAIL);
        }
        return RespDTO.onSuc(res);
    }

    public RespDTO<User> getUserAuthStatus(Long userId) {
        return RespDTO.onSuc(this.getById(userId));
    }

    /**
     * 根据用户ID列表获取用户数据
     *
     * @param ids 用户ID列表
     * @return 用户名信息列表
     */
    public Map<String, String> getUserInfoByIds(List<String> ids) {
        List<Long> longList = new ArrayList<>();
        for (String id : ids){
            if(!longList.contains(id)){
                longList.add(Long.valueOf(id));
            }
        }
        List<User> userList = this.getByIds(longList);
        Map<String, String> map = new HashMap<>();
        if (ListUtil.isNotEmpty(userList)){
            for (User user: userList){
                map.put(user.getId().toString(), user.getLinkman());
            }
        }
        return map;
    }
}
