From 621f2eb73b862920a395a1b74d1fd9e4c26a85d3 Mon Sep 17 00:00:00 2001
From: zj <1772600164@qq.com>
Date: Tue, 06 May 2025 01:40:27 +0800
Subject: [PATCH] 1

---
 src/main/java/com/nq/service/impl/UserPositionServiceImpl.java |  908 +++++++++++++++++++++++++++++++++++++++++---------------
 1 files changed, 664 insertions(+), 244 deletions(-)

diff --git a/src/main/java/com/nq/service/impl/UserPositionServiceImpl.java b/src/main/java/com/nq/service/impl/UserPositionServiceImpl.java
index 2762d34..04a75f6 100644
--- a/src/main/java/com/nq/service/impl/UserPositionServiceImpl.java
+++ b/src/main/java/com/nq/service/impl/UserPositionServiceImpl.java
@@ -1,5 +1,9 @@
 package com.nq.service.impl;
 
+import cn.hutool.core.collection.CollectionUtil;
+import cn.hutool.core.convert.Convert;
+import cn.hutool.core.date.DateUtil;
+import cn.hutool.core.util.ObjectUtil;
 import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
 import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
 import com.nq.dao.*;
@@ -13,6 +17,9 @@
 import com.google.common.collect.Lists;
 import com.nq.common.ServerResponse;
 import com.nq.utils.*;
+import com.nq.utils.redis.RedisKeyConstant;
+import com.nq.utils.redis.RedisKeyUtil;
+import com.nq.utils.redis.RedisShardedPoolUtils;
 import com.nq.utils.stock.BuyAndSellUtils;
 import com.nq.utils.stock.GeneratePosition;
 import com.nq.utils.stock.GetStayDays;
@@ -32,11 +39,15 @@
 
 
 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.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.locks.Lock;
+import java.util.concurrent.locks.ReentrantLock;
 import javax.annotation.Resource;
 import javax.servlet.http.HttpServletRequest;
 
@@ -57,6 +68,9 @@
 
     @Autowired
     IUserAssetsServices userAssetsServices;
+
+    @Autowired
+    UserAssetsMapper userAssetsMapper;
 
     @Autowired
     ISiteSettingService iSiteSettingService;
@@ -117,113 +131,245 @@
     @Autowired
     IStockConfigServices iStockConfigServices;
 
+    @Autowired
+    UserPositionCheckDzService userPositionCheckDzService;
+
+    @Autowired
+    UserPendingorderService userPendingorderService;
+
+    @Autowired
+    UserPendingorderMapper userPendingorderMapper;
+
     @Transactional
     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() && user.getIsActive() != 2) {
-            return ServerResponse.createByErrorMsg("订单失败,请先实名认证", request);
+        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());
+            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);
+            }
+
+            UserAssets userAssets = iUserAssetsServices.assetsByTypeAndUserId(stock.getStockType(), user.getId());
+            StockConfig maxBuyConfig =  iStockConfigServices.queryByKey(EConfigKey.MAX_BUY.getCode());
+            if(buyNum<Integer.parseInt(mainBuyConfig.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   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);
+            }
+            UserPosition position = userPositionMapper.selectOne(new LambdaQueryWrapper<>(UserPosition.class)
+                    .eq(UserPosition::getUserId, user.getId())
+                    .eq(UserPosition::getStockCode, stock.getStockCode())
+                    .eq(UserPosition::getOrderDirection,(buyType.intValue() == 0) ? "买涨" : "买跌")
+                    .isNull(UserPosition::getSellOrderId)
+            );
+            if(ObjectUtil.isEmpty(position)){
+                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);
+            }else{
+                position.setOrderNum(position.getOrderNum()+buyNum);
+                position.setOrderTotalPrice(position.getOrderTotalPrice().add(buyAmt));
+                position.setOrderFee(position.getOrderFee().add(orderFree));
+                double divide = position.getOrderTotalPrice().doubleValue() / position.getOrderNum();
+                position.setBuyOrderPrice(new BigDecimal(divide));
+                position.setAllProfitAndLose(position.getAllProfitAndLose().add(orderFree));
+                userPositionMapper.updateById(position);
+                iUserAssetsServices.availablebalanceChange(stock.getStockType(), user.getId(), EUserAssets.BUY, buyAmt.negate(), "", "");
+                iUserAssetsServices.availablebalanceChange(stock.getStockType(), user.getId(), EUserAssets.HANDLING_CHARGE, orderFree, "", "");
+                return ServerResponse.createBySuccessMsg("下单成功", request);
+            }
         }
-        // 手续费率
-        BigDecimal siteSettingBuyFee = new BigDecimal(iStockConfigServices.queryByKey(EConfigKey.BUY_HANDLING_CHARGE.getCode()).getCValue()) ;
+    }
 
