package com.crm.manager.service.impl;

import com.crm.manager.dao.mapper.UserInfoDao;
import com.crm.manager.dao.repository.SysUserLoginHistoryRepository;
import com.crm.manager.dao.repository.UserGroupRepository;
import com.crm.manager.dao.repository.UserInfoRepository;
import com.crm.manager.service.*;
import com.crm.rely.backend.core.constant.*;
import com.crm.rely.backend.core.dto.base.BaseResultDto;
import com.crm.rely.backend.core.dto.base.BaseResultWithPagerDto;
import com.crm.rely.backend.core.dto.base.PageDto;
import com.crm.rely.backend.core.dto.base.ResultWithPagerDto;
import com.crm.rely.backend.core.dto.user.department.UserDepartmentSearchDto;
import com.crm.rely.backend.core.dto.user.info.SalesInfoDropdownDto;
import com.crm.rely.backend.core.dto.user.role.UserRoleDto;
import com.crm.rely.backend.core.entity.system.email.SysEmailSendEntity;
import com.crm.rely.backend.core.exception.DataNotFoundException;
import com.crm.rely.backend.core.exception.ServiceException;
import com.crm.rely.backend.core.pojo.table.SysUserLoginHistoryTable;
import com.crm.rely.backend.core.pojo.table.UserGroupTable;
import com.crm.rely.backend.model.dto.user.info.UserInfoSearchDto;
import com.crm.rely.backend.model.entity.custom.info.CustomInfoUpdateAgentEntity;
import com.crm.rely.backend.model.entity.user.info.*;
import com.crm.rely.backend.model.entity.user.role.UserRoleUpdateNumberEntity;
import com.crm.rely.backend.model.pojo.table.CustomInfoTable;
import com.crm.rely.backend.model.pojo.table.UserInfoTable;
import com.crm.rely.backend.model.pojo.view.UserInfoView;
import com.crm.rely.backend.service.MqSendService;
import com.crm.rely.backend.service.RedisService;
import com.crm.rely.backend.util.AESUtil;
import com.crm.rely.backend.util.DateUtil;
import com.crm.rely.backend.util.StampUtil;
import com.crm.rely.backend.util.UUIDUtil;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @program: crm-backend
 * @description:
 * @author: houn
 * @create: 2019-07-25 16:14
 */
@Service
public class UserInfoServiceImpl implements UserInfoService {

    @Autowired
    private UserInfoRepository userInfoRepository;

    @Autowired
    private SysUserLoginHistoryRepository sysUserLoginHistoryRepository;

    @Autowired
    private UserRoleService userRoleService;

    @Autowired
    private UserInfoDao userInfoDao;

    @Autowired
    private UserDepartmentService userDepartmentService;

    @Autowired
    private UserGroupRepository userGroupRepository;

    @Autowired
    private RedisService redisService;

    @Autowired
    private MqSendService mqSendService;

    @Autowired
    private SysIpLimitService sysIpLimitService;
    @Autowired
    private SysConfigService sysConfigService;

