From 2326c31e5457433b323fd6d648dfe561a9a510f8 Mon Sep 17 00:00:00 2001
From: zyy <zyy@email.com>
Date: Fri, 12 Sep 2025 15:06:23 +0800
Subject: [PATCH] 注册修复

---
 src/main/java/com/nq/service/impl/UserPositionServiceImpl.java | 1641 ++++++++++++++++++++++++++++++++++++----------------------
 1 files changed, 1,010 insertions(+), 631 deletions(-)

diff --git a/src/main/java/com/nq/service/impl/UserPositionServiceImpl.java b/src/main/java/com/nq/service/impl/UserPositionServiceImpl.java
index 8560221..5533181 100644
--- a/src/main/java/com/nq/service/impl/UserPositionServiceImpl.java
+++ b/src/main/java/com/nq/service/impl/UserPositionServiceImpl.java
@@ -1,7 +1,13 @@
 package com.nq.service.impl;
 
+import cn.hutool.core.convert.Convert;
+import cn.hutool.core.date.DateUtil;
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
 import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
+import com.nq.common.ResponseCode;
 import com.nq.dao.*;
+import com.nq.enums.EConfigKey;
+import com.nq.enums.EStockType;
 import com.nq.enums.EUserAssets;
 import com.nq.pojo.*;
 import com.nq.service.*;
@@ -13,7 +19,6 @@
 import com.nq.utils.stock.BuyAndSellUtils;
 import com.nq.utils.stock.GeneratePosition;
 import com.nq.utils.stock.GetStayDays;
-import com.nq.utils.stock.pinyin.GetPyByChinese;
 import com.nq.utils.stock.sina.StockApi;
 import com.nq.utils.timeutil.DateTimeUtil;
 import com.nq.vo.agent.AgentIncomeVO;
@@ -29,8 +34,13 @@
 
 
 import java.math.BigDecimal;
+import java.math.RoundingMode;
 import java.sql.Timestamp;
+import java.time.LocalDateTime;
+import java.time.ZoneId;
+import java.time.temporal.ChronoUnit;
 import java.util.*;
+import java.util.stream.Collectors;
 import javax.annotation.Resource;
 import javax.servlet.http.HttpServletRequest;
 
@@ -51,6 +61,9 @@
 
     @Autowired
     IUserAssetsServices userAssetsServices;
+
+    @Autowired
+    UserAssetsMapper userAssetsMapper;
 
     @Autowired
     ISiteSettingService iSiteSettingService;
@@ -75,14 +88,10 @@
     @Autowired
     StockMapper stockMapper;
     @Autowired
-    AgentAgencyFeeMapper agentAgencyFeeMapper;
-    @Autowired
     IAgentAgencyFeeService iAgentAgencyFeeService;
     @Autowired
     ISiteProductService iSiteProductService;
 
-    @Autowired
-    FundsApplyMapper fundsApplyMapper;
     @Autowired
     UserStockSubscribeMapper userStockSubscribeMapper;
     @Resource
@@ -90,12 +99,6 @@
     @Resource
     UserIndexPositionMapper userIndexPositionMapper;
 
-    @Autowired
-    IStockFuturesService iStockFuturesService;
-    @Autowired
-    IStockCoinService iStockCoinService;
-    @Autowired
-    CurrencyUtils currencyUtils;
     @Resource
     StockDzMapper stockDzMapper;
 
@@ -103,116 +106,147 @@
     IUserAssetsServices iUserAssetsServices;
 
     @Autowired
-    TradingHourServiceImpl tradingHourService;
+    ITradingHourService tradingHourService;
 