-        if (siteProduct.getRealNameDisplay() && user.getIsLock().intValue() == 1) {
-            return ServerResponse.createByErrorMsg("订单失败,帐户已被锁定", request);
+    @Transactional
+    public ServerResponse goldCrudeOilbuy(String name, Integer buyNum, Integer buyType,Integer lever, BigDecimal profitTarget, BigDecimal stopTarget, HttpServletRequest request) {
+
+        SiteProduct siteProduct = iSiteProductService.getProductSetting();
+
+        User user = this.iUserService.getCurrentRefreshUser(request);
+        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);
+            }
+
+            String s = RedisShardedPoolUtils.get(name);
+            BigDecimal price = new BigDecimal(s);
+            if (price == null) {
+                return ServerResponse.createByErrorMsg("下单失败,请稍候再试!", request);
+            }
+
+
+            UserAssets userAssets = iUserAssetsServices.assetsByTypeAndUserId("USD", user.getId());
+
+            if(userAssets.getAmountToBeCovered().compareTo(BigDecimal.ZERO) > 0){
+                return ServerResponse.createByErrorMsg("请先缴清待补资金", request);
+            }
+
+            if (price.compareTo(new BigDecimal("0")) == 0) {
+                return ServerResponse.createByErrorMsg("报价0,请稍后再试", request);
+            }
+
+            BigDecimal buyAmt = price.multiply(new BigDecimal(buyNum)).divide(new BigDecimal(lever));
+            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);
+            }
+            UserPosition position = userPositionMapper.selectOne(new LambdaQueryWrapper<>(UserPosition.class)
+                    .eq(UserPosition::getUserId, user.getId())
+                    .eq(UserPosition::getStockCode, "HJYY")
+                    .eq(UserPosition::getStockName,name)
+                    .eq(UserPosition::getOrderDirection,(buyType.intValue() == 0) ? "买涨" : "买跌")
+                    .isNull(UserPosition::getSellOrderId)
+            );
+            if(ObjectUtil.isEmpty(position)) {
+                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("HJYY");
+                userPosition.setStockName(name);
+                userPosition.setStockGid("HJYY");
+                userPosition.setStockSpell(name);
+                userPosition.setBuyOrderId(GeneratePosition.getPositionId());
+                userPosition.setBuyOrderTime(new Date());
+                userPosition.setBuyOrderPrice(price);
+                userPosition.setOrderDirection((buyType.intValue() == 0) ? "买涨" : "买跌");
+                userPosition.setOrderNum(buyNum);
+                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("USD", user.getId(), EUserAssets.BUY, buyAmt.negate(), "", "");
+                iUserAssetsServices.availablebalanceChange("USD", user.getId(), EUserAssets.HANDLING_CHARGE, orderFree, "", "");
+                return ServerResponse.createBySuccessMsg("下单成功", request);
+            }else{
+                position.setOrderNum(position.getOrderNum()+buyNum);
+                position.setOrderTotalPrice(position.getOrderTotalPrice().add(buyAmt));
+                position.setOrderFee(position.getOrderFee().add(orderFree));
+                double divide = position.getOrderTotalPrice().doubleValue() / position.getOrderNum();
+                position.setBuyOrderPrice(new BigDecimal(divide*position.getOrderLever()));
+                position.setAllProfitAndLose(position.getAllProfitAndLose().add(orderFree));
+                userPositionMapper.updateById(position);
+                iUserAssetsServices.availablebalanceChange("USD", user.getId(), EUserAssets.BUY, buyAmt.negate(), "", "");
+                iUserAssetsServices.availablebalanceChange("USD", user.getId(), EUserAssets.HANDLING_CHARGE, orderFree, "", "");
+                return ServerResponse.createBySuccessMsg("下单成功", request);
+            }
         }
-
-        Stock stock = stockMapper.selectByPrimaryKey(stockId);
-        if (stock == null) {
-            return ServerResponse.createByErrorMsg("订单失败,股票代码不存在", request);
-        }
-        //判断股票是否在可交易时间段
-        Boolean b = tradingHourService.timeCheck(stock.getStockCode());
-        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);
-        }
-
-
-        StockConfig maxBuyConfig =  iStockConfigServices.queryByKey(EConfigKey.MAX_BUY.getCode());
-
-        if(buyNum<Integer.parseInt(mainBuyConfig.getCValue())){
-            return ServerResponse.createByErrorMsg("最高购买数量"+maxBuyConfig.getCValue(), 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);
-
-        UserAssets userAssets = iUserAssetsServices.assetsByTypeAndUserId(stock.getStockType(), user.getId());
-        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);
-        }
-        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);
     }
 
 
@@ -281,6 +427,9 @@
             return ServerResponse.createByErrorMsg("平仓失败,订单不存在");
         }
         User user = this.userMapper.selectById(userPosition.getUserId());
+        if (user.getIsLock() == 1) {
+            return ServerResponse.createByErrorMsg("账户已被限制交易");
+        }
         if (user == null) {
             return ServerResponse.createByErrorMsg("平仓失败,用户不存在");
         }
@@ -290,8 +439,18 @@
         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());
+
+        BigDecimal nowPrice = BigDecimal.ZERO;
+        String stockType;
+        if(userPosition.getStockSpell().equals("XAUUSD") || userPosition.getStockSpell().equals("USOIL")){
+            nowPrice = new BigDecimal(RedisShardedPoolUtils.get(userPosition.getStockSpell()));
+            stockType = "USD";
+        }else{
+            Stock stock = stockMapper.selectOne(new QueryWrapper<Stock>().eq("stock_code", userPosition.getStockCode()));
+            nowPrice = priceServices.getNowPrice(userPosition.getStockCode());
+            stockType = stock.getStockType();
+        }
+
         if (nowPrice.compareTo(new BigDecimal("0")) != 1) {
             return ServerResponse.createByErrorMsg("报价0,平仓失败,请稍后再试");
         }
