xiaoyong931011
2020-05-25 cf909807ff63a31954ee8dbe5d0eda010923e096
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
package com.xcong.excoin.modules.coin.service.impl;
 
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
import javax.annotation.Resource;
 
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
 
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kebex.app.entity.member.Member;
import com.kebex.app.entity.member.MemberAccountFlowRecord;
import com.kebex.app.entity.member.WalletCoin;
import com.kebex.app.entity.order.CoinOrderMain;
import com.kebex.app.entity.order.CoinsOrderDetail;
import com.kebex.app.entity.trade.TradeSetting;
import com.kebex.common.huobiapi.CoinTypeConConvert;
import com.xcong.excoin.common.LoginUserUtils;
import com.xcong.excoin.common.enumerates.MemberWalletCoinEnum;
import com.xcong.excoin.common.response.Result;
import com.xcong.excoin.modules.coin.dao.MemberSelectSymbolsDao;
import com.xcong.excoin.modules.coin.dao.OrderCoinDao;
import com.xcong.excoin.modules.coin.dao.platform.CnyUsdtExchangeDao;
import com.xcong.excoin.modules.coin.dao.platform.TradeSettingDao;
import com.xcong.excoin.modules.coin.entity.CnyUsdtExchange;
import com.xcong.excoin.modules.coin.entity.OrderCoinEntity;
import com.xcong.excoin.modules.coin.entity.PlatformTradeSettingEntity;
import com.xcong.excoin.modules.coin.service.OrderCoinService;
import com.xcong.excoin.modules.member.dao.MemberWalletCoinDao;
import com.xcong.excoin.modules.member.entity.MemberSelectSymbolsEntity;
import com.xcong.excoin.modules.member.entity.MemberWalletCoinEntity;
import com.xcong.excoin.utils.MessageSourceUtils;
 
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
 
@Service
public class OrderCoinServiceImpl extends ServiceImpl<OrderCoinDao, OrderCoinEntity> implements OrderCoinService{
    
    @Resource
    TradeSettingDao platformTradeSettingDao;
    @Resource
    MemberWalletCoinDao memberWalletCoinDao;
    @Resource
    MemberSelectSymbolsDao memberSelectSymbolsDao;
    @Resource
    CnyUsdtExchangeDao cnyUsdtExchangeDao;
 