    /**
     * 用户登录
     *
     * @param entity
     * @return
     * @throws ServiceException
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public UserInfoEntity login(UserLoginEntity entity) throws ServiceException {

        UserInfoTable userInfoTable = userInfoRepository.findFirstByUsernameAndPassword(entity.getLoginName(), entity.getPassword());

        if (userInfoTable == null) {
            throw new ServiceException(Constants.LOGIN_FAIL);
        }
        limitIp(entity.getIp(), userInfoTable);
//        if (userInfoTable.getWithdrawCId() != null || userInfoTable.getCustomId() != null) {
//            throw ServiceException.exception(Constants.NOT_PERMIT);
//        }
        if (userInfoTable.getRoleId() != null && userInfoTable.getRoleId().equals(-1)) {
            throw ServiceException.exception(Constants.NOT_PERMIT);
        }
        if (userInfoTable.getValid() == null || !userInfoTable.getValid().equals(1)) {
            throw ServiceException.exception(Constants.RESTRICTED_LOGIN);
        }
        UserRoleDto userRoleDto;
        UserDepartmentSearchDto userDepartmentSearchDto;
        if (userInfoTable.getRoleId() != null) {
            userRoleDto = userRoleService.getRoleInfo(userInfoTable.getRoleId());
            if (userRoleDto == null) {
                throw ServiceException.exception(Constants.SYSTEM_ERROR);
            }
            userDepartmentSearchDto = userDepartmentService.searchSingle(userRoleDto.getDepartmentId());
            if (userDepartmentSearchDto == null) {
                throw ServiceException.exception(Constants.SYSTEM_ERROR);
            }
        } else {
            userRoleDto = null;
            userDepartmentSearchDto = null;
        }
        userInfoTable.setLastAddress(entity.getAddress());
        userInfoTable.setLastIp(entity.getIp());
        userInfoTable.setLastTime(entity.getTime());
        UserGroupTable userGroupTable = null;
        if (userInfoTable.getGroupId() != null && userInfoTable.getGroupId() > 0) {
            userGroupTable = userGroupRepository.getFirstById(userInfoTable.getGroupId());
        }
        UserInfoEntity infoEntity = transform(userInfoTable, entity, userRoleDto, userDepartmentSearchDto, userGroupTable);


        /**
         * 更新登录信息
         */
        userInfoRepository.save(userInfoTable);

        try {
            SysUserLoginHistoryTable sysUserLoginHistoryTable = new SysUserLoginHistoryTable();
            sysUserLoginHistoryTable.setAddress(entity.getAddress());
            sysUserLoginHistoryTable.setLoginIp(entity.getIp());
            sysUserLoginHistoryTable.setLoginUser(userInfoTable.getId());
            sysUserLoginHistoryTable.setLoginTime(entity.getTime());
            sysUserLoginHistoryRepository.save(sysUserLoginHistoryTable);
        } catch (Exception e) {
            e.getStackTrace();
        }