@@ -302,32 +461,76 @@
         BigDecimal sellOrderTotel = nowPrice.multiply(new BigDecimal(userPosition.getOrderNum()));
         BigDecimal xsPrice = sellOrderTotel.multiply(siitteBuyFee);
         userPositionMapper.updateById(userPosition);
-        userAssetsServices.availablebalanceChange(stock.getStockType(),
+        userAssetsServices.availablebalanceChange(stockType,
                 userPosition.getUserId(), EUserAssets.CLOSE_POSITION_RETURN_SECURITY_DEPOSIT,
                 userPosition.getOrderTotalPrice(), "", "");
-        userAssetsServices.availablebalanceChange(stock.getStockType(),
+        userAssetsServices.availablebalanceChange(stockType,
                 userPosition.getUserId(), EUserAssets.HANDLING_CHARGE,
                 xsPrice, "", "");
 
         PositionProfitVO profitVO = UserPointUtil.getPositionProfitVO(userPosition, priceServices.getNowPrice(userPosition.getStockCode()));
-        userAssetsServices.availablebalanceChange(stock.getStockType(), userPosition.getUserId(), EUserAssets.CLOSE_POSITION,
+        userAssetsServices.availablebalanceChange(stockType, userPosition.getUserId(), EUserAssets.CLOSE_POSITION,
                 profitVO.getAllProfitAndLose(), "", "");
         return ServerResponse.createBySuccessMsg("平仓成功!");
     }
 
 
     @Transactional
-    public ServerResponse sell(String positionSn, int doType, HttpServletRequest request) {
+    public ServerResponse sell(String positionSn, int doType, Integer number,String salePrice,HttpServletRequest request) {
         UserPosition userPosition = this.userPositionMapper.findPositionBySn(positionSn);
+        if(null == number || number <= 0 || number > userPosition.getOrderNum()){
+            return ServerResponse.createByErrorMsg("请输入正确的平仓数", request);
+        }
+        List<UserPendingorder> list = userPendingorderService.list(new LambdaQueryWrapper<>(UserPendingorder.class)
+                .eq(UserPendingorder::getPositionType, 1)
+                .eq(UserPendingorder::getPositionSn,positionSn)
+                .eq(UserPendingorder::getHangingOrderType,2)
+        );
+        if(CollectionUtil.isNotEmpty(list)){
+            return ServerResponse.createByErrorMsg("当前有平仓挂单未成交,禁止平仓。",request);
+        }
         // 手续费率
-        BigDecimal siitteBuyFee = new BigDecimal(iStockConfigServices.queryByKey(EConfigKey.SELL_HANDLING_CHARGE.getCode()).getCValue()) ;
+        BigDecimal siitteBuyFee = new BigDecimal(iStockConfigServices.queryByKey(EConfigKey.SELL_HANDLING_CHARGE.getCode()).getCValue());
 
-        Boolean b = tradingHourService.timeCheck(userPosition.getStockCode());
-        if (!b) {
-            return ServerResponse.createByErrorMsg("订单失败,不在交易时间之内", request);
+        UserAssets userAssets = userAssetsMapper.selectOne(new LambdaQueryWrapper<UserAssets>()
+                .eq(UserAssets::getUserId, userPosition.getUserId())
+                .eq(UserAssets::getAccectType, EStockType.ST.getCode())
+        );
+        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);
+        }
+        BigDecimal nowPrice = BigDecimal.ZERO;
+        String stockType = null;
+        if(userPosition.getStockSpell().equals("XAUUSD") || userPosition.getStockSpell().equals("USOIL")){
+            nowPrice = new BigDecimal(RedisShardedPoolUtils.get(userPosition.getStockSpell()));
+            stockType = "USD";
+        }else{
+            Stock stock = stockMapper.selectOne(new QueryWrapper<Stock>().eq("stock_code", userPosition.getStockCode()));
+
+            stockType = stock.getStockType();
+
+            if(null == stock){
+                return ServerResponse.createByErrorMsg("股票不存在,平仓失败", request);
+            }
+            Boolean b = tradingHourService.timeCheck(userPosition.getStockCode());
+            if (!b) {
+                return ServerResponse.createByErrorMsg("订单失败,不在交易时间之内", request);
+            }
+            if (!priceServices.isLimitDownSell(stock.getStockCode())) {
+                return ServerResponse.createByErrorMsg("股票跌停,无法平仓", request);
+            }
+            nowPrice = priceServices.getNowPrice(userPosition.getStockCode());
+            if (nowPrice.compareTo(new BigDecimal("0")) != 1) {
+                return ServerResponse.createByErrorMsg("报价0,平仓失败,请稍后再试", request);
+            }
         }
         if(userPosition.getPositionType() == 3){
-            StockDz stockDz = stockDzMapper.selectOne(new LambdaQueryWrapper<StockDz>().eq(StockDz::getStockCode, userPosition.getStockCode()));
+            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());
@@ -339,6 +542,9 @@
             return ServerResponse.createByErrorMsg("平仓失败,订单不存在", request);
         }
         User user = this.userMapper.selectById(userPosition.getUserId());
+        if (user.getIsLock() == 1) {
+            return ServerResponse.createByErrorMsg("账户已被限制交易", request);
+        }
         if (user == null) {
             return ServerResponse.createByErrorMsg("平仓失败,用户不存在", request);
         }
@@ -348,33 +554,75 @@
         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()));