    @Override
    public Result enterTransactionPageOfWalletCoin(String symbol, String type) {
        if (StrUtil.isBlank(symbol)) {
            return Result.fail(MessageSourceUtils.getString("order_service_0001"));
        }
        //获取用户ID
        Long memberId = LoginUserUtils.getAppLoginUser().getId();
        //获取该币种的币币账户信息
        MemberWalletCoinEntity walletCoin = memberWalletCoinDao.selectWalletCoinBymIdAndCode(memberId, symbol);
        
        PlatformTradeSettingEntity tradeSetting = platformTradeSettingDao.findTradeSetting();
        if (tradeSetting == null) {
            return Result.fail(MessageSourceUtils.getString("order_service_0003"));
        }
        //获取USDT的币币账户信息
        MemberWalletCoinEntity walletCoinUsdt = memberWalletCoinDao.selectWalletCoinBymIdAndCode(memberId, 
                                                            MemberWalletCoinEnum.WALLETCOINCODE.getValue());
        /**
         * todo
         */
        //获取某个币种的收盘价
        //Double closePrice = symbolsService.getCloseSymbolsBySymbolsName(symbol+"/USDT");
        BigDecimal closePrice = new BigDecimal("100.0000");
        
        List<MemberSelectSymbolsEntity> memSymbols = memberSelectSymbolsDao.selectSymbolByMemIdAndSymbol(memberId, symbol);
        
        CnyUsdtExchange cnyUsdtExchange = cnyUsdtExchangeDao.getCNYAndUSDTOne();
        BigDecimal cnyUsdt = cnyUsdtExchange.getValue();
        
        Map<String, Object> map = new HashMap<String, Object>();
        if(CollUtil.isEmpty(memSymbols)) {
            map.put(MemberWalletCoinEnum.ENTERTRANSACTIONPAGEOFWALLETCOIN_ISCOLLECT_NO.getName(),
                    MemberWalletCoinEnum.ENTERTRANSACTIONPAGEOFWALLETCOIN_ISCOLLECT_NO.getValue());//是否已经自选该币种
        }else {
            map.put(MemberWalletCoinEnum.ENTERTRANSACTIONPAGEOFWALLETCOIN_ISCOLLECT_YES.getName(),
                    MemberWalletCoinEnum.ENTERTRANSACTIONPAGEOFWALLETCOIN_ISCOLLECT_YES.getValue());//是否已经自选该币种
        }
        if (ObjectUtil.isEmpty(walletCoin))
            return Result.fail(MessageSourceUtils.getString("order_service_0003"));
        
        map.put(MemberWalletCoinEnum.ENTERTRANSACTIONPAGEOFWALLETCOIN_SPREAD.getValue(), tradeSetting.getSpread());// 点差
        map.put(MemberWalletCoinEnum.ENTERTRANSACTIONPAGEOFWALLETCOIN_CLOSINGRATIO.getValue(), tradeSetting.getFeeRatio());// 手续费用率
        if(MemberWalletCoinEnum.ENTERTRANSACTIONPAGEOFWALLETCOIN_BUY.getValue().equals(type)) {//买入
            map.put(MemberWalletCoinEnum.ENTERTRANSACTIONPAGEOFWALLETCOIN_MEMBERMONEY.getValue(), walletCoinUsdt.getAvailableBalance());// 用户可用金额
        }else {
            map.put(MemberWalletCoinEnum.ENTERTRANSACTIONPAGEOFWALLETCOIN_MEMBERMONEY.getValue(), walletCoin.getAvailableBalance());// 用户可用金额
        }
        
        map.put(MemberWalletCoinEnum.ENTERTRANSACTIONPAGEOFWALLETCOIN_CURRENTPRICE.getValue(), closePrice);//当前价
        map.put(MemberWalletCoinEnum.ENTERTRANSACTIONPAGEOFWALLETCOIN_CNYUSDT.getValue(), cnyUsdt);//比例
        map.put(MemberWalletCoinEnum.ENTERTRANSACTIONPAGEOFWALLETCOIN_CURRENTPRICECNY.getValue(), cnyUsdt.multiply(closePrice));//换算成人民币的币种价格
        return Result.ok(map);
}
 