-    @Transactional
-    public ServerResponse buy(Integer stockId, Integer buyNum, Integer buyType, Integer lever, BigDecimal profitTarget, BigDecimal stopTarget, HttpServletRequest request) throws Exception {
+    @Autowired
+    IPriceServices priceServices;
+
+    @Autowired
+    IStockConfigServices iStockConfigServices;
+
+    @Autowired
+    UserPositionCheckDzService userPositionCheckDzService;
+
+
+
+    @Transactional(rollbackFor = Exception.class)
+    public ServerResponse buy(Integer stockId, Integer buyNum, Integer buyType, Integer lever, BigDecimal profitTarget, BigDecimal stopTarget, HttpServletRequest request) {
 
         SiteProduct siteProduct = iSiteProductService.getProductSetting();
 
         User user = this.iUserService.getCurrentRefreshUser(request);
-        if (siteProduct.getRealNameDisplay() && (StringUtils.isBlank(user.getRealName()) || StringUtils.isBlank(user.getIdCard()))) {
-            return ServerResponse.createByErrorMsg("Order failed, please first real name authentication");
+        try {
+            synchronized (user.getId()){
+                if (siteProduct.getRealNameDisplay() && user.getIsActive() != 2) {
+                    return ServerResponse.createByErrorMsg("订单失败,请先实名认证", request);
+                }
+                // 手续费率
+                BigDecimal siteSettingBuyFee = new BigDecimal(iStockConfigServices.queryByKey(EConfigKey.BUY_HANDLING_CHARGE.getCode()).getCValue()) ;
+
+                if (siteProduct.getRealNameDisplay() && user.getIsLock().intValue() == 1) {
+                    return ServerResponse.createByErrorMsg("订单失败,帐户已被锁定", request);
+                }
+
+                Stock stock = stockMapper.selectByPrimaryKey(stockId);
+                if (stock == null) {
+                    return ServerResponse.createByErrorMsg("订单失败,股票代码不存在", request);
+                }
+                //判断股票是否在可交易时间段
+                Boolean b = tradingHourService.timeCheck(stock.getStockCode(), stock.getStockType());
+                if (!b) {
+                    return ServerResponse.createByErrorMsg("订单失败,不在交易时间之内", request);
+                }
+
+
+                /*StockConfig mainBuyConfig =  iStockConfigServices.queryByKey(EConfigKey.MIN_BUY.getCode());
+                if(buyNum<Integer.parseInt(mainBuyConfig.getCValue())){
+                    return ServerResponse.createByErrorMsg("最低购买数量"+mainBuyConfig.getCValue(), request);
+                }*/
+                //最低购买数量 US 10 印度100 香港台湾1000
+                Integer minBuyNum;
+                if (stock.getStockType().equals(EStockType.US.getCode())) {
+                    minBuyNum = 10;
+                } else if (stock.getStockType().equals(EStockType.IN.getCode())) {
+                    minBuyNum = 100;
+                } else {
+                    minBuyNum = 1000;
+                }
+                if(buyNum < minBuyNum){
+                    return ServerResponse.createByErrorMsg("最低购买数量" + minBuyNum, request);
+                }
+
+                UserAssets userAssets = iUserAssetsServices.assetsByTypeAndUserId(stock.getStockType(), user.getId());
+                StockConfig maxBuyConfig =  iStockConfigServices.queryByKey(EConfigKey.MAX_BUY.getCode());
+                if(buyNum > Integer.parseInt(maxBuyConfig.getCValue())){
+                    return ServerResponse.createByErrorMsg("最高购买数量" + maxBuyConfig.getCValue(), request);
+                }
+                if(userAssets.getAmountToBeCovered().compareTo(BigDecimal.ZERO) > 0){
+                    return ServerResponse.createByErrorMsg("请先缴清待补资金", request);
+                }
+                if (stock.getIsLock() != 0) {
+                    return ServerResponse.createByErrorMsg("订单失败,股票被锁定", request);
+                }
+
+                if (!priceServices.isLimitUpBuy(stock.getStockCode())) {
+                    return ServerResponse.createByErrorMsg("暂无配额", request);
+                }
+
+                //股票类型 现价 数据源的处理
+                BigDecimal nowPrice = priceServices.getNowPrice(stock.getStockCode());
+
+                if (nowPrice.compareTo(new BigDecimal("0")) == 0) {
+                    return ServerResponse.createByErrorMsg("报价0,请稍后再试", request);
+                }
+
+                BigDecimal buyAmt = nowPrice.multiply(new BigDecimal(buyNum)).divide(new BigDecimal(lever));
+                //手续费
+                BigDecimal orderFree = siteSettingBuyFee.multiply(buyAmt);
+                BigDecimal needBuyAmt = buyAmt.add(orderFree);
+                //资金校验
+                /*if (!stock.getStockType().equals(EStockType.getDefault().getCode())) {
+                    needBuyAmt = userAssetsServices.exchangeAmountByRate(stock.getStockType(), buyAmt);
+                }*/
+                BigDecimal fundratio = new BigDecimal(user.getFundRatio()).divide(new BigDecimal(100));
+                BigDecimal availableBalance =  fundratio.multiply(userAssets.getAvailableBalance());
+                if (availableBalance.compareTo(needBuyAmt) < 0) {
+                    return ServerResponse.createByErrorMsg("订单失败,配资不足", request);
+                }
+
+                UserPosition userPosition = new UserPosition();
+                if (profitTarget != null && profitTarget.compareTo(new BigDecimal("0")) > 0) {
+                    userPosition.setProfitTargetPrice(profitTarget);
+                }
+                if (stopTarget != null && stopTarget.compareTo(new BigDecimal("0")) > 0) {
+                    userPosition.setStopTargetPrice(stopTarget);
+                }
+                userPosition.setPositionType(user.getAccountType());
+                userPosition.setPositionSn(KeyUtils.getUniqueKey());
+                userPosition.setUserId(user.getId());
+                userPosition.setNickName(user.getRealName());
+                userPosition.setAgentId(user.getAgentId());
+                userPosition.setStockCode(stock.getStockCode());
+                userPosition.setStockName(stock.getStockName());
+                userPosition.setStockGid(stock.getStockType());
+                userPosition.setStockSpell(stock.getStockSpell());
+                userPosition.setBuyOrderId(GeneratePosition.getPositionId());
+                userPosition.setBuyOrderTime(new Date());
+                userPosition.setBuyOrderPrice(nowPrice);
+                userPosition.setOrderDirection((buyType.intValue() == 0) ? "买涨" : "买跌");
+                userPosition.setOrderNum(buyNum);
+                if (stock.getStockPlate() != null) {
+                    userPosition.setStockPlate(stock.getStockPlate());
+                }
+                userPosition.setIsLock(Integer.valueOf(0));
+                userPosition.setOrderLever(lever);
+                userPosition.setOrderTotalPrice(buyAmt);
+                // 手续费
+
+                userPosition.setOrderFee(orderFree);
+                userPosition.setOrderSpread(BigDecimal.ZERO);
+                userPosition.setSpreadRatePrice(BigDecimal.ZERO);
+                BigDecimal profit_and_lose = new BigDecimal("0");
+                userPosition.setProfitAndLose(profit_and_lose);
+                userPosition.setAllProfitAndLose(profit_and_lose.add(orderFree));
+                userPosition.setOrderStayDays(Integer.valueOf(0));
+                userPosition.setOrderStayFee(BigDecimal.ZERO);
+                userPositionMapper.insert(userPosition);
+                iUserAssetsServices.availablebalanceChange(stock.getStockType(), user.getId(), EUserAssets.BUY, buyAmt.negate(), "", "");
+                iUserAssetsServices.availablebalanceChange(stock.getStockType(), user.getId(), EUserAssets.HANDLING_CHARGE, orderFree, "", "");
+                return ServerResponse.createBySuccessMsg("下单成功", request);
+            }
+        } catch (Exception e) {
+            return ServerResponse.createByErrorMsg(e.getMessage());
         }
-
-
-        if (siteProduct.getRealNameDisplay() && user.getIsLock().intValue() == 1) {
-            return ServerResponse.createByErrorMsg("Order failed, account has been locked");
-        }
-
-        SiteSetting siteSetting = this.iSiteSettingService.getSiteSetting();
-        if (siteSetting == null) {
-            log.error("下单出错,网站设置表不存在");
-            return ServerResponse.createByErrorMsg("Order failed, system setting error");
-        }
-
-        Stock stock = stockMapper.selectByPrimaryKey(stockId);
-        if (stock == null) {
-            return ServerResponse.createByErrorMsg("Order failed, stock code error");
-        }
-        //判断股票是否在可交易时间段
-        Boolean b = tradingHourService.timeCheck();
-        if (!b) {
-            return ServerResponse.createByErrorMsg("Order failed, not in the  stock trading session");
-        }
-
-
-        if (stock.getIsLock() != 0) {
-            return ServerResponse.createByErrorMsg("Order failed, shares cannot be traded at present");
-        }
-
-        BigDecimal now_price;
-        //股票类型 现价 数据源的处理
-        StockListVO  stockListVO = StockApi.getStockRealTime(stock);
-        now_price = new BigDecimal(stockListVO.getNowPrice());
-
-        if (now_price.compareTo(new BigDecimal("0")) == 0) {
-            return ServerResponse.createByErrorMsg("Quote 0, please try again later");
-        }
-
-        BigDecimal buy_amt = now_price.multiply(new BigDecimal(buyNum));
-
-        UserAssets userAssets = iUserAssetsServices.assetsByTypeAndUserId(stock.getStockType(),user.getId());
-        if(userAssets.getAvailableBalance().compareTo(buy_amt)<0){
-            return ServerResponse.createByErrorMsg("Order failed,Insufficient balance");
-
-        }
-
-
-        UserPosition userPosition = new UserPosition();
-
-        if (profitTarget != null && profitTarget.compareTo(new BigDecimal("0")) > 0) {
-            userPosition.setProfitTargetPrice(profitTarget);
-        }
-        if (stopTarget != null && stopTarget.compareTo(new BigDecimal("0")) > 0) {
-            userPosition.setStopTargetPrice(stopTarget);
-        }
-
-
-        userPosition.setPositionType(user.getAccountType());
-        userPosition.setPositionSn(KeyUtils.getUniqueKey());
-        userPosition.setUserId(user.getId());
-        userPosition.setNickName(user.getRealName());
-        userPosition.setAgentId(user.getAgentId());
-        userPosition.setStockCode(stock.getStockCode());
-        userPosition.setStockName(stock.getStockName());
-        userPosition.setStockGid(stock.getStockType());
-        userPosition.setStockSpell(stock.getStockSpell());
-        userPosition.setBuyOrderId(GeneratePosition.getPositionId());
-        userPosition.setBuyOrderTime(new Date());
-        userPosition.setBuyOrderPrice(now_price);
-        userPosition.setOrderDirection((buyType.intValue() == 0) ? "买涨" : "买跌");
-        userPosition.setOrderNum(buyNum);
-        if (stock.getStockPlate() != null) {
-            userPosition.setStockPlate(stock.getStockPlate());
-        }
-        userPosition.setIsLock(Integer.valueOf(0));
-        userPosition.setOrderLever(lever);
-        userPosition.setOrderTotalPrice(buy_amt);
-        BigDecimal allStayFee = BigDecimal.valueOf(0);
-        userPosition.setOrderStayFee(allStayFee);
-        userPosition.setOrderStayDays(1);
-
-        BigDecimal buy_fee_amt = BigDecimal.valueOf(0);
-        log.info("用户购买手续费(配资后总资金 * 百分比) = {}", buy_fee_amt);
-        userPosition.setOrderFee(buy_fee_amt);
-
-        BigDecimal buy_yhs_amt = BigDecimal.valueOf(0);
-        log.info("用户购买印花税(配资后总资金 * 百分比) = {}", buy_yhs_amt);
-        userPosition.setOrderSpread(buy_yhs_amt);
-
-        BigDecimal spread_rate_amt = new BigDecimal("0");
-
-        userPosition.setSpreadRatePrice(spread_rate_amt);
-        BigDecimal profit_and_lose = new BigDecimal("0");
-        userPosition.setProfitAndLose(profit_and_lose);
-        BigDecimal all_profit_and_lose = profit_and_lose.subtract(buy_fee_amt).subtract(buy_yhs_amt).subtract(spread_rate_amt);
-        userPosition.setAllProfitAndLose(all_profit_and_lose);
-        userPosition.setOrderStayDays(Integer.valueOf(0));
-        userPosition.setOrderStayFee(new BigDecimal("0"));
-        this.userPositionMapper.insert(userPosition);
-        iUserAssetsServices.availablebalanceChange(stock.getStockType(),user.getId(), EUserAssets.BUY,buy_amt.negate(),"","");
-        return ServerResponse.createBySuccessMsg("Order successful");
     }
 
 
@@ -226,7 +260,7 @@
         if (positionSn.contains("index")) {
             UserIndexPosition userIndexPosition = userIndexPositionMapper.selectIndexPositionBySn(positionSn.replace("index", ""));
             if (userIndexPosition == null) {
-                return ServerResponse.createByErrorMsg("指数持仓单不存在");
+                return ServerResponse.createByErrorMsg("指数持仓单不存在", request);
             }
             if (profitTarget != null && profitTarget > 0) {
                 userIndexPosition.setProfitTargetPrice(BigDecimal.valueOf(profitTarget));
@@ -234,13 +268,12 @@
             if (stopTarget != null && stopTarget > 0) {
                 userIndexPosition.setStopTargetPrice(BigDecimal.valueOf(stopTarget));
             }
-            log.info("指数止盈线" + profitTarget + "-------指数止损线" + stopTarget);
             update = this.userIndexPositionMapper.updateByPrimaryKeySelective(userIndexPosition);
         } else {
             UserPosition userPosition = this.userPositionMapper.findPositionBySn(positionSn);
 
             if (userPosition == null) {
-                return ServerResponse.createByErrorMsg("持仓记录不存在");
+                return ServerResponse.createByErrorMsg("持仓记录不存在", request);
             }
             if (profitTarget != null && profitTarget > 0) {
                 userPosition.setProfitTargetPrice(BigDecimal.valueOf(profitTarget));
@@ -252,128 +285,207 @@
             update = this.userPositionMapper.updateByPrimaryKeySelective(userPosition);
         }
         if (update > 0) {
-            return ServerResponse.createBySuccessMsg("修改成功");
+            return ServerResponse.createBySuccessMsg("修改成功", request);
         } else {
-            return ServerResponse.createByErrorMsg("修改失败");
+            return ServerResponse.createByErrorMsg("修改失败", request);
         }
     }
 
 
-
-    @Transactional
-    public ServerResponse sell(String positionSn, int doType) throws Exception  {
-        SiteSetting siteSetting = this.iSiteSettingService.getSiteSetting();
-        if (siteSetting == null) {
-            log.error("平仓出错,网站设置表不存在");
-            return ServerResponse.createByErrorMsg("Order failed, system setting error");
-        }
-        SiteProduct siteProduct = iSiteProductService.getProductSetting();
-        UserPosition userPosition = this.userPositionMapper.findPositionBySn(positionSn);
-        if (doType != 0) {
-//            if (userPosition.getStockGid().contains(EStockType.US.getCode())) {
-//                String am_begin = siteSetting.getTransAmBeginUs();
-//                String am_end = siteSetting.getTransAmEndUs();
-//                String pm_begin = siteSetting.getTransPmBeginUs();
-//                String pm_end = siteSetting.getTransPmEndUs();
-//                boolean am_flag = BuyAndSellUtils.isTransTime(am_begin, am_end);
-//                boolean pm_flag = BuyAndSellUtils.isTransTime(pm_begin, pm_end);
-//                if (!am_flag && !pm_flag) {
-//                    return ServerResponse.createByErrorMsg("平仓失败,不在交易时段内");
-//                }
-//            } else {
-//                String am_begin = siteSetting.getTransAmBegin();
-//                String am_end = siteSetting.getTransAmEnd();
-//                String pm_begin = siteSetting.getTransPmBegin();
-//                String pm_end = siteSetting.getTransPmEnd();
-//                boolean am_flag = BuyAndSellUtils.isTransTime(am_begin, am_end);
-//                boolean pm_flag = BuyAndSellUtils.isTransTime(pm_begin, pm_end);
-//                if (!am_flag && !pm_flag) {
-//                    return ServerResponse.createByErrorMsg("Order failed,Out of trading hours");
-//                }
-//            }
-//            if (siteProduct.getHolidayDisplay()) {
-//                return ServerResponse.createByErrorMsg("No trading on weekends or holidays!");
-//            }
-            //判断股票是否在可交易时间段
-            Boolean b = tradingHourService.timeCheck();
-            if (!b) {
-                return ServerResponse.createByErrorMsg("Order failed, not in the  stock trading session");
+    @Transactional(rollbackFor = Exception.class)
+    public ServerResponse sell(String positionSn, int doType) {
+        try {
+            UserPosition userPosition = this.userPositionMapper.findPositionBySn(positionSn);
+            if (userPosition == null) {
+                return ServerResponse.createByErrorMsg("平仓失败,订单不存在");
             }
+            BigDecimal siitteBuyFee = iSiteSettingService.getSiteSetting().getBuyFee();
+            Stock stock = stockMapper.selectOne(new QueryWrapper<Stock>().eq("stock_code", userPosition.getStockCode()));
+            if(null == stock){
+                return ServerResponse.createByErrorMsg("股票不存在,平仓失败");
+            }
+            Boolean b = tradingHourService.timeCheck(userPosition.getStockCode(), stock.getStockType());
+            if (!b) {
+                return ServerResponse.createByErrorMsg("订单失败,不在交易时间之内");
+            }
+            User user = this.userMapper.selectById(userPosition.getUserId());
+            if (user == null) {
+                return ServerResponse.createByErrorMsg("平仓失败,用户不存在");
+            }
+            if (user.getIsLock() == 1) {
+                return ServerResponse.createByErrorMsg("账户已被限制交易");
+            }
+            if (userPosition.getSellOrderId() != null) {
+                return ServerResponse.createByErrorMsg("平仓失败, 订单已平仓");
+            }
+            if (1 == userPosition.getIsLock().intValue()) {
+                return ServerResponse.createByErrorMsg("this order is closed " + userPosition.getLockMsg());
+            }
+            //Stock stock = stockMapper.selectOne(new QueryWrapper<Stock>().eq("stock_code", userPosition.getStockCode()));
+            BigDecimal nowPrice = priceServices.getNowPrice(userPosition.getStockCode());
+            if (nowPrice.compareTo(new BigDecimal("0")) != 1) {
+                return ServerResponse.createByErrorMsg("报价0,平仓失败,请稍后再试");
+            }
+            userPosition.setSellOrderId(GeneratePosition.getPositionId());
+            userPosition.setSellOrderPrice(nowPrice);
+            userPosition.setSellOrderTime(new Date());
 
+            BigDecimal sellOrderTotel = nowPrice.multiply(new BigDecimal(userPosition.getOrderNum()));
+            BigDecimal xsPrice = sellOrderTotel.multiply(siitteBuyFee);
+            userPositionMapper.updateById(userPosition);
+            userAssetsServices.availablebalanceChange(stock.getStockType(),
+                    userPosition.getUserId(), EUserAssets.CLOSE_POSITION_RETURN_SECURITY_DEPOSIT,
+                    userPosition.getOrderTotalPrice(), "", "");
+            userAssetsServices.availablebalanceChange(stock.getStockType(),
+                    userPosition.getUserId(), EUserAssets.HANDLING_CHARGE,
+                    xsPrice, "", "");
+
+            PositionProfitVO profitVO = UserPointUtil.getPositionProfitVO(userPosition, priceServices.getNowPrice(userPosition.getStockCode()));
+            userAssetsServices.availablebalanceChange(stock.getStockType(), userPosition.getUserId(), EUserAssets.CLOSE_POSITION,
+                    profitVO.getAllProfitAndLose(), "", "");
+            return ServerResponse.createBySuccessMsg("平仓成功!");
+        } catch (Exception e) {
+            return ServerResponse.createByErrorMsg(e.getMessage());
+        }
+    }
+
+
+    @Transactional(rollbackFor = Exception.class)
+    public ServerResponse sell(String positionSn, int doType, Integer number,HttpServletRequest request) {
+        UserPosition userPosition = this.userPositionMapper.findPositionBySn(positionSn);
+        if (userPosition == null) {
+            return ServerResponse.createByErrorMsg("平仓失败,订单不存在", request);
+        }
+        if(null == number || number <= 0 || number > userPosition.getOrderNum()){
+            return ServerResponse.createByErrorMsg("请输入正确的平仓数", request);
+        }
+        // 手续费率
+        BigDecimal siitteBuyFee = new BigDecimal(iStockConfigServices.queryByKey(EConfigKey.SELL_HANDLING_CHARGE.getCode()).getCValue());
+
+        Stock stock = stockMapper.selectOne(new QueryWrapper<Stock>().eq("stock_code", userPosition.getStockCode()));
+        if(null == stock){
+            return ServerResponse.createByErrorMsg("股票不存在,平仓失败", request);
+        }
+        /*UserAssets userAssets = userAssetsMapper.selectOne(new LambdaQueryWrapper<UserAssets>()
+                .eq(UserAssets::getUserId, userPosition.getUserId())
+                .eq(UserAssets::getAccectType, stock.getStockType())
+        );*/
+        UserAssets userAssets = userAssetsServices.assetsByTypeAndUserId(stock.getStockType(),  userPosition.getUserId());
+        if(userAssets.getAmountToBeCovered().compareTo(BigDecimal.ZERO) > 0){
+            return ServerResponse.createByErrorMsg("请先缴清待补资金", request);
+        }
+        StockSubscribe stockSubscribe = stockSubscribeMapper.selectOne(new LambdaQueryWrapper<StockSubscribe>()
+                .eq(StockSubscribe::getCode, userPosition.getStockCode()));
+        if (null != stockSubscribe && DateUtil.date().before(stockSubscribe.getListDate())) {
+            return ServerResponse.createByErrorMsg("股票未上市,不能平仓", request);
         }
 
-
-        if (userPosition == null) {
-            return ServerResponse.createByErrorMsg("Closing failed, order does not exist");
+        Boolean b = tradingHourService.timeCheck(userPosition.getStockCode(), stock.getStockType());
+        if (!b) {
+            return ServerResponse.createByErrorMsg("订单失败,不在交易时间之内", request);
+        }
+        if(userPosition.getPositionType() == 3){
+            StockDz stockDz = stockDzMapper.selectOne(new LambdaQueryWrapper<StockDz>().eq(StockDz::getId, userPosition.getDzId()));
+            LocalDateTime buyOrderLocalDateTime = LocalDateTime.ofInstant(userPosition.getBuyOrderTime().toInstant(), ZoneId.systemDefault());
+            // 计算天数差
+            long daysBetween = ChronoUnit.DAYS.between(buyOrderLocalDateTime, LocalDateTime.now());
+            if(daysBetween < stockDz.getPeriod()){
+                return ServerResponse.createByErrorMsg("内幕交易未到平仓周期", request);
+            }
         }
 
         User user = this.userMapper.selectById(userPosition.getUserId());
         if (user == null) {
-            return ServerResponse.createByErrorMsg("Closed position failed, user does not exist");
+            return ServerResponse.createByErrorMsg("平仓失败,用户不存在", request);
         }
-
-        /*实名认证开关开启*/
-        if (siteProduct.getRealNameDisplay() && user.getIsLock().intValue() == 1) {
-
-            return ServerResponse.createByErrorMsg("Closing failed, user is locked");
-
+        if (user.getIsLock() == 1) {
+            return ServerResponse.createByErrorMsg("账户已被限制交易", request);
         }
-
-
         if (userPosition.getSellOrderId() != null) {
-            return ServerResponse.createByErrorMsg("Closing failed, this order is closed");
+            return ServerResponse.createByErrorMsg("平仓失败, 订单已平仓", request);
         }
-
         if (1 == userPosition.getIsLock().intValue()) {
             return ServerResponse.createByErrorMsg("this order is closed " + userPosition.getLockMsg());
         }
-        BigDecimal now_price;
-        Stock stock = stockMapper.selectOne(new QueryWrapper<Stock>().eq("stock_code", userPosition.getStockCode()));
-        //股票卖出的 价格 数据源
-
-        StockListVO    stockListVO = StockApi.getStockRealTime(stock);
-        now_price = new BigDecimal(stockListVO.getNowPrice());
-        if (stockListVO.getNowPrice() == null) {
-            return ServerResponse.createByErrorMsg("Failed to close position, failed to obtain stock information");
+        if (!priceServices.isLimitDownSell(stock.getStockCode())) {
+            return ServerResponse.createByErrorMsg("股票跌停,无法平仓", request);
         }
-        if (now_price.compareTo(new BigDecimal("0")) != 1) {
-            log.error("股票 = {} 收到报价 = {}", userPosition.getStockName(), now_price);
-            return ServerResponse.createByErrorMsg("Quote 0, closing failed, please try again later");
+        BigDecimal nowPrice = priceServices.getNowPrice(userPosition.getStockCode());
+        if (nowPrice.compareTo(new BigDecimal("0")) != 1) {
+            return ServerResponse.createByErrorMsg("报价0,平仓失败,请稍后再试", request);
         }
 
-        userPosition.setSellOrderId(GeneratePosition.getPositionId());
-        userPosition.setSellOrderPrice(now_price);
-        userPosition.setSellOrderTime(new Date());
-        userPositionMapper.updateById(userPosition);
-        userAssetsServices.availablebalanceChange(stock.getStockType(),userPosition.getUserId(),EUserAssets.CLOSE_POSITION_RETURN_SECURITY_DEPOSIT,
-                userPosition.getOrderTotalPrice(),"","");
-        userAssetsServices.availablebalanceChange(stock.getStockType(),userPosition.getUserId(),EUserAssets.CLOSE_POSITION,
-                userPosition.getProfitAndLose() ,"","");
-        return ServerResponse.createBySuccessMsg("Closed position successfully!");
+        //部分平仓
+        if(number < userPosition.getOrderNum()){
+            //拆分订单
+            UserPosition position = ConverterUtil.convert(userPosition,UserPosition.class);
+            position.setId(null);
+            position.setPositionSn(KeyUtils.getUniqueKey());
+            position.setOrderNum(number);
+            position.setOrderTotalPrice(position.getBuyOrderPrice().multiply(new BigDecimal(number)));
+            position.setBuyOrderId(GeneratePosition.getPositionId());
+            //修改拆分订单手续费
+            BigDecimal BuyFee = new BigDecimal(iStockConfigServices.queryByKey(EConfigKey.BUY_HANDLING_CHARGE.getCode()).getCValue());
+            BigDecimal buyPrice = position.getBuyOrderPrice().multiply(new BigDecimal(position.getOrderNum()));
+            BigDecimal xsPrice = buyPrice.multiply(BuyFee);
+            position.setOrderFee(xsPrice);
+
+            //修改原订单
+            userPosition.setOrderNum(userPosition.getOrderNum()-number);
+            userPosition.setOrderTotalPrice(userPosition.getBuyOrderPrice().multiply(new BigDecimal(userPosition.getOrderNum())));
+            userPosition.setOrderFee(userPosition.getOrderFee().subtract(position.getOrderFee()));
+            userPositionMapper.insert(position);
+            userPositionMapper.updateById(userPosition);
+
+            return getObjectServerResponse(request, position, nowPrice, siitteBuyFee, stock);
+        }
+        return getObjectServerResponse(request, userPosition, nowPrice, siitteBuyFee, stock);
     }
 
-    @Transactional
+    private ServerResponse<Object> getObjectServerResponse(HttpServletRequest request, UserPosition userPosition, BigDecimal nowPrice, BigDecimal siitteBuyFee, Stock stock) {
+        try {
+            userPosition.setSellOrderId(GeneratePosition.getPositionId());
+            userPosition.setSellOrderPrice(nowPrice);
+            userPosition.setSellOrderTime(new Date());
+
+            BigDecimal sellOrderTotel = nowPrice.multiply(new BigDecimal(userPosition.getOrderNum()));
+            BigDecimal xsPrice = sellOrderTotel.multiply(siitteBuyFee);
+            userPosition.setOrderFee(userPosition.getOrderFee().add(xsPrice));
+            userPositionMapper.updateById(userPosition);
+            userAssetsServices.availablebalanceChange(stock.getStockType(),
+                    userPosition.getUserId(),
+                    EUserAssets.CLOSE_POSITION_RETURN_SECURITY_DEPOSIT,
+                    userPosition.getOrderTotalPrice(), "", "");
+            userAssetsServices.availablebalanceChange(stock.getStockType(),
+                    userPosition.getUserId(), EUserAssets.HANDLING_CHARGE,
+                    xsPrice, "", "");
+
+            PositionProfitVO profitVO = UserPointUtil.getPositionProfitVO(userPosition,
+                    priceServices.getNowPrice(userPosition.getStockCode()));
+
+            userAssetsServices.availablebalanceChange(stock.getStockType(),
+                    userPosition.getUserId(), EUserAssets.CLOSE_POSITION,
+                    profitVO.getAllProfitAndLose(), "", "");
+            return ServerResponse.createBySuccessMsg("平仓成功!", request);
+        } catch (Exception e) {
+            return ServerResponse.createByErrorMsg(e.getMessage());
+        }
+    }
+
+    @Transactional(rollbackFor = Exception.class)
     @Override
-    public ServerResponse allSell(HttpServletRequest request,String stockType) throws Exception{
+    public ServerResponse allSell(HttpServletRequest request, String stockType) throws Exception {
         //判断股票是否在可交易时间段
-        Boolean b = tradingHourService.timeCheck();
-        if (!b) {
-            return ServerResponse.createByErrorMsg("Order failed, not in the  stock trading session");
-        }
-        User user =    iUserService.getCurrentUser(request);
-        if(user == null){
-            return ServerResponse.createByErrorMsg("Please login");
-        }
+        User user = iUserService.getCurrentUser(request);
         QueryWrapper<UserPosition> queryWrapper = new QueryWrapper<>();
-        queryWrapper.eq("user_id",user.getId());
-        queryWrapper.eq("stock_gid",stockType);
+        queryWrapper.eq("user_id", user.getId());
         queryWrapper.isNull("sell_order_id");
 
         List<UserPosition> userPositionList = userPositionMapper.selectList(queryWrapper);
         for (int i = 0; i < userPositionList.size(); i++) {
-            sell(userPositionList.get(i).getPositionSn(),0);
+            sell(userPositionList.get(i).getPositionSn(), 0);
         }
-        return ServerResponse.createBySuccessMsg("Closed position successfully!");
+        return ServerResponse.createBySuccessMsg("平仓成功!");
     }
 
     //用户追加保证金操作
@@ -519,23 +631,62 @@
         return ServerResponse.createByErrorMsg("删除失败");
     }
 
+    @Override
+    public UserPositionVO findByPostionSn(String positionSn) {
+        UserPosition userPosition = userPositionMapper.selectOne(new QueryWrapper<UserPosition>().eq("position_sn", positionSn));
+        if (userPosition == null) {
+            return null;
+        }
+
+        return UserPointUtil.assembleUserPositionVO(userPosition, priceServices.getNowPrice(userPosition.getStockCode()));
+    }
+
     public ServerResponse findMyPositionByCodeAndSpell(String stockCode, String stockSpell,
                                                        Integer state, HttpServletRequest request,
                                                        int pageNum, int pageSize, String stockType) {
         User user = this.iUserService.getCurrentUser(request);
-
         PageHelper.startPage(pageNum, pageSize);
+        List<UserPosition> userPositions;
 
 
-        List<UserPosition> userPositions = this.userPositionMapper.
+
+        userPositions = userPositionMapper.
                 findMyPositionByCodeAndSpell(user.getId(),
                         stockCode, stockSpell,
                         state, stockType);
 
+
         List<UserPositionVO> userPositionVOS = Lists.newArrayList();
         if (userPositions.size() > 0) {
             for (UserPosition position : userPositions) {
-                UserPositionVO userPositionVO = assembleUserPositionVO(position);
+                BigDecimal nowPrice = BigDecimal.ZERO;
+                if(state == 0){
+                    nowPrice = priceServices.getNowPrice(position.getStockCode());
+                }else{
+                    nowPrice = position.getSellOrderPrice();
+                }
+////                if(state == 1){
+////                    nowPrice = position.getSellOrderPrice();
+////                }else{
+////                    nowPrice = priceServices.getNowPrice(position.getStockCode());
+////                }
+                UserPositionVO userPositionVO = UserPointUtil.assembleUserPositionVO(position,nowPrice);
+                userPositionVO.setOrderTotalPrice(userPositionVO.getOrderTotalPrice().multiply(new BigDecimal(userPositionVO.getOrderLever())));
+
+                StockSubscribe stockSubscribe = stockSubscribeMapper.selectOne(new LambdaQueryWrapper<StockSubscribe>()
+                        .eq(StockSubscribe::getCode, userPositionVO.getStockCode()));
+                if(position.getSellOrderId() == null){
+                    if (null != stockSubscribe && DateUtil.date().before(stockSubscribe.getListDate())) {
+                        userPositionVO.setProfitAndLose(BigDecimal.ZERO);
+                        userPositionVO.setProfitAndLoseParent("0%");
+                        userPositionVO.setIsListed(false);
+                    }else{
+                        userPositionVO.setIsListed(true);
+                        userPositionVO.setProfitAndLose(userPositionVO.getProfitAndLose().multiply(new BigDecimal(userPositionVO.getOrderLever())));
+                    }
+                }else{
+                    userPositionVO.setProfitAndLose(userPositionVO.getProfitAndLose().multiply(new BigDecimal(userPositionVO.getOrderLever())));
+                }
                 userPositionVOS.add(userPositionVO);
             }
         }
@@ -546,39 +697,81 @@
         return ServerResponse.createBySuccess(pageInfo);
     }
 
+    public ServerResponse findMyPositionByParam(String stockCode, String stockSpell,
+                                                       Integer state, HttpServletRequest request,
+                                                       int pageNum, int pageSize, String stockType, Integer positionType) {
+        try {
+            User user = iUserService.getCurrentUser(request);
+            if (user == null ){
+                return ServerResponse.createByErrorCodeMsg(ResponseCode.NEED_LOGIN.getCode(),"请先登录", request);
+            }
+
+            PageHelper.startPage(pageNum, pageSize);
+            List<UserPositionVO> userPositions = userPositionMapper.findMyPositionByParam(user.getId(),
+                            stockCode, stockSpell, state, stockType, positionType);
+            PageInfo<UserPositionVO> pageInfo = new PageInfo<>(userPositions);
+
+            List<UserPositionVO> resultUserPositions = new ArrayList<>();
+            if (!pageInfo.getList().isEmpty()) {
+                for (UserPositionVO position : userPositions) {
+                    UserPositionVO userPositionVO = position;
+                    if (position.getPositionType() != 4) {
+                        BigDecimal nowPrice;
+                        if(state == 0){
+                            nowPrice = priceServices.getNowPrice(position.getStockCode());
+                        }else{
+                            nowPrice = position.getSellOrderPrice();
+                        }
+
+                        userPositionVO = UserPointUtil.assembleUserPositionVO2(position,nowPrice);
+                        userPositionVO.setOrderTotalPrice(userPositionVO.getOrderTotalPrice().multiply(new BigDecimal(userPositionVO.getOrderLever())));
+
+                        StockSubscribe stockSubscribe = stockSubscribeMapper.selectOne(new LambdaQueryWrapper<StockSubscribe>()
+                                .eq(StockSubscribe::getCode, userPositionVO.getStockCode()));
+                        if(position.getSellOrderId() == null){
+                            if (null != stockSubscribe && DateUtil.date().before(stockSubscribe.getListDate())) {
+                                userPositionVO.setProfitAndLose(BigDecimal.ZERO);
+                                userPositionVO.setProfitAndLoseParent("0%");
+                                userPositionVO.setIsListed(false);
+                            }else{
+                                userPositionVO.setIsListed(true);
+                                userPositionVO.setProfitAndLose(userPositionVO.getProfitAndLose().multiply(new BigDecimal(userPositionVO.getOrderLever())));
+                            }
+                        }else{
+                            userPositionVO.setProfitAndLose(userPositionVO.getProfitAndLose().multiply(new BigDecimal(userPositionVO.getOrderLever())));
+                        }
+                    } else {
+                        //ai交易 计算收益率 收益/本金*100
+                        BigDecimal profitAndLose = userPositionVO.getProfitAndLose()
+                                .divide(userPositionVO.getOrderTotalPrice(), RoundingMode.HALF_UP)
+                                .multiply(new BigDecimal(100))
+                                .setScale(2, RoundingMode.DOWN);
+                        userPositionVO.setNow_price(String.valueOf(userPositionVO.getSellOrderPrice().setScale(2, RoundingMode.HALF_UP)));
+                        userPositionVO.setProfitAndLoseParent(profitAndLose + "%");
+                        userPositionVO.setSellOrderTotalPrice(userPositionVO.getSellOrderPrice().multiply(BigDecimal.valueOf(userPositionVO.getOrderNum())));
+                    }
+                    resultUserPositions.add(userPositionVO);
+                }
+            }
+            pageInfo.setList(resultUserPositions);
+            return ServerResponse.createBySuccess(pageInfo);
+        } catch (Exception e) {
+            e.printStackTrace();
+            log.error("IUserPositionService findMyPositionByParam  {}", e.getMessage());
+        }
+        return ServerResponse.createByError();
+    }
+
     public PositionVO findUserPositionAllProfitAndLose(Integer userId) {
         List<UserPosition> userPositions = this.userPositionMapper.findPositionByUserIdAndSellIdIsNull(userId);
 
         BigDecimal allProfitAndLose = new BigDecimal("0");
         BigDecimal allFreezAmt = new BigDecimal("0");
         for (UserPosition position : userPositions) {
-            Stock stock = stockMapper.selectOne(new QueryWrapper<Stock>().eq("stock_code", position.getStockCode()));
-            StockListVO stockListVO = StockApi.getStockRealTime(
-                    stock);
-            if (stockListVO.getNowPrice() == null) {
-                stockListVO.setNowPrice("0");
-            }
-            BigDecimal nowPrice = new BigDecimal(stockListVO.getNowPrice());
-            if (nowPrice.compareTo(new BigDecimal("0")) != 0) {
-                BigDecimal buyPrice = position.getBuyOrderPrice();
-                BigDecimal subPrice = nowPrice.subtract(buyPrice);
-                BigDecimal profit_and_lose = subPrice.multiply(new BigDecimal(position.getOrderNum().intValue()));
-                if ("买跌".equals(position.getOrderDirection())) {
-                    profit_and_lose = profit_and_lose.negate();
-                }
-                BigDecimal total_fee = position.getOrderFee().add(position.getOrderSpread()).add(position.getOrderStayFee());
-                BigDecimal position_profit = profit_and_lose.subtract(total_fee);
-                allProfitAndLose = allProfitAndLose.add(position_profit);
-                BigDecimal position_freez = position.getOrderTotalPrice().divide(new BigDecimal(position.getOrderLever().intValue()), 2, 4);
-                allFreezAmt = allFreezAmt.add(position_freez).add(position.getMarginAdd());
-                continue;
-            }
-            log.info("查询所有持仓单的总盈亏,现价返回0,当前为集合竞价");
-        }
-        //加上分仓交易保证金
-        List<FundsApply> fundsApplyList = fundsApplyMapper.getUserMarginList(userId);
-        for (FundsApply fundsApply : fundsApplyList) {
-            allFreezAmt = allFreezAmt.add(fundsApply.getMargin());
+            BigDecimal nowPrice = priceServices.getNowPrice(position.getStockCode());
+            PositionProfitVO positionProfitVO = UserPointUtil.getPositionProfitVO(position, nowPrice);
+            allProfitAndLose.add(positionProfitVO.getAllProfitAndLose());
+            allFreezAmt.add(positionProfitVO.getProfitAndLose());
         }
 
 
@@ -590,41 +783,15 @@
 
     @Override
     public PositionVO findUserPositionAllProfitAndLose(Integer userId, String stockType) {
-        List<UserPosition> userPositions = this.userPositionMapper.findPositionByUserIdAndSellId(userId, stockType);
-
+        List<UserPosition> userPositions = userPositionMapper.findPositionByUserIdAndSellId(userId, stockType);
         BigDecimal allProfitAndLose = new BigDecimal("0");
         BigDecimal allFreezAmt = new BigDecimal("0");
         for (UserPosition position : userPositions) {
-            Stock stock = stockMapper.selectOne(new QueryWrapper<Stock>().eq("stock_code", position.getStockCode()));
-            StockListVO stockListVO = StockApi.getStockRealTime(
-                    stock);
-            if (stockListVO.getNowPrice() == null) {
-                stockListVO.setNowPrice("0");
-            }
-            BigDecimal nowPrice = new BigDecimal(stockListVO.getNowPrice());
-            if (nowPrice.compareTo(new BigDecimal("0")) != 0) {
-                BigDecimal buyPrice = position.getBuyOrderPrice();
-                BigDecimal subPrice = nowPrice.subtract(buyPrice);
-                BigDecimal profit_and_lose = subPrice.multiply(new BigDecimal(position.getOrderNum().intValue()));
-                if ("买跌".equals(position.getOrderDirection())) {
-                    profit_and_lose = profit_and_lose.negate();
-                }
-                BigDecimal total_fee = position.getOrderFee().add(position.getOrderSpread()).add(position.getOrderStayFee());
-                BigDecimal position_profit = profit_and_lose.subtract(total_fee);
-                allProfitAndLose = allProfitAndLose.add(position_profit);
-                BigDecimal position_freez = position.getOrderTotalPrice().divide(new BigDecimal(position.getOrderLever().intValue()), 2, 4);
-                allFreezAmt = allFreezAmt.add(position_freez).add(position.getMarginAdd());
-                continue;
-            }
-            log.info("查询所有持仓单的总盈亏,现价返回0,当前为集合竞价");
+            BigDecimal nowPrice = priceServices.getNowPrice(position.getStockCode());
+            PositionProfitVO positionProfitVO = UserPointUtil.getPositionProfitVO(position, nowPrice);
+            allProfitAndLose.add(positionProfitVO.getAllProfitAndLose());
+            allFreezAmt.add(positionProfitVO.getProfitAndLose());
         }
-        //加上分仓交易保证金
-        List<FundsApply> fundsApplyList = fundsApplyMapper.getUserMarginList(userId);
-        for (FundsApply fundsApply : fundsApplyList) {
-            allFreezAmt = allFreezAmt.add(fundsApply.getMargin());
-        }
-
-
         PositionVO positionVO = new PositionVO();
         positionVO.setAllProfitAndLose(allProfitAndLose);
         positionVO.setAllFreezAmt(allFreezAmt);
@@ -649,7 +816,10 @@
         return transNum;
     }
 
-    public ServerResponse listByAgent(Integer positionType, Integer state, Integer userId, Integer agentId, String positionSn, String beginTime, String endTime, HttpServletRequest request, int pageNum, int pageSize) {
+    public ServerResponse listByAgent(Integer positionType, Integer state,
+                                      Integer userId, Integer agentId,
+                                      String positionSn, String beginTime,
+                                      String endTime,HttpServletRequest request, int pageNum, int pageSize) {
         AgentUser currentAgent = this.iAgentUserService.getCurrentAgent(request);
 
 
@@ -677,10 +847,17 @@
             end_time = DateTimeUtil.searchStrToTimestamp(endTime);
         }
 
+
+
+
+        List<Integer> ids = new ArrayList<>();
+        if(null != searchId){
+            ids = getSubordinates(searchId);
+            ids.add(searchId);
+        }
         PageHelper.startPage(pageNum, pageSize);
-
-
-        List<UserPosition> userPositions = this.userPositionMapper.listByAgent(positionType, state, userId, searchId, positionSn, begin_time, end_time);
+        List<UserPosition> userPositions = this.userPositionMapper.listByAgent(positionType, state,
+                userId, ids, positionSn, begin_time, end_time,null);
 
         List<AgentPositionVO> agentPositionVOS = Lists.newArrayList();
         for (UserPosition position : userPositions) {
@@ -709,7 +886,14 @@
         }
 
 
-        List<UserPosition> userPositions = this.userPositionMapper.listByAgent(positionType, Integer.valueOf(1), null, agentId, null, begin_time, end_time);
+        List<Integer> ids = new ArrayList<>();
+        if(null != agentId){
+            ids = getSubordinates(agentId);
+            ids.add(agentId);
+        }
+
+        List<UserPosition> userPositions = this.userPositionMapper.listByAgent(positionType, Integer.valueOf(1),
+                null, ids, null, begin_time, end_time,null);
 
 
         BigDecimal order_fee_amt = new BigDecimal("0");
@@ -729,7 +913,7 @@
         return ServerResponse.createBySuccess(agentIncomeVO);
     }
 
-    public ServerResponse listByAdmin(Integer agentId, Integer positionType, Integer state, Integer userId, String positionSn, String beginTime, String endTime, int pageNum, int pageSize) {
+    public ServerResponse listByAdmin(Integer agentId, Integer positionType, Integer state, Integer userId, String positionSn, String beginTime, String endTime, int pageNum, int pageSize,String phone) {
         PageHelper.startPage(pageNum, pageSize);
 
 
@@ -741,15 +925,38 @@
         if (StringUtils.isNotBlank(endTime)) {
             end_time = DateTimeUtil.searchStrToTimestamp(endTime);
         }
-        List<UserPosition> userPositions = this.userPositionMapper.listByAgent(positionType, state, userId, agentId, positionSn, begin_time, end_time);
+        List<Integer> ids = new ArrayList<>();
+        if(null != agentId){
+            ids = getSubordinates(agentId);
+            ids.add(agentId);
+        }
+
+
+        List<UserPosition> userPositions = this.userPositionMapper.listByAgent(positionType, state, userId, ids, positionSn, begin_time, end_time,phone);
         List<AdminPositionVO> adminPositionVOS = Lists.newArrayList();
         for (UserPosition position : userPositions) {
             AdminPositionVO adminPositionVO = assembleAdminPositionVO(position);
+            AgentUser agentUser = agentUserMapper.selectById(adminPositionVO.getAgentId());
+            adminPositionVO.setAgentName(agentUser.getAgentName());
+            User user = userMapper.selectById(adminPositionVO.getUserId());
+            adminPositionVO.setPhone(user.getPhone());
             adminPositionVOS.add(adminPositionVO);
         }
         PageInfo pageInfo = new PageInfo(userPositions);
         pageInfo.setList(adminPositionVOS);
         return ServerResponse.createBySuccess(pageInfo);
+    }
+
+    public List<Integer> getSubordinates(Integer id) {
+        List<AgentUser> agentUsers = agentUserMapper.selectList(new LambdaQueryWrapper<AgentUser>());
+        List<Integer> subordinates = new ArrayList<>();
+        for (AgentUser user : agentUsers) {
+            if (id.equals(user.getParentId())) {
+                subordinates.add(user.getId());
+                subordinates.addAll(getSubordinates(user.getId()));
+            }
+        }
+        return subordinates;
     }
 
     public int CountPositionNum(Integer state, Integer accountType) {
@@ -802,7 +1009,6 @@
         }
 
 
-
         BigDecimal buy_amt = (new BigDecimal(buyPrice)).multiply(new BigDecimal(buyNum.intValue()));
         BigDecimal buy_amt_autual = buy_amt.divide(new BigDecimal(lever.intValue()), 2, 4);
 
@@ -824,7 +1030,7 @@
         userPosition.setAgentId(user.getAgentId());
         userPosition.setStockCode(stock.getStockCode());
         userPosition.setStockName(stock.getStockName());
-        userPosition.setStockGid(stock.getStockGid());
+        userPosition.setStockGid(stock.getStockType());
         userPosition.setStockSpell(stock.getStockSpell());
         userPosition.setBuyOrderId(GeneratePosition.getPositionId());
         userPosition.setBuyOrderTime(DateTimeUtil.strToDate(buyTime));
@@ -1004,7 +1210,7 @@
         }
     }
 
-    @Transactional
+    @Transactional(rollbackFor = Exception.class)
     public ServerResponse closingStayTask(UserPosition position, Integer stayDays) throws Exception {
         log.info("=================closingStayTask====================");
         log.info("修改留仓费,持仓id={},持仓天数={}", position.getId(), stayDays);
@@ -1081,7 +1287,7 @@
 
         adminPositionVO.setStockPlate(position.getStockPlate());
 
-        PositionProfitVO positionProfitVO = getPositionProfitVO(position);
+        PositionProfitVO positionProfitVO = UserPointUtil.getPositionProfitVO(position, priceServices.getNowPrice(position.getStockCode()));
         adminPositionVO.setProfitAndLose(positionProfitVO.getProfitAndLose());
         adminPositionVO.setAllProfitAndLose(positionProfitVO.getAllProfitAndLose());
         adminPositionVO.setNow_price(positionProfitVO.getNowPrice());
@@ -1092,7 +1298,14 @@
 
     private AgentPositionVO assembleAgentPositionVO(UserPosition position) {
         AgentPositionVO agentPositionVO = new AgentPositionVO();
-
+        User user = userMapper.selectById(position.getUserId());
+        if(null != user){
+            AgentUser agentUser = agentUserMapper.selectById(user.getAgentId());
+            agentPositionVO.setPhone(user.getPhone());
+            if(null != agentUser){
+                agentPositionVO.setAgentName(agentUser.getAgentName());
+            }
+        }
         agentPositionVO.setId(position.getId());
         agentPositionVO.setPositionSn(position.getPositionSn());
         agentPositionVO.setPositionType(position.getPositionType());
@@ -1123,91 +1336,13 @@
 
         agentPositionVO.setStockPlate(position.getStockPlate());
 
-        PositionProfitVO positionProfitVO = getPositionProfitVO(position);
+        PositionProfitVO positionProfitVO = UserPointUtil.getPositionProfitVO(position, priceServices.getNowPrice(position.getStockCode()));
         agentPositionVO.setProfitAndLose(positionProfitVO.getProfitAndLose());
         agentPositionVO.setAllProfitAndLose(positionProfitVO.getAllProfitAndLose());
         agentPositionVO.setNow_price(positionProfitVO.getNowPrice());
 
 
         return agentPositionVO;
-    }
-
-    private UserPositionVO assembleUserPositionVO(UserPosition position) {
-        UserPositionVO userPositionVO = new UserPositionVO();
-
-        userPositionVO.setId(position.getId());
-        userPositionVO.setPositionType(position.getPositionType());
-        userPositionVO.setPositionSn(position.getPositionSn());
-        userPositionVO.setUserId(position.getUserId());
-        userPositionVO.setNickName(position.getNickName());
-        userPositionVO.setAgentId(position.getAgentId());
-        userPositionVO.setStockName(position.getStockName());
-        userPositionVO.setStockCode(position.getStockCode());
-        userPositionVO.setStockGid(position.getStockGid());
-        userPositionVO.setStockSpell(position.getStockSpell());
-        userPositionVO.setBuyOrderId(position.getBuyOrderId());
-        userPositionVO.setBuyOrderTime(position.getBuyOrderTime());
-        userPositionVO.setBuyOrderPrice(position.getBuyOrderPrice());
-        userPositionVO.setSellOrderId(position.getSellOrderId());
-        userPositionVO.setSellOrderTime(position.getSellOrderTime());
-        userPositionVO.setSellOrderPrice(position.getSellOrderPrice());
-        userPositionVO.setProfitTargetPrice(position.getProfitTargetPrice());
-        userPositionVO.setStopTargetPrice(position.getStopTargetPrice());
-        userPositionVO.setOrderDirection(position.getOrderDirection());
-        userPositionVO.setOrderNum(position.getOrderNum());
-        userPositionVO.setOrderLever(position.getOrderLever());
-        userPositionVO.setOrderTotalPrice(position.getOrderTotalPrice());
-        userPositionVO.setOrderFee(position.getOrderFee());
-        userPositionVO.setOrderSpread(position.getOrderSpread());
-        userPositionVO.setOrderStayFee(position.getOrderStayFee());
-        userPositionVO.setOrderStayDays(position.getOrderStayDays());
-        userPositionVO.setMarginAdd(position.getMarginAdd());
-
-        userPositionVO.setStockPlate(position.getStockPlate());
-        userPositionVO.setSpreadRatePrice(position.getSpreadRatePrice());
-
-        PositionProfitVO positionProfitVO = getPositionProfitVO(position);
-        userPositionVO.setProfitAndLose(positionProfitVO.getProfitAndLose());
-        userPositionVO.setAllProfitAndLose(positionProfitVO.getAllProfitAndLose());
-        userPositionVO.setNow_price(positionProfitVO.getNowPrice());
-        return userPositionVO;
-    }
-
-    public PositionProfitVO getPositionProfitVO(UserPosition position) {
-        BigDecimal profitAndLose = new BigDecimal("0");
-        BigDecimal allProfitAndLose = new BigDecimal("0");
-        String nowPrice = "";
-
-        if (position.getSellOrderId() != null) {
-
-            BigDecimal subPrice = position.getSellOrderPrice().subtract(position.getBuyOrderPrice());
-            profitAndLose = subPrice.multiply(new BigDecimal(position.getOrderNum().intValue()));
-            if ("买跌".equals(position.getOrderDirection())) {
-                profitAndLose = profitAndLose.negate();
-            }
-            allProfitAndLose = profitAndLose.subtract(position.getOrderFee()).subtract(position.getOrderSpread()).subtract(position.getOrderStayFee()).subtract(position.getSpreadRatePrice());
-        } else {
-            StockListVO stockListVO = new StockListVO();
-            StockCoin stockCoin = new StockCoin();
-            Stock stock = stockMapper.selectOne(new QueryWrapper<Stock>().eq("stock_code", position.getStockCode()));
-            stockListVO = StockApi.getStockRealTime(stock);
-            nowPrice = stockListVO.getNowPrice();
-            if (nowPrice == null) {
-                nowPrice = String.valueOf(0);
-            }
-            BigDecimal subPrice = (new BigDecimal(nowPrice)).subtract(position.getBuyOrderPrice());
-            profitAndLose = subPrice.multiply(new BigDecimal(position.getOrderNum().intValue()));
-            if ("买跌".equals(position.getOrderDirection())) {
-                profitAndLose = profitAndLose.negate();
-            }
-            //总盈亏= 浮动盈亏 – 手续费 – 印花税 – 留仓费 – 点差费
-            allProfitAndLose = profitAndLose.subtract(position.getOrderFee()).subtract(position.getOrderSpread()).subtract(position.getOrderStayFee()).subtract(position.getSpreadRatePrice());
-        }
-        PositionProfitVO positionProfitVO = new PositionProfitVO();
-        positionProfitVO.setProfitAndLose(profitAndLose);
-        positionProfitVO.setAllProfitAndLose(allProfitAndLose);
-        positionProfitVO.setNowPrice(nowPrice);
-        return positionProfitVO;
     }
 
 
@@ -1217,7 +1352,7 @@
         List<UserPositionVO> userPositionVOS = Lists.newArrayList();
         if (userPositions.size() > 0) {
             for (UserPosition position : userPositions) {
-                UserPositionVO userPositionVO = assembleUserPositionVO(position);
+                UserPositionVO userPositionVO = UserPointUtil.assembleUserPositionVO(position, priceServices.getNowPrice(position.getStockCode()));
                 userPositionVOS.add(userPositionVO);
             }
         }
@@ -1234,7 +1369,7 @@
         List<UserPositionVO> userPositionVOS = Lists.newArrayList();
         UserPositionVO userPositionVO = null;
         if (position != null) {
-            userPositionVO = assembleUserPositionVO(position);
+            userPositionVO = UserPointUtil.assembleUserPositionVO(position, priceServices.getNowPrice(position.getStockCode()));
         }
         userPositionVOS.add(userPositionVO);
 
@@ -1252,32 +1387,43 @@
      * @Date: 2022/10/26
      */
     @Override
-    public ServerResponse newStockToPosition(Integer id) {
-        UserStockSubscribe userStockSubscribe = userStockSubscribeMapper.load(id);
-        if (userStockSubscribe == null) {
-            return ServerResponse.createByErrorMsg("无该申购记录");
-        }
-        StockSubscribe stockSubscribe = stockSubscribeMapper.selectOne(new QueryWrapper<StockSubscribe>().eq("code", userStockSubscribe.getNewCode()));
-        if (userStockSubscribe == null) {
-            return ServerResponse.createByErrorMsg("该新股不存在");
-        }
-        if (userStockSubscribe.getStatus() == 4 || userStockSubscribe.getStatus() == 3 && stockSubscribe.getType() == 2) {
+    @Transactional(rollbackFor = Exception.class)
+    public ServerResponse newStockToPosition(Integer id,BigDecimal amountToBeCovered) {
+        try {
+            UserStockSubscribe userStockSubscribe = userStockSubscribeMapper.load(id);
+            if (userStockSubscribe == null) {
+                return ServerResponse.createByErrorMsg("无该申购记录");
+            }
+            StockSubscribe stockSubscribe = stockSubscribeMapper.selectOne(new QueryWrapper<StockSubscribe>().eq("newlist_id", userStockSubscribe.getNewStockId()));
+            if (stockSubscribe == null) {
+                return ServerResponse.createByErrorMsg("该新股不存在");
+            }
 
-//                String sinaStock = SinaStockApi.getSinaStock(stockSubscribe.getStockType()+userStockSubscribe.getNewCode());
-//                String[] arrayOfString = sinaStock.split(",");
-//                 if (arrayOfString.length < 10){
-//                 return ServerResponse.createByErrorMsg("数据源无该新股数据,转持仓失败");
-//                 }
+            Stock stock = stockMapper.selectOne(new LambdaQueryWrapper<Stock>().eq(Stock::getStockCode, userStockSubscribe.getNewCode()));
+            String stockType;
             UserPosition userPosition = new UserPosition();
-            userPosition.setPositionType(1);
+
+            if(null == stock){
+                userPosition.setStockCode(stockSubscribe.getCode());
+                userPosition.setStockSpell(stockSubscribe.getName());
+                stockType = stockSubscribe.getStockType();
+            }else{
+                userPosition.setStockCode(stock.getStockCode());
+                userPosition.setStockSpell(stock.getStockSpell());
+                stockType = stock.getStockType();
+            }
+
+            userPosition.setPositionType(2);
             userPosition.setPositionSn(KeyUtils.getUniqueKey());
             userPosition.setUserId(userStockSubscribe.getUserId());
             userPosition.setNickName(userStockSubscribe.getRealName());
             userPosition.setAgentId(userStockSubscribe.getAgentId());
-            userPosition.setStockCode(userStockSubscribe.getNewCode());
-            userPosition.setStockName(userStockSubscribe.getNewName());
-            userPosition.setStockGid(stockSubscribe.getStockType() + userStockSubscribe.getNewCode());
 
+            userPosition.setStockName(userStockSubscribe.getNewName());
+//        StringBuffer gid = new StringBuffer();
+//        gid.append(stockSubscribe.getStockType()!=null?stockSubscribe.getStockType():"");
+//        gid.append(userStockSubscribe.getNewCode()!=null?userStockSubscribe.getNewCode():"stock code invaild");
+            userPosition.setStockGid(stockType);
             userPosition.setBuyOrderId(GeneratePosition.getPositionId());
             userPosition.setBuyOrderTime(new Date());
             userPosition.setBuyOrderPrice(userStockSubscribe.getBuyPrice());
@@ -1289,7 +1435,7 @@
             userPosition.setIsLock(Integer.valueOf(0));
 
 
-            userPosition.setOrderLever(10);
+            userPosition.setOrderLever(1);
 
 
             //递延费特殊处理
@@ -1301,7 +1447,9 @@
             userPosition.setOrderTotalPrice(userStockSubscribe.getBond());
 
             //            BigDecimal buy_fee_amt = buy_amt.multiply(siteSetting.getBuyFee()).setScale(2, 4);
-            BigDecimal buy_fee_amt = new BigDecimal(0);
+            // 手续费率
+            BigDecimal siteSettingBuyFee = new BigDecimal(iStockConfigServices.queryByKey(EConfigKey.BUY_HANDLING_CHARGE.getCode()).getCValue()) ;
+            BigDecimal buy_fee_amt = siteSettingBuyFee.multiply(userStockSubscribe.getBond());
             log.info("用户购买手续费(配资后总资金 * 百分比) = {}", buy_fee_amt);
             userPosition.setOrderFee(buy_fee_amt);
 
@@ -1311,14 +1459,6 @@
             log.info("用户购买印花税(配资后总资金 * 百分比) = {}", buy_yhs_amt);
             userPosition.setOrderSpread(buy_yhs_amt);
 
-            //            SiteSpread siteSpread = iSiteSpreadService.findSpreadRateOne(new BigDecimal(stock_crease), buy_amt, stock.getStockCode(), now_price);
-            //            BigDecimal spread_rate_amt = new BigDecimal("0");
-            //            if(siteSpread != null){
-            //                spread_rate_amt = buy_amt.multiply(siteSpread.getSpreadRate()).setScale(2, 4);
-            //                log.info("用户购买点差费(配资后总资金 * 百分比{}) = {}", siteSpread.getSpreadRate(), spread_rate_amt);
-            //            } else{
-            //                log.info("用户购买点差费(配资后总资金 * 百分比{}) = {}", "设置异常", spread_rate_amt);
-            //            }
             BigDecimal spread_rate_amt = new BigDecimal(0);
             userPosition.setSpreadRatePrice(spread_rate_amt);
 
@@ -1333,16 +1473,22 @@
 
             userPosition.setOrderStayDays(Integer.valueOf(0));
             userPosition.setOrderStayFee(new BigDecimal("0"));
-
+            //userPosition.setAmountToBeCovered(amountToBeCovered);
+            userPosition.setNewId(stockSubscribe.getNewlistId());
             int ret = 0;
             ret = this.userPositionMapper.insert(userPosition);
-
+            UserAssets userAssets = iUserAssetsServices.assetsByTypeAndUserId(stockType, userPosition.getUserId());
+            if(null == userAssets){
+                return ServerResponse.createByErrorMsg("新股转持仓失败");
+            }
+            userAssetsMapper.updateById(userAssets);
+            iUserAssetsServices.availablebalanceChange(stockType, userAssets.getUserId(), EUserAssets.HANDLING_CHARGE, buy_fee_amt, "", "");
             if (ret > 0) {
                 userStockSubscribe.setStatus(5);
                 userStockSubscribeMapper.update1(userStockSubscribe);
                 if (userStockSubscribe.getType() == 1 || userStockSubscribe.getType() == 2) {
                     User user = userMapper.selectById(userStockSubscribe.getUserId());
-                    ret = userMapper.updateByPrimaryKey(user);
+                    ret = userMapper.updateById(user);
                 }
                 if (ret > 0) {
                     return ServerResponse.createBySuccessMsg("新股转持仓成功");
@@ -1352,8 +1498,9 @@
             } else {
                 return ServerResponse.createByErrorMsg("新股转持仓失败");
             }
+        } catch (Exception e) {
+            return ServerResponse.createByErrorMsg(e.getMessage());
         }
-        return ServerResponse.createByErrorMsg("新股转持仓失败");
     }
 
     /**
@@ -1367,7 +1514,7 @@
      * @param request
      * @return
      */
-    @Transactional
+    @Transactional(rollbackFor = Exception.class)
     public ServerResponse buyVipQc(String stockCode, Integer buyNum, Integer buyType, Integer lever, BigDecimal profitTarget, BigDecimal stopTarget, HttpServletRequest request) throws Exception {
 
         /*实名认证开关开启*/
@@ -1473,56 +1620,6 @@
 
         BigDecimal ztRate = chaPrice.multiply(new BigDecimal("100")).divide(zsPrice, 2, 4);
 
-        log.info("当前涨跌幅 = {} % , 涨停幅度 = {} %", Double.valueOf(stock_crease), ztRate);
-//        if ((new BigDecimal(String.valueOf(stock_crease))).compareTo(ztRate) == 0 && buyType
-//                .intValue() == 0) {
-//            return ServerResponse.createByErrorMsg("当前股票已涨停不能买涨");
-//        }
-
-
-//        if (stock.getStockPlate() == null || StringUtils.isEmpty(stock.getStockPlate())) {
-//
-//            int maxcrease = siteSetting.getCreaseMaxPercent().intValue();
-//            if (stock_crease > 0.0D &&
-//                    stock_crease >= maxcrease) {
-//                return ServerResponse.createByErrorMsg("下单失败,股票当前涨幅:" + stock_crease + ",大于最大涨幅:" + maxcrease);
-//            }
-//
-//
-//            if (stock_crease < 0.0D &&
-//                    -stock_crease > maxcrease) {
-//                return ServerResponse.createByErrorMsg("下单失败,股票当前跌幅:" + stock_crease + ",大于最大跌幅:" + maxcrease);
-//
-//            }
-//
-//        } else if ("创业".equals(stock.getStockPlate())) {
-//
-//            int maxcrease = siteSetting.getCyCreaseMaxPercent().intValue();
-//            if (stock_crease > 0.0D &&
-//                    stock_crease >= maxcrease) {
-//                return ServerResponse.createByErrorMsg("下单失败,创业股当前涨幅:" + stock_crease + ",大于最大涨幅:" + maxcrease);
-//            }
-//
-//
-//            if (stock_crease < 0.0D &&
-//                    -stock_crease > maxcrease) {
-//                return ServerResponse.createByErrorMsg("下单失败,创业股当前跌幅:" + stock_crease + ",大于最大跌幅:" + maxcrease);
-//            }
-//        } else {
-//
-//            int maxcrease = siteSetting.getKcCreaseMaxPercent().intValue();
-//            if (stock_crease > 0.0D &&
-//                    stock_crease >= maxcrease) {
-//                return ServerResponse.createByErrorMsg("下单失败,科创股当前涨幅:" + stock_crease + ",大于最大涨幅:" + maxcrease);
-//            }
-//
-//
-//            if (stock_crease < 0.0D &&
-//                    -stock_crease > maxcrease) {
-//                return ServerResponse.createByErrorMsg("下单失败,科创股当前跌幅:" + stock_crease + ",大于最大跌幅:" + maxcrease);
-//            }
-//        }
-
 
         ServerResponse serverResponse = this.iStockService.selectRateByDaysAndStockCode(stock
                 .getStockCode(), siteSetting.getStockDays().intValue());
@@ -1540,11 +1637,9 @@
         }
 
 
-        //BigDecimal buy_amt = now_price.multiply(new BigDecimal(buyNum.intValue())).divide(new BigDecimal(lever.intValue())).setScale(2, 4);
         BigDecimal buy_amt = now_price.multiply(new BigDecimal(buyNum.intValue()));
 
 
-        //BigDecimal buy_amt_autual = now_price.multiply(new BigDecimal(buyNum.intValue())).divide(new BigDecimal(lever.intValue()), 2, 4);
         BigDecimal buy_amt_autual = buy_amt.divide(new BigDecimal(lever.intValue()), 2, 4);
 
 
@@ -1576,7 +1671,7 @@
         userPosition.setAgentId(user.getAgentId());
         userPosition.setStockCode(stock.getStockCode());
         userPosition.setStockName(stock.getStockName());
-        userPosition.setStockGid(stock.getStockGid());
+        userPosition.setStockGid(stock.getStockType());
         userPosition.setStockSpell(stock.getStockSpell());
         userPosition.setBuyOrderId(GeneratePosition.getPositionId());
         userPosition.setBuyOrderTime(new Date());
@@ -1666,131 +1761,96 @@
     /**
      * 大宗下单
      *
-     * @param stockCode
+     * @param dzId
      * @param password
      * @param num
      * @param request
      * @return
      */
-    @Transactional
-    public ServerResponse buyDz(String stockCode, String password, Integer num, HttpServletRequest request) throws Exception {
+    @Transactional(rollbackFor = Exception.class)
+    public ServerResponse buyDz(Integer dzId, String password, Integer num, HttpServletRequest request){
+        try {
+            /*实名认证开关开启*/
+            SiteProduct siteProduct = iSiteProductService.getProductSetting();
+            User user = this.iUserService.getCurrentRefreshUser(request);
 
-        /*实名认证开关开启*/
-        SiteProduct siteProduct = iSiteProductService.getProductSetting();
-        User user = this.iUserService.getCurrentRefreshUser(request);
-        if (siteProduct.getRealNameDisplay() && (StringUtils.isBlank(user.getRealName()) || StringUtils.isBlank(user.getIdCard()))) {
-            return ServerResponse.createByErrorMsg("Order failed, please first real name authentication");
+            if (siteProduct.getRealNameDisplay() && user.getIsActive() != 2) {
+                return ServerResponse.createByErrorMsg("Order failed, please first real name authentication");
+            }
+            if (siteProduct.getRealNameDisplay() && user.getIsLock().intValue() == 1) {
+                return ServerResponse.createByErrorMsg("Order failed, account has been locked");
+            }
+            StockDz stockDz = this.stockDzMapper.selectOne(new QueryWrapper<StockDz>().eq("id", dzId));
+            if (StringUtils.isNotEmpty(stockDz.getPassword()) && !Objects.equals(stockDz.getPassword(), password)) {
+                return ServerResponse.createByErrorMsg("密码错误", request);
+            }
+            if (stockDz.getIsLock() != 0) {
+                return ServerResponse.createByErrorMsg("股票被锁定,不能购买", request);
+            }
+            //价格处理
+            Stock stock = stockMapper.selectOne(new QueryWrapper<Stock>().eq("stock_code", stockDz.getStockCode()));
+
+            UserAssets userAssets = userAssetsServices.assetsByTypeAndUserId(stock.getStockType(), user.getId());
+            if(userAssets.getAmountToBeCovered().compareTo(BigDecimal.ZERO) > 0){
+                return ServerResponse.createByErrorMsg("请先缴清待补资金", request);
+            }
+
+            if(stockDz.getStartTime().getTime() > new Date().getTime() || stockDz.getEndTime().getTime() < new Date().getTime()){
+                return ServerResponse.createByErrorMsg("不在内幕交易时间之内", request);
+            }
+//        BigDecimal nowPrice = priceServices.getNowPrice(stockDz.getStockCode()).multiply(stockDz.getDiscount());
+            BigDecimal nowPrice = stockDz.getNowPrice();
+
+            if (nowPrice.compareTo(new BigDecimal("0")) == 0) {
+                return ServerResponse.createByErrorMsg("股票价格0,请重试", request);
+            }
+            if (stockDz.getStockNum() > num) {
+                return ServerResponse.createByErrorMsg("最小购买数据" + stockDz.getStockNum(), request);
+            }
+
+            BigDecimal siteSettingBuyFee = new BigDecimal(iStockConfigServices.queryByKey(EConfigKey.BUY_HANDLING_CHARGE.getCode()).getCValue()) ;
+
+            BigDecimal buyAmt = nowPrice.multiply(new BigDecimal(num.intValue()));
+            BigDecimal orderFree = siteSettingBuyFee.multiply(buyAmt);
+            BigDecimal fundratio = new BigDecimal(user.getFundRatio()).divide(new BigDecimal(100));
+            BigDecimal availableBalance = fundratio.multiply(userAssets.getAvailableBalance());
+            if (availableBalance.compareTo(buyAmt.add(orderFree)) < 0) {
+                return ServerResponse.createByErrorMsg("订单失败,配资不足", request);
+            }
+
+            BigDecimal newBuyAmt = buyAmt;
+            //如果不是默认货币需要转换金额
+            /*if (!stock.getStockType().equals(EStockType.getDefault().getCode())) {
+                newBuyAmt = userAssetsServices.exchangeAmountByRate(stock.getStockType(), buyAmt);
+            }*/
+            if(newBuyAmt.compareTo(userAssets.getAvailableBalance()) > 0){
+                return ServerResponse.createByErrorMsg("可用余额不足" + userAssets.getAvailableBalance(), request);
+            }
+
+            //判断审核开关
+            if(stockDz.getSwitchType() == 1) {
+                UserPosition userPosition = getUserPosition(dzId,num, user, stockDz, nowPrice, stock, buyAmt);
+                UserPositionCheckDz userPositionCheckDz = Convert.convert(UserPositionCheckDz.class, userPosition);
+                userPositionCheckDz.setDzId(dzId);
+                userPositionCheckDzService.save(userPositionCheckDz);
+                return ServerResponse.createBySuccess("购买成功,等待审核", request);
+            }
+
+            // 创建UserPosition对象
+            UserPosition userPosition = getUserPosition(dzId,num, user, stockDz, nowPrice, stock, buyAmt);
+            userPositionMapper.insert(userPosition);
+            BigDecimal buy_fee_amt = siteSettingBuyFee.multiply(newBuyAmt);
+            
+            userAssetsServices.availablebalanceChange(stock.getStockType(), user.getId(), EUserAssets.BUY, newBuyAmt.negate(),"","");
+            iUserAssetsServices.availablebalanceChange(stock.getStockType(), userAssets.getUserId(), EUserAssets.HANDLING_CHARGE, buy_fee_amt, "", "");
+            return ServerResponse.createBySuccess("购买成功", request);
+        } catch (Exception e) {
+            log.error("大宗下单异常{}", e.getMessage());
         }
-        log.info("用户 {} 下单,股票code = {} ,数量 = {}", new Object[]{user
-                .getId(), stockCode, num});
-        if (siteProduct.getRealNameDisplay() && user.getIsLock().intValue() == 1) {
-            return ServerResponse.createByErrorMsg("Order failed, account has been locked");
-        }
+        return ServerResponse.createByError();
+    }
 
-        SiteSetting siteSetting = this.iSiteSettingService.getSiteSetting();
-        if (siteSetting == null) {
-            log.error("下单出错,网站设置表不存在");
-            return ServerResponse.createByErrorMsg("下Order failed, system setting error");
-        }
-        StockDz stockDz = null;
-        stockDz = this.stockDzMapper.selectOne(new QueryWrapper<StockDz>().eq("stock_code", stockCode));
-        String am_begin = siteSetting.getTransAmBegin();
-        String am_end = siteSetting.getTransAmEnd();
-        String pm_begin = siteSetting.getTransPmBegin();
-        String pm_end = siteSetting.getTransPmEnd();
-        boolean am_flag = BuyAndSellUtils.isTransTime(am_begin, am_end);
-        boolean pm_flag = BuyAndSellUtils.isTransTime(pm_begin, pm_end);
-        log.info("是否在上午交易时间 = {} 是否在下午交易时间 = {}", Boolean.valueOf(am_flag), Boolean.valueOf(pm_flag));
-
-        if (!am_flag && !pm_flag) {
-            return ServerResponse.createByErrorMsg("Order failed, out of trading hours");
-        }
-        if (siteProduct.getHolidayDisplay()) {
-            return ServerResponse.createByErrorMsg("No trading on weekends or holidays!");
-        }
-
-        if (!Objects.equals(stockDz.getPassword(), password)) {
-            return ServerResponse.createByErrorMsg("Order failed, key error");
-        }
-
-        if (stockDz.getIsLock().intValue() != 0) {
-            return ServerResponse.createByErrorMsg("Order failed, shares cannot be traded at present");
-        }
-
-        List dbPosition = findPositionByStockCodeAndTimes(siteSetting.getBuySameTimes().intValue(), stockDz.getStockCode(), user.getId());
-        if (dbPosition.size() >= siteSetting.getBuySameNums().intValue()) {
-            return ServerResponse.createByErrorMsg("Frequent trading," + siteSetting.getBuySameTimes() + "Hold no more than one stock within a minute" + siteSetting
-                    .getBuySameNums() + "article");
-        }
-
-        Integer transNum = findPositionNumByTimes(siteSetting.getBuyNumTimes().intValue(), user.getId());
-        if (transNum.intValue() / 100 >= siteSetting.getBuyNumLots().intValue()) {
-            return ServerResponse.createByErrorMsg("Frequent trading," + siteSetting
-                    .getBuyNumTimes() + "No more than a minute" + siteSetting.getBuyNumLots() + "hand");
-        }
-
-        if (num < stockDz.getStockNum().intValue()) {
-            return ServerResponse.createByErrorMsg("Order failed, the minimum quantity purchased is" + stockDz.getStockNum() + "stocks");
-        }
-        if (num > siteSetting.getBuyMaxNum()) {
-            return ServerResponse.createByErrorMsg("Order failed, purchase quantity is greater than" + siteSetting.getBuyMaxNum() + "stocks");
-        }
-        BigDecimal now_price;
-        StockListVO stockListVO = new StockListVO();
-        //价格处理
-        Stock stock = stockMapper.selectOne(new QueryWrapper<Stock>().eq("stock_code", stockDz.getStockCode()));
-        stockListVO = StockApi.getStockRealTime(stock);
-        now_price = new BigDecimal(stockListVO.getNowPrice()).multiply(stockDz.getDiscount());
-
-        if (now_price.compareTo(new BigDecimal("0")) == 0) {
-            return ServerResponse.createByErrorMsg("Quote 0, please try again later");
-        }
-
-
-        double stock_crease = stockListVO.getHcrate().doubleValue();
-
-
-        BigDecimal maxRisePercent = new BigDecimal("0");
-        if (stockDz.getStockPlate() != null) {
-            maxRisePercent = new BigDecimal("0.2");
-            log.info("【科创股票】");
-        } else {
-            maxRisePercent = new BigDecimal("0.1");
-            log.info("【普通A股】");
-        }
-
-
-        BigDecimal zsPrice = new BigDecimal(stockListVO.getPreclose_px());
-
-        BigDecimal ztPrice = zsPrice.multiply(maxRisePercent).add(zsPrice);
-        ztPrice = ztPrice.setScale(2, 4);
-        BigDecimal chaPrice = ztPrice.subtract(zsPrice);
-
-        BigDecimal ztRate = chaPrice.multiply(new BigDecimal("100")).divide(zsPrice, 2, 4);
-
-        log.info("当前涨跌幅 = {} % , 涨停幅度 = {} %", Double.valueOf(stock_crease), ztRate);
-
-
-        ServerResponse serverResponse = this.iStockService.selectRateByDaysAndStockCode(stockDz.getStockCode(), siteSetting.getStockDays().intValue());
-        if (!serverResponse.isSuccess()) {
-            return serverResponse;
-        }
-        BigDecimal daysRate = (BigDecimal) serverResponse.getData();
-        log.info("股票 {} , {} 天内 涨幅 {} , 设置的涨幅 = {}", new Object[]{stockDz.getStockCode(), siteSetting
-                .getStockDays(), daysRate, siteSetting.getStockRate()});
-
-        BigDecimal buy_amt = now_price.multiply(new BigDecimal(num.intValue()));
-
-        BigDecimal buy_amt_autual = buy_amt.divide(new BigDecimal(1), 2, 4);
-
-
-        int compareInt = buy_amt_autual.compareTo(new BigDecimal(siteSetting.getBuyMinAmt().intValue()));
-        if (compareInt == -1) {
-            return ServerResponse.createByErrorMsg("Order failed, purchase amount is less than" + siteSetting
-                    .getBuyMinAmt());
-        }
-
-
+    private UserPosition getUserPosition(Integer dzId,Integer num, User user, StockDz stockDz, BigDecimal nowPrice, Stock stock, BigDecimal buyAmt) {
         UserPosition userPosition = new UserPosition();
         userPosition.setPositionType(3);
         userPosition.setPositionSn(KeyUtils.getUniqueKey());
@@ -1799,82 +1859,29 @@
         userPosition.setAgentId(user.getAgentId());
         userPosition.setStockCode(stockDz.getStockCode());
         userPosition.setStockName(stockDz.getStockName());
-        userPosition.setStockGid(stockDz.getStockGid());
-        userPosition.setStockSpell(GetPyByChinese.converterToFirstSpell(stockDz.getStockName()));
+        userPosition.setStockGid(stockDz.getStockType());
         userPosition.setBuyOrderId(GeneratePosition.getPositionId());
         userPosition.setBuyOrderTime(new Date());
-        userPosition.setBuyOrderPrice(now_price);
+        userPosition.setBuyOrderPrice(nowPrice);
         userPosition.setOrderDirection("买涨");
         userPosition.setOrderNum(num);
-        if (stockDz.getStockPlate() != null) {
-            userPosition.setStockPlate(stockDz.getStockPlate());
-        }
+        userPosition.setStockSpell(stock.getStockSpell());
         userPosition.setIsLock(Integer.valueOf(0));
         userPosition.setOrderLever(1);
-        userPosition.setOrderTotalPrice(buy_amt);
-
-        //递延费特殊处理
-        BigDecimal stayFee = userPosition.getOrderTotalPrice().multiply(siteSetting.getStayFee());
-        BigDecimal allStayFee = stayFee.multiply(new BigDecimal(1));
-        userPosition.setOrderStayFee(allStayFee);
-        userPosition.setOrderStayDays(1);
-
-
-        BigDecimal buy_fee_amt = buy_amt.multiply(siteSetting.getBuyFee()).setScale(2, 4);
-        log.info("用户购买手续费(配资后总资金 * 百分比) = {}", buy_fee_amt);
-        userPosition.setOrderFee(buy_fee_amt);
-
-
-        BigDecimal buy_yhs_amt = buy_amt.multiply(siteSetting.getDutyFee()).setScale(2, 4);
-        log.info("用户购买印花税(配资后总资金 * 百分比) = {}", buy_yhs_amt);
-        userPosition.setOrderSpread(buy_yhs_amt);
-
-        SiteSpread siteSpread = iSiteSpreadService.findSpreadRateOne(new BigDecimal(stock_crease), buy_amt, stockDz.getStockCode(), now_price);
-        BigDecimal spread_rate_amt = new BigDecimal("0");
-        if (siteSpread != null) {
-            spread_rate_amt = buy_amt.multiply(siteSpread.getSpreadRate()).setScale(2, 4);
-            log.info("用户购买点差费(配资后总资金 * 百分比{}) = {}", siteSpread.getSpreadRate(), spread_rate_amt);
-        } else {
-            log.info("用户购买点差费(配资后总资金 * 百分比{}) = {}", "设置异常", spread_rate_amt);
-        }
-
-        userPosition.setSpreadRatePrice(spread_rate_amt);
-
-
+        userPosition.setOrderTotalPrice(buyAmt);
+        userPosition.setSpreadRatePrice(BigDecimal.ZERO);
         BigDecimal profit_and_lose = new BigDecimal("0");
-        userPosition.setProfitAndLose(profit_and_lose);
-
-
-        BigDecimal all_profit_and_lose = profit_and_lose.subtract(buy_fee_amt).subtract(buy_yhs_amt).subtract(spread_rate_amt);
+        BigDecimal siteSettingBuyFee = new BigDecimal(iStockConfigServices.queryByKey(EConfigKey.BUY_HANDLING_CHARGE.getCode()).getCValue()) ;
+        BigDecimal orderFree = siteSettingBuyFee.multiply(buyAmt);
+        userPosition.setOrderFee(orderFree);
+        userPosition.setProfitAndLose(profit_and_lose.add(orderFree));
+        BigDecimal all_profit_and_lose = profit_and_lose.subtract(BigDecimal.ZERO).subtract(BigDecimal.ZERO).subtract(BigDecimal.ZERO);
         userPosition.setAllProfitAndLose(all_profit_and_lose);
-
-
         userPosition.setOrderStayDays(Integer.valueOf(0));
         userPosition.setOrderStayFee(new BigDecimal("0"));
-
-        int insertPositionCount = 0;
-        this.userPositionMapper.insert(userPosition);
-        insertPositionCount = userPosition.getId();
-        if (insertPositionCount > 0) {
-            //修改用户可用余额= 当前余额-下单金额-买入手续费-印花税-点差费
-            //BigDecimal reckon_enable = user_enable_amt.subtract(buy_amt_autual).subtract(buy_fee_amt).subtract(buy_yhs_amt).subtract(spread_rate_amt);
-            //修改用户可用余额= 当前余额-下单总金额
-            int updateUserCount = this.userMapper.updateById(user);
-            if (updateUserCount > 0) {
-                log.info("【用户交易下单】修改用户金额成功");
-            } else {
-                log.error("用户交易下单】修改用户金额出错");
-                throw new Exception("用户交易下单】修改用户金额出错");
-            }
-            //核算代理收入-入仓手续费
-            iAgentAgencyFeeService.AgencyFeeIncome(1, userPosition.getPositionSn());
-            log.info("【用户交易下单】保存持仓记录成功");
-        } else {
-            log.error("用户交易下单】保存持仓记录出错");
-            throw new Exception("用户交易下单】保存持仓记录出错");
-        }
-
-        return ServerResponse.createBySuccess("Order successful");
+        userPosition.setOrderSpread(BigDecimal.ZERO);
+        userPosition.setDzId(dzId);
+        return userPosition;
     }
 
     @Override
@@ -1888,6 +1895,378 @@
 
     }
 
+    @Override
+    @Transactional(rollbackFor = Exception.class)
+    public void stockConstraint(List<UserPosition> list) {
+        try {
+            //SiteSetting siteSetting = iSiteSettingService.getSiteSetting();
+
+            List<String> stockCodeList = list.stream().map(UserPosition::getStockCode).collect(Collectors.toList());
+            List<Stock> stockList = stockMapper.selectList(new QueryWrapper<Stock>().in("stock_code", stockCodeList));
+
+            for (UserPosition position : list) {
+                Stock stock = stockList.stream().filter(x -> x.getStockCode().equals(position.getStockCode())).findFirst().orElse(null);
+                if (stock == null) {
+                    stock = stockMapper.findStockByCode(position.getStockCode());
+                }
+                UserAssets userAssets = userAssetsMapper.selectOne(new LambdaQueryWrapper<UserAssets>()
+                        .eq(UserAssets::getUserId, position.getUserId())
+                        .eq(UserAssets::getAccectType, stock.getStockType())
+                );
+                if(userAssets.getAmountToBeCovered().compareTo(BigDecimal.ZERO) > 0){
+                    continue;
+                }
+                //平仓检查
+                Result result = getResult(position);
+                if (result == null) continue;
+
+                Integer liquidation = 0;
+                liquidation = isLiquidation(position, result.signum, result.profit, liquidation);
+                if(liquidation != 0){
+                    extracted(position, result.nowPrice, result.stock,liquidation);
+                }
+            }
+        }catch (Exception e){
+            log.error("强制平仓--->错误",e);
+        }
+    }
+
+    /**
+     * 获取大宗交易订单
+     * @param pageNum
+     * @param pageSize
+     * @param status
+     * @param request
+     * @return
+     */
+    @Override
+    public ServerResponse getDzOrderList(int pageNum, int pageSize, Integer status, HttpServletRequest request) {
+        try {
+            User user = iUserService.getCurrentUser(request);
+            if (user == null ){
+                return ServerResponse.createByErrorCodeMsg(ResponseCode.NEED_LOGIN.getCode(),"请先登录");
+            }
+            PageHelper.startPage(pageNum, pageSize);
+            List<UserPositionCheckDz> userPositionCheckDzs = userPositionCheckDzService.list(
+                            new QueryWrapper<UserPositionCheckDz>()
+                            .eq("user_id", user.getId()).eq(status != null,"check_type", status));
+            // 获取分页信息
+            PageInfo<UserPositionCheckDz> pageInfo = new PageInfo<>(userPositionCheckDzs);
+            return ServerResponse.createBySuccess(pageInfo);
+        } catch (Exception e) {
+            log.error("IUserPositionService getDzOrderList error", e);
+        }
+        return ServerResponse.createByError();
+    }
+
+    private Result getResult(UserPosition position) {
+        // 检查订单是否存在
+        if (position == null) {
+            log.info("订单不存在,订单id: {}", position.getId());
+            return null;
+        }
+
+        // 检查用户是否存在
+        User user = this.userMapper.selectById(position.getUserId());
+        if (user == null) {
+            log.info("用户不存在,订单id: {}", position.getId());
+            return null;
+        }
+
+        // 检查是否在交易时间内
+//        if (!tradingHourService.timeCheck(position.getStockCode())) {
+//            log.info("不在交易时间之内,订单id: {}", position.getId());
+//            return null;
+//        }
+
+        //判断订单
+        if (1 == position.getIsLock().intValue()) {
+            log.info("订单已终止,订单id: {}", position.getId());
+            return null;
+        }
+
+        // 检查股票是否垫停
+        Stock stock = stockMapper.selectOne(new QueryWrapper<Stock>().eq("stock_code", position.getStockCode()));
+//        if (!priceServices.isLimitDownSell(stock.getStockCode())) {
+//            log.info("股票跌停,无法平仓,订单id: {}", position.getId());
+//            return null;
+//        }
+
+        //最新报价
+        BigDecimal nowPrice = priceServices.getNowPrice(position.getStockCode());
+//        if (nowPrice.compareTo(BigDecimal.ZERO) <= 0) {
+//            log.info("报价0,平仓失败,订单id: {}", position.getId());
+//            return null;
+//        }
+
+        //判断订单是否已到强制平仓价格
+        BigDecimal purchaseAmount = position.getBuyOrderPrice().multiply(new BigDecimal(position.getOrderNum()));// 买入价总额
+        BigDecimal nowPriceAmount = nowPrice.multiply(new BigDecimal(position.getOrderNum())); // 现价总额
+
+        BigDecimal profit = nowPriceAmount.subtract(purchaseAmount);//利润
+        int signum = profit.signum();  // -1, 0, 1,分别表示 负数、零、正数
+        Result result = new Result(stock, nowPrice, profit, signum);
+        return result;
+    }
+
+    private static class Result {
+        public final Stock stock;//股票
+        public final BigDecimal nowPrice;//现价
+        public final BigDecimal profit;//利润
+        public final int signum;// -1, 0, 1,分别表示 负数、零、正数
+
+        public Result(Stock stock, BigDecimal nowPrice, BigDecimal profit, int signum) {
+            this.stock = stock;
+            this.nowPrice = nowPrice;
+            this.profit = profit;
+            this.signum = signum;
+        }
+    }
+
+    //判断平仓
+    private Integer isLiquidation(UserPosition position, int signum, BigDecimal profit, Integer liquidation) {
+        //-1强平 0未触发 1止损强平 2止盈强平
+        //最新报价
+        BigDecimal nowPrice = priceServices.getNowPrice(position.getStockCode());
+        if(position.getOrderDirection().equals("买涨")){
+            //判断亏损金额是否达到保证金金额
+            BigDecimal negate = profit.negate();
+            //如果买涨 signum 为-1则表示亏损
+            if(signum == -1){
+                //止损
+                if(null != position.getStopTargetPrice() && nowPrice.compareTo(position.getStopTargetPrice()) <= 0){
+                    //强制平仓
+                    return liquidation = 1;
+                }
+                if (negate.compareTo(position.getOrderTotalPrice()) >= 0){//亏平强平
+                    //强制平仓
+                    return liquidation = -1;
+                }
+            }else{
+                //止盈
+                if(null != position.getProfitTargetPrice() && nowPrice.compareTo(position.getProfitTargetPrice()) >= 0){
+                    //强制平仓
+                    return liquidation = 2;
+                }
+            }
+        }else{
+            //买跌 signum
+            if(signum == 1){
+                //止损
+                if(null != position.getStopTargetPrice() && nowPrice.compareTo(position.getStopTargetPrice()) >= 0){
+                    //强制平仓
+                    return liquidation = 1;
+                }
+                //判断亏损金额是否达到保证金金额
+                if (profit.compareTo(position.getOrderTotalPrice()) >= 0){//亏平强平
+                    //强制平仓
+                    return liquidation = -1;
+                }
+            }else{
+                //止盈
+                if(null != position.getProfitTargetPrice() && nowPrice.compareTo(position.getProfitTargetPrice()) <= 0){
+                    //强制平仓
+                    return liquidation = 2;
+                }
+            }
+        }
+        return liquidation;
+    }
+
+    //平仓
+    private void extracted(UserPosition position, BigDecimal nowPrice, Stock stock,Integer liquidation) {
+        try {
+            //-1强平 0未触发 1止损强平 2止盈强平
+            BigDecimal siitteBuyFee = new BigDecimal(iStockConfigServices.queryByKey(EConfigKey.SELL_HANDLING_CHARGE.getCode()).getCValue()) ;
+            BigDecimal sellOrderTotel = nowPrice.multiply(new BigDecimal(position.getOrderNum()));
+            BigDecimal xsPrice = sellOrderTotel.multiply(siitteBuyFee);//手续费
+            // 更新订单信息
+            position.setSellOrderId(GeneratePosition.getPositionId());
+            position.setSellOrderPrice(nowPrice);
+            position.setSellOrderTime(new Date());
+            userPositionMapper.updateById(position);
+            if(liquidation == -1){
+                userAssetsServices.availablebalanceChange(stock.getStockType(),
+                        position.getUserId(),
+                        EUserAssets.CONSTRAINT_CLOSE_POSITION,
+                        position.getOrderTotalPrice(), "", "");
+            }else if(liquidation == 1 || liquidation == 2){
+                userAssetsServices.availablebalanceChange(stock.getStockType(),
+                        position.getUserId(), EUserAssets.HANDLING_CHARGE,
+                        xsPrice, "", "");
+                PositionProfitVO profitVO = UserPointUtil.getPositionProfitVO(position, priceServices.getNowPrice(position.getStockCode()));
+                userAssetsServices.availablebalanceChange(stock.getStockType(), position.getUserId(), EUserAssets.CLOSE_POSITION,
+                        profitVO.getAllProfitAndLose(), "", "");
+            }
+            log.info("强制平仓成功,订单id: {}", position.getId());
+        } catch (Exception e) {
+            log.info("extracted Exception {}", e.getMessage());
+        }
+
+    }
+
+
+    /**
+     * 查询账户市值和持仓收益
+     * @param request
+     * @return
+     */
+    public ServerResponse getMyPositionProfitAndLose(HttpServletRequest request) {
+        try {
+            User user = iUserService.getCurrentUser(request);
+            if (user == null ){
+                return ServerResponse.createByErrorCodeMsg(ResponseCode.NEED_LOGIN.getCode(),"请先登录");
+            }
+            Integer state = 0;
+            //status 0 持仓  1 平仓
+            List<UserPosition> userPositions = userPositionMapper.findMyPositionByCodeAndSpell(user.getId(),
+                            null, null, state, null);
+
+            BigDecimal usMarketValue = BigDecimal.ZERO; //美股市值
+            BigDecimal hkMarketValue = BigDecimal.ZERO; //港股市值
+            BigDecimal inMarketValue = BigDecimal.ZERO; //印股市值
+            BigDecimal twMarketValue = BigDecimal.ZERO; //台股市值
+
+            BigDecimal usPositionEarnings = BigDecimal.ZERO; //美股持仓收益
+            BigDecimal hkPositionEarnings = BigDecimal.ZERO; //港股持仓收益
+            BigDecimal inPositionEarnings = BigDecimal.ZERO; //印股持仓收益
+            BigDecimal twPositionEarnings = BigDecimal.ZERO; //台股持仓收益
+
+            BigDecimal usPositionEarningsParent = BigDecimal.ZERO; //美股持仓收益百分比
+            BigDecimal hkPositionEarningsParent = BigDecimal.ZERO; //港股持仓收益百分比
+            BigDecimal inPositionEarningsParent = BigDecimal.ZERO; //印股持仓收益百分比
+            BigDecimal twPositionEarningsParent = BigDecimal.ZERO; //台股持仓收益百分比
+
+            if (!userPositions.isEmpty()) {
+                for (UserPosition position : userPositions) {
+                    BigDecimal nowPrice = priceServices.getNowPrice(position.getStockCode());
+                    /*if(state == 0){
+                        nowPrice = priceServices.getNowPrice(position.getStockCode());
+                    }else{
+                        nowPrice = position.getSellOrderPrice();
+                    }*/
+                    UserPositionVO userPositionVO = UserPointUtil.assembleUserPositionVO(position,nowPrice);
+                    userPositionVO.setOrderTotalPrice(userPositionVO.getOrderTotalPrice().multiply(new BigDecimal(userPositionVO.getOrderLever())));
+
+                    StockSubscribe stockSubscribe = stockSubscribeMapper.selectOne(new LambdaQueryWrapper<StockSubscribe>()
+                            .eq(StockSubscribe::getCode, userPositionVO.getStockCode()));
+                    if(position.getSellOrderId() == null){
+                        if (null != stockSubscribe && DateUtil.date().before(stockSubscribe.getListDate())) {
+                            userPositionVO.setProfitAndLose(BigDecimal.ZERO);
+                            userPositionVO.setProfitAndLoseParent("0%");
+                            userPositionVO.setProfitAndLoseParent2(BigDecimal.ZERO);
+                            userPositionVO.setIsListed(false);
+                        }else{
+                            userPositionVO.setIsListed(true);
+                            userPositionVO.setProfitAndLose(userPositionVO.getProfitAndLose().multiply(new BigDecimal(userPositionVO.getOrderLever())));
+                        }
+                    }else{
+                        userPositionVO.setProfitAndLose(userPositionVO.getProfitAndLose().multiply(new BigDecimal(userPositionVO.getOrderLever())));
+                    }
+                    BigDecimal nowPriceSUM = nowPrice.multiply(BigDecimal.valueOf(position.getOrderNum()));
+                    if (position.getStockGid().equals(EStockType.US.getCode())) {
+                        usMarketValue = usMarketValue.add(nowPriceSUM);
+                        usPositionEarnings = usPositionEarnings.add(userPositionVO.getProfitAndLose());
+                        usPositionEarningsParent = usPositionEarningsParent.add(userPositionVO.getProfitAndLoseParent2());
+                    } else if(position.getStockGid().equals(EStockType.HK.getCode())) {
+                        hkMarketValue = hkMarketValue.add(nowPriceSUM);
+                        hkPositionEarnings = hkPositionEarnings.add(userPositionVO.getProfitAndLose());
+                        hkPositionEarningsParent = hkPositionEarningsParent.add(userPositionVO.getProfitAndLoseParent2());
+                    } else if(position.getStockGid().equals(EStockType.IN.getCode())) {
+                        inMarketValue = inMarketValue.add(nowPriceSUM);
+                        inPositionEarnings = inPositionEarnings.add(userPositionVO.getProfitAndLose());
+                        inPositionEarningsParent = inPositionEarningsParent.add(userPositionVO.getProfitAndLoseParent2());
+                    } else if(position.getStockGid().equals(EStockType.TW.getCode())) {
+                        twMarketValue = twMarketValue.add(nowPriceSUM);
+                        twPositionEarnings = twPositionEarnings.add(userPositionVO.getProfitAndLose());
+                        twPositionEarningsParent = twPositionEarningsParent.add(userPositionVO.getProfitAndLoseParent2());
+                    }
+
+                }
+                usPositionEarnings = usPositionEarnings.setScale(2, RoundingMode.DOWN);
+                hkPositionEarnings = hkPositionEarnings.setScale(2, RoundingMode.DOWN);
+                inPositionEarnings = inPositionEarnings.setScale(2, RoundingMode.DOWN);
+                twPositionEarnings = twPositionEarnings.setScale(2, RoundingMode.DOWN);
+            }
+
+            Map<String, String> map = new HashMap<>();
+            map.put("usMarketValue", String.valueOf(usMarketValue));            //美股市值
+            map.put("usPositionEarnings", String.valueOf(usPositionEarnings));  //美股持仓收益
+            map.put("usPositionEarningsParent", usPositionEarningsParent + "%");//美股持仓收益率
+
+            map.put("hkMarketValue", String.valueOf(hkMarketValue));            //港股市值
+            map.put("hkPositionEarnings", String.valueOf(hkPositionEarnings));  //港股持仓收益
+            map.put("hkPositionEarningsParent", hkPositionEarningsParent + "%");//港股持仓收益率
+
+            map.put("inMarketValue", String.valueOf(inMarketValue));            //印股市值
+            map.put("inPositionEarnings", String.valueOf(inPositionEarnings));  //印股持仓收益
+            map.put("inPositionEarningsParent", inPositionEarningsParent + "%");//印股持仓收益率
+
+            map.put("twMarketValue", String.valueOf(twMarketValue));            //台股市值
+            map.put("twPositionEarnings", String.valueOf(twPositionEarnings));  //台股持仓收益
+            map.put("twPositionEarningsParent", twPositionEarningsParent + "%");//台股持仓收益率
+
+            return ServerResponse.createBySuccess(map);
+        } catch (Exception e) {
+            log.error("IUserPositionService getMyPositionProfitAndLose error", e);
+        }
+        return ServerResponse.createByError();
+    }
+
+    @Override
+    public ServerResponse checkDz(Integer id, Integer checkType, Integer orderNum, HttpServletRequest request) {
+        try {
+            UserPositionCheckDz userPositionCheckDz = userPositionCheckDzService.getById(id);
+            if (userPositionCheckDz == null) {
+                return ServerResponse.createByErrorMsg("订单不存在", request);
+            }
+            if (userPositionCheckDz.getCheckType() != 0) {
+                return ServerResponse.createByErrorMsg("订单已审核", request);
+            }
+            if (checkType == 2) {
+                userPositionCheckDz.setCheckType(checkType);
+                userPositionCheckDzService.updateById(userPositionCheckDz);
+                return ServerResponse.createBySuccess("审核成功", request);
+            }
+            if (orderNum > userPositionCheckDz.getOrderNum()) {
+                return ServerResponse.createByErrorMsg("输入数量大于用户买入数量", request);
+            }
+            User user = userMapper.selectById(userPositionCheckDz.getUserId());
+
+            StockDz stockDz = this.stockDzMapper.selectOne(new QueryWrapper<StockDz>().eq("id", userPositionCheckDz.getDzId()));
+
+            UserAssets userAssets = userAssetsServices.assetsByTypeAndUserId(stockDz.getStockType(), user.getId());
+            if (userAssets.getAmountToBeCovered().compareTo(BigDecimal.ZERO) > 0) {
+                return ServerResponse.createByErrorMsg("用户账户有待补资金未补齐,审核失败", request);
+            }
+
+            BigDecimal nowPrice = stockDz.getNowPrice();
+
+            if (nowPrice.compareTo(new BigDecimal("0")) == 0) {
+                return ServerResponse.createByErrorMsg("股票价格0,请重试", request);
+            }
+            userPositionCheckDz.setOrderNum(orderNum);
+            userPositionCheckDz.setOrderTotalPrice(nowPrice.multiply(new BigDecimal(orderNum.intValue())));
+            BigDecimal buyAmt = nowPrice.multiply(new BigDecimal(userPositionCheckDz.getOrderNum()));
+            BigDecimal fundratio = new BigDecimal(user.getFundRatio()).divide(new BigDecimal(100));
+            BigDecimal availableBalance = fundratio.multiply(userAssets.getAvailableBalance());
+            if (buyAmt.compareTo(availableBalance) > 0) {
+                return ServerResponse.createByErrorMsg("订单失败,配资不足", request);
+            }
+            userPositionCheckDz.setCheckType(checkType);
+            userPositionCheckDzService.updateById(userPositionCheckDz);
+            UserPosition userPosition = Convert.convert(UserPosition.class, userPositionCheckDz);
+            userPosition.setBuyOrderPrice(nowPrice);
+            userPosition.setId(null);
+            userPosition.setDzId(stockDz.getId());
+            userPositionMapper.insert(userPosition);
+            userAssetsServices.availablebalanceChange(stockDz.getStockType(), user.getId(), EUserAssets.BUY, buyAmt.negate(), "", "");
+            return ServerResponse.createBySuccessMsg("审核成功,订单已转客户持仓", request);
+        } catch (Exception e) {
+            return ServerResponse.createByErrorMsg(e.getMessage());
+        }
+    }
+
 }
 
 

--
Gitblit v1.9.3