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.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.huifu.adapay.core.exception.BaseAdaPayException;
import com.huifu.adapay.model.AdapayCommon;
import com.huifu.adapay.model.SettleAccount;
import com.izouma.nineth.config.SysConstants;
import com.izouma.nineth.domain.*;
import com.izouma.nineth.dto.*;
import com.izouma.nineth.enums.*;
import com.izouma.nineth.event.AccountCreatedEvent;
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.loginLog.LoginLogService;
import com.izouma.nineth.service.pay.UniformPayConstants;
import com.izouma.nineth.service.realname.RealNameLogService;
import com.izouma.nineth.service.rewardpoints.UserIntegralChangeLogService;
import com.izouma.nineth.service.sms.SmsService;
import com.izouma.nineth.service.storage.StorageService;
import com.izouma.nineth.utils.*;
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.collections.MapUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.context.ApplicationContext;
import org.springframework.context.event.EventListener;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.scheduling.annotation.Async;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.Predicate;
import javax.transaction.Transactional;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
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 NFTService nftService;
    private AdapayMerchantService adapayMerchantService;
    private final ApplicationContext context;
    private ProjectService projectService;
    private final LoginLogService loginLogService;
    private final RealNameLogService realNameLogService;
    private UserFundAccountForLianlianpayService userFundAccountForLianlianpayService;
    private UserIntegralChangeLogService userIntegralChangeLogService;


    @CacheEvict(value = "user", key = "#user.username")
    @Transactional
    public User update(User user) {
        User orig = userRepo.findById(user.getId()).orElseThrow(new BusinessException("用户无记录"));
        ObjUtils.merge(orig, user);
        orig = userRepo.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());
        return orig;
    }

    @CacheEvict(value = "user", allEntries = true)
    public void clearCache() {
    }

    public Page<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");
                and.add(criteriaBuilder.isMember(Authority.get(AuthorityName.valueOf(roleName)), root.get("authorities")));
            }
            return criteriaBuilder.and(and.toArray(new Predicate[0]));
        });
        return userRepo.findAll(specification, JpaUtils.toPageRequest(pageQuery));
    }

    /**
     * 创建账户
     *
     * @param userRegister
     * @return
     */
    @Transactional
    public User create(UserRegister userRegister) {
        if (StringUtils.isNoneEmpty(userRegister.getPhone()) && userRepo.findByPhone(userRegister.getPhone())
                .orElse(null) != null) {
            throw new BusinessException("该手机号已注册");
        }

        User oldUser = userRepo.findByUsername(userRegister.getUsername());
        if (oldUser != null) {
            throw new BusinessException("该用户名已被使用");
        }

        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(new BCryptPasswordEncoder().encode(userRegister.getPassword()));
        }
        user = userRepo.saveAndFlush(user);

        //注册成功送积分
        long registeredIntegral = sysConfigService.getInt(SysConstants.REGISTERED_INTEGRAL);
        if(registeredIntegral > 0){
            userIntegralChangeLogService.createByChangeType(IntegralChangeType.REGISTER, user.getId(), registeredIntegral);
        }

        return user;
    }

    /**
     * 异步操作，不能内部类直接使用
     *
     * @param userId
     */
    @Async
    public void createNFTAccount(Long userId) {
        User user = userRepo.findById(userId).orElseThrow(new BusinessException("创建NFT时用户不存在"));
        NFTAccount account = null;
        try {
            account = nftService.createAccount(user.getUsername());
        } catch (Exception e) {
            log.error("创建NFT账户失败，用户ID:" + userId, e);
        }

        if (account != null) {
            context.publishEvent(new AccountCreatedEvent(this, userId, account));
        }
    }

    @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());
            userRepo.save(user);
        });
    }


    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));
        }
        userRepo.save(user);
    }


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

            if (StringUtils.isEmpty(user.getPassword())) {
                throw new BusinessException("账号或密码错误");
            }
            if (StringUtils.isNoneEmpty(user.getPassword()) &&
                    !new BCryptPasswordEncoder().matches(password, user.getPassword())) {
                throw new BusinessException("账号或密码错误");
            }
            return user;
        }catch (BusinessException e){
            loginSuccess = false;
            throw e;
        }finally {
            LoginLog loginLog = LoginLog.builder().loginSuccess(loginSuccess).loginTime(LocalDateTime.now())
                    .phone(phone).userId(user == null ? null : user.getId()).loginType(LoginType.PASSWORD)
                    .build();
            loginLogService.pushLoginLog(loginLog);
        }
    }

    public User loginMp(String code) throws WxErrorException {
        User user = null;
        boolean loginSuccess = true;
        try {
            WxMpOAuth2AccessToken accessToken = wxMpService.oauth2getAccessToken(code);
            WxMpUser wxMpUser = wxMpService.oauth2getUserInfo(accessToken, null);
            user = userRepo.findByOpenIdAndDelFalse(wxMpUser.getOpenId()).orElse(null);
            if (user == null) {
                String name = projectService.getUserPrefix() + 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();
                userRepo.save(user);
            }
            return user;
        }catch (WxErrorException e){
            loginSuccess = false;
            throw e;
        }finally {
            loginLogService.pushLoginLog(loginSuccess, LoginType.SMS, user ==null ? null:user.getPhone(), user == null ? null : user.getId());
        }

    }

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

    public User loginMa(String code) {
        User user = null;
        boolean loginSuccess = true;
        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 = projectService.getUserPrefix() + RandomStringUtils.randomAlphabetic(8);
            userInfo = User.builder()
                    .username(name)
                    .nickname(name)
                    .openId(openId)
                    .avatar(sysConfigService.getString(SysConstants.DEFAULT_AVATAR))
                    .authorities(Collections.singleton(Authority.get(AuthorityName.ROLE_USER)))
                    .authStatus(AuthStatus.NOT_AUTH)
                    .build();
            userInfo = userRepo.save(userInfo);
            user =  userInfo;
            return user;
        } catch (WxErrorException e) {
            e.printStackTrace();
            throw new BusinessException("登录失败");
        }finally{
            loginLogService.pushLoginLog(loginSuccess, LoginType.MA, user == null ? null : user.getPhone(), user == null ? null : user.getId());
        }
    }

    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 = sysConfigService.getString(SysConstants.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.get(AuthorityName.ROLE_USER)))
                    .build();
            user = userRepo.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 = userRepo.save(user);
        }

        return user;
    }

    public String setPassword(Long userId, String password) {
        User user = userRepo.findById(userId).orElseThrow(new BusinessException("用户不存在"));
        user.setPassword(new BCryptPasswordEncoder().encode(password));
        user = userRepo.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);
        userRepo.save(user);
    }


    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())));
            }
            //查询绑卡的数量
            Integer bindCardCount = userBankCardRepo.countByUserId(user.getId());
            dto.setBindCardCount(bindCardCount);
            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(new BCryptPasswordEncoder().encode(tradeCode));
        userRepo.save(user);
    }

    @CacheEvict(value = "user", allEntries = true)
    public void setTradeCode(Long userId, String phone, String code, String tradeCode) {
        smsService.verify(phone,code);
        User user = userRepo.findById(userId).orElseThrow(new BusinessException("用户不存在"));
        user.setTradeCode(new BCryptPasswordEncoder().encode(tradeCode));
        userRepo.save(user);
    }

    public void verifyTradeCode(Long userId, String tradeCode) {
        User user = userRepo.findById(userId).orElseThrow(new BusinessException("用户不存在"));
        if (!new BCryptPasswordEncoder().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("\\s+", ",")
                        .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 Map<String, Object> searchByIdAdmin(String ids) {
        List<Long> userIds = Arrays.stream(ids.replaceAll("\\s+", ",")
                .split(","))
                .map((item) -> {
                    return Long.valueOf(item.trim());
                }).collect(Collectors.toList());
        List<User> users = userRepo.findByIdInAndDelFalse(userIds);
        Map<String, Object> map = new HashMap<>();
        map.put("users", users);
        List<Long> notFound = userIds.stream().filter(p -> users.stream().noneMatch(u -> p.equals(u.getId())))
                .collect(Collectors.toList());
        map.put("notFound", notFound);
        return map;
    }


    public void removeAuth(Long userId) {
        User user = userRepo.findById(userId).orElseThrow(new BusinessException("用户不存在"));
        if (user.getAuthStatus() == AuthStatus.SUCCESS) {
            user.setAuthStatus(AuthStatus.NOT_AUTH);
            userRepo.save(user);
            List<IdentityAuth> identityAuths = identityAuthRepo.findByUserIdAndDelFalse(userId);
            identityAuthRepo.deleteAll(identityAuths);
            String ipAddr = IPUtils.getIpAddr();
            User currentUser = SecurityUtils.getAuthenticatedUser();

            RealNameLog realNameLog = RealNameLog.builder().operatorId(currentUser.getId())
                    .operatorName(currentUser.getUsername())
                    .operatorIp(ipAddr).changeUserId(user.getId()).changeUserName(identityAuths.stream().map(IdentityAuth::getRealName).filter(StringUtils::isNotBlank)
                    .findFirst().orElse("")).operateType("解除实名")
                    .idNo(identityAuths.stream().filter(p -> p.getIdNo() != null).findFirst().get().getIdNo()).build();
            realNameLogService.insert(realNameLog);
        }
    }

    public void switchAccount(String appId) {
        userRepo.findBySettleAccountIdIsNotNull().parallelStream().forEach(user -> {
            try {
                IdentityAuth identityAuth = identityAuthRepo.findFirstByUserIdAndStatusAndDelFalseOrderByCreatedAtDesc(user.getId(), AuthStatus.SUCCESS)
                        .orElseThrow(new BusinessException("用户未通过实名认证"));
                UserBankCard userBankCard = userBankCardRepo.findByUserId(user.getId()).stream().findAny()
                        .orElseThrow(new BusinessException("未绑卡"));
                createMember(appId, user.getId().toString(), Optional.ofNullable(userBankCard.getPhone())
                        .orElse(user.getPhone()), identityAuth.getRealName(), identityAuth.getIdNo());
                createSettleAccount(appId, 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);
                userRepo.save(user);
                userBankCardRepo.deleteByUserIdAndPayPlatform(user.getId(), UniformPayConstants.ADAPAY_PLATFORM);
            }
        });
    }

    public void createMember(String appId, String memberId, String tel, String realName, String idno) throws BaseAdaPayException {
        Map<String, Object> memberParams = new HashMap<>();
        memberParams.put("adapay_func_code", "members.realname");
        memberParams.put("member_id", memberId);
        memberParams.put("app_id", appId);
        memberParams.put("tel_no", tel);
        memberParams.put("user_name", realName);
        memberParams.put("cert_type", "00");
        memberParams.put("cert_id", idno);
        Map<String, Object> res = AdapayCommon.requestAdapay(memberParams);
        log.info("createMember\n{}", JSON.toJSONString(res, SerializerFeature.PrettyFormat));
        if (!("succeeded".equals(MapUtils.getString(res, "status"))
                || "member_id_exists".equals(MapUtils.getString(res, "error_code")))) {
            String errMsg = MapUtils.getString(res, "error_msg");
            String errCode = MapUtils.getString(res, "error_code");
            throw new BusinessException(errMsg + "(" + errCode + ")");
        }
    }

    public String createSettleAccount(String appId, String memberId, String realName, String idNo, String phone, String bankNo) throws BaseAdaPayException {
        Map<String, Object> settleCountParams = new HashMap<>();
        Map<String, Object> accountInfo = new HashMap<>();
        accountInfo.put("card_id", bankNo);
        accountInfo.put("card_name", realName);
        accountInfo.put("cert_id", idNo);
        accountInfo.put("cert_type", "00");
        accountInfo.put("tel_no", phone);
        accountInfo.put("bank_acct_type", "2");
        settleCountParams.put("member_id", memberId);
        settleCountParams.put("app_id", appId);
        settleCountParams.put("channel", "bank_account");
        settleCountParams.put("account_info", accountInfo);
        Map<String, Object> res = SettleAccount.create(settleCountParams);
        log.info("createSettleAccount\n{}", JSON.toJSONString(res, SerializerFeature.PrettyFormat));
        if (!("succeeded".equals(MapUtils.getString(res, "status"))
                || "account_exists".equals(MapUtils.getString(res, "error_code")))) {
            String errMsg = MapUtils.getString(res, "error_msg");
            String errCode = MapUtils.getString(res, "error_code");
            throw new BusinessException(errMsg + "(" + errCode + ")");
        }
        return MapUtils.getString(res, "id");
    }

    @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) {
                log.error("绑卡失败，用户ID:{} , 账户ID：{}， 原因: {}", user.getId(), user.getSettleAccountId(), e.getMessage());
                user.setSettleAccountId(null);
                userRepo.save(user);
                userBankCardRepo.deleteByUserIdAndPayPlatform(user.getId(), UniformPayConstants.ADAPAY_PLATFORM);
            }
            count.getAndIncrement();
            log.info("checkSettleAccount {}/{}", count.get(), list.size());
        });
    }



    /**
     * 获取昨天注册数
     * @return 昨天注册数
     */
    public Integer lastDayRegisterNum(){
        return userRepo.lastDayRegisterNum();
    }

    /**
     * 是否开通钱包
     */
    public boolean whetherCreatewallet(Long userId){
        UserFundAccount lianlianAccount = userFundAccountForLianlianpayService.getAccount(userId);
        return lianlianAccount != null && lianlianAccount.getAccountStatus() == AccountStatus.NORMAL;
    }

    /**
     * 更新用户appClientId
     * @param userId
     * @param appClientId
     */
    @Transactional
    public void updateAppClientId(Long userId, String appClientId){
        userRepo.updateAppClientId(userId, appClientId);
    }


}