    @Override
    @Transactional
    public Result submitSalesWalletCoinOrder(String symbol, Integer type, Integer tradeType, BigDecimal price,
            BigDecimal amount) {
        try {
            //获取用户ID
            Long memberId = LoginUserUtils.getAppLoginUser().getId();
            
            String[] symbols = symbol.split("/");
            if (symbols.length <= 0) {
                return Result.fail(MessageSourceUtils.getString("order_service_0008"));
            }
            /**
             * todo
             */
            //查询当前价
            //BigDecimal nowPrice = new BigDecimal(redisUtil.getString(CoinTypeConConvert.convertToKey(symbol+"/USDT")));
            BigDecimal nowPrice = new BigDecimal("100.0000");
            
            // 获取交易管理的杠杠倍率,手续费率等信息,由平台进行设置
            symbol = symbol.toUpperCase();
            MemberWalletCoinEntity walletCoin = memberWalletCoinDao.selectWalletCoinBymIdAndCode(memberId, symbols[0]);
            MemberWalletCoinEntity walletCoinUsdt = memberWalletCoinDao.selectWalletCoinBymIdAndCode(memberId, 
                                                                        MemberWalletCoinEnum.WALLETCOINCODE.getValue());
            if (ObjectUtil.isEmpty(walletCoin) || ObjectUtil.isEmpty(walletCoinUsdt) ) {
                return Result.fail(MessageSourceUtils.getString("order_service_0003"));
            }
            // 查询交易设置
            PlatformTradeSettingEntity tradeSetting = platformTradeSettingDao.findTradeSetting();
            if(ObjectUtil.isEmpty(tradeSetting)) {
                return Result.fail(MessageSourceUtils.getString("order_service_0009"));
            }
            //手续费率
            BigDecimal ServiceRate = new BigDecimal(MemberWalletCoinEnum.SUBMITSALESWALLETCOINORDER_SERVICERATE.getValue());
            // 手续费用(手续费=建仓价X数量X手续费率)
            BigDecimal closingPrice = price.multiply(amount).multiply(ServiceRate).setScale(4, BigDecimal.ROUND_DOWN);
            //总费用 = 成交价*数量+手续费
            BigDecimal totalPayPrice = price.multiply(amount).add(closingPrice).setScale(4, BigDecimal.ROUND_DOWN);
            if(MemberWalletCoinEnum.SUBMITSALESWALLETCOINORDER_TYPE.getValue().equals(type.toString())) {
                //买入,所需总费用跟用户USDT金额进行比较
                if (totalPayPrice.compareTo(walletCoinUsdt.getAvailableBalance()) > 0) {
                    return Result.fail(MessageSourceUtils.getString("order_service_0010"));
                }
            }else {
                //卖出,所需总费用跟用户所对应的币种金额进行比较
                if (amount.compareTo(walletCoin.getAvailableBalance()) > 0) {
                    return Result.fail(MessageSourceUtils.getString("order_service_0010"));
                }
            }
            
            CoinOrderMain order = new CoinOrderMain();
            
            // 创建订单
            if (tradeType == 2) {// 如果是限价交易直接插入主表数据
                order.setStatus(1);
                order.setMemId(member.getmId());
                order.setOpenPrice(price.doubleValue());
                order.setOpenTime(new Date());
                order.setOrderNo(generateSimpleSerialno(member.getmId() + ""));
                order.setOrderType(type);
                order.setRewardRatio(price
                        .multiply(amount).doubleValue());
                order.setForceSetPrice(nowPrice.doubleValue());
//                order.setStatus(3);
                order.setSysbol(symbol);
                order.setSysbolNumber(amount);
                order.setSysbolFlatNumber(amount);
                order.setTradeType(tradeType);
                order.setVersion(1);
                order.setClosingPrice(closingPrice);
                orderMapper.addCoinMainOrder(order);
                
                //更新用户钱包信息
                //冻结相应的资产
                if(type == 1) {//如果是买入,所对应的币种增加,USDT账户减少金额
                    // 更新用户的可用金额,冻结金额
                    walletCoinUsdt.setAvailableBalance(walletCoinUsdt.getAvailableBalance()-totalPayPrice.doubleValue());
                    walletCoinUsdt.setFrozenBalance(walletCoinUsdt.getFrozenBalance()+totalPayPrice.doubleValue());
                    walletCoinDao.updateByModel(walletCoinUsdt);
                }else {
                    //如果是卖出,币种减少,USDT增加
                    BigDecimal availableBalance = new BigDecimal(walletCoin.getAvailableBalance()).subtract(amount).setScale(8, BigDecimal.ROUND_HALF_UP);
                    walletCoin.setAvailableBalance(availableBalance.doubleValue());
                    walletCoin.setFrozenBalance(walletCoin.getFrozenBalance()+amount.doubleValue());
                    walletCoinDao.updateByModel(walletCoin);
                } 
            } else {
                //如果是市价交易,主表和附表都需要插入数据
                order.setStatus(3);
                order.setMemId(member.getmId());
                order.setForceSetPrice(nowPrice.doubleValue());
                order.setOpenPrice(nowPrice.doubleValue());
                order.setOpenTime(new Date());
                order.setOrderNo(generateSimpleSerialno(member.getmId() + ""));
                order.setOrderType(type);
                order.setRewardRatio(nowPrice
                        .multiply(amount).doubleValue());
//                order.setStatus(3);
                order.setSysbol(symbol);
                order.setSysbolNumber(amount);
                order.setSysbolFlatNumber(amount);
                order.setTradeType(tradeType);
                order.setVersion(1);
                order.setClosingPrice(closingPrice);
                orderMapper.addCoinMainOrder(order);
                //
                CoinsOrderDetail detail = new CoinsOrderDetail();
                detail.setClosingPrice(closingPrice.doubleValue());
                detail.setCreateTime(new Date());
                detail.setEntrustStatus(1);
                detail.setEntrustType(type);
                detail.setExitPrice(price.doubleValue());
                detail.setExitType(1);
                detail.setMainId(order.getId());
                detail.setMemberId(member.getmId());
                detail.setMemberPhone(member.getPhone());
                detail.setPrePrice(price
                        .multiply(amount).doubleValue());
                detail.setRewardRatio(0.0);
                detail.setSerialno(generateSimpleSerialno(member.getmId() + ""));
                detail.setSymbol(symbol);
                detail.setSymbolSku(amount);
                detail.setSymbolSkuNumber(amount);
                detail.setTradePrice(price.doubleValue());
                detail.setTradeType(tradeType);
                detail.setVersion(1);
                coinOrderDetailMapper.insert(detail);
                
                if(type == 1) {//如果是买入,所对应的币种增加,USDT账户减少金额
                    // 更新用户的可用金额
                    BigDecimal availableBalance = new BigDecimal(walletCoin.getAvailableBalance()).add(amount).setScale(8, BigDecimal.ROUND_HALF_UP);
                    walletCoin.setAvailableBalance(availableBalance.doubleValue());
                    walletCoinDao.updateByModel(walletCoin);
                    
                    walletCoinUsdt.setAvailableBalance(walletCoinUsdt.getAvailableBalance()-totalPayPrice.doubleValue());
                    walletCoinDao.updateByModel(walletCoinUsdt);
                }else {
                    //如果是卖出,币种减少,USDT增加
                    BigDecimal availableBalance = new BigDecimal(walletCoin.getAvailableBalance()).subtract(amount).setScale(8, BigDecimal.ROUND_HALF_UP);
                    walletCoin.setAvailableBalance(availableBalance.doubleValue());
                    walletCoinDao.updateByModel(walletCoin);
                    
                    walletCoinUsdt.setAvailableBalance(walletCoinUsdt.getAvailableBalance()+totalPayPrice.doubleValue());
                    walletCoinDao.updateByModel(walletCoinUsdt);
                }
                
                //返佣
//                calYj(member.getmId(), closingPrice, order);
//                String reference = member.getReference();
                //返佣
//                agentReturn(reference,closingPrice.doubleValue(),detail);
                
            }
            // 流水记录
            MemberAccountFlowRecord record = new MemberAccountFlowRecord();
            record.setCreateTime(new Date());
            if (type == 1) {
                record.setDirectionSource("币币买入"+symbol);
                record.setRemark("买入"+symbol+":"+amount);
                record.setPrice(totalPayPrice.doubleValue());
            } else {
                record.setDirectionSource("币币卖出"+symbol);
                record.setRemark("卖出"+symbol+":"+amount);
                record.setPrice(-totalPayPrice.doubleValue());
            }
            record.setMemberBalance(walletCoinUsdt.getAvailableBalance());
            record.setMemberid(member.getmId());
            record.setSymbolName(symbol);
            record.setMemberName(member.getRealName());
            record.setMemberPhone(member.getPhone());
            
            memberMapper.addFlowRecord(record);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.success(MessageSourceUtils.getString("order_service_0011"));
    }
 
}