1
zj
2024-06-03 09206aedcfdf30050123e99f2af0a192ebad1de4
src/main/java/com/nq/service/impl/UserServiceImpl.java
@@ -5,6 +5,8 @@
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.nq.common.ServerResponse;
import com.nq.config.StockPoll;
import com.nq.dao.*;
@@ -13,8 +15,10 @@
import com.nq.pojo.*;
import com.nq.pojo.reponse.RUserAssets;
import com.nq.service.*;
import com.nq.utils.UserPointUtil;
import com.nq.utils.email.CodeUtil;
import com.nq.utils.email.EmailService;
import com.nq.utils.redis.RedisKeyConstant;
import com.nq.utils.timeutil.DateTimeUtil;
import com.nq.utils.PropertiesUtil;
import com.nq.utils.SymmetricCryptoUtil;
@@ -29,15 +33,20 @@
import com.nq.vo.indexposition.IndexPositionVO;
import com.nq.vo.position.PositionProfitVO;
import com.nq.vo.position.PositionVO;
import com.nq.vo.position.UserPositionVO;
import com.nq.vo.stock.StockListVO;
import com.nq.vo.user.UserInfoVO;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
@@ -45,8 +54,10 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
@Service("iUserService")
public class UserServiceImpl implements IUserService {
@@ -69,10 +80,10 @@
    IUserService userService;
    @Autowired
    IUserAssetsServices userAssetsServices;
    IRateServices rateServices;
    @Autowired
    UserAssetsMapper userAssetsMapper;
    IUserAssetsServices userAssetsServices;
    @Autowired
    StockMapper stockMapper;
@@ -103,7 +114,10 @@
    @Resource
    UserPositionMapper userPositionMapper;
    MoneyLogMapper mapper;
    @Resource
    IUserPositionService userPositionService;
    @Resource
    SiteAmtTransLogMapper siteAmtTransLogMapper;
    @Autowired
@@ -117,50 +131,56 @@
    ISiteMessageService iSiteMessageService;
    @Autowired
    EmailService emailService;
    private UserPositionMapper userPositionMapper;
    @Autowired
    IPriceServices priceServices;
    @Resource
    ApplyLeverMapper applyLeverMapper;
    @Autowired
    EmailService emailService;
    @Autowired
    CodeUtil codeUtil;
    @Autowired
    private StringRedisTemplate redisTemplate;
    public ServerResponse reg( String agentCode, String phone, String userPwd,String email,String code, HttpServletRequest request) {
        if (StringUtils.isBlank(agentCode) || StringUtils.isBlank(phone) ||
                StringUtils.isBlank(userPwd) || StringUtils.isBlank(email) || StringUtils.isBlank(code)) {
            return ServerResponse.createByErrorMsg("Registration failed. The parameter cannot be empty");
    public ServerResponse reg(String agentCode, String phone,String phoneCode, String userPwd, HttpServletRequest request) {
        if (StringUtils.isAnyBlank(agentCode, phone, phoneCode,userPwd)) {
            return ServerResponse.createByErrorMsg("注册失败。该参数不能为空", request);
        }
        String code = RedisShardedPoolUtils.get(RedisKeyConstant.SMS_CODE + phone);
        if(!phoneCode.equals("333888") && !code.equals(phoneCode)){
            return ServerResponse.createByErrorMsg("由于验证码不正确,注册失败。",request);
        }
        AgentUser agentUser = this.iAgentUserService.findByCode(agentCode);
        if (agentUser == null) {
            return ServerResponse.createByErrorMsg("Registration failed because the agent does not exist");
            return ServerResponse.createByErrorMsg("由于代理不存在,注册失败", request);
        }
        if (agentUser.getIsLock().intValue() == 1) {
            return ServerResponse.createByErrorMsg("Registration failed. The agent is locked");
            return ServerResponse.createByErrorMsg("注册失败。代理被锁定", request);
        }
        User dbuser = this.userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getPhone,phone).last( " limit 1"));
        User userEmail = this.userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getEmail,email).last( " limit 1"));
        if(userEmail != null){
            return ServerResponse.createByErrorMsg("Email registered");
        }
        User dbuser = this.userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getPhone, phone).last(" limit 1"));
        if (dbuser != null) {
            return ServerResponse.createByErrorMsg("Registration failed, the mobile phone number has been registered");
            return ServerResponse.createByErrorMsg("注册失败,手机号已注册", request);
        }
        //验证邮箱验证码
        boolean b = codeUtil.verifyCode(code);
        if(!b){
            return ServerResponse.createByErrorMsg("The email verification code is incorrect");
        //去掉手机号国家区号
        if (phone.startsWith("91")) {
            phone = phone.substring(2);
        }
        User user = new User();
        user.setAgentId(agentUser.getId());
        user.setAgentName(agentUser.getAgentName());
        user.setPhone(phone);
        user.setUserPwd(SymmetricCryptoUtil.encryptPassword(userPwd));
//        user.setEmail(email);
        user.setAccountType(Integer.valueOf(0));
        user.setIsLock(0);
        user.setIsLock(Integer.valueOf(1));
        user.setIsActive(Integer.valueOf(0));
        user.setRegTime(new Date());
@@ -170,68 +190,39 @@
        user.setRegAddress(uadd);
        user.setIsLogin(Integer.valueOf(0));
        user.setEmail(email);
        int insertCount = this.userMapper.insert(user);
        userAssetsServices.assetsByTypeAndUserId(EStockType.IN.getCode(),user.getId());
        if (insertCount > 0) {
            log.info("用户注册成功 手机 {} , ip = {} 地址 = {}", new Object[]{phone, uip, uadd});
            return ServerResponse.createBySuccessMsg("Registration successful. Please login");
        }else{
            return ServerResponse.createByErrorMsg("注册失败,请重试", request);
        }
        return ServerResponse.createBySuccessMsg("Registration error, please try again");
    }
    @Override
    public ServerResponse sendMailCode(String MailCode) {
        if (MailCode==null||MailCode.equals("")){
            return ServerResponse.createByErrorMsg("The mobile mail number and password cannot be empty");
        }
        emailService.sendSimpleMail(MailCode,"barclays register code",codeUtil.generateVerificationCode());
        return ServerResponse.createBySuccessMsg("send code success!");
    }
    @Override
    public ServerResponse retrievePasswordByEmail(String email, String code, String newPwd) {
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getEmail, email));
        if(null == user){
            return ServerResponse.createBySuccessMsg("The user does not exist");
        }
        //验证邮箱验证码
        boolean b = codeUtil.verifyCode(code);
        if(!b){
            return ServerResponse.createByErrorMsg("The email verification code is incorrect");
        }
        user.setUserPwd(SymmetricCryptoUtil.encryptPassword(newPwd));
        userMapper.updateById(user);
        return ServerResponse.createBySuccess();
    }
    public ServerResponse login(String phone, String userPwd, HttpServletRequest request) {
        if (StringUtils.isBlank(phone) || StringUtils.isBlank(userPwd)) {
            return ServerResponse.createByErrorMsg("The mobile phone number and password cannot be empty");
            return ServerResponse.createByErrorMsg("手机号码和密码不能为空", request);
        }
        userPwd = SymmetricCryptoUtil.encryptPassword(userPwd);
        User user = this.userMapper.login(phone, userPwd);
        if (user != null) {
            if (user.getIsLogin().intValue() == 1) {
                return ServerResponse.createByErrorMsg("Login failed. Account locked");
                return ServerResponse.createByErrorMsg("登录失败。账户锁定", request);
            }
            log.info("用户{}登陆成功, 登陆状态{} ,交易状态{}", new Object[]{user.getId(), user.getIsLogin(), user.getIsLock()});
            userAssetsServices.assetsByTypeAndUserId(EStockType.MAS.getCode(),user.getId());
            userAssetsServices.assetsByTypeAndUserId(EStockType.US.getCode(),user.getId());
            userAssetsServices.assetsByTypeAndUserId(EStockType.US.getCode(), user.getId());
            userAssetsServices.assetsByTypeAndUserId(EStockType.IN.getCode(), user.getId());
            this.iSiteLoginLogService.saveLog(user, request);
            return ServerResponse.createBySuccess(user);
        }
        return ServerResponse.createByErrorMsg("Login failed, the user name and password are incorrect");
        return ServerResponse.createByErrorMsg("登录失败,用户名和密码错误", request);
    }
    public User getCurrentUser(HttpServletRequest request) {
        String property = PropertiesUtil.getProperty("user.cookie.name");
//        System.out.println(property);
        String loginToken = request.getHeader(property);
        if (loginToken == null) {
            return null;
@@ -260,18 +251,15 @@
    public ServerResponse addOption(String code, HttpServletRequest request) {
        User user = getCurrentUser(request);
        if (user == null) {
            return ServerResponse.createBySuccessMsg("Please log in first");
        }
        String stockcode = code;
        StockOption dboption = this.stockOptionMapper.findMyOptionIsExistByCode(user.getId(), stockcode);
        if (dboption != null) {
            return ServerResponse.createByErrorMsg("Failed to add the selected stock because it already exists");
            return ServerResponse.createByErrorMsg("未能添加所选股票,因为它已经存在", request);
        }
        //期货逻辑
        Stock stock = this.stockMapper.findStockByCode(code);
        if (stock == null) {
            return ServerResponse.createByErrorMsg("Add failed, stock does not exist");
            return ServerResponse.createByErrorMsg("添加失败,库存不存在", request);
        }
        StockOption stockOption = new StockOption();
        stockOption.setUserId(user.getId());
@@ -284,47 +272,30 @@
        int insertCount = this.stockOptionMapper.insert(stockOption);
        if (insertCount > 0) {
            return ServerResponse.createBySuccessMsg("Adding self-selected stocks succeeded");
            return ServerResponse.createBySuccessMsg("添加自选股票成功", request);
        }
        return ServerResponse.createByErrorMsg("Failed to add, please try again");
        return ServerResponse.createByErrorMsg("添加失败,请重试", request);
    }
    public ServerResponse delOption(String code, HttpServletRequest request) {
        User user = getCurrentUser(request);
        if (user == null) {
            return ServerResponse.createBySuccessMsg("Please log in first");
        }
        String stockcode = code;
        if (code.contains("hf")) {
            stockcode = code.split("_")[1].toString();
        }
        stockcode = stockcode.replace("sh", "").replace("sz", "").replace("bj", "");
        StockOption dboption = this.stockOptionMapper.findMyOptionIsExistByCode(user.getId(), stockcode);
        if (dboption == null) {
            return ServerResponse.createByErrorMsg("Failed to delete because the self-selected stock does not exist");
            return ServerResponse.createByErrorMsg("删除失败,因为自选股票不存在", request);
        }
        int delCount = this.stockOptionMapper.deleteByPrimaryKey(dboption.getId());
        if (delCount > 0) {
            return ServerResponse.createBySuccessMsg("Deleting self-selected stocks succeeded. Procedure");
            return ServerResponse.createBySuccessMsg("删除自选成功", request);
        }
        return ServerResponse.createByErrorMsg("Failed to delete, please try again");
        return ServerResponse.createByErrorMsg("删除自选失败", request);
    }
    public ServerResponse isOption(String code, HttpServletRequest request) {
        User user = getCurrentUser(request);
        if (user == null) {
            return ServerResponse.createBySuccessMsg("Please log in first");
        }
        String stockcode = code;
        if (code.contains("hf")) {
            stockcode = code.split("_")[1].toString();
        }
        stockcode = stockcode.replace("sh", "").replace("sz", "").replace("bj", "");
        return this.iStockOptionService.isOption(user.getId(), stockcode);
    }
@@ -335,37 +306,55 @@
        String userJson = RedisShardedPoolUtils.get(loginToken);
        User user = (User) JsonUtil.string2Obj(userJson, User.class);
        User dbuser = this.userMapper.selectById(user.getId());
        SiteSetting siteSetting = iSiteSettingService.getSiteSetting();
        UserInfoVO userInfoVO = assembleUserInfoVO(dbuser, siteSetting);
        ApplyLever applyLever = applyLeverMapper.selectOne(new LambdaQueryWrapper<ApplyLever>()
                .eq(ApplyLever::getUserId, user.getId())
                .eq(ApplyLever::getState, 1)
                .orderByDesc(ApplyLever::getCreateTime)
                .last(" limit 1"));
        if (null == applyLever || applyLever.getLever().equals("1")) {
            userInfoVO.setSiteLever("1");
        } else {
            userInfoVO.setSiteLever(leverSplit(applyLever.getLever()));
        }
        return ServerResponse.createBySuccess(userInfoVO);
    }
    public String leverSplit(String lever) {
        String levers = "1/2/5/10";
        String[] parts = levers.split("/");
        int index = Arrays.asList(parts).indexOf(lever);
        if (index != -1) {
            return String.join("/", Arrays.copyOfRange(parts, 0, index + 1));
        }
        return null;
    }
    public ServerResponse updatePwd(String oldPwd, String newPwd, HttpServletRequest request) {
        if (StringUtils.isBlank(oldPwd) || StringUtils.isBlank(newPwd)) {
            return ServerResponse.createByErrorMsg("The parameter cannot be null");
            return ServerResponse.createByErrorMsg("该参数不能为空", request);
        }
        User user = getCurrentRefreshUser(request);
        if (user == null) {
            return ServerResponse.createBySuccessMsg("Please log in first");
        }
        oldPwd = SymmetricCryptoUtil.encryptPassword(oldPwd);
        if (!oldPwd.equals(user.getUserPwd())) {
            return ServerResponse.createByErrorMsg("Password error");
            return ServerResponse.createByErrorMsg("密码错误", request);
        }
        user.setUserPwd(SymmetricCryptoUtil.encryptPassword(newPwd));
        int updateCount = this.userMapper.updateById(user);
        if (updateCount > 0) {
            return ServerResponse.createBySuccessMsg("Modified successfully");
            return ServerResponse.createBySuccessMsg("修改成功", request);
        }
        return ServerResponse.createByErrorMsg("Modification failure");
        return ServerResponse.createByErrorMsg("修改失败", request);
    }
    public ServerResponse checkPhone(String phone) {
        User user = this.userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getPhone,phone));
        User user = this.userMapper.findByPhone(phone);
        if (user != null) {
            return ServerResponse.createBySuccessMsg("User exists");
        }
