package com.izouma.nineth.service;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
import com.huifu.adapay.core.exception.BaseAdaPayException;
import com.izouma.nineth.TokenHistory;
import com.izouma.nineth.config.Constants;
import com.izouma.nineth.config.GeneralProperties;
import com.izouma.nineth.domain.Collection;
import com.izouma.nineth.domain.*;
import com.izouma.nineth.dto.*;
import com.izouma.nineth.enums.AuthStatus;
import com.izouma.nineth.enums.AuthorityName;
import com.izouma.nineth.event.AccountCreatedEvent;
import com.izouma.nineth.event.RegisterEvent;
import com.izouma.nineth.exception.BusinessException;
import com.izouma.nineth.repo.*;
import com.izouma.nineth.security.Authority;
import com.izouma.nineth.security.JwtTokenUtil;
import com.izouma.nineth.security.JwtUserFactory;
import com.izouma.nineth.service.sms.SmsService;
import com.izouma.nineth.service.storage.StorageService;
import com.izouma.nineth.utils.BankUtils;
import com.izouma.nineth.utils.JpaUtils;
import com.izouma.nineth.utils.ObjUtils;
import com.izouma.nineth.utils.SecurityUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.context.event.EventListener;
import org.springframework.core.env.Environment;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.Predicate;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Service
@Slf4j
@AllArgsConstructor
public class UserService {
    private UserRepo                      userRepo;
    private WxMaService                   wxMaService;
    private WxMpService                   wxMpService;
    private SmsService                    smsService;
    private StorageService                storageService;
    private JwtTokenUtil                  jwtTokenUtil;
    private FollowService                 followService;
    private FollowRepo                    followRepo;
    private IdentityAuthRepo              identityAuthRepo;
    private SysConfigService              sysConfigService;
    private UserBankCardRepo              userBankCardRepo;
    private InviteRepo                    inviteRepo;
    private NFTService                    nftService;
    private CacheService                  cacheService;
    private TokenHistoryRepo              tokenHistoryRepo;
    private CollectionRepo                collectionRepo;
    private AdapayMerchantService         adapayMerchantService;
    private Environment                   env;
    private RocketMQTemplate              rocketMQTemplate;
    private GeneralProperties             generalProperties;
    private RedisTemplate<String, Object> redisTemplate;
    private PasswordEncoder               passwordEncoder;
    private AssetRepo                     assetRepo;

    public User update(User user) {
        if (!SecurityUtils.hasRole(AuthorityName.ROLE_ADMIN)) {
            if (!SecurityUtils.getAuthenticatedUser().getId().equals(user.getId())) {
                throw new BusinessException("无权限");
            }
        }
        User orig = userRepo.findById(user.getId()).orElseThrow(new BusinessException("无记录"));
        ObjUtils.merge(orig, user);
        orig = save(orig);
        userRepo.updateAssetMinter(orig.getId());
        userRepo.updateAssetOwner(orig.getId());
        userRepo.updateCollectionMinter(orig.getId());
        userRepo.updateCollectionOwner(orig.getId());
        userRepo.updateOrderMinter(orig.getId());
        userRepo.updateHistoryFromUser(orig.getId());
        userRepo.updateHistoryToUser(orig.getId());
        userRepo.updateShowroomToUser(orig.getId());
        cacheService.clearCollection();
        cacheService.clearUserMy(user.getId());
        return orig;
    }

    public User save(User user) {
        if (user.getId() != null) {
            cacheService.clearUserMy(user.getId());
        }
        return userRepo.save(user);
    }

