
package com.tmerclub.cloud.auth.feign;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.tmerclub.cloud.api.auth.bo.UidInfoBO;
import com.tmerclub.cloud.api.auth.bo.UserRegisterNotifyBO;
import com.tmerclub.cloud.api.auth.constant.SysTypeEnum;
import com.tmerclub.cloud.api.auth.dto.*;
import com.tmerclub.cloud.api.auth.feign.AccountFeignClient;
import com.tmerclub.cloud.api.auth.vo.AuthAccountVO;
import com.tmerclub.cloud.api.auth.vo.TokenInfoVO;
import com.tmerclub.cloud.auth.manager.PasswordManager;
import com.tmerclub.cloud.auth.manager.TokenStore;
import com.tmerclub.cloud.auth.mapper.AuthAccountMapper;
import com.tmerclub.cloud.auth.mapper.AuthSocialMapper;
import com.tmerclub.cloud.auth.model.AuthAccount;
import com.tmerclub.cloud.auth.model.AuthSocial;
import com.tmerclub.cloud.common.constant.Constant;
import com.tmerclub.cloud.common.constant.UserAdminType;
import com.tmerclub.cloud.common.exception.LuckException;
import com.tmerclub.cloud.common.leaf.manager.SegmentManager;
import com.tmerclub.cloud.common.response.ResponseEnum;
import com.tmerclub.cloud.common.response.ServerResponseEntity;
import com.tmerclub.cloud.common.rocketmq.config.RocketMqConstant;
import com.tmerclub.cloud.common.security.AuthUserContext;
import com.tmerclub.cloud.common.security.bo.AuthAccountInVerifyBO;
import com.tmerclub.cloud.common.security.constant.InputUserNameEnum;
import com.tmerclub.cloud.common.util.BeanUtil;
import com.tmerclub.cloud.common.util.PasswordUtil;
import com.tmerclub.cloud.common.util.PrincipalUtil;
import com.tmerclub.cloud.constant.DistributedIdKey;
import org.apache.dubbo.config.annotation.DubboService;
import org.apache.rocketmq.client.producer.LocalTransactionState;
import org.apache.rocketmq.client.producer.TransactionSendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.support.GenericMessage;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import org.yaml.snakeyaml.tokens.ScalarToken;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author tmerclub
 * @date 2020/9/22
 */
@DubboService
public class AccountFeignController implements AccountFeignClient {

    @Autowired
    private AuthAccountMapper authAccountMapper;
    @Autowired
    private AuthSocialMapper authSocialMapper;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private TokenStore tokenStore;
    @Autowired
    private RocketMQTemplate userNotifyRegisterTemplate;
    @Autowired
    private SegmentManager segmentManager;
    @Autowired
    private PasswordManager passwordManager;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ServerResponseEntity<Long> save(AuthAccountDTO authAccountDTO) {

        ServerResponseEntity<AuthAccount> verify = verify(authAccountDTO);
        if (!verify.isSuccess()) {
            return ServerResponseEntity.transform(verify);
        }
        AuthAccount data = verify.getData();
        // 设置uid
        data.setUid(segmentManager.getSegmentId(DistributedIdKey.tmerclub_AUTH_USER));
        authAccountMapper.save(data);

        return ServerResponseEntity.success(data.getUid());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ServerResponseEntity<Void> update(AuthAccountDTO authAccountDTO) {
        ServerResponseEntity<AuthAccount> verify = verify(authAccountDTO);
        if (!verify.isSuccess()) {
            return ServerResponseEntity.transform(verify);
        }
        AuthAccount authAccount = authAccountMapper.getByUserIdAndType(authAccountDTO.getUserId(), authAccountDTO.getSysType());
        if (!Objects.equals(authAccountDTO.getStatus(), 1)) {
            if (Objects.equals(authAccount.getIsAdmin(), UserAdminType.ADMIN.value())) {
                return ServerResponseEntity.showFailMsg("该账号为管理员不能禁用");
            }

        }
        if (StrUtil.isBlank(verify.getData().getPassword())) {
            verify.getData().setPassword(null);
        }
        authAccountMapper.updateAccountInfo(verify.getData());
        // 修改了用户的状态 or 密码 or 用户名，要将用户下线
        if (!Objects.equals(authAccountDTO.getStatus(), 1) || StrUtil.isNotBlank(verify.getData().getPassword())
                || !Objects.equals(authAccountDTO.getUsername(), authAccount.getUsername())) {
            AuthAccount dbAccount = authAccountMapper.getByUserIdAndType(authAccountDTO.getUserId(), authAccountDTO.getSysType());
            tokenStore.deleteTokenByUidInfo(BeanUtil.map(dbAccount, UidInfoBO.class));
        }
        return ServerResponseEntity.success();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ServerResponseEntity<Void> updateAuthAccountStatus(AuthAccountDTO authAccountDTO) {
        if (Objects.isNull(authAccountDTO.getStatus())) {
            throw new LuckException(ResponseEnum.EXCEPTION);
        }
        AuthAccount authAccount = BeanUtil.map(authAccountDTO, AuthAccount.class);
        authAccountMapper.updateAccountInfo(authAccount);
        return ServerResponseEntity.success();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ServerResponseEntity<Void> deleteByUserIdAndSysType(Long userId) {
        UidInfoBO uidInfoBO = AuthUserContext.get();
        Integer sysType = uidInfoBO.getSysType();
        AuthAccount authAccount = authAccountMapper.getByUserIdAndType(userId, sysType);
        if (Objects.isNull(authAccount)) {
            return ServerResponseEntity.success();
        }
        if (Objects.equals(authAccount.getIsAdmin(), UserAdminType.ADMIN.value())) {
            throw new LuckException("管理员账号不能删除");
        }
        authAccountMapper.deleteByUserIdAndSysType(userId, sysType);

        if (Objects.equals(sysType, SysTypeEnum.ORDINARY.value())) {
            authSocialMapper.unBindUserByUid(authAccount.getUid());
        }
        // 删除对应的token信息，使用户下线
        AuthAccount dbAccount = authAccountMapper.getByUserIdAndType(userId, sysType);
        tokenStore.deleteTokenByUidInfo(BeanUtil.map(dbAccount, UidInfoBO.class));

        return ServerResponseEntity.success();
    }

    @Override
    public void deleteByTenantIdAndSysType(Long tenantId, Integer sysType) {
        AuthAccountVO authAccountVO = authAccountMapper.getAccountInfoByTenantId(sysType, tenantId);
        authAccountMapper.deleteByTenantIdAndSysType(tenantId, sysType);
        // 清除缓存
        tokenStore.deleteTokenByUidInfo(BeanUtil.map(authAccountVO, UidInfoBO.class));
    }

    @Override
    public ServerResponseEntity<Integer> countByMobile(String mobile) {
        return ServerResponseEntity.success(authAccountMapper.countByMobile(mobile, SysTypeEnum.ORDINARY.value()));
    }

    @Override
    public ServerResponseEntity<AuthAccountVO> getByUserIdAndSysType(Long userId, Integer sysType) {
        AuthAccount authAccount = authAccountMapper.getByUserIdAndType(userId, sysType);
        if (Objects.nonNull(authAccount)) {
            authAccount.setPassword(null);
        }
        return ServerResponseEntity.success(BeanUtil.map(authAccount, AuthAccountVO.class));
    }

    @Override
    public ServerResponseEntity<AuthAccountVO> getInsiderDataByUserIdAndSysType(Long userId, Integer sysType) {
        return getByUserIdAndSysType(userId, sysType);
    }

    @Override
    public ServerResponseEntity<AuthAccountVO> getBySysTypeAndIsAdminAndTenantId(Integer sysType, Integer isAdmin, Long tenantId) {
        AuthAccount authAccount = authAccountMapper.getBySysTypeAndIsAdminAndTenantId(sysType, isAdmin, tenantId);
        if (Objects.nonNull(authAccount)) {
            authAccount.setPassword(null);
        }
        return ServerResponseEntity.success(BeanUtil.map(authAccount, AuthAccountVO.class));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ServerResponseEntity<Long> saveAccountWithSocial(AuthAccountWithSocialDTO authAccountWithSocialDTO) {
        AuthAccountDTO authAccount = authAccountWithSocialDTO.getAuthAccount();
        String tempUid = authAccountWithSocialDTO.getTempUid();

        // 保存账户
        ServerResponseEntity<Long> serverResponse = save(authAccount);
        if (!serverResponse.isSuccess()) {
            return ServerResponseEntity.transform(serverResponse);
        }
        Long uid = serverResponse.getData();

        // 如果有社交帐户信息
        if (tempUid != null) {
            authSocialMapper.bindUidByTempUid(uid, tempUid);
        }

        return ServerResponseEntity.success(uid);
    }

    @Override
    public ServerResponseEntity<TokenInfoVO> storeTokenAndGetVo(UidInfoBO uidInfoBO) {
        return ServerResponseEntity.success(tokenStore.storeAndGetVo(uidInfoBO));
    }

    @Override
    public ServerResponseEntity<List<AuthAccountVO>> listByUserAccount(String userName, String phone, String email, SysTypeEnum sysType) {
        return ServerResponseEntity.success(authAccountMapper.listByUserAccount(userName, phone, email, sysType.value()));
    }

    @Override
    public ServerResponseEntity<Void> updateUserMobile(AuthAccountDTO authAccountDTO) {
        if (authAccountMapper.countByMobile(authAccountDTO.getSysType(), authAccountDTO.getPhone()) > 0) {
            throw new LuckException("该手机号码已在系统存在");
        }
        authAccountMapper.updateUserMobile(authAccountDTO);
        return ServerResponseEntity.success();
    }

    @Override
    public ServerResponseEntity<List<AuthAccountVO>> listUserByUserIdsAndType(List<Long> userIds, Integer systemType) {
        if (CollUtil.isEmpty(userIds)) {
            return ServerResponseEntity.success(new ArrayList<>(0));
        }
        List<AuthAccountVO> authAccountList = authAccountMapper.listUserByUserIdsAndType(userIds, systemType);
        return ServerResponseEntity.success(authAccountList);
    }

    @Override
    public ServerResponseEntity<List<AuthAccountVO>> listByUserIdsAndPhoneAndType(List<Long> userIds, String phone, Integer sysType) {
        List<AuthAccountVO> authAccountList = authAccountMapper.listByUserIdsAndPhoneAndType(userIds, phone, sysType);
        return ServerResponseEntity.success(authAccountList);
    }

    @Override
    public ServerResponseEntity<AuthAccountVO> getByUserIdAndType(Long userId, Integer sysType) {
        List<AuthAccountVO> authAccountList = authAccountMapper.listUserByUserIdsAndType(Collections.singletonList(userId), sysType);
        if (CollUtil.isEmpty(authAccountList)) {
            throw new LuckException("用户不存在或已删除");
        }
        return ServerResponseEntity.success(authAccountList.get(0));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ServerResponseEntity<Void> updateUserInfoByUserIdAndSysType(UidInfoBO uidInfoBO, Long userId, Integer sysType) {
        AuthAccount byUserIdAndType = authAccountMapper.getByUserIdAndType(userId, sysType);
        uidInfoBO.setAccountUid(byUserIdAndType.getUid());
        tokenStore.updateUidInfo(uidInfoBO);
        AuthAccount authAccount = BeanUtil.map(uidInfoBO, AuthAccount.class);
        int res = authAccountMapper.updateUserInfoByUserId(authAccount, userId, sysType);
        if (res != 1) {
            throw new LuckException("用户信息错误，更新失败");
        }
        return ServerResponseEntity.success();
    }

    @Override
    public ServerResponseEntity<Integer> countByMobileAndSysType(String mobile, Integer sysType) {
        return ServerResponseEntity.success(authAccountMapper.countByMobile(mobile, sysType));
    }

    @Override
    public ServerResponseEntity<Integer> countByUserNameAndSysType(String userName, Integer sysType) {
        return ServerResponseEntity.success(authAccountMapper.countByUserNameAndSysType(userName, sysType));
    }

    @Override
    public ServerResponseEntity<List<String>> listUserNameByNames(List<String> names) {
        if (CollUtil.isEmpty(names)) {
            return ServerResponseEntity.success(new ArrayList<>(0));
        }
        return ServerResponseEntity.success(authAccountMapper.listUserNameByNames(names));
    }

    @Override
    public ServerResponseEntity<Void> updateNoAuditUidInfo(UidInfoBO uidInfoBO) {
        AuthAccount byUserIdAndType = authAccountMapper.getByUserIdAndType(uidInfoBO.getUserId(), uidInfoBO.getSysType());
        uidInfoBO.setAccountUid(byUserIdAndType.getUid());
        AuthAccount authAccount = BeanUtil.map(uidInfoBO, AuthAccount.class);
        StringBuffer uidBuffer = new StringBuffer();
        uidBuffer.append(uidInfoBO.getSysType()).append(Constant.UNDERLINE)
                    .append(uidInfoBO.getAccountUid()).append(Constant.UNDERLINE)
                        .append(uidInfoBO.getUserId()).append(Constant.UNDERLINE)
                            // 未开店成功的店铺、供应商id默认是-1
                            .append(byUserIdAndType.getTenantId()).append(Constant.UNDERLINE)
                                .append(uidInfoBO.getIsAdmin()).append(Constant.UNDERLINE)
                                    // 未开店成功的店铺、供应商默认是未入驻
                                    .append(byUserIdAndType.getIsPassShop());
        tokenStore.updateUidInfoByUid(uidBuffer.toString(), uidInfoBO);
        int res = authAccountMapper.updateUserInfoByUserId(authAccount, uidInfoBO.getUserId(), uidInfoBO.getSysType());
        if (res != 1) {
            throw new LuckException("用户信息错误，更新失败");
        }
        return ServerResponseEntity.success();
    }


    @Override
    public ServerResponseEntity<Void> updateAuthAccountStatusAndDeleteUserToken(AuthAccountDTO authAccountDTO) {
        // 修改了用户的状态，应该要将用户下线
        if (Objects.isNull(authAccountDTO.getUserId())) {
            throw new LuckException("用户id不能为空");
        }
        if (Objects.isNull(authAccountDTO.getSysType())) {
            throw new LuckException("系统类型不能为空");
        }
        if (Objects.isNull(authAccountDTO.getStatus())) {
            throw new LuckException("用户状态不能为空");
        }
        AuthAccount authAccount = BeanUtil.map(authAccountDTO, AuthAccount.class);
        authAccountMapper.updateAccountInfo(authAccount);
        // 删除对应的token信息，使用户下线
        AuthAccount dbAccount = authAccountMapper.getByUserIdAndType(authAccountDTO.getUserId(), authAccountDTO.getSysType());
        tokenStore.deleteTokenByUidInfo(BeanUtil.map(dbAccount, UidInfoBO.class));
        return ServerResponseEntity.success();
    }

    @Override
    public ServerResponseEntity<List<String>> getBizUserIdListByUserId(Long userId) {
        List<String> bizUserIdListByUserId = authAccountMapper.getBizUserIdListByUserId(userId);
        return ServerResponseEntity.success(bizUserIdListByUserId);
    }

    @Override
    public ServerResponseEntity<AuthSocialDTO> getBizUserIdByTempUid(String tempUid) {
        AuthSocial authSocial = authSocialMapper.getByTempUid(tempUid);
        AuthSocialDTO authSocialDTO = new AuthSocialDTO();
        BeanUtils.copyProperties(authSocial, authSocialDTO);
        return ServerResponseEntity.success(authSocialDTO);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ServerResponseEntity<String> batchRegisterAccount(AuthAccountUserDTO authAccountUserDTO) {
        List<AuthAccountDTO> accountDTOList = authAccountUserDTO.getAccountDTOList();
        if (CollUtil.isEmpty(accountDTOList)) {
            ServerResponseEntity.showFailMsg("用户信息列表为空");
        }
        accountDTOList = filterAuthAccountsByPhonesOrEmailsOrUserNames(accountDTOList);
        int size = accountDTOList.size();
        if (CollUtil.isEmpty(accountDTOList)) {
            ServerResponseEntity.showFailMsg("符合导入规则的数据" + size + "条");
        }
        List<AuthAccount> authAccounts = new ArrayList<>(Constant.INITIAL_CAPACITY);
        int i = 0;
        for (AuthAccountDTO authAccountDTO : accountDTOList) {
            // 邮箱
            if (StrUtil.isNotBlank(authAccountDTO.getEmail()) && !PrincipalUtil.isEmail(authAccountDTO.getEmail())) {
                continue;
            }
            // 手机号
            if (StrUtil.isNotBlank(authAccountDTO.getPhone()) && !PrincipalUtil.isMobile(authAccountDTO.getPhone())) {
                continue;
            }
            AuthAccount authAccount = BeanUtil.map(authAccountDTO, AuthAccount.class);
            // 设置分布式id
            Long uid = segmentManager.getSegmentId(DistributedIdKey.tmerclub_AUTH_USER);
            authAccount.setUid(uid);
            authAccounts.add(authAccount);
            i++;
        }


        // 批量注册用户
        if (CollUtil.isNotEmpty(authAccounts)) {
            List<Long> userIds = authAccounts.stream().map(AuthAccount::getUserId).toList();
            // 需要插入的用户信息
            List<UserRegisterDTO> userRegisterList = authAccountUserDTO.getUserRegisterList();
            List<UserRegisterExtensionDTO> userRegisterExtensionDTOList = authAccountUserDTO.getUserRegisterExtensionDTOList();
            List<UserRegisterDTO> userList = userRegisterList.stream().filter(item -> userIds.contains(item.getUserId())).collect(Collectors.toList());
            List<UserRegisterExtensionDTO> userExtensionList = userRegisterExtensionDTOList.stream().filter(item -> userIds.contains(item.getUserId())).collect(Collectors.toList());
            UserRegisterNotifyBO userRegisterNotifyBO = new UserRegisterNotifyBO(BeanUtil.mapAsList(authAccounts, AuthAccountDTO.class), userList, userExtensionList);
            // 发送用户注册事件
            TransactionSendResult transactionSendResult = userNotifyRegisterTemplate.sendMessageInTransaction(RocketMqConstant.BATCH_USER_REGISTER_TOPIC, new GenericMessage<>(userRegisterNotifyBO), authAccounts);
            if (!Objects.equals(transactionSendResult.getLocalTransactionState(), LocalTransactionState.COMMIT_MESSAGE)) {
                throw new LuckException(ResponseEnum.EXCEPTION);
            }
            return ServerResponseEntity.success(String.valueOf(userIds.size()));
        }
        return ServerResponseEntity.showFailMsg("无数据导入");
    }

    @Override
    public ServerResponseEntity<AuthAccountVO> getAccountInfoByTenantId(Long tenantId, Integer sysType) {
        sysType = Objects.isNull(sysType) ? AuthUserContext.get().getSysType() : sysType;
        AuthAccountVO authAccountVO = authAccountMapper.getAccountInfoByTenantId(sysType, tenantId);
        if (Objects.isNull(authAccountVO)) {
            throw new LuckException("找不到此账户信息，账户已删除");
        }
        return ServerResponseEntity.success(authAccountVO);
    }

    @Override
    public ServerResponseEntity<Boolean> verifyAccount(AuthAccountDTO authAccountDTO) {
        ServerResponseEntity<AuthAccount> verify = verify(authAccountDTO);
        if (!verify.isSuccess()) {
            return ServerResponseEntity.showFailMsg(verify.getMsg());
        }
        return ServerResponseEntity.success(verify.isSuccess());
    }

    /**
     * 过滤掉已经存在的 手机号号 用户名 邮箱 的账户
     *
     * @param accountDTOList 未过滤前的账户集合
     * @return 过滤后的账户集合
     */
    private List<AuthAccountDTO> filterAuthAccountsByPhonesOrEmailsOrUserNames(List<AuthAccountDTO> accountDTOList) {
        List<String> phones = accountDTOList.stream().map(AuthAccountDTO::getPhone).distinct().filter(StrUtil::isNotBlank).collect(Collectors.toList());
        List<String> emails = accountDTOList.stream().map(AuthAccountDTO::getEmail).distinct().filter(StrUtil::isNotBlank).collect(Collectors.toList());
        // 获取已存在的email用户
        List<String> dbEmails;
        if (CollUtil.isNotEmpty(emails)) {
            List<AuthAccountVO> authAccountEmailList = authAccountMapper.getAuthAccountByInputUserName(InputUserNameEnum.EMAIL.value(), emails, SysTypeEnum.ORDINARY.value());
            if (CollUtil.isNotEmpty(authAccountEmailList)) {
                dbEmails = authAccountEmailList.stream().map(AuthAccountVO::getEmail).collect(Collectors.toList());
            } else {
                dbEmails = new ArrayList<>(0);
            }
        } else {
            dbEmails = new ArrayList<>(0);
        }
        // 获取已存在的phone用户
        List<String> dbPhones;
        if (CollUtil.isNotEmpty(phones)) {
            List<AuthAccountVO> authAccountPhoneList = authAccountMapper.getAuthAccountByInputUserName(InputUserNameEnum.PHONE.value(), phones, SysTypeEnum.ORDINARY.value());
            if (CollUtil.isNotEmpty(authAccountPhoneList)) {
                dbPhones = authAccountPhoneList.stream().map(AuthAccountVO::getPhone).collect(Collectors.toList());
            } else {
                dbPhones = new ArrayList<>(0);
            }
        } else {
            dbPhones = new ArrayList<>(0);
        }
        // 过滤已存在的 username email phone用户
        accountDTOList = accountDTOList.stream().filter(item -> {
            boolean isExist = dbEmails.contains(item.getEmail()) || dbPhones.contains(item.getPhone());
            return !isExist;
        }).collect(Collectors.toList());
        // 过滤掉邮箱用户重复的数据。导入的用户手机号不为空，phone已经过滤了，响应的username也过滤了,这里只给邮箱去重就可以了
        List<AuthAccountDTO> accountList = accountDTOList.stream().filter(item -> Objects.isNull(item.getEmail())).collect(Collectors.toList());
        accountDTOList = accountDTOList.stream()
                .filter(item -> Objects.nonNull(item.getEmail()))
                .collect(Collectors.collectingAndThen(
                        Collectors.toCollection(() ->
                                new TreeSet<>(Comparator.comparing(AuthAccountDTO::getEmail, Comparator.nullsLast(String::compareTo)))), ArrayList::new));
        accountList.addAll(accountDTOList);
        return accountList;
    }

    private ServerResponseEntity<AuthAccount> verify(AuthAccountDTO authAccountDTO) {
        boolean isStationAccount = authAccountDTO.getSysType() != null
                && Objects.equals(SysTypeEnum.STATION.value(), authAccountDTO.getSysType());
        // 用户名(自提门店账号无格式要求)
        if (!isStationAccount
                && StrUtil.isNotBlank(authAccountDTO.getUsername())
                && !PrincipalUtil.isUserName(authAccountDTO.getUsername())) {
            return ServerResponseEntity.showFailMsg("用户名格式不正确");
        }

        // 邮箱
        if (StrUtil.isNotBlank(authAccountDTO.getEmail()) && !PrincipalUtil.isEmail(authAccountDTO.getEmail())) {
            return ServerResponseEntity.showFailMsg("邮箱格式不正确");
        }

        // 手机号
        if (StrUtil.isNotBlank(authAccountDTO.getPhone()) && !PrincipalUtil.isMobile(authAccountDTO.getPhone())) {
            return ServerResponseEntity.showFailMsg("手机号格式不正确");
        }

        if (StrUtil.isNotBlank(authAccountDTO.getUsername())) {
            AuthAccountInVerifyBO userNameBo = authAccountMapper.getAuthAccountInVerifyByInputUserName(InputUserNameEnum.USERNAME.value(), authAccountDTO.getUsername(), authAccountDTO.getSysType());
            if (userNameBo != null && !Objects.equals(userNameBo.getUserId(), authAccountDTO.getUserId())) {
                String failMsg;
                if (isStationAccount) {
                    failMsg = "账号已存在，请更换账号名再次尝试";
                } else {
                    failMsg = "用户名已存在，请更换用户名再次尝试";
                }
                return ServerResponseEntity.showFailMsg(failMsg);
            }
        }

        if (StrUtil.isNotBlank(authAccountDTO.getEmail())) {
            AuthAccountInVerifyBO emailBO = authAccountMapper.getAuthAccountInVerifyByInputUserName(InputUserNameEnum.EMAIL.value(), authAccountDTO.getEmail(), authAccountDTO.getSysType());
            if (emailBO != null && !Objects.equals(emailBO.getUserId(), authAccountDTO.getUserId())) {
                return ServerResponseEntity.showFailMsg("邮箱已存在，请更换邮箱再次尝试");
            }
        }

        if (StrUtil.isNotBlank(authAccountDTO.getPhone())) {
            AuthAccountInVerifyBO phoneBo = authAccountMapper.getAuthAccountInVerifyByInputUserName(InputUserNameEnum.PHONE.value(), authAccountDTO.getPhone(), authAccountDTO.getSysType());
            if (phoneBo != null && !Objects.equals(phoneBo.getUserId(), authAccountDTO.getUserId())) {
                return ServerResponseEntity.showFailMsg("手机号已存在，请更换手机号再次尝试");
            }
        }

        AuthAccount authAccount = BeanUtil.map(authAccountDTO, AuthAccount.class);

        if (StrUtil.isNotBlank(authAccount.getPassword())) {
            ServerResponseEntity<String> decryptPasswordEntity = passwordManager.decryptPassword(authAccount.getPassword());
            if (!decryptPasswordEntity.isSuccess()) {
                return ServerResponseEntity.transform(decryptPasswordEntity);
            }
            // 密码格式检验
            if (!PasswordUtil.checkFormat(decryptPasswordEntity.getData())) {
                return ServerResponseEntity.showFailMsg("密码由字母加数字或符号至少两种以上字符组成6-20位半角字符，区分大小写");
            }
            authAccount.setPassword(passwordEncoder.encode(decryptPasswordEntity.getData()));
        }

        return ServerResponseEntity.success(authAccount);
    }

}