-        if (!priceServices.isLimitDownSell(stock.getStockCode())) {
-            return ServerResponse.createByErrorMsg("股票跌停,无法平仓", request);
+
+        if(StringUtils.isEmpty(salePrice)){
+            //部分平仓
+            if(number < userPosition.getOrderNum()){
+                //拆分订单
+                UserPosition position = ConverterUtil.convert(userPosition,UserPosition.class);
+                position.setId(null);
+                position.setPositionSn(KeyUtils.getUniqueKey());
+                //得到均价
+                double buyOrderPrice = position.getOrderTotalPrice().doubleValue() / position.getOrderNum().doubleValue() * position.getOrderLever();
+                position.setOrderNum(userPosition.getOrderNum()-number);
+                BigDecimal positionBuyAmt = new BigDecimal(buyOrderPrice).multiply(new BigDecimal(position.getOrderNum())).divide(new BigDecimal(position.getOrderLever()));
+                position.setOrderTotalPrice(positionBuyAmt);
+                position.setBuyOrderPrice(new BigDecimal(buyOrderPrice));
+                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);
+                userPositionMapper.insert(position);
+                //得到均价
+                double orderPrice = userPosition.getOrderTotalPrice().doubleValue() / userPosition.getOrderNum().doubleValue() * position.getOrderLever();
+                //修改原订单
+                userPosition.setOrderNum(number);
+                BigDecimal buyAmt = new BigDecimal(orderPrice).multiply(new BigDecimal(userPosition.getOrderNum())).divide(new BigDecimal(userPosition.getOrderLever()));
+                userPosition.setOrderTotalPrice(buyAmt);
+                userPosition.setOrderFee(userPosition.getOrderFee().subtract(position.getOrderFee()));
+
+                userPositionMapper.updateById(userPosition);
+
+                return getObjectServerResponse(request, userPosition, nowPrice, siitteBuyFee, stockType);
+            }
+            return getObjectServerResponse(request, userPosition, nowPrice, siitteBuyFee, stockType);
+        }else{
+            UserPendingorder userPendingorder = ConverterUtil.convert(userPosition,UserPendingorder.class);
+            userPendingorder.setId(null);
+            userPendingorder.setOrderNum(number);
+            userPendingorder.setHangingOrderType(2);
+            userPendingorder.setPositionType(1);
+            userPendingorder.setStockType(stockType);
+            userPendingorder.setSellOrderPrice(new BigDecimal(salePrice));
+            userPendingorderMapper.insert(userPendingorder);
         }
-        BigDecimal nowPrice = priceServices.getNowPrice(userPosition.getStockCode());
-        if (nowPrice.compareTo(new BigDecimal("0")) != 1) {
-            return ServerResponse.createByErrorMsg("报价0,平仓失败,请稍后再试", request);
-        }
+        return ServerResponse.createBySuccess("操作成功",request);
+    }
+
+    public ServerResponse<Object> getObjectServerResponse(HttpServletRequest request, UserPosition userPosition, BigDecimal nowPrice, BigDecimal siitteBuyFee,String stockType) {
         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(),
+
+        userAssetsServices.availablebalanceChange(stockType,
                 userPosition.getUserId(),
                 EUserAssets.CLOSE_POSITION_RETURN_SECURITY_DEPOSIT,
                 userPosition.getOrderTotalPrice(), "", "");
-        userAssetsServices.availablebalanceChange(stock.getStockType(),
+        userAssetsServices.availablebalanceChange(stockType,
                 userPosition.getUserId(), EUserAssets.HANDLING_CHARGE,
                 xsPrice, "", "");
 
         PositionProfitVO profitVO = UserPointUtil.getPositionProfitVO(userPosition,
                 priceServices.getNowPrice(userPosition.getStockCode()));
 
-        userAssetsServices.availablebalanceChange(stock.getStockType(),
+        userAssetsServices.availablebalanceChange(stockType,
                 userPosition.getUserId(), EUserAssets.CLOSE_POSITION,
                 profitVO.getAllProfitAndLose(), "", "");
         return ServerResponse.createBySuccessMsg("平仓成功!", request);
@@ -551,32 +799,94 @@
 
     public ServerResponse findMyPositionByCodeAndSpell(String stockCode, String stockSpell,
                                                        Integer state, HttpServletRequest request,
-                                                       int pageNum, int pageSize, String stockType) {
+                                                       int pageNum, int pageSize, String stockType,Integer pendingStatus) {
         User user = this.iUserService.getCurrentUser(request);
-
         PageHelper.startPage(pageNum, pageSize);
-        List<UserPosition> userPositions;
+        List<UserPosition> userPositions = null;
+        if(state == 2){
+            List<UserPendingorder> list = userPendingorderService.list(new LambdaQueryWrapper<>(UserPendingorder.class)
+                    .eq(UserPendingorder::getUserId, user.getId())
+                    .eq(UserPendingorder::getStockGid,(null != stockCode && "HJYY".equals(stockCode)) ? stockCode :  stockType)
+                    .eq(UserPendingorder::getPositionType,pendingStatus)
+            );
+            PageInfo pageInfo = new PageInfo();
+            pageInfo.setList(list);
+            return ServerResponse.createBySuccess(pageInfo);
+        }else if(state == 3){
+            List<UserPositionCheckDz> list = userPositionCheckDzService.list(new LambdaQueryWrapper<UserPositionCheckDz>()
+                    .eq(UserPositionCheckDz::getUserId, user.getId())
+                    .orderByDesc(UserPositionCheckDz::getBuyOrderTime)
+            );
+            PageInfo pageInfo = new PageInfo();
+            pageInfo.setList(list);
+            return ServerResponse.createBySuccess(pageInfo);
+        }else {
+            if (null != stockCode && stockCode.equals("HJYY")) {
+                LambdaQueryWrapper<UserPosition> wrapper = getUserPositionLambdaQueryWrapper(stockCode, state, user);
+                userPositions = userPositionMapper.selectList(wrapper);
+            } else {
+                userPositions = userPositionMapper.
+                        findMyPositionByCodeAndSpell(user.getId(),
+                                stockCode, stockSpell,
+                                state, stockType);
+            }
 
+            List<UserPositionVO> userPositionVOS = Lists.newArrayList();
+            if (userPositions.size() > 0) {
+                for (UserPosition position : userPositions) {
+                    BigDecimal nowPrice = BigDecimal.ZERO;
+                    if (position.getStockSpell().equals("XAUUSD") || position.getStockSpell().equals("USOIL")) {
+                        nowPrice = new BigDecimal(RedisShardedPoolUtils.get(position.getStockSpell()));
+                    } else {
+                        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())));
 
-        userPositions = userPositionMapper.
-                findMyPositionByCodeAndSpell(user.getId(),
-                        stockCode, stockSpell,
-                        state, stockType);
+                    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());
+                        }
+                    } else {
+                        userPositionVO.setProfitAndLose(userPositionVO.getProfitAndLose());
+                    }
+                    userPositionVOS.add(userPositionVO);
+                }
+            }
 