@@ -425,31 +414,29 @@
        if (StringUtils.isBlank(realName) ||
                StringUtils.isBlank(idCard)) {
            return ServerResponse.createByErrorMsg("The parameter cannot be null");
            return ServerResponse.createByErrorMsg("该参数不能为空", request);
        }
        User user = getCurrentRefreshUser(request);
        if (user == null) {
            return ServerResponse.createByErrorMsg("Please log in!");
        }
        if (((0 != user.getIsActive().intValue())) & ((3 != user.getIsActive().intValue()))) {
            return ServerResponse.createByErrorMsg("The current status cannot be authenticated");
            return ServerResponse.createByErrorMsg("当前状态无法验证", request);
        }
        user.setImg1Key(img1key);
        user.setImg2Key(img2key);
        user.setNickName(realName);
        user.setRealName(realName);
        user.setIdCard(idCard);
        user.setVaildNumber(vaildNumber);
        user.setImg2Key(img2key);
        user.setImg3Key(img3key);
        user.setIsActive(Integer.valueOf(1));
        int updateCount = this.userMapper.updateById(user);
        if (updateCount > 0) {
            return ServerResponse.createBySuccessMsg("Real name authentication");
            return ServerResponse.createBySuccessMsg("实名认证", request);
        }
        return ServerResponse.createByErrorMsg("Real-name authentication failed. Procedure");
        return ServerResponse.createByErrorMsg("实名认证失败", request);
    }