        return infoEntity;
    }

    /**
     * 添加用户代理信息
     *
     * @throws ServiceException
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public UserInfoTable add(CustomInfoTable customInfoTable) throws ServiceException {

        UserInfoTable userInfoTable = userInfoRepository.getFirstByUsername(customInfoTable.getEmail());

        if (userInfoTable != null) {
            //如果cid为空 或者cid和要添加的cid不同 则判断已存在账户
            if (userInfoTable.getCId() == null || !userInfoTable.getCId().equals(customInfoTable.getCId())) {
                throw new ServiceException(Constants.USERNAME_IS_EXIST_ERROR);
            }
            return userInfoTable;
        } else {
            Long superAgentId = getPid(customInfoTable);
            UserInfoTable salesTable = userInfoRepository.getFirstById(superAgentId);
            userInfoTable = new UserInfoTable();

            Long roleId = -1L;
            userInfoTable.setEmail(customInfoTable.getEmail());
            userInfoTable.setUsername(customInfoTable.getEmail());
            userInfoTable.setName(customInfoTable.getFirstName());
            userInfoTable.setGroupId(1000L);
            userInfoTable.setValid(0);
            userInfoTable.setIpLimit(0);
            userInfoTable.setAddUser(customInfoTable.getId());
            userInfoTable.setRoleId(roleId);
            userInfoTable.setAddIp("127.0.0.1");
            userInfoTable.setAddTime(new Date());
            userInfoTable.setCId(customInfoTable.getCId());
            userInfoTable.setIbNo("IB" + customInfoTable.getCId());
            userInfoTable.setStamp(getStampByPId(superAgentId));
            userInfoTable.setPid(superAgentId);

            if (salesTable.getRoleId() > 0) {
                userInfoTable.setSalesId(superAgentId);
            } else {
                userInfoTable.setSalesId(salesTable.getSalesId());
            }

            userInfoTable.setPStamp(salesTable.getStamp());

            userInfoRepository.save(userInfoTable);

            return userInfoTable;
        }
    }

    private Long getPid(CustomInfoTable customInfoTable) throws ServiceException {
        Long superAgentId = customInfoTable.getAgentId();
        if (superAgentId == null || superAgentId == 0) {
            superAgentId = Long.parseLong(sysConfigService.getByCode("COMPANY_ACCOUNT_SUPER").getValue());
        } else {
            UserInfoTable userInfoTable = userInfoRepository.findOne(superAgentId);
            if (userInfoTable == null) {
                superAgentId = Long.parseLong(sysConfigService.getByCode("COMPANY_ACCOUNT_SUPER").getValue());
            }
        }
        return superAgentId;
    }

    private String getStampByPId(Long pid) {

        String maxNo = userInfoDao.getMaxStampByPid(pid);

        if (maxNo == null) {
            UserInfoTable superAgent = userInfoRepository.getFirstById(pid);
            return StampUtil.getStamp(superAgent.getStamp() + "00");
        } else {
            return StampUtil.getStamp(maxNo);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(UserInfoAddEntity entity) throws ServiceException, InterruptedException {

        //判断角色是否存在
        userRoleService.existRole(entity.getRoleId());

        //用户名
        existByUsername(entity.getUsername());

        //邮箱
        existByEmail(entity.getEmail());

        UserInfoTable userInfoTable = new UserInfoTable();
        BeanUtils.copyProperties(entity, userInfoTable);

         /*
            判断角色
         */
        Long roleId = userInfoTable.getRoleId();
        String roleCode = userRoleService.getRoleCodeById(roleId);
        if ("ROLE_SALE".equalsIgnoreCase(roleCode)) {
            if (userInfoTable.getPid() == null || userInfoTable.getPid() <= 0) {
                //获取超级管理员ID
                UserInfoTable superAdmin = userInfoDao.getSuperAdminInfo();
                userInfoTable.setPid(superAdmin.getId());
                userInfoTable.setPStamp(superAdmin.getStamp());
            } else {
                //获取上级信息
                UserInfoTable superUser = userInfoRepository.getOne(userInfoTable.getPid());
                userInfoTable.setPStamp(superUser.getStamp());
            }
            //生成stamp
            String stamp = this.getStampByPId(userInfoTable.getPid());
            userInfoTable.setStamp(stamp);
        } else {
            userInfoTable.setStamp("01");
        }
        userRoleService.getRoleCodeById(roleId);

        userInfoRepository.save(userInfoTable);

         /*
            如果是销售更新销售ID
         */
        if ("ROLE_SALE".equalsIgnoreCase(roleCode)) {
            userInfoTable.setSalesId(userInfoTable.getId());
            userInfoRepository.save(userInfoTable);
        }

        UserRoleUpdateNumberEntity userRoleUpdateNumberEntity = new UserRoleUpdateNumberEntity();
        userRoleUpdateNumberEntity.setId(entity.getRoleId());
        userRoleUpdateNumberEntity.setChangeNumber(1);
        userRoleService.updateNumber(userRoleUpdateNumberEntity);
    }

    /**
     * 删除用户
     *
     * @param entity
     * @throws ServiceException
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(UserInfoDeleteEntity entity) throws ServiceException {

        List<UserInfoTable> userInfoTables = userInfoRepository.findAll(entity.getIds());
        if (userInfoTables == null || userInfoTables.size() <= 0) {
            return;
        }

        userInfoRepository.delete(userInfoTables);

        List<UserRoleUpdateNumberEntity> userRoleUpdateNumberEntities = new ArrayList<>(userInfoTables.size());
        userInfoTables.forEach(value -> {
            if (value.getRoleId() != null) {
                UserRoleUpdateNumberEntity userRoleUpdateNumberEntity = new UserRoleUpdateNumberEntity();
                userRoleUpdateNumberEntity.setId(value.getRoleId());
                userRoleUpdateNumberEntity.setChangeNumber(-1);
                userRoleUpdateNumberEntities.add(userRoleUpdateNumberEntity);
            }
        });
        if (userRoleUpdateNumberEntities != null && userRoleUpdateNumberEntities.size() > 0) {

            userRoleService.updateNumber(userRoleUpdateNumberEntities);
        }
    }

    /**
     * 修改用户信息
     *
     * @param entity
     * @throws ServiceException
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public UserInfoTable update(UserInfoUpdateEntity entity) throws ServiceException {

        UserInfoTable userInfoTable = userInfoRepository.findFirstById(entity.getId());

        if (userInfoTable == null) {
            throw new ServiceException(Constants.USER_NOT_EXIST_ERROR);
        }

        List<UserRoleUpdateNumberEntity> userRoleUpdateNumberEntities = null;
        //角色
        if (!entity.getRoleId().equals(userInfoTable.getRoleId())) {
            userRoleService.existRole(entity.getRoleId());

            userRoleUpdateNumberEntities = new ArrayList<>(2);
            UserRoleUpdateNumberEntity userRoleUpdateNumberEntityOld = new UserRoleUpdateNumberEntity();
            userRoleUpdateNumberEntityOld.setId(userInfoTable.getRoleId());
            userRoleUpdateNumberEntityOld.setChangeNumber(-1);
            userRoleUpdateNumberEntities.add(userRoleUpdateNumberEntityOld);

            UserRoleUpdateNumberEntity userRoleUpdateNumberEntityNew = new UserRoleUpdateNumberEntity();
            userRoleUpdateNumberEntityNew.setId(entity.getRoleId());
            userRoleUpdateNumberEntityNew.setChangeNumber(1);
            userRoleUpdateNumberEntities.add(userRoleUpdateNumberEntityNew);

        }

        //用户名
        if (!entity.getUsername().equals(userInfoTable.getUsername())) {
            existByUsername(entity.getUsername());
        }

        //邮箱
        if (!entity.getEmail().equals(userInfoTable.getEmail())) {
            existByEmail(entity.getEmail());
        }

        if (Strings.isNullOrEmpty(entity.getPassword())) {
            entity.setPassword(userInfoTable.getPassword());
        }

        /*
            上级发生变动
         */
        //新上级
        UserInfoTable pUser = null;
        if (entity.getPid() != null) {
            pUser = userInfoRepository.getFirstById(entity.getPid());
        }
        if (entity.getPid() != null && pUser == null) {
            throw new ServiceException(Constants.USER_NOT_EXIST_ERROR);
        }
        BeanUtils.copyProperties(entity, userInfoTable);

        userInfoRepository.save(userInfoTable);

        if (userRoleUpdateNumberEntities != null) {
            userRoleService.updateNumber(userRoleUpdateNumberEntities);
        }
        return userInfoTable;
    }


    /**
     * 根据条件搜索列表
     *
     * @param entity
     * @return
     * @throws ServiceException
     */
    @Override
    public BaseResultWithPagerDto<List<UserInfoSearchDto>> searchPage(UserInfoSearchEntity entity) throws ServiceException {

        Integer count = userInfoDao.searchByPageCount(entity);
        PageDto pageDto = PageDto.format(entity, count);
        if (count == null || count <= 0) {
            return ResultWithPagerDto.success(pageDto);
        }
        List<UserInfoView> userInfoViews = userInfoDao.searchByPageList(entity);

        if (userInfoViews == null || userInfoViews.size() <= 0) {

            throw new ServiceException(Constants.SYSTEM_ERROR);
        }
        List<UserInfoSearchDto> userInfoSearchDtos = new ArrayList<>(userInfoViews.size());

        for (UserInfoView sysEmailConfigTable : userInfoViews) {
            UserInfoSearchDto sysConfigSearchDto = transform(sysEmailConfigTable);
            userInfoSearchDtos.add(sysConfigSearchDto);
        }

        return new BaseResultWithPagerDto(pageDto, userInfoSearchDtos);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateLang(UserInfoUpdateLangEntity entity) throws ServiceException {

        UserInfoTable userInfoTable = userInfoRepository.findFirstById(entity.getId());
        if (userInfoTable == null) {
            throw ServiceException.exception(Constants.SYSTEM_ERROR);
        }
        if (entity.getLang() != null && !entity.getLang().equals(userInfoTable.getLang())) {
            userInfoTable.setLang(entity.getLang());
            userInfoRepository.save(userInfoTable);
        }
    }

    @Override
    public void updatePasswordSendEmail(UserUpdatePasswordSendEmailEntity entity) throws ServiceException {

        UserInfoTable userInfoTable = userInfoRepository.getFirstByEmailNotNullAndEmail(entity.getEmail());

        if (userInfoTable == null || Strings.isNullOrEmpty(userInfoTable.getPassword())) {
            throw new ServiceException(Constants.USER_NOT_EXIST_ERROR);
        }

        SysEmailSendEntity sysEmailSendEntity = createUpdatePasswordSendEmailSysEmailEntity(entity, userInfoTable);


        redisService.save(sysEmailSendEntity.getMap().get(MapConstants.TOKEN), userInfoTable.getId(), Constants.EMAIL_TOKEN_TIME * 60 * 1000);

        mqSendService.send(Constants.ACTIVEMQ_JMS_URL_EMAIL, sysEmailSendEntity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updatePassword(UserUpdateEmailPasswordEntity entity) throws ServiceException {

        Long id = redisService.getEntity(entity.getToken(), Long.class);
        if (id == null) {
            throw new ServiceException(Constants.EMAIL_EXPIRE);
        }

        UserInfoTable userInfoTable = userInfoRepository.findFirstById(id);

        if (userInfoTable == null) {
            throw new ServiceException(Constants.USER_NOT_EXIST_ERROR);
        }

        /**
         * 填写修改时间和密码
         */
        userInfoTable.setPassword(entity.getPassword());
        userInfoTable.setModifyIp(entity.getModifyIp());
        userInfoTable.setModifyTime(entity.getModifyTime());
        userInfoTable.setModifyUser(userInfoTable.getModifyUser());

        userInfoRepository.save(userInfoTable);
        redisService.remove(entity.getToken());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updatePassword(UserUpdateLoginPasswordEntity entity) throws ServiceException {

        UserInfoTable userInfoTable = userInfoRepository.findFirstById(entity.getId());

        if (userInfoTable == null) {
            throw new ServiceException(Constants.USER_NOT_EXIST_ERROR);
        }

        if (!entity.getOldPassword().equals(userInfoTable.getPassword())) {
            throw new ServiceException(Constants.PASSWORD_ERROR);
        }
        /**
         * 填写修改时间和密码
         */
        userInfoTable.setPassword(entity.getNewPassword());
        userInfoTable.setModifyIp(entity.getModifyIp());
        userInfoTable.setModifyTime(entity.getModifyTime());
        userInfoTable.setModifyUser(userInfoTable.getModifyUser());

        userInfoRepository.save(userInfoTable);
    }

    @Override
    public BaseResultDto<List<SalesInfoDropdownDto>> getSalesInfoDropdown() throws Exception {

        String roleCode = "ROLE_SALE";

        List<UserInfoTable> tables = userInfoDao.findAllByRoleCode(roleCode);
        List<SalesInfoDropdownDto> dtos = Lists.newArrayList();
        tables.forEach((table) -> {
            SalesInfoDropdownDto dto = new SalesInfoDropdownDto();
            dto.setEmail(table.getEmail());
            dto.setIbNo(table.getIbNo());
            dto.setId(table.getId());
            dto.setName(table.getName());
            dtos.add(dto);
        });

        return BaseResultDto.success(dtos);
    }

    @Override
    public BaseResultDto<List<SalesInfoDropdownDto>> getAgentDropdown() throws Exception {

        List<UserInfoTable> tables = userInfoDao.getAllAgent();
        List<SalesInfoDropdownDto> dtos = Lists.newArrayList();
        tables.forEach((table) -> {
            SalesInfoDropdownDto dto = new SalesInfoDropdownDto();
            dto.setEmail(table.getEmail());
            dto.setIbNo(table.getIbNo());
            dto.setId(table.getId());
            dto.setName(table.getName());
            dtos.add(dto);
        });

        return BaseResultDto.success(dtos);
    }

    @Override
    public CustomInfoUpdateAgentEntity getAgent(CustomInfoUpdateAgentEntity entity) throws ServiceException {
        UserInfoTable userInfoTable = userInfoRepository.getFirstById(entity.getAgentId());
        if (userInfoTable == null) {
            throw ServiceException.exception(Constants.INFO_NOT_FOUND);
        }
        entity.setPStamp(userInfoTable.getStamp());
        String stamp = getStampByPId(entity.getAgentId());
        entity.setStamp(stamp);

        if (userInfoTable.getRoleId() > 0) {
            entity.setSalesId(entity.getAgentId());
        } else {
            entity.setSalesId(userInfoTable.getSalesId());
        }
        return entity;
    }

    /**
     * 根据id查询
     *
     * @param id
     * @return
     * @throws ServiceException
     */
    @Override
    public UserInfoSearchDto searchSingle(Long id) throws ServiceException {

        UserInfoView userInfoView = userInfoDao.getOne(id);
        if (userInfoView == null) {
            throw new DataNotFoundException(Constants.USER_NOT_EXIST_ERROR);
        }

        UserInfoSearchDto userInfoSearchDto = transform(userInfoView);

        return userInfoSearchDto;
    }

    /**
     * 验证用户名是否已存在
     *
     * @param username
     * @throws ServiceException
     */
    private void existByUsername(String username) throws ServiceException {
        boolean existByUsername = userInfoRepository.existsByUsername(username);
        if (existByUsername) {
            throw new ServiceException(Constants.USERNAME_IS_EXIST_ERROR);
        }
    }


    /**
     * 验证邮箱是否已存在
     *
     * @param email
     * @throws ServiceException
     */
    private void existByEmail(String email) throws ServiceException {
        boolean existByEmail = userInfoRepository.existsByEmail(email);
        if (existByEmail) {
            throw new ServiceException(Constants.EMAIL_IS_EXIST_ERROR);
        }
    }

    /**
     * 构建修改密码发送邮件实体
     *
     * @param entity
     * @param userInfoTable
     * @return
     */
    private SysEmailSendEntity createUpdatePasswordSendEmailSysEmailEntity(UserUpdatePasswordSendEmailEntity entity, UserInfoTable userInfoTable) {
        SysEmailSendEntity sysEmailSendEntity = new SysEmailSendEntity();
        String token = AESUtil.encrypt(entity.getEmail() + Constants.LOGIN_LINK + UUIDUtil.getUUID() + Constants.LOGIN_LINK + userInfoTable.getId());
        Date time = DateUtil.operationMinute(new Date(), Constants.EMAIL_TOKEN_TIME);
        Map<String, String> map = new HashMap<>(3);
        map.put(MapConstants.TOKEN, token);
        map.put(MapConstants.EXPIRE_TIME, DateUtil.formatTime(time));
        map.put(MapConstants.DATE_TIME, DateUtil.formatTime());

        sysEmailSendEntity.setAddIp(entity.getIp());
        sysEmailSendEntity.setAddTime(entity.getTime());
        sysEmailSendEntity.setAddUser(userInfoTable.getAddUser());
        sysEmailSendEntity.setUsers(entity.getEmail());
        sysEmailSendEntity.setEmailSendEnum(EmailSendEnum.FORGET_PASSWORD);
        sysEmailSendEntity.setTemplateName(GlobalSystemEmailCodeConstants.USER_UPDATE_PASSWORD_SEND_CN);
        sysEmailSendEntity.setMap(map);

        return sysEmailSendEntity;
    }

    private UserInfoEntity transform(UserInfoTable userInfoTable, UserLoginEntity entity, UserRoleDto userRoleDto, UserDepartmentSearchDto userDepartmentSearchDto, UserGroupTable userGroupTable) {

        UserInfoEntity infoEntity = new UserInfoEntity();

        BeanUtils.copyProperties(userInfoTable, infoEntity);
        if (userRoleDto != null) {
            infoEntity.setRoleName(userRoleDto.getName());
            infoEntity.setRoleCode(userRoleDto.getCode());
        } else {
            infoEntity.setRoleName(ManagerConstant.ROLE_CODE_SYSTEM);
            infoEntity.setRoleCode(ManagerConstant.ROLE_CODE_SYSTEM);
        }
        infoEntity.setId(userInfoTable.getId());
        infoEntity.setThisAddress(entity.getAddress());
        infoEntity.setThisIp(entity.getIp());
        infoEntity.setThisTime(entity.getTime());
        infoEntity.setValid(userInfoTable.getValid() == null ? 0 : userInfoTable.getValid());

        PrefixEnum prefixEnum;
        switch (infoEntity.getRoleCode()) {
            case ManagerConstant.ROLE_CODE_SYSTEM:
                prefixEnum = PrefixEnum.PREFIX_SYSTEM;
                infoEntity.setRoleId(0L);
                break;
            case ManagerConstant.ROLE_CODE_SALE:
                prefixEnum = PrefixEnum.PREFIX_SALE;
                break;
            case ManagerConstant.ROLE_CODE_ADMIN:
                prefixEnum = PrefixEnum.PREFIX_ADMIN;
                break;
            case ManagerConstant.ROLE_CODE_FINANCE:
                prefixEnum = PrefixEnum.PREFIX_FINANCE;
                break;
            case ManagerConstant.ROLE_CODE_MARKET:
                prefixEnum = PrefixEnum.PREFIX_MARKET;
                break;
            case ManagerConstant.ROLE_CODE_LEGAL_AFFAIRS:
                prefixEnum = PrefixEnum.PREFIX_LEGAL_AFFAIRS;
                break;
            case ManagerConstant.ROLE_CODE_USER:
                prefixEnum = PrefixEnum.PREFIX_USER;
            default:
                prefixEnum = PrefixEnum.PREFIX_USER;
                break;
        }
        infoEntity.setPrefix(prefixEnum);

        return infoEntity;
    }


    /**
     * 转化(list转化为dtos)
     *
     * @param userInfoViews
     * @return
     */
    private List<UserInfoSearchDto> transform(List<UserInfoView> userInfoViews) {

        if (userInfoViews == null || userInfoViews.size() <= 0) {
            return null;
        }

        List<UserInfoSearchDto> transform = new ArrayList<>(userInfoViews.size());
        userInfoViews.forEach(value -> transform.add(transform(value)));

        return transform;
    }

    /**
     * 转化为dto
     *
     * @param userInfoView
     * @return
     */
    private UserInfoSearchDto transform(UserInfoView userInfoView) {

        UserInfoSearchDto userInfoSearchDto = new UserInfoSearchDto();

        BeanUtils.copyProperties(userInfoView, userInfoSearchDto);

        return userInfoSearchDto;
    }

    private void limitIp(String ip, UserInfoTable userInfoTable) throws ServiceException {
        if (userInfoTable == null) {
            throw ServiceException.exception(Constants.SYSTEM_ERROR);
        }
        if (userInfoTable.getIpLimit() == null || userInfoTable.getIpLimit().equals(0)) {
            return;
        }
        /**
         * 如果ip限制开启 则进行ip校验 如果记录上的ip限制地址不为空
         */
        if (!Strings.isNullOrEmpty(userInfoTable.getLimitIp())) {
            /**
             * 记录ip限制校验
             */
            if (!userInfoTable.getIpLimit().equals(ip)) {
                throw ServiceException.exception(Constants.RESTRICTED_LOGIN);
            }
        } else {
            boolean validateResult = sysIpLimitService.validatedIpExist(ip);
            if (!validateResult) {
                throw ServiceException.exception(Constants.RESTRICTED_LOGIN);
            }
        }
    }

}