+            PageInfo pageInfo = new PageInfo(userPositions);
+            pageInfo.setList(userPositionVOS);
 
-        List<UserPositionVO> userPositionVOS = Lists.newArrayList();
-        if (userPositions.size() > 0) {
-            for (UserPosition position : userPositions) {
-                UserPositionVO userPositionVO = UserPointUtil.assembleUserPositionVO(position, priceServices.getNowPrice(position.getStockCode()));
-                userPositionVOS.add(userPositionVO);
+            return ServerResponse.createBySuccess(pageInfo);
+        }
+    }
+
+    private static LambdaQueryWrapper<UserPosition> getUserPositionLambdaQueryWrapper(String stockCode, Integer state,  User user) {
+        LambdaQueryWrapper<UserPosition> wrapper = new LambdaQueryWrapper<>();
+        wrapper.eq(UserPosition::getUserId, user.getId());
+        wrapper.eq(UserPosition::getStockCode, stockCode);
+        wrapper.eq(UserPosition::getStockGid, stockCode);
+        if (state != null) {
+            if (state == 0) {
+                wrapper.isNull(UserPosition::getSellOrderId);
+            } else if (state == 1) {
+                wrapper.isNotNull(UserPosition::getSellOrderId);
             }
         }
-
-        PageInfo pageInfo = new PageInfo(userPositions);
-        pageInfo.setList(userPositionVOS);
-
-        return ServerResponse.createBySuccess(pageInfo);
+        wrapper.orderByDesc(UserPosition::getId);
+        return wrapper;
     }
 
     public PositionVO findUserPositionAllProfitAndLose(Integer userId) {
@@ -664,11 +974,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,null);
+                userId, ids, positionSn, begin_time, end_time,null,null);
 
         List<AgentPositionVO> agentPositionVOS = Lists.newArrayList();
         for (UserPosition position : userPositions) {
@@ -697,8 +1013,14 @@
         }
 
 
+        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, agentId, null, begin_time, end_time,null);
+                null, ids, null, begin_time, end_time,null,null);
 
 
         BigDecimal order_fee_amt = new BigDecimal("0");
@@ -718,7 +1040,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,String phone) {
+    public ServerResponse listByAdmin(Integer agentId, Integer positionType, Integer state, Integer userId, String positionSn, String beginTime, String endTime, int pageNum, int pageSize,String phone,String productType) {
         PageHelper.startPage(pageNum, pageSize);
 
 
@@ -730,15 +1052,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,phone);
+        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,productType);
         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) {
@@ -1068,8 +1413,13 @@
         adminPositionVO.setLockMsg(position.getLockMsg());
 
         adminPositionVO.setStockPlate(position.getStockPlate());
-
-        PositionProfitVO positionProfitVO = UserPointUtil.getPositionProfitVO(position, priceServices.getNowPrice(position.getStockCode()));
+        BigDecimal nowPrice = BigDecimal.ZERO;
+        if(position.getStockSpell().equals("XAUUSD") || position.getStockSpell().equals("USOIL")){
+            nowPrice = new BigDecimal(RedisShardedPoolUtils.get(position.getStockSpell()));
+        }else{
+            nowPrice = priceServices.getNowPrice(position.getStockCode());
+        }
+        PositionProfitVO positionProfitVO = UserPointUtil.getPositionProfitVO(position,nowPrice );
         adminPositionVO.setProfitAndLose(positionProfitVO.getProfitAndLose());
         adminPositionVO.setAllProfitAndLose(positionProfitVO.getAllProfitAndLose());
         adminPositionVO.setNow_price(positionProfitVO.getNowPrice());
@@ -1080,7 +1430,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());
@@ -1162,99 +1519,113 @@
      * @Date: 2022/10/26
      */
     @Override
-    public ServerResponse newStockToPosition(Integer id) {
+    public ServerResponse newStockToPosition(Integer id,BigDecimal amountToBeCovered) {
         UserStockSubscribe userStockSubscribe = userStockSubscribeMapper.load(id);
         if (userStockSubscribe == null) {
             return ServerResponse.createByErrorMsg("无该申购记录");
         }
-        StockSubscribe stockSubscribe = stockSubscribeMapper.selectOne(new QueryWrapper<StockSubscribe>().eq("code", userStockSubscribe.getNewCode()).eq("type",userStockSubscribe.getType()));
+        StockSubscribe stockSubscribe = stockSubscribeMapper.selectOne(new QueryWrapper<StockSubscribe>().eq("newlist_id", userStockSubscribe.getNewStockId()));
         if (userStockSubscribe == null) {
             return ServerResponse.createByErrorMsg("该新股不存在");
         }
-        if (userStockSubscribe.getStatus() == 4 || userStockSubscribe.getStatus() == 3 && stockSubscribe.getType() == 2) {
-            Stock stock = stockMapper.selectOne(new LambdaQueryWrapper<Stock>().eq(Stock::getStockCode, userStockSubscribe.getNewCode()));
-            if(null == stock){
-                return ServerResponse.createByErrorMsg("该新股不存在");
-            }
-            UserPosition userPosition = new UserPosition();
-            userPosition.setPositionType(1);
-            userPosition.setPositionSn(KeyUtils.getUniqueKey());
-            userPosition.setUserId(userStockSubscribe.getUserId());
-            userPosition.setNickName(userStockSubscribe.getRealName());
-            userPosition.setAgentId(userStockSubscribe.getAgentId());
+
+        Stock stock = stockMapper.selectOne(new LambdaQueryWrapper<Stock>().eq(Stock::getStockCode, userStockSubscribe.getNewCode()));
+
+        UserPosition userPosition = new UserPosition();
+
+        if(null == stock){
+            userPosition.setStockCode(stockSubscribe.getCode());
+            userPosition.setStockSpell(stockSubscribe.getName());
+        }else{
             userPosition.setStockCode(stock.getStockCode());
             userPosition.setStockSpell(stock.getStockSpell());
-            userPosition.setStockName(userStockSubscribe.getNewName());
-            userPosition.setStockGid(stockSubscribe.getStockType() + userStockSubscribe.getNewCode());
+        }
 
-            userPosition.setBuyOrderId(GeneratePosition.getPositionId());
-            userPosition.setBuyOrderTime(new Date());
-            userPosition.setBuyOrderPrice(userStockSubscribe.getBuyPrice());
-            userPosition.setOrderDirection("买涨");
+        userPosition.setPositionType(1);
+        userPosition.setPositionSn(KeyUtils.getUniqueKey());
+        userPosition.setUserId(userStockSubscribe.getUserId());
+        userPosition.setNickName(userStockSubscribe.getRealName());
+        userPosition.setAgentId(userStockSubscribe.getAgentId());
 
-            userPosition.setOrderNum(userStockSubscribe.getApplyNumber());
+        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(EStockType.ST.getCode());
+        userPosition.setBuyOrderId(GeneratePosition.getPositionId());
+        userPosition.setBuyOrderTime(new Date());
+        userPosition.setBuyOrderPrice(userStockSubscribe.getBuyPrice());
+        userPosition.setOrderDirection("买涨");
+
+        userPosition.setOrderNum(userStockSubscribe.getApplyNumber());
 
 
-            userPosition.setIsLock(Integer.valueOf(0));
+        userPosition.setIsLock(Integer.valueOf(0));
 
 
-            userPosition.setOrderLever(10);
+        userPosition.setOrderLever(1);
 
 
-            //递延费特殊处理
-            //            BigDecimal stayFee = userPosition.getOrderTotalPrice().multiply(siteSetting.getStayFee());
-            BigDecimal stayFee = new BigDecimal(0);
-            BigDecimal allStayFee = stayFee.multiply(new BigDecimal(1));
-            userPosition.setOrderStayFee(allStayFee);
-            userPosition.setOrderStayDays(1);
-            userPosition.setOrderTotalPrice(userStockSubscribe.getBond());
+        //递延费特殊处理
+        //            BigDecimal stayFee = userPosition.getOrderTotalPrice().multiply(siteSetting.getStayFee());
+        BigDecimal stayFee = new BigDecimal(0);
+        BigDecimal allStayFee = stayFee.multiply(new BigDecimal(1));
+        userPosition.setOrderStayFee(allStayFee);
+        userPosition.setOrderStayDays(1);
+        userPosition.setOrderTotalPrice(userStockSubscribe.getBond());
 
-            //            BigDecimal buy_fee_amt = buy_amt.multiply(siteSetting.getBuyFee()).setScale(2, 4);
-            BigDecimal buy_fee_amt = new BigDecimal(0);
-            log.info("用户购买手续费(配资后总资金 * 百分比) = {}", buy_fee_amt);
-            userPosition.setOrderFee(buy_fee_amt);
+        //            BigDecimal buy_fee_amt = buy_amt.multiply(siteSetting.getBuyFee()).setScale(2, 4);
+        // 手续费率
+        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);
 
 
-            //            BigDecimal buy_yhs_amt = buy_amt.multiply(siteSetting.getDutyFee()).setScale(2, 4);
-            BigDecimal buy_yhs_amt = new BigDecimal(0);
-            log.info("用户购买印花税(配资后总资金 * 百分比) = {}", buy_yhs_amt);
-            userPosition.setOrderSpread(buy_yhs_amt);
+        //            BigDecimal buy_yhs_amt = buy_amt.multiply(siteSetting.getDutyFee()).setScale(2, 4);
+        BigDecimal buy_yhs_amt = new BigDecimal(0);
+        log.info("用户购买印花税(配资后总资金 * 百分比) = {}", buy_yhs_amt);
+        userPosition.setOrderSpread(buy_yhs_amt);
 
-            BigDecimal spread_rate_amt = new BigDecimal(0);
-            userPosition.setSpreadRatePrice(spread_rate_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 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);
+        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"));
-
-            int ret = 0;
-            ret = this.userPositionMapper.insert(userPosition);
-
+        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(EStockType.ST.getCode(), userPosition.getUserId());
+        if(null == userAssets){
+            return ServerResponse.createByErrorMsg("新股转持仓失败");
+        }
+        userAssetsMapper.updateById(userAssets);
+        iUserAssetsServices.availablebalanceChange(EStockType.ST.getCode(), 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.updateById(user);
+            }
             if (ret > 0) {
-                userStockSubscribe.setStatus(5);
-                userStockSubscribeMapper.update1(userStockSubscribe);
-                if (userStockSubscribe.getType() == 1 || userStockSubscribe.getType() == 2) {
-                    User user = userMapper.selectById(userStockSubscribe.getUserId());
-                    ret = userMapper.updateById(user);
-                }
-                if (ret > 0) {
-                    return ServerResponse.createBySuccessMsg("新股转持仓成功");
-                } else {
-                    return ServerResponse.createByErrorMsg("新股转持仓失败");
-                }
+                return ServerResponse.createBySuccessMsg("新股转持仓成功");
             } else {
                 return ServerResponse.createByErrorMsg("新股转持仓失败");
             }
+        } else {
+            return ServerResponse.createByErrorMsg("新股转持仓失败");
         }
-        return ServerResponse.createByErrorMsg("新股转持仓失败");
     }
 
     /**
@@ -1522,18 +1893,23 @@
      * @return
      */
     @Transactional
-    public ServerResponse buyDz(String stockCode, String password, Integer num, HttpServletRequest request) throws Exception {
+    public ServerResponse buyDz(Integer dzId, String password, Integer num, HttpServletRequest request) throws Exception {
         /*实名认证开关开启*/
         SiteProduct siteProduct = iSiteProductService.getProductSetting();
         User user = this.iUserService.getCurrentRefreshUser(request);
+
         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("stock_code", stockCode));
-        if (!Objects.equals(stockDz.getPassword(), password)) {
+        UserAssets userAssets = userAssetsServices.assetsByTypeAndUserId(EStockType.ST.getCode(), user.getId());
+        if(userAssets.getAmountToBeCovered().compareTo(BigDecimal.ZERO) > 0){
+            return ServerResponse.createByErrorMsg("请先缴清待补资金", request);
+        }
+        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) {
@@ -1545,7 +1921,8 @@
         if(stockDz.getStartTime().getTime() > new Date().getTime() || stockDz.getEndTime().getTime() < new Date().getTime()){
             return ServerResponse.createByErrorMsg("不在内幕交易时间之内", request);
         }
-        BigDecimal nowPrice = priceServices.getNowPrice(stockCode).multiply(stockDz.getDiscount());
+//        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);
@@ -1553,13 +1930,36 @@
         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()));
-        UserAssets userAssets = iUserAssetsServices.assetsByTypeAndUserId(stock.getStockType(), user.getId());
-        BigDecimal   fundratio = new BigDecimal(user.getFundRatio()).divide(new BigDecimal(100));
-        BigDecimal availableBalance =  fundratio.multiply(userAssets.getAvailableBalance());
-        if (buyAmt.compareTo(availableBalance) > 0) {
+        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);
         }