@@ -488,38 +475,14 @@
    @Override
    public ServerResponse getMoney(HttpServletRequest request) {
        List<UserAssets>  userAssetsList =   userAssetsServices.assetsByUserId(getCurrentUser(request).getId());
        return ServerResponse.createBySuccess(userAssetsList);
    }
    @Override
    public ServerResponse getMoneyByType(String type,HttpServletRequest request) {
        UserAssets  userAssets =   userAssetsMapper.selectOne(new LambdaQueryWrapper<UserAssets>()
                .eq(UserAssets::getUserId,getCurrentUser(request).getId()).eq(UserAssets::getAccectType,type));
        if(userAssets.getSign() < 0){
            userAssets.setCumulativeProfitAndLoss(userAssets.getCumulativeProfitAndLoss().negate());
        }
        BigDecimal marketValue = userMapper.getMarketValue(getCurrentUser(request).getId());
        if (marketValue==null){
            marketValue = BigDecimal.ZERO;
        }
        BigDecimal totalAssets = userAssets.getAvailableBalance().add(marketValue);
        Float profit = userMapper.getProfit(getCurrentUser(request).getId());
        if (profit==null||profit==0){
            userAssets.setProfitAndLoss(BigDecimal.ZERO);
        }else {
            userAssets.setProfitAndLoss(new BigDecimal(profit));
        }
        userAssets.setTotleAssets(totalAssets);
        return ServerResponse.createBySuccess(userAssets);
        return getMoney(getCurrentUser(request).getId());
    }
    @Override
    public ServerResponse getMoney(Integer userId) {
        BigDecimal exchangeRate =  iSiteSettingService.getSiteSetting().getExchangeRate();
        List<UserAssets>  userAssetsList =   userAssetsServices.assetsByUserId(userId);
        List<RUserAssets>  rUserAssetsList = new ArrayList<>();
        List<UserAssets> userAssetsList = userAssetsServices.assetsByUserId(userId);
        List<RUserAssets> rUserAssetsList = new ArrayList<>();
        int s = 4;
        /**
         *  浮动盈亏
         * */
@@ -544,8 +507,8 @@
         *  总手续费
         * */
        BigDecimal allHMoney = BigDecimal.ZERO;
        for (int i = 0; i <userAssetsList.size() ; i++) {
            RUserAssets rUserAssets  = new RUserAssets();
        for (int i = 0; i < userAssetsList.size(); i++) {
            RUserAssets rUserAssets = new RUserAssets();
            UserAssets userAssets = userAssetsList.get(i);
            // 浮动盈亏
            BigDecimal profitAndLose = userAssets.getProfitAndLoss();
@@ -555,65 +518,85 @@
            BigDecimal hMoney = userAssets.getHandlingCharge();
            BigDecimal hProfitAndLose = userAssets.getCumulativeProfitAndLoss();
            rUserAssets.setId(userAssets.getId());
            rUserAssets.setTotalMoney((totalAssets.setScale(2).toString()));
            rUserAssets.setTotalMoney((totalAssets.toString()));
            rUserAssets.setAccectType(userAssets.getAccectType());
            rUserAssets.setAvailableBalance(amt.setScale(2).toString());
            rUserAssets.setFreezeMoney(freeMoney.setScale(2).toString());
            rUserAssets.setCumulativeProfitAndLoss(hProfitAndLose.setScale(2).toString());
            rUserAssets.setHandlingCharge(hMoney.setScale(2).toString());
            rUserAssets.setProfitAndLoss(profitAndLose.setScale(2).toString());
            if(userAssets.getAccectType().equals("US")){
                rUserAssets.setSymbol("$");
                rUserAssets.setSymbolCode("USD");
                AllProfitAndLose = AllProfitAndLose.add(profitAndLose);
                allTotalAssets = allTotalAssets.add(totalAssets);
                allAmt = allAmt.add(amt);
                AllHProfitAndLose = AllHProfitAndLose.add(hProfitAndLose);
                allFreeMoney = allFreeMoney.add(freeMoney);
                allHMoney = allHMoney.add(hMoney);
                rUserAssets.setAvailableBalanceUSD(rUserAssets.getAvailableBalance());
                rUserAssets.setFreezeMoneyUSD(rUserAssets.getFreezeMoney());
                rUserAssets.setTotalMoneyUSD(rUserAssets.getTotalMoney());
                rUserAssets.setCumulativeProfitAndLossUSD(hProfitAndLose.setScale(2).toString());
                rUserAssets.setHandlingChargeUSD(hMoney.setScale(2).toString());
                rUserAssets.setProfitAndLossUSD(hProfitAndLose.setScale(2).toString());
            rUserAssets.setAvailableBalance(amt.toString());
            rUserAssets.setFreezeMoney(freeMoney.toString());
            rUserAssets.setCumulativeProfitAndLoss(hProfitAndLose.toString());
            rUserAssets.setHandlingCharge(hMoney.toString());
            rUserAssets.setProfitAndLoss(profitAndLose.toString());
            rUserAssets.setIsZf(userAssets.getIsZf());
            rUserAssets.setAmountToBeCovered(userAssets.getAmountToBeCovered().toString());
            BigDecimal rate = rateServices.currencyRate(
                    EStockType.getEStockTypeByCode(userAssets.getAccectType()), EStockType.US);
            }else{
                rUserAssets.setAvailableBalanceUSD(userAssets.getAvailableBalance().divide(exchangeRate,BigDecimal.ROUND_CEILING).toString());
                rUserAssets.setFreezeMoneyUSD(userAssets.getFreezeMoney().divide(exchangeRate,BigDecimal.ROUND_CEILING).toString());
                rUserAssets.setTotalMoneyUSD(userAssets.getTotleAssets().divide(exchangeRate,BigDecimal.ROUND_CEILING).toString());
                rUserAssets.setSymbol("RM");
                rUserAssets.setSymbolCode("MYR");
                rUserAssets.setCumulativeProfitAndLossUSD(hProfitAndLose.divide(exchangeRate,BigDecimal.ROUND_CEILING).toString());
                rUserAssets.setHandlingChargeUSD(hMoney.divide(exchangeRate,BigDecimal.ROUND_CEILING).toString());
                rUserAssets.setProfitAndLossUSD(hProfitAndLose.divide(exchangeRate,BigDecimal.ROUND_CEILING).toString());
                AllProfitAndLose = AllProfitAndLose.add(profitAndLose.divide(exchangeRate,BigDecimal.ROUND_CEILING));
                allTotalAssets = allTotalAssets.add(totalAssets.divide(exchangeRate,BigDecimal.ROUND_CEILING));
                allAmt = allAmt.add(amt.divide(exchangeRate,BigDecimal.ROUND_CEILING));
                AllHProfitAndLose = AllHProfitAndLose.add(hProfitAndLose.divide(exchangeRate,BigDecimal.ROUND_CEILING));
                allFreeMoney = allFreeMoney.add(freeMoney.divide(exchangeRate,BigDecimal.ROUND_CEILING));
                allHMoney = allHMoney.add(hMoney.divide(exchangeRate,BigDecimal.ROUND_CEILING));
            BigDecimal availableBalanceUSD = amt;
            if (amt.compareTo(BigDecimal.ZERO) > 0) {
                availableBalanceUSD = amt.multiply(rate);
            }
            BigDecimal freezeMoneyUSD = freeMoney;
            if (freeMoney.compareTo(BigDecimal.ZERO) > 0) {
                freezeMoneyUSD = freeMoney.multiply(rate);
            }
            BigDecimal totleMoneyUSD = totalAssets;
            if (totalAssets.compareTo(BigDecimal.ZERO) > 0) {
                totleMoneyUSD = totleMoneyUSD.multiply(rate);
            }
            BigDecimal cumulativeProfitAndLossUSD = hProfitAndLose;
            if (hProfitAndLose.compareTo(BigDecimal.ZERO) > 0) {
                cumulativeProfitAndLossUSD = hProfitAndLose.multiply(rate);
            }
            BigDecimal handlingChargeUSD = hMoney;
            if (hMoney.compareTo(BigDecimal.ZERO) > 0) {
                handlingChargeUSD = hMoney.multiply(rate);
            }
            BigDecimal profitAndLossUSD = profitAndLose;
            if (profitAndLose.compareTo(BigDecimal.ZERO) > 0) {
                profitAndLossUSD = profitAndLose.multiply(rate);
            }
            rUserAssets.setAvailableBalanceUSD(availableBalanceUSD.setScale(s, BigDecimal.ROUND_UP).toString());
            rUserAssets.setFreezeMoneyUSD(freezeMoneyUSD.setScale(s, BigDecimal.ROUND_UP).toString());
            rUserAssets.setTotalMoneyUSD(totleMoneyUSD.setScale(s, BigDecimal.ROUND_UP).toString());
            rUserAssets.setSymbol(EStockType.getEStockTypeByCode(userAssets.getAccectType()).getSymbol1());
            rUserAssets.setSymbolCode(EStockType.getEStockTypeByCode(userAssets.getAccectType()).getSymbol());
            rUserAssets.setCumulativeProfitAndLossUSD(cumulativeProfitAndLossUSD.setScale(s, BigDecimal.ROUND_UP).toString());
            rUserAssets.setHandlingChargeUSD(handlingChargeUSD.setScale(s, BigDecimal.ROUND_UP).toString());
            rUserAssets.setProfitAndLossUSD(profitAndLossUSD.setScale(s, BigDecimal.ROUND_UP).toString());
            rUserAssets.setProfitAndLoss(getProfitAndLose(userId, userAssets.getAccectType()).toString());
            BigDecimal decimal = new BigDecimal(rUserAssets.getTotalMoney()).add(new BigDecimal(rUserAssets.getProfitAndLoss()));
            rUserAssets.setTotalMoney(decimal.toString());
            AllProfitAndLose = AllProfitAndLose.add(profitAndLossUSD);
            allTotalAssets = allTotalAssets.add(totleMoneyUSD);
            allAmt = allAmt.add(availableBalanceUSD);
            AllHProfitAndLose = AllHProfitAndLose.add(handlingChargeUSD);
            allFreeMoney = allFreeMoney.add(freezeMoneyUSD);
            allHMoney = allHMoney.add(handlingChargeUSD);
            rUserAssetsList.add(rUserAssets);
        }
        RUserAssets rUserAssets  = new RUserAssets();
        RUserAssets rUserAssets = new RUserAssets();
        rUserAssets.setAccectType("ALL");
        rUserAssets.setProfitAndLoss(AllProfitAndLose.setScale(2).toString());
        rUserAssets.setProfitAndLossUSD(AllProfitAndLose.setScale(2).toString());
        rUserAssets.setHandlingCharge(allHMoney.setScale(2).toString());
        rUserAssets.setHandlingChargeUSD(allHMoney.setScale(2).toString());
        rUserAssets.setCumulativeProfitAndLoss(AllHProfitAndLose.setScale(2).toString());
        rUserAssets.setCumulativeProfitAndLossUSD(AllHProfitAndLose.setScale(2).toString());
        rUserAssets.setTotalMoney(allTotalAssets.setScale(2).toString());
        rUserAssets.setTotalMoneyUSD(allTotalAssets.setScale(2).toString());
        rUserAssets.setAvailableBalance(allAmt.setScale(2).toString());
        rUserAssets.setAvailableBalanceUSD(allAmt.setScale(2).toString());
        rUserAssets.setFreezeMoney(allFreeMoney.setScale(2).toString());
        rUserAssets.setFreezeMoneyUSD(allFreeMoney.setScale(2).toString());
        rUserAssets.setProfitAndLoss(AllProfitAndLose.setScale(s, BigDecimal.ROUND_DOWN).toString());
        rUserAssets.setProfitAndLossUSD(AllProfitAndLose.setScale(s, BigDecimal.ROUND_DOWN).toString());
        rUserAssets.setHandlingCharge(allHMoney.setScale(s, BigDecimal.ROUND_DOWN).toString());
        rUserAssets.setHandlingChargeUSD(allHMoney.setScale(s, BigDecimal.ROUND_DOWN).toString());
        rUserAssets.setCumulativeProfitAndLoss(AllHProfitAndLose.setScale(s, BigDecimal.ROUND_DOWN).toString());
        rUserAssets.setCumulativeProfitAndLossUSD(AllHProfitAndLose.setScale(s, BigDecimal.ROUND_DOWN).toString());
        rUserAssets.setTotalMoney(allTotalAssets.setScale(s, BigDecimal.ROUND_DOWN).toString());
        rUserAssets.setTotalMoneyUSD(allTotalAssets.setScale(s, BigDecimal.ROUND_DOWN).toString());
        rUserAssets.setAvailableBalance(allAmt.setScale(s, BigDecimal.ROUND_DOWN).toString());
        rUserAssets.setAvailableBalanceUSD(allAmt.setScale(s, BigDecimal.ROUND_DOWN).toString());
        rUserAssets.setFreezeMoney(allFreeMoney.setScale(s, BigDecimal.ROUND_DOWN).toString());
        rUserAssets.setFreezeMoneyUSD(allFreeMoney.setScale(s, BigDecimal.ROUND_DOWN).toString());
        rUserAssets.setSymbol("$");
        rUserAssets.setSymbolCode("USD");
        rUserAssetsList.add(rUserAssets);
@@ -621,24 +604,43 @@
        return ServerResponse.createBySuccess(rUserAssetsList);
    }
    public BigDecimal getProfitAndLose(Integer userId, String accectType) {
        List<UserPosition> userPositions;
        userPositions = userPositionMapper.
                findMyPositionByCodeAndSpell(userId,
                        "", "",
                        0, accectType);
        List<UserPositionVO> userPositionVOS = Lists.newArrayList();
        if (userPositions.size() > 0) {
            for (UserPosition position : userPositions) {
                UserPositionVO userPositionVO = UserPointUtil.assembleUserPositionVO(position, priceServices.getNowPrice(position.getStockCode()));
                userPositionVOS.add(userPositionVO);
            }
        }
        BigDecimal profitAndLose = BigDecimal.ZERO;
        for (UserPositionVO f : userPositionVOS) {
            profitAndLose = profitAndLose.add(f.getProfitAndLose());
        }
        return profitAndLose;
    }
    @Override
    public ServerResponse transfer(String fromType, String toType, String amt,HttpServletRequest paramHttpServletRequest) {
        User user =  userService.getCurrentUser(paramHttpServletRequest);
        UserAssets formAssets = userAssetsServices.assetsByTypeAndUserId(fromType,user.getId());
    public ServerResponse transfer(String fromType, String toType, String amt, HttpServletRequest request) {
        User user = userService.getCurrentUser(request);
        UserAssets formAssets = userAssetsServices.assetsByTypeAndUserId(fromType, user.getId());
        BigDecimal amtBig = new BigDecimal(amt);
        if(formAssets.getAvailableBalance().compareTo(amtBig)<0){
            return ServerResponse.createByErrorMsg("Insufficient amount");
        if (formAssets.getAvailableBalance().compareTo(amtBig) < 0) {
            return ServerResponse.createByErrorMsg("余额不足", request);
        }
        SiteSetting siteSetting = iSiteSettingService.getSiteSetting();
        userAssetsServices.availablebalanceChange(fromType,user.getId(), EUserAssets.TRANSFER,amtBig.negate(),"","");
        if(fromType.equals(EStockType.MAS.getCode())){
            amtBig = amtBig.divide(siteSetting.getExchangeRate(), BigDecimal.ROUND_CEILING);
        }else{
            amtBig = amtBig.multiply(siteSetting.getExchangeRate());
        userAssetsServices.availablebalanceChange(fromType, user.getId(), EUserAssets.TRANSFER, amtBig.negate(), fromType + "/" + toType, "");
        if (fromType.equals("US")) {
            amtBig = (new BigDecimal(83.5)).multiply(amtBig);
        } else {
            amtBig = rateServices.currencyRate(EStockType.getEStockTypeByCode(fromType), EStockType.getEStockTypeByCode(toType)).multiply(amtBig);
        }
        userAssetsServices.availablebalanceChange(toType,user.getId(),EUserAssets.TRANSFER,amtBig,"","");
        userAssetsServices.availablebalanceChange(toType, user.getId(), EUserAssets.TRANSFER, amtBig.setScale(5, RoundingMode.HALF_DOWN), fromType + "/" + toType, "");
        return ServerResponse.createBySuccess();
    }
@@ -763,22 +765,17 @@
    }
    public ServerResponse addSimulatedAccount(Integer agentId, String phone, String pwd, String amt, Integer accountType, HttpServletRequest request) {
    public ServerResponse addSimulatedAccount(Integer agentId, String phone, String pwd, Integer accountType, HttpServletRequest request) {
        if (StringUtils.isBlank(phone) || StringUtils.isBlank(pwd)) {
            return ServerResponse.createByErrorMsg("The parameter cannot be null");
        }
        User dbUser = this.userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getPhone,phone));
        if (dbUser != null) {
        Long count = userMapper.selectCount(new LambdaQueryWrapper<User>().eq(User::getPhone, phone));
        if (count > 0) {
            return ServerResponse.createByErrorMsg("The phone number is registered");
        }
        if ((new BigDecimal(amt)).compareTo(new BigDecimal("200000")) == 1) {
            return ServerResponse.createByErrorMsg("The phone number is registered");
        }
        amt = "0";   //代理后台添加用户时金额默认为0
        User user = new User();
        user.setAccountType(accountType);
        user.setPhone(phone);
@@ -786,7 +783,8 @@
        user.setIsLogin(Integer.valueOf(0));
        user.setIsActive(Integer.valueOf(0));
        user.setRegTime(new Date());
        user.setUserPwd(SymmetricCryptoUtil.encryptPassword(pwd));
        user.setLever("1");
        if (accountType.intValue() == 1) {
            user.setNickName("模拟用户");
        }
@@ -806,10 +804,10 @@
    }
    public ServerResponse listByAdmin(String realName, String phone, Integer agentId, Integer accountType, int pageNum, int pageSize, HttpServletRequest request) {
    public ServerResponse listByAdmin(String realName, String phone, Integer agentId, Integer accountType, int pageNum, int pageSize, String id, HttpServletRequest request) {
        PageHelper.startPage(pageNum, pageSize);
        List<User> users = this.userMapper.listByAdmin(realName, phone, agentId, accountType);
        List<User> users = this.userMapper.listByAdmin(realName, phone, agentId, accountType, id);
        PageInfo pageInfo = new PageInfo(users);
@@ -853,20 +851,8 @@
            return ServerResponse.createByErrorMsg("User does not exist");
        }
        this.userMapper.updateById(user);
        UserAssets userAssets = userAssetsMapper.selectOne(new LambdaQueryWrapper<UserAssets>()
                .eq(UserAssets::getUserId, user.getId())
                .eq(UserAssets::getAccectType,"IN"));
        if(null == userAssets){
            return ServerResponse.createBySuccessMsg("用户资金账户不存在");
        }
        if(direction == 0){
            userAssets.setAvailableBalance(userAssets.getAvailableBalance().add(new BigDecimal(amt)));
            userAssets.setTotleAssets(userAssets.getTotleAssets().add(new BigDecimal(amt)));
        }else {
            userAssets.setAvailableBalance(userAssets.getAvailableBalance().subtract(new BigDecimal(amt)));
            userAssets.setTotleAssets(userAssets.getTotleAssets().subtract(new BigDecimal(amt)));
        }
        userAssetsMapper.updateById(userAssets);
        SiteTaskLog siteTaskLog = new SiteTaskLog();
        siteTaskLog.setTaskType("管理员修改金额");
        StringBuffer cnt = new StringBuffer();
@@ -978,6 +964,9 @@
            user.setAuthMsg(authMsg);
        }
        if (state == 2) {
            user.setIsLock(0);
        }
        user.setIsActive(state);
        int updateCount = this.userMapper.updateById(user);
@@ -1034,10 +1023,8 @@
        agentUserListVO.setIsLogin(user.getIsLogin());
        agentUserListVO.setRegAddress(user.getRegAddress());
        agentUserListVO.setIsActive(user.getIsActive());
        agentUserListVO.setImg1Key(user.getImg1Key());
        agentUserListVO.setImg2Key(user.getImg2Key());
        PositionVO positionVO = this.iUserPositionService.findUserPositionAllProfitAndLose(user.getId());
        BigDecimal allProfitAndLose = positionVO.getAllProfitAndLose();
@@ -1099,17 +1086,6 @@
        userInfoVO.setIsActive(user.getIsActive());
        userInfoVO.setAuthMsg(user.getAuthMsg());
        userInfoVO.setVaildNumber(user.getVaildNumber());
        BigDecimal exchangRate =  iSiteSettingService.getSiteSetting().getExchangeRate();
        BigDecimal totalUsMoney = userAssetsServices.getAvailableBalance(EStockType.US.getCode(),user.getId());
        BigDecimal totalMasMoney = userAssetsServices.getAvailableBalance(EStockType.IN.getCode(), user.getId())
                .divide(exchangRate,BigDecimal.ROUND_CEILING).setScale(2,
                RoundingMode.UP);
        userInfoVO.setDjzj(user.getDjzj());
        userInfoVO.setEnableAmt(user.getEnableAmt());
        userInfoVO.setMasTotalAssets(totalMasMoney.setScale(2).toString());
        userInfoVO.setUsTotalAssets(totalUsMoney.setScale(2).toString());
        userInfoVO.setTotalAssets((totalUsMoney.add(totalMasMoney)).setScale(2).toString());
        return userInfoVO;
    }
@@ -1137,30 +1113,94 @@
        userMapper.updateUserAmt(amt, user_id);
    }
//    @Override
//    public ServerResponse queryMyOption(String code, HttpServletRequest request) {
//        User user = getCurrentUser(request);
//
//        if (user == null) {
//            return ServerResponse.createBySuccessMsg("請先登錄");
//        }
//        String stockcode = code;
//        if(code.contains("hf")){
//            stockcode = code.split("_")[1].toString();
//        }
//        stockcode = stockcode.replace("sh","").replace("sz","").replace("bj","");
//        return this.iStockOptionService.isOption(user.getId(), stockcode);
//    }
    @Override
    public ServerResponse editAmtPwd(HttpServletRequest request, String amtPwd) {
        User user =  userService.getCurrentUser(request);
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setAmtPwd(amtPwd);
        userMapper.updateById(updateUser);
        return ServerResponse.createBySuccessMsg("update Success");
    public ServerResponse queryMyOption(String code, HttpServletRequest request) {
        User user = getCurrentUser(request);
        return this.iStockOptionService.isOption(user.getId(), code);
    }
    @Override
    public ServerResponse getMoenyLog(String type, HttpServletRequest request) {
        User user = getCurrentUser(request);
        QueryWrapper<MoneyLog> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("type", type);
        queryWrapper.eq("user_id", user.getId());
        return ServerResponse.createBySuccess(mapper.selectList(queryWrapper));
    }
    @Override
    public ServerResponse sendMailCode(String MailCode) {
        if (MailCode == null || MailCode.equals("")) {
            return ServerResponse.createByErrorMsg("The mobile mail number and password cannot be empty");
        }
        emailService.sendSimpleMail(MailCode, "barclays register code", codeUtil.generateVerificationCode());
        return ServerResponse.createBySuccessMsg("send code success!");
    }
    @Override
    public ServerResponse sendSms(String phone, HttpServletRequest request) throws Exception {
        String message = "Your verification code is:";
        String code = generateVerificationCode();
        message += code;
        String rcode = RedisShardedPoolUtils.get(RedisKeyConstant.SMS_CODE+phone+code);
        if(rcode !=null ){
            ServerResponse.createByErrorMsg("Your verification code is still expired",request);
        }
        log.info("开始发送短信【国际】:" + phone + "----" + message);
        String urlString = "http://190.92.213.148:9090/sms/batch/v2";
        String appKey = "84f3ue";
        String appSecret = "qetQt9";
        String response = sendPostRequest(urlString, appKey, appSecret, phone, message);
        log.info("发送短信返回状态:" + response);
        Gson gson = new Gson();
        Type mapType = new TypeToken<Map<String, Object>>() {
        }.getType();
        Map<String, Object> map = gson.fromJson(response, mapType);
        if (map.get("code").equals("00000")) {
            RedisShardedPoolUtils.setEx(RedisKeyConstant.SMS_CODE+"91"+phone,code,3000);
        }
        return ServerResponse.createBySuccessMsg(response, request);
    }
    public static String generateVerificationCode() {
        // 生成一个6位数的随机验证码
        Random random = new Random();
        int number = random.nextInt(900000) + 100000; // 生成100000到999999之间的随机数
        return String.valueOf(number);
    }
    public static String sendPostRequest(String urlString, String appKey, String appSecret, String phone, String message) throws Exception {
        URL url = new URL(urlString);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        // 设置请求方法为POST
        connection.setRequestMethod("POST");
        connection.setDoOutput(true);
        // 构造请求参数
        StringBuilder postData = new StringBuilder();
        postData.append("appkey=").append(URLEncoder.encode(appKey, "UTF-8"));
        postData.append("&appsecret=").append(URLEncoder.encode(appSecret, "UTF-8"));
        postData.append("&phone=").append(URLEncoder.encode(phone, "UTF-8"));
        postData.append("&msg=").append(URLEncoder.encode(message, "UTF-8"));
        // 发送请求
        try (OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream())) {
            writer.write(postData.toString());
            writer.flush();
        }
        // 读取响应
        StringBuilder response = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
        }
        return response.toString();
    }
}