    @Cacheable(value = "userList", key = "#pageQuery.hashCode()")
    public PageWrapper<User> all(PageQuery pageQuery) {
        Specification<User> specification = JpaUtils.toSpecification(pageQuery, User.class);

        specification = specification.and((Specification<User>) (root, criteriaQuery, criteriaBuilder) -> {
            List<Predicate> and = new ArrayList<>();
            and.add(criteriaBuilder.equal(root.get("del"), false));
            if (!pageQuery.getQuery().containsKey("admin")) {
                and.add(criteriaBuilder.equal(root.get("admin"), false));
            }

            if (pageQuery.getQuery().containsKey("hasRole")) {
                String roleName = (String) pageQuery.getQuery().get("hasRole");
                if (roleName.equals("ROLE_MINTER")) {
                    and.add(criteriaBuilder.equal(root.get("minter"), true));
                } else {
                    and.add(criteriaBuilder
                            .isMember(Authority.get(AuthorityName.valueOf(roleName)), root.get("authorities")));
                }
            }

            if (pageQuery.getQuery().containsKey("vip")) {
                boolean vip = (boolean) pageQuery.getQuery().get("vip");
                if (vip) {
                    and.add(criteriaBuilder.greaterThan(root.get("vipPurchase"), 0));
                } else {
                    and.add(criteriaBuilder.lessThanOrEqualTo(root.get("vipPurchase"), 0));
                }
            }
            return criteriaBuilder.and(and.toArray(new Predicate[0]));
        });
        Page<User> page = userRepo.findAll(specification, JpaUtils.toPageRequest(pageQuery));
        return PageWrapper.of(page);
    }

    public User create(UserRegister userRegister) {
        User user = new User();
        BeanUtils.copyProperties(userRegister, user);
        user.setShareRatio(sysConfigService.getBigDecimal("share_ratio"));
        user.setAuthStatus(AuthStatus.NOT_AUTH);
        if (StringUtils.isNotBlank(userRegister.getPassword())) {
            user.setPassword(passwordEncoder.encode(userRegister.getPassword()));
        }
        return save(user);
    }

    @EventListener
    public void accountCreated(AccountCreatedEvent event) {
        userRepo.findById(event.getUserId()).ifPresent(user -> {
            user.setNftAccount(event.getAccount().getAccountId());
            user.setKmsId(event.getAccount().getAccountKmsId());
            user.setPublicKey(event.getAccount().getPublicKey());
            save(user);
        });
    }

    public User phoneRegister(String phone, String code, String password, String inviteCode, Long invitor, Long collectionId) {
        String name = "nft_" + RandomStringUtils.randomAlphabetic(8);
        Invite invite = null;
        if (StringUtils.isNotBlank(inviteCode)) {
            invite = inviteRepo.findFirstByCode(inviteCode).orElse(null);
        }
        smsService.verify(phone, code);
        Collection collection;
        if (collectionId != null) {
            collection = collectionRepo.findById(collectionId).orElseThrow(new BusinessException("无藏品"));
//            if (!collection.isOnShelf() || !collection.isSalable()) {
//                collectionId = null;
//            } else if (collection.isScheduleSale()) {
//                if (collection.getStartTime().isAfter(LocalDateTime.now())) {
//                    collectionId = null;
//                }
//            }
            // 只看是否开去分享
            if (ObjectUtils.isEmpty(collection.getOpenQuota()) || !collection.getOpenQuota()) {
                collectionId = null;
            }
        }
        User user = create(UserRegister.builder()
                .username(name)
                .nickname(name)
                .password(password)
                .avatar(Constants.DEFAULT_AVATAR)
                .phone(phone)
                .invitorPhone(Optional.ofNullable(invite).map(Invite::getPhone).orElse(null))
                .invitorName(Optional.ofNullable(invite).map(Invite::getName).orElse(null))
                .inviteCode(Optional.ofNullable(invite).map(Invite::getCode).orElse(null))
                .collectionInvitor(invitor)
                .collectionId(collectionId)
                .build());
        if (invite != null) {
            inviteRepo.increaseNum(invite.getId());
        }

        // 加积分
//        if (collectionId != null && invitor != null) {
//            // 额度或者额度为空， 库存不为空
//            if (collection.getStock() > 0 && (collection.getVipQuota() > 0 || ObjectUtils.isEmpty(collection.getVipQuota()))) {
//                int countUser = userRepo.countAllByCollectionIdAndCollectionInvitor(collectionId, invitor);
//                // 邀请人数
//                if (countUser >= collection.getAssignment()) {
//                    int point = pointRecordRepo.countByUserIdAndCollectionId(invitor, collectionId);
//                    // 是否已有积分
//                    if (point <= 0) {
//                        long count = userRepo.countAllByCollectionIdAndCollectionInvitor(collectionId, invitor);
//                        if (count >= collection.getAssignment()) {
//                            // 扣除藏品额度
//                            if (ObjectUtils.isNotEmpty(collection.getVipQuota())) {
//                                collectionService.decreaseQuota(collectionId, 1);
//                            }
//                            userRepo.updateVipPoint(invitor, 1);
//                            pointRecordRepo.save(PointRecord.builder()
//                                    .collectionId(collectionId)
//                                    .userId(invitor)
//                                    .type("VIP_POINT")
//                                    .point(1)
//                                    .build());
//
//                        }
//                    }
//                }
//            }
//        }
        return user;
    }

    public String mqRegister(String phone, String code, String password, String inviteCode, Long invitor, Long collectionId) {
        rocketMQTemplate.convertAndSend(generalProperties.getRegisterTopic(),
                new RegisterEvent(phone, code, password, inviteCode, invitor, collectionId));
        return phone;
    }

    public Object getRegisterResult(String phone) {
        return redisTemplate.opsForValue().get("register::" + phone);
    }

    public User testPhoneRegister(String phone) {
        return create(UserRegister.builder()
                .avatar(Constants.DEFAULT_AVATAR)
                .username(RandomStringUtils.randomAlphabetic(32))
                .nickname(RandomStringUtils.randomAlphabetic(32))
                .phone(RandomStringUtils.randomNumeric(16))
                .password("123456")
                .build());
    }

    public void del(Long id) {
        User user = userRepo.findById(id).orElseThrow(new BusinessException("用户不存在"));
        user.setDel(true);
        if (StringUtils.isNoneEmpty(user.getOpenId())) {
            user.setOpenId(user.getOpenId() + "###" + RandomStringUtils.randomAlphabetic(8));
        }
        if (StringUtils.isNoneEmpty(user.getPhone())) {
            user.setPhone(user.getPhone() + "###" + RandomStringUtils.randomAlphabetic(8));
        }
        save(user);
        //删除实名认证
        identityAuthRepo.softDeleteByUserId(id);
    }

    public User loginByPhone(String phone, String code) {
        User user = userRepo.findByPhoneAndDelFalse(phone).orElse(null);
        smsService.verify(phone, code);
        if (user == null) {
            String name = "nft_" + RandomStringUtils.randomAlphabetic(8);
            user = create(UserRegister.builder()
                    .authorities(Collections.singleton(Authority.get(AuthorityName.ROLE_USER)))
                    .username(name)
                    .nickname(name)
                    .avatar(Constants.DEFAULT_AVATAR)
                    .phone(phone)
                    .build());
        }
        return user;
    }

    public User loginByPhonePwd(String phone, String password) {
        if (StringUtils.isEmpty(phone)) {
            throw new BusinessException("手机号错误");
        }
        User user = userRepo.findByPhoneAndDelFalse(phone).orElseThrow(new BusinessException("账号或密码错误"));

        if (StringUtils.isEmpty(user.getPassword())) {
            throw new BusinessException("账号或密码错误");
        }
        if (StringUtils.isNoneEmpty(user.getPassword()) &&
                !passwordEncoder.matches(password, user.getPassword())) {
            throw new BusinessException("账号或密码错误");
        }

        return user;
    }

    public User loginByUsernamePwd(String username, String password) {
        if (StringUtils.isEmpty(username)) {
            throw new BusinessException("用户名错误");
        }
        User user = userRepo.findByUsernameAndDelFalse(username).orElseThrow(new BusinessException("账号或密码错误"));

        if (StringUtils.isEmpty(user.getPassword())
                || !passwordEncoder.matches(password, user.getPassword())) {
            throw new BusinessException("账号或密码错误");
        }

        return user;
    }

    public User loginMp(String code) throws WxErrorException {
        WxMpOAuth2AccessToken accessToken = wxMpService.oauth2getAccessToken(code);
        WxMpUser wxMpUser = wxMpService.oauth2getUserInfo(accessToken, null);
        User user = userRepo.findByOpenIdAndDelFalse(wxMpUser.getOpenId()).orElse(null);
        if (user == null) {
            String name = "nft_" + RandomStringUtils.randomAlphabetic(8);
            user = User.builder()
                    .username(name)
                    .nickname(name)
                    .avatar(wxMpUser.getHeadImgUrl())
                    .sex(wxMpUser.getSexDesc())
                    .country(wxMpUser.getCountry())
                    .province(wxMpUser.getProvince())
                    .city(wxMpUser.getCity())
                    .openId(wxMpUser.getOpenId())
                    .language(wxMpUser.getLanguage())
                    .authorities(Collections.singleton(Authority.get(AuthorityName.ROLE_USER)))
                    .authStatus(AuthStatus.NOT_AUTH)
                    .build();
            save(user);
        }
        return user;
    }

    public String code2openId(String code) throws WxErrorException {
        WxMpOAuth2AccessToken accessToken = wxMpService.oauth2getAccessToken(code);
        return wxMpService.oauth2getUserInfo(accessToken, null).getOpenId();
    }

    public User loginMa(String code) {
        try {
            WxMaJscode2SessionResult result = wxMaService.jsCode2SessionInfo(code);
            String openId = result.getOpenid();
            String sessionKey = result.getSessionKey();
            User userInfo = userRepo.findByOpenIdAndDelFalse(openId).orElse(null);
            ;
            if (userInfo != null) {
                return userInfo;
            }
            String name = "nft_" + RandomStringUtils.randomAlphabetic(8);
            userInfo = User.builder()
                    .username(name)
                    .nickname(name)
                    .openId(openId)
                    .avatar(Constants.DEFAULT_AVATAR)
                    .authorities(Collections.singleton(Authority.get(AuthorityName.ROLE_USER)))
                    .authStatus(AuthStatus.NOT_AUTH)
                    .build();
            userInfo = save(userInfo);
            return userInfo;
        } catch (WxErrorException e) {
            e.printStackTrace();
        }
        throw new BusinessException("登录失败");
    }

    public User getMaUserInfo(String sessionKey, String rawData, String signature,
                              String encryptedData, String iv) {
        // 用户信息校验
        if (!wxMaService.getUserService().checkUserInfo(sessionKey, rawData, signature)) {
            throw new BusinessException("获取用户信息失败");
        }

        // 解密用户信息
        WxMaUserInfo wxUserInfo = wxMaService.getUserService().getUserInfo(sessionKey, encryptedData, iv);
        User user = userRepo.findByOpenIdAndDelFalse(wxUserInfo.getOpenId()).orElse(null);

        String avatarUrl = Constants.DEFAULT_AVATAR;
        try {
            String path = "image/avatar/" +
                    new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date()) +
                    RandomStringUtils.randomAlphabetic(8) +
                    ".jpg";
            avatarUrl = storageService.uploadFromUrl(wxUserInfo.getAvatarUrl(), path);
        } catch (Exception e) {
            log.error("获取头像失败", e);
        }

        if (user == null) {

            user = User.builder()
                    .username(UUID.randomUUID().toString())
                    .nickname(wxUserInfo.getNickName())
                    .openId(wxUserInfo.getOpenId())
                    .avatar(avatarUrl)
                    .sex(wxUserInfo.getGender())
                    .country(wxUserInfo.getCountry())
                    .province(wxUserInfo.getProvince())
                    .city(wxUserInfo.getCity())
                    .authorities(Collections.singleton(Authority.builder().name("ROLE_USER").build()))
                    .build();
            user = save(user);

        } else {
            user.setAvatar(avatarUrl);
            user.setNickname(wxUserInfo.getNickName());
            user.setSex(wxUserInfo.getGender());
            user.setCountry(wxUserInfo.getCountry());
            user.setProvince(wxUserInfo.getProvince());
            user.setCity(wxUserInfo.getCity());
            user = save(user);
        }

        return user;
    }

    public String setPassword(Long userId, String password) {
        User user = userRepo.findById(userId).orElseThrow(new BusinessException("用户不存在"));
        user.setPassword(passwordEncoder.encode(password));
        user = save(user);
        return jwtTokenUtil.generateToken(JwtUserFactory.create(user));
    }

    public String setPassword(Long userId, String code, String password) {
        User user = userRepo.findById(userId).orElseThrow(new BusinessException("用户不存在"));
        smsService.verify(user.getPhone(), code);
        return setPassword(userId, password);
    }

    public String forgotPassword(String phone, String password, String code) {
        User user = userRepo.findByPhoneAndDelFalse(phone).orElseThrow(new BusinessException("手机号未注册"));
        smsService.verify(user.getPhone(), code);
        return setPassword(user.getId(), password);
    }

    public void bindPhone(Long userId, String phone) {
        User user = userRepo.findByIdAndDelFalse(userId).orElseThrow(new BusinessException("用户不存在"));
        if (StringUtils.isNoneEmpty(user.getPhone())) {
            throw new BusinessException("该账号已绑定手机");
        }
        userRepo.findByPhoneAndDelFalse(phone).ifPresent(user1 -> {
            if (!user1.getId().equals(userId)) {
                throw new BusinessException("该手机号已绑定其他账号");
            }
        });

        user.setPhone(phone);
        save(user);
    }

    public UserDTO toDTO(User user) {
        return toDTO(user, true);
    }

    public UserDTO toDTO(User user, boolean join) {
        UserDTO userDTO = new UserDTO();
        BeanUtils.copyProperties(user, userDTO);
        if (user.getAuthorities() != null) {
            userDTO.setAuthorities(new HashSet<>(user.getAuthorities()));
        }
        if (join) {
            if (SecurityUtils.getAuthenticatedUser() != null) {
                userDTO.setFollow(followService.isFollow(SecurityUtils.getAuthenticatedUser().getId(), user.getId()));
            }
        }
        return userDTO;
    }

    public List<UserDTO> toDTO(List<User> users) {
        List<Follow> follows = new ArrayList<>();
        if (SecurityUtils.getAuthenticatedUser() != null) {
            follows.addAll(followRepo.findByUserId(SecurityUtils.getAuthenticatedUser().getId()));
        }
        return users.stream().parallel().map(user -> {
            UserDTO dto = toDTO(user, false);
            if (!follows.isEmpty()) {
                dto.setFollow(follows.stream().anyMatch(f -> f.getFollowUserId().equals(user.getId())));
            }
            return dto;
        }).collect(Collectors.toList());
    }

    public Page<UserDTO> toDTO(Page<User> users) {
        List<UserDTO> userDTOS = toDTO(users.getContent());
        return new PageImpl<>(userDTOS, users.getPageable(), users.getTotalElements());
    }

    @CacheEvict(value = "user", allEntries = true)
    public void setTradeCode(Long userId, String token, String tradeCode) {
        String phone = smsService.verifyToken(token);
        User user = userRepo.findById(userId).orElseThrow(new BusinessException("用户不存在"));
        if (!StringUtils.equals(phone, user.getPhone())) {
            throw new BusinessException("验证码无效");
        }
        user.setTradeCode(passwordEncoder.encode(tradeCode));
        save(user);
    }

    public void verifyTradeCode(Long userId, String tradeCode) {
        User user = userRepo.findById(userId).orElseThrow(new BusinessException("用户不存在"));
        if (!passwordEncoder.matches(tradeCode, user.getTradeCode())) {
            throw new BusinessException("校验失败");
        }
    }

    public Map<String, Object> searchByPhone(String phone) {
        if (AuthStatus.SUCCESS != SecurityUtils.getAuthenticatedUser().getAuthStatus()) {
            throw new BusinessException("实名认证后才能赠送");
        }
        User user = userRepo.findByPhoneAndDelFalse(phone).orElseThrow(new BusinessException("用户不存在或未认证"));
        if (AuthStatus.SUCCESS != user.getAuthStatus()) {
            throw new BusinessException("用户不存在或未认证");
        }
        String realName = identityAuthRepo.findFirstByUserIdAndStatusAndDelFalseOrderByCreatedAtDesc(
                user.getId(), AuthStatus.SUCCESS)
                .map(IdentityAuth::getRealName).orElse("").replaceAll(".*(?=.)", "**");
        Map<String, Object> map = new HashMap<>();
        map.put("id", user.getId());
        map.put("avatar", user.getAvatar());
        map.put("phone", user.getPhone().replaceAll("(?<=.{3}).*(?=.{4})", "**"));
        map.put("realName", realName);
        return map;
    }


    public Map<String, Object> searchByPhoneAdmin(String phoneStr) {
        List<String> phone = Arrays.stream(phoneStr.replaceAll("\n", " ")
                .replaceAll("\r\n", " ")
                .split(" "))
                .map(String::trim)
                .filter(s -> !StringUtils.isEmpty(s))
                .collect(Collectors.toList());
        List<User> users = userRepo.findByPhoneInAndDelFalse(phone);
        Map<String, Object> map = new HashMap<>();
        map.put("users", users);
        List<String> notFound = phone.stream().filter(p -> users.stream().noneMatch(u -> p.equals(u.getPhone())))
                .collect(Collectors.toList());
        map.put("notFound", notFound);
        return map;
    }

    public void addBankCard(Long userId, String bankNo, String phone, String code) throws BaseAdaPayException {
        User user = userRepo.findById(userId).orElseThrow(new BusinessException("用户不存在"));
        IdentityAuth identityAuth = identityAuthRepo
                .findFirstByUserIdAndStatusAndDelFalseOrderByCreatedAtDesc(userId, AuthStatus.SUCCESS)
                .orElseThrow(new BusinessException("用户未认证"));
        if (identityAuth.isOrg()) {
            //throw new BusinessException("企业认证用户请绑定对公账户");
        }
        if (!StringUtils.isBlank(user.getSettleAccountId())) {
            throw new BusinessException("此账号已绑定");
        }
        BankValidate bankValidate = BankUtils.validate(bankNo);
        if (!bankValidate.isValidated()) {
            throw new BusinessException("暂不支持此卡");
        }
        smsService.verify(phone, code);

        /*adapayMerchantService.createMemberForAll(userId.toString(), user.getPhone(), identityAuth.getRealName(), identityAuth.getIdNo());
        user.setMemberId(user.getId().toString());
        save(user);

        String accountId = adapayMerchantService.createSettleAccountForAll
                (user.getMemberId(), identityAuth.getRealName(),
                        identityAuth.getIdNo(), phone, bankNo);
        user.setSettleAccountId(Optional.ofNullable(accountId).orElse("1"));
        save(user);*/

        userBankCardRepo.save(UserBankCard.builder()
                .bank(bankValidate.getBank())
                .bankName(bankValidate.getBankName())
                .bankNo(bankNo)
                .cardType(bankValidate.getCardType())
                .cardTypeDesc(bankValidate.getCardTypeDesc())
                .userId(userId)
                .phone(phone)
                .realName(identityAuth.getRealName())
                .idNo(identityAuth.getIdNo())
                .build());
    }

    public void removeBankCard(Long userId) throws BaseAdaPayException {
        User user = userRepo.findById(userId).orElseThrow(new BusinessException("用户不存在"));
        if (StringUtils.isNotBlank(user.getSettleAccountId()) && StringUtils.isNotBlank(user.getMemberId())) {
            adapayMerchantService.delSettleAccountForAll(user.getMemberId());
            user.setSettleAccountId(null);
            save(user);
            userBankCardRepo.deleteByUserId(userId);
        } else {
            throw new BusinessException("未绑定");
        }
    }

    public void removeAuth(Long userId) {
        User user = userRepo.findById(userId).orElseThrow(new BusinessException("用户不存在"));
        if (user.getAuthStatus() == AuthStatus.SUCCESS) {
            user.setAuthStatus(AuthStatus.NOT_AUTH);
            save(user);
            identityAuthRepo.deleteAll(identityAuthRepo.findByUserIdAndDelFalse(userId));
        }
    }

    public Map<String, Object> batchRegister(String phones, String defaultPassword) {
        List<String> exist = new ArrayList<>();
        List<String> err = new ArrayList<>();
        List<String> success = new ArrayList<>();
        Arrays.stream(phones.replaceAll(",", " ")
                .replaceAll("，", " ")
                .replaceAll("\n", " ")
                .replaceAll("\r\n", " ")
                .split(" ")).forEach(phone -> {

            if (userRepo.findByPhoneAndDelFalse(phone).isPresent()) {
                exist.add(phone);
            } else {
                if (!Pattern.matches("^1[3-9]\\d{9}$", phone)) {
                    err.add(phone);
                } else {
                    try {
                        String name = "nft_" + RandomStringUtils.randomAlphabetic(8);
                        User user = create(UserRegister.builder()
                                .authorities(Collections.singleton(Authority.get(AuthorityName.ROLE_USER)))
                                .username(name)
                                .nickname(name)
                                .password(defaultPassword)
                                .avatar(Constants.DEFAULT_AVATAR)
                                .phone(phone)
                                .build());
                        success.add(phone);
                    } catch (Exception e) {
                        log.error("注册失败", e);
                        err.add(phone);
                    }
                }
            }
        });
        Map<String, Object> map = new HashMap<>();
        map.put("exist", exist);
        map.put("error", err);
        map.put("success", success);
        return map;
    }

    public Map<String, Object> invite(PageQuery pageQuery) {
        Page<User> all = this.all(pageQuery).toPage();

        List<Long> userIds = all.map(User::getId).getContent();
        List<TokenHistory> page = tokenHistoryRepo.userBuy(userIds);
        Map<Long, BigDecimal> buy = page.stream()
                .collect(Collectors.groupingBy(TokenHistory::getToUserId,
                        Collectors.mapping(TokenHistory::getPrice,
                                Collectors.reducing(BigDecimal.ZERO, BigDecimal::add))));

        Page<InvitePhoneDTO> users = all.map(user -> {
            InvitePhoneDTO dto = new InvitePhoneDTO(user);
            dto.setTotal(buy.get(user.getId()) == null ? BigDecimal.ZERO : buy.get(user.getId()));
            return dto;
        });

        BigDecimal total = buy.values().stream().reduce(BigDecimal.ZERO, BigDecimal::add);

        Map<String, Object> map = new HashMap<>();
        map.put("user", users);
        map.put("total", total);
        return map;
    }

    @Async
    public void checkSettleAccountAsync() {
        checkSettleAccount();
    }

    public void checkSettleAccount() {
        List<User> list = userRepo.findBySettleAccountIdIsNotNull();
        AtomicInteger count = new AtomicInteger();
        list.forEach(user -> {
            try {
                Thread.sleep(500);
                IdentityAuth identityAuth = identityAuthRepo
                        .findFirstByUserIdAndStatusAndDelFalseOrderByCreatedAtDesc(user.getId(), AuthStatus.SUCCESS)
                        .orElseThrow(new BusinessException("用户未认证"));
                UserBankCard userBankCard = userBankCardRepo.findByUserId(user.getId()).stream().findAny()
                        .orElseThrow(new BusinessException("未绑卡"));
                adapayMerchantService.createMemberForAll(
                        user.getId().toString(), Optional.ofNullable(userBankCard.getPhone()).orElse(user.getPhone()),
                        identityAuth.getRealName(), identityAuth.getIdNo());
                adapayMerchantService.createSettleAccountForAll(
                        user.getId().toString(), identityAuth.getRealName(),
                        identityAuth.getIdNo(), Optional.ofNullable(userBankCard.getPhone()).orElse(user.getPhone()),
                        userBankCard.getBankNo());
                userBankCard.setPhone(Optional.ofNullable(userBankCard.getPhone()).orElse(user.getPhone()));
                userBankCardRepo.save(userBankCard);
            } catch (Exception e) {
                user.setSettleAccountId(null);
                save(user);
                userBankCardRepo.deleteByUserId(user.getId());
            }
            count.getAndIncrement();
            log.info("checkSettleAccount {}/{}", count.get(), list.size());
        });
    }


    @Cacheable(value = "myUserInfo", key = "#id")
    public User my(Long id) {
        User user = userRepo.findById(id).orElseThrow(new BusinessException("用户不存在"));
        user.setPassword(null);
        user.setTradeCode(null);
        List<UserBankCard> byUserId = userBankCardRepo.findByUserId(user.getId());
        if (byUserId.size() == 0 || byUserId == null) {
            user.setIsUserBankCard(false);
        } else {
            user.setIsUserBankCard(true);
        }
        return user;
    }

}