+
+        //判断审核开关
+        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(buyAmt);
+        userAssetsServices.availablebalanceChange(EStockType.ST.getCode(), user.getId(), EUserAssets.BUY, buyAmt.negate(),"","");
+        iUserAssetsServices.availablebalanceChange(EStockType.ST.getCode(), userAssets.getUserId(), EUserAssets.HANDLING_CHARGE, buy_fee_amt, "", "");
+        return ServerResponse.createBySuccess("购买成功", request);
+    }
+
+    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());
@@ -1568,7 +1968,7 @@
         userPosition.setAgentId(user.getAgentId());
         userPosition.setStockCode(stockDz.getStockCode());
         userPosition.setStockName(stockDz.getStockName());
-        userPosition.setStockGid(stockDz.getStockGid());
+        userPosition.setStockGid(stockDz.getStockType());
         userPosition.setBuyOrderId(GeneratePosition.getPositionId());
         userPosition.setBuyOrderTime(new Date());
         userPosition.setBuyOrderPrice(nowPrice);
@@ -1588,11 +1988,9 @@
         userPosition.setAllProfitAndLose(all_profit_and_lose);
         userPosition.setOrderStayDays(Integer.valueOf(0));
         userPosition.setOrderStayFee(new BigDecimal("0"));
-
         userPosition.setOrderSpread(BigDecimal.ZERO);
-        userPositionMapper.insert(userPosition);
-        userAssetsServices.availablebalanceChange(EStockType.IN.getCode(), user.getId(), EUserAssets.BUY, buyAmt.negate(),"","");
-        return ServerResponse.createBySuccess("购买成功", request);
+        userPosition.setDzId(dzId);
+        return userPosition;
     }
 
     @Override
@@ -1609,19 +2007,29 @@
     @Override
     @Transactional
     public void stockConstraint(List<UserPosition> list) {
-        SiteSetting siteSetting = iSiteSettingService.getSiteSetting();
-        BigDecimal siteBuyFee = siteSetting.getBuyFee();
+        try {
+            SiteSetting siteSetting = iSiteSettingService.getSiteSetting();
 
-        for (UserPosition position : list) {
-            //平仓检查
-            Result result = getResult(position);
-            if (result == null) continue;
+            for (UserPosition position : list) {
+                UserAssets userAssets = userAssetsMapper.selectOne(new LambdaQueryWrapper<UserAssets>()
+                        .eq(UserAssets::getUserId, position.getUserId())
+                        .eq(UserAssets::getAccectType, EStockType.ST.getCode())
+                );
+                if(userAssets.getAmountToBeCovered().compareTo(BigDecimal.ZERO) > 0){
+                    continue;
+                }
+                //平仓检查
+                Result result = getResult(position);
+                if (result == null) continue;
 
-            boolean liquidation = false;
-            liquidation = isLiquidation(position, result.signum, result.profit, liquidation);
-            if(liquidation){
-                extracted(position, result.nowPrice, result.stock);
+                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);
         }
     }
 
@@ -1690,7 +2098,8 @@
     }
 
     //判断平仓
-    private boolean isLiquidation(UserPosition position, int signum, BigDecimal profit, boolean liquidation) {
+    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("买涨")){
@@ -1701,17 +2110,17 @@
                 //止损
                 if(null != position.getStopTargetPrice() && nowPrice.compareTo(position.getStopTargetPrice()) <= 0){
                     //强制平仓
-                    return liquidation = true;
+                    return liquidation = 1;
                 }
                 if (negate.compareTo(position.getOrderTotalPrice()) >= 0){//亏平强平
                     //强制平仓
-                    return liquidation = true;
+                    return liquidation = -1;
                 }
             }else{
                 //止盈
                 if(null != position.getProfitTargetPrice() && nowPrice.compareTo(position.getProfitTargetPrice()) >= 0){
                     //强制平仓
-                    return liquidation = true;
+                    return liquidation = 2;
                 }
             }
         }else{
@@ -1720,18 +2129,18 @@
                 //止损
                 if(null != position.getStopTargetPrice() && nowPrice.compareTo(position.getStopTargetPrice()) >= 0){
                     //强制平仓
-                    return liquidation = true;
+                    return liquidation = 1;
                 }
                 //判断亏损金额是否达到保证金金额
                 if (profit.compareTo(position.getOrderTotalPrice()) >= 0){//亏平强平
                     //强制平仓
-                    return liquidation = true;
+                    return liquidation = -1;
                 }
             }else{
                 //止盈
                 if(null != position.getProfitTargetPrice() && nowPrice.compareTo(position.getProfitTargetPrice()) <= 0){
                     //强制平仓
-                    return liquidation = true;
+                    return liquidation = 2;
                 }
             }
         }
@@ -1739,21 +2148,32 @@
     }
 
     //平仓
-    private void extracted(UserPosition position, BigDecimal nowPrice, Stock stock) {
+    private void extracted(UserPosition position, BigDecimal nowPrice, Stock stock,Integer liquidation) {
+        //-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(), "", "");
+        }
 
-        // 计算手续费等
-        BigDecimal handlingFee = BigDecimal.ZERO;
 
-        //更新用户资产
-        userAssetsServices.availablebalanceChange(stock.getStockType(),
-                position.getUserId(),
-                EUserAssets.CONSTRAINT_CLOSE_POSITION,
-                position.getOrderTotalPrice(), "", "");
+
         log.info("强制平仓成功,订单id: {}", position.getId());
     }
 

--
Gitblit v1.9.3