package com.muchinfo.mtp3century.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.protobuf.InvalidProtocolBufferException;
import com.muchinfo.mtp.proto.AccountRedis;
import com.muchinfo.mtp.proto.Common;
import com.muchinfo.mtp.proto.SystemMI1;
import com.muchinfo.mtp3century.service.ICommonService;
import com.muchinfo.mtp3century.service.IMarketRunManageService;
import com.muchinfo.mtp3century.utils.RedisServiceUtil;
import com.muchinfo.mtp3common.enumtype.Constants;
import com.muchinfo.mtp3common.enumtype.FunCodeConstants;
import com.muchinfo.mtp3common.enumtype.MessageType;
import com.muchinfo.mtp3common.enumtype.SysConstants;
import com.muchinfo.mtp3common.utils.*;
import com.muchinfo.mtp3century.utils.AjaxResult;
import com.muchinfo.mtp3common.vo.Calculator;
import com.muchinfo.mtp3common.vo.PageResult;
import com.muchinfo.mtp3common.vo.ProtoHelper;
import com.muchinfo.mtp3interface.mapper.*;
import com.muchinfo.mtp3pojos.entity.Goods;
import com.muchinfo.mtp3pojos.entity.Market;
import com.muchinfo.mtp3pojos.entity.Systemmanager;
import com.muchinfo.mtp3pojos.entity.Useraccount;
import com.muchinfo.mtp3pojos.vo.ProtoErrorCodes;
import com.muchinfo.mtp3pojos.vo.marketrun.*;
import com.muchinfo.mtp3pojos.vo.query.position.PositionSheetParam;
import com.muchinfo.mtp3pojos.vo.query.position.PositionSheetResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import com.muchinfo.mtp.proto.AccountRedis.AccRiskInfo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

@Service
public class MarketRunManageServiceImpl implements IMarketRunManageService {
    private final Logger log = LoggerFactory.getLogger(this.getClass());
    @Resource
    private ICommonService iCommonService;
    @Resource
    private ISystemmanagerMapper iSystemmanagerMapper;
    @Resource
    private SystemmanagerServiceImpl systemmanagerService;
    @Resource
    private RabbitTemplate rabbitTemplate;
    @Resource
    private ITradeOrderdetailMapper iTradeOrderdetailMapper;
    @Resource
    private RedisServiceUtil redisServiceUtil;
    @Resource
    private ITaaccountMapper taaccountMapper;
    @Resource
    private IUseraccountMapper iUseraccountMapper;
    @Resource
    private IGoodsMapper iGoodsMapper;
    @Resource
    private IMarketMapper iMarketMapper;
    @Resource
    private QueryServiceImpl queryService;

    @Override
    public PageResult<MarketRunLoginUserResult> queryUserLogin(String loginid, Integer pageNum, Integer pageSize, HttpServletRequest request) {
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        Long memberuserid = null;
        Long parentuserid = null;
        if (systemmanager.getReletype() == 2) {
            memberuserid = systemmanager.getAreauserid();
        } else if (systemmanager.getReletype() == 3) {
            parentuserid = systemmanager.getAreauserid();
        }
        IPage<MarketRunLoginUserResult> page = new Page<>(pageNum, pageSize);
        IPage<MarketRunLoginUserResult> queryResultIPage = iSystemmanagerMapper.queryUserOnlineByPage(page, loginid, memberuserid, parentuserid);
        PageResult<MarketRunLoginUserResult> result = new PageResult<>();
        result.setCode(Constants.Success_Code_Design);
        result.setMessage(AjaxResult.dealMsg(MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language")));
        result.setPages(queryResultIPage.getPages());
        result.setCurrent(queryResultIPage.getCurrent());
        result.setTotal(queryResultIPage.getTotal());
        result.setPageSize(queryResultIPage.getSize());
        result.setData(queryResultIPage.getRecords());
        return result;
    }

    @Override
    public AjaxResult downonline(Long loginid, HttpServletRequest request) {
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        Long uuid = SerialNumberUtils.getNewSerialNumber(SerialNumberUtils.prefix_login);
        SystemMI1.ManageKickoffReq.Builder builder = SystemMI1.ManageKickoffReq.newBuilder();
        Common.MessageHead.Builder hd = Common.MessageHead.newBuilder();
        hd.setUUID(uuid.toString());
        hd.setClientTime(System.currentTimeMillis());
        hd.setResponseTopic(SysConstants.RabbitUserNtfKey);
        hd.setFunCode(FunCodeConstants.FunCode_Trade_ManageKickoffReq);
        builder.setHeader(hd);
        if (loginid != null) {
            builder.addLoginIDs(loginid);
        }
        if (loginid == null) {
            systemmanagerService.writeOperateLog(SysConstants.CLIENT_ONLINE_QUERY, "强制所有用户下线", systemmanager, null, null, null);
        } else {
            systemmanagerService.writeOperateLog(SysConstants.CLIENT_ONLINE_QUERY, "强制用户下线:" + loginid, systemmanager, null, null, null);
        }

        log.debug("强制下线：{}", builder.build());
        Calculator ca = new Calculator(uuid);
        SerialNumberUtils.lockMap.put(uuid, ca);
        byte[] body = ProtoHelper.getNTAS(builder.build().toByteArray(), FunCodeConstants.FunCode_Trade_ManageKickoffReq);
        rabbitTemplate.send(SysConstants.RabbitUserNtfKey, new Message(body, new MessageProperties()));

        synchronized (ca) {
            try {
                ca.wait(5000);
                Object rsp = ca.obj;
                if (rsp != null) {
                    SystemMI1.ManageKickoffRsp rsp_ = (SystemMI1.ManageKickoffRsp) rsp;
                    if (rsp_.getRetCode() == 0) {
                        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MARKET_RUN_MESSAGE_001.getCode(), request.getHeader("Accept-Language"));
                    } else {
                        return AjaxResult.error(Constants.Error_Code_Design, ProtoErrorCodes.resultMsg(rsp_.getRetCode()), "");
                    }
                } else {
                    return AjaxResult.success(Constants.Success_Code_Design, MessageType.MARKET_RUN_MESSAGE_001.getCode(), request.getHeader("Accept-Language"));
                }
            } catch (InterruptedException e) {
                log.error("强制下线/强制所有用户下线，失败原因：" + Arrays.toString(e.getStackTrace()));
            } finally {
                SerialNumberUtils.lockMap.remove(uuid);
            }
        }
        return null;
    }

    @Override
    public PageResult<MarketRunCutPositionResult> queryCutposition(Integer pageNum, Integer pageSize, HttpServletRequest request) {
        IPage<MarketRunCutPositionResult> page = new Page<>(pageNum, pageSize);
        IPage<MarketRunCutPositionResult> queryResultIPage = iTradeOrderdetailMapper.queryCutListFromOrderDetail(page);
        PageResult<MarketRunCutPositionResult> result = new PageResult<>();
        result.setCode(Constants.Success_Code_Design);
        result.setMessage(AjaxResult.dealMsg(MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language")));
        result.setPages(queryResultIPage.getPages());
        result.setCurrent(queryResultIPage.getCurrent());
        result.setTotal(queryResultIPage.getTotal());
        result.setPageSize(queryResultIPage.getSize());
        result.setData(queryResultIPage.getRecords());
        return result;
    }

    @Override
    public AjaxResult<MarketRunInitInvestor> initInvestor(HttpServletRequest request) {
        MarketRunInitInvestor marketRunInitInvestor = new MarketRunInitInvestor();
        //是否按风险率风控
        String sp = iCommonService.getSysparmById(SysConstants.SYSPARAM_CODE_ISSHOWRATE);
        if (StringUtils.isNotBlank(sp))
            marketRunInitInvestor.setIsshowrate(sp);
        else
            marketRunInitInvestor.setIsshowrate("1");

        //是否按安全度风控
        String sp1 = iCommonService.getSysparmById(SysConstants.SYSPARAM_CODE_ISSHOWSAFE);
        if (StringUtils.isNotBlank(sp1))
            marketRunInitInvestor.setIsshowsafe(sp);
        else
            marketRunInitInvestor.setIsshowrate("1");

        //是否显示授信金额
        String sp2 = iCommonService.getSysparmById(SysConstants.SYSPAMA_CODE_SHOUXIN);
        if (StringUtils.isNotBlank(sp2))
            marketRunInitInvestor.setIsshowshouxin(sp);
        else
            marketRunInitInvestor.setIsshowrate("1");
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), marketRunInitInvestor);
    }

    @Override
    public AjaxResult<MarketRunInvestorResult> investor(MarketRunInvestorParam param, HttpServletRequest request) {
        try {
            Systemmanager user = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
            List<MarketRunInvestorResult> result = getAccountRisk(param, 1, user);
            return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), result);
        } catch (Exception e) {
            log.error("账户风险监控信息加载失败，失败原因：" + Arrays.toString(e.getStackTrace()));
            return AjaxResult.error(Constants.Error_Code_Design, MessageType.MESSAGE_ERROR_CODE_SYSTEM002.getCode(), request.getHeader("Accept-Language"));
        }
    }

    @Override
    public AjaxResult<MarketRunMemberResult> memberRisk(MarketRunInvestorParam param, HttpServletRequest request) {
        try {
            Systemmanager user = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
            param.setSearchtype(0);
            List<MarketRunInvestorResult> result = getAccountRisk(param, 2, user);
            return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), result);
        } catch (Exception e) {
            log.error("做市会员监控信息加载失败，失败原因：" + Arrays.toString(e.getStackTrace()));
            return AjaxResult.error(Constants.Error_Code_Design, MessageType.MESSAGE_ERROR_CODE_SYSTEM002.getCode(), request.getHeader("Accept-Language"));
        }
    }

    @Override
    public AjaxResult<AccPosInfoVo> accpage(Long accountid, HttpServletRequest request) {
        try {
            List<AccPosInfoVo> results = new ArrayList<>();
            byte[] valuebts = redisServiceUtil.getBytes("risk:" + accountid);
            AccountRedis.AccRiskInfo accRiskInfo = null;
            if (valuebts != null) {
                accRiskInfo = AccountRedis.AccRiskInfo.newBuilder().mergeFrom(valuebts).build();
                log.info("risk:" + accountid + "--------------accRiskInfo:" + accRiskInfo);

                TaaccountMonitorVo vo = taaccountMapper.getMonitorInvestor(accountid, null);
                results = generateAccPosInfo(accRiskInfo, null, vo, accountid);
            }
            return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), results);
        } catch (Exception e) {
            log.error("设置风险率失败，请检查！失败原因：" + Arrays.toString(e.getStackTrace()));
            return AjaxResult.error(Constants.Error_Code_Design, MessageType.MESSAGE_ERROR_CODE_SYSTEM002.getCode(), request.getHeader("Accept-Language"));
        }
    }

    @Override
    public AjaxResult<PositionSheetResult> queryHolderDetailMonitor(Long accountid, Long goodsid,  HttpServletRequest request) {
        PositionSheetParam param = new PositionSheetParam();
        param.setAccountId(accountid.toString());
        param.setGoodsId(goodsid);
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        //监控不会传市场id，这边查询一下
        if (param.getGoodsId() != null && param.getGoodsId() > 0) {
            Goods g = iGoodsMapper.selectOne(new QueryWrapper<Goods>().eq("goodsid",param.getGoodsId()));
            param.setMarketId(g.getMarketid());
        }
        if(queryService.checkMarketAuth(systemmanager, param.getMarketId(), param.getOrgztypes())){
            return AjaxResult.error(Constants.Error_Code_Design,MessageType.QUERY_ERROR_CODE_004.getCode(), request.getHeader("Accept-Language"));
        }
        if (systemmanager.getReletype() != 1){
            param.setAreaUserid(systemmanager.getAreauserid());
        }

        List<PositionSheetResult> results = iTradeOrderdetailMapper.queryTradeHolderDetailList(param);
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), results);
    }

    private List<AccPosInfoVo> generateAccPosInfo(AccRiskInfo accRiskInfo, AccPosInfoVo param, TaaccountMonitorVo taVo, Long accountid) {
        List<AccPosInfoVo> resultList = new ArrayList<>();
        List<AccountRedis.AccPosInfo> list = accRiskInfo.getPOSINFOList();
        AccountRedis.AccPosInfo l = null;
        int size = list.size();
        List<Long> ids = new ArrayList<>();
        // #6653 【交易中心-管理端】账户持仓汇总监控界面的单据在数量被平仓完的情况下还会一直显示
        if (size == 0){
            // 无记录时返回空记录
            return resultList;
        }
        for (AccountRedis.AccPosInfo accPosInfo : list) {
            l = accPosInfo;

            // 根据商品条件过滤
            if (param != null && param.getGoodsid() != null && !param.getGoodsid().equals((long) l.getGOODSID())) {
                continue;
            }

            ids.add((long) l.getGOODSID());
            AccPosInfoVo avo = new AccPosInfoVo();
            avo.setGoodsid((long) l.getGOODSID());
            avo.setMargin(l.getMARGIN());
            avo.setBuy_hold_qty(l.getBUYHOLDQTY());
            avo.setBuy_hold_value(l.getBUYHOLDVALUE());
            avo.setTotal_float_pl(0.0);
            if (l.hasBUYFLOATPL()) {
                avo.setBuy_float_pl(l.getBUYFLOATPL());
                avo.setTotal_float_pl(l.getBUYFLOATPL());
            }
            avo.setSell_hold_qty(l.getSELLHOLDQTY());
            avo.setSell_hold_value(l.getSELLHOLDVALUE());
            if (l.hasSELLFLOATPL()) {
                avo.setSell_float_pl(l.getSELLFLOATPL());
                avo.setTotal_float_pl(avo.getTotal_float_pl() + l.getSELLFLOATPL());
            }
            avo.setQuote_price_buy(l.getQUOTEPRICEBUY());
            avo.setQuote_price_sell(l.getQUOTEPRICESELL());
            if (l.hasQUOTEPRICELAST())
                avo.setQuote_price_last(l.getQUOTEPRICELAST());

            //资金账户
            avo.setAccountid(accountid);
            //用户名称
            avo.setUsername(accountid + "/" + taVo.getLoginid() + "/" + taVo.getUseraccountname());
            //上级机构
            avo.setParentname(taVo.getParentusername());
            //占用保证金
            avo.setMargin((BigDecimal.valueOf(accRiskInfo.getSumMargin()).doubleValue()));

            resultList.add(avo);
        }
        List<Goods> goods = iGoodsMapper.selectList(new QueryWrapper<Goods>().in("goodsid", ids));
        Map<Long, String> gnames = new HashMap<>();
        goods.forEach(pg -> {
            gnames.put(pg.getGoodsid(), pg.getGoodsname());
        });

        Map<Long, Integer> dp = new HashMap<>();
        goods.forEach(pg -> {
            dp.put(pg.getGoodsid(), pg.getDecimalplace());
        });

        Map<Long, Integer> tm = new HashMap<>();
        for (Goods g : goods) {
            Market m = iMarketMapper.selectOne(new QueryWrapper<Market>().eq("marketid", g.getMarketid()));
            if (m != null) {
                tm.put(g.getGoodsid(), m.getTrademode());
            }
        }
        Map<Long, BigDecimal> gunits = new HashMap<>();
        goods.forEach(pg -> {
            gunits.put(pg.getGoodsid(), pg.getAgreeunit());
        });

        for (AccPosInfoVo accPosInfoVo : resultList) {
            accPosInfoVo.setGoodsname(gnames.get(accPosInfoVo.getGoodsid()));
            accPosInfoVo.setDecimalplace(dp.get(accPosInfoVo.getGoodsid()));
            accPosInfoVo.setTrademode(tm.get(accPosInfoVo.getGoodsid()));
            // 格式化均价 金额/(数量*合约乘数)
            int goodsDP = dp.get(accPosInfoVo.getGoodsid()) + 1;
            BigDecimal goodsAU = gunits.get(accPosInfoVo.getGoodsid());
            if (accPosInfoVo.getBuy_hold_qty() > 0) {
                accPosInfoVo.setBuy_avg_price(BigDecimal.valueOf(accPosInfoVo.getBuy_hold_value()).divide(
                        new BigDecimal(accPosInfoVo.getBuy_hold_qty()).multiply(goodsAU), goodsDP, RoundingMode.HALF_UP).doubleValue());
            }
            if (accPosInfoVo.getSell_hold_qty() > 0) {
                accPosInfoVo.setSell_avg_price(BigDecimal.valueOf(accPosInfoVo.getSell_hold_value()).divide(
                        new BigDecimal(accPosInfoVo.getSell_hold_qty()).multiply(goodsAU), goodsDP, RoundingMode.HALF_UP).doubleValue());
            }
        }
        return resultList;
    }

    private List<MarketRunInvestorResult> getAccountRisk(MarketRunInvestorParam param, int type, Systemmanager user) throws InvalidProtocolBufferException {
        List<MarketRunInvestorResult> resultList = new ArrayList<>();
        Double risk = param.getRisk() == null ? 50.0 : param.getRisk();
        String key;
        if (param.getOrderbytype() == 1) {
            //安全度
            key = type == 1 ? "sort_by_saferate_investor" : "sort_by_saferate_member";
        } else {
            //风险率
            key = type == 1 ? "sort_by_rate_investor" : "sort_by_rate_member";
        }
        Set<String> set = null;
        if (key.equals("sort_by_rate_investor") || key.equals("sort_by_rate_member")) {
            //风险率
            if (risk.compareTo(0.0) == 0) {
                set = redisServiceUtil.getCacheSet(key, -10000, 10000000.0);
            } else {
                set = redisServiceUtil.getCacheSet(key, risk / 100, 10000000.0);
            }
        } else {
            //安全度
            if (risk.compareTo(0.0) == 0) {
                set = redisServiceUtil.getCacheSet(key, -100000, 100.0);
            } else {
                set = redisServiceUtil.getCacheSet(key, -100000.0, risk / 100);
            }
        }

        if (CollectionUtils.isNotEmpty(set)) {
            TaaccountMonitorVo vo;
            for (Object p : set) {
                String str_accountid = p.toString();
                if (param.getPuserid() == null) {
                    vo = taaccountMapper.getMonitorInvestor(Long.valueOf(str_accountid), null);
                } else {
                    vo = taaccountMapper.getMonitorInvestor(Long.valueOf(str_accountid), param.getPuserid());
                }
                if (Objects.isNull(vo)) {
                    continue;
                }

                if (param.getSearchtype() == 5 && vo.getUsertype() != 5) {
                    continue;
                } else if (param.getSearchtype() == 2) {
                    if (vo.getUsertype() != 2 && vo.getUsertype() != 3)
                        continue;
                }

                if (user.getReletype() != 1) {
                    if (user.getReletype() == 2) {
                        String[] roletyes = param.getOrgztypes().split(",");
                        String role = "";
                        //如果其中一个有权限
                        for (String roletype : roletyes) {
                            if (roletype.equals("3")) {
                                role = roletype;
                                break;
                            }
                        }
                        if (role.equals("3")) {
                            if (vo.getParentuserid().compareTo(user.getAreauserid()) == 0
                                    || vo.getUserid().compareTo(user.getAreauserid()) == 0) {

                            } else {
                                Useraccount broker = iUseraccountMapper.selectOne(new QueryWrapper<Useraccount>().eq("userid", vo.getMemberuserid()));
                                if (!broker.getMemberuserid().equals(user.getAreauserid())
                                        && !broker.getParentuserid().equals(user.getAreauserid())) {
                                    continue;
                                }
                            }
                        } else {
                            if ((type == 1 && vo.getMemberuserid().compareTo(user.getAreauserid()) != 0) ||
                                    (type == 2 && vo.getUserid().compareTo(user.getAreauserid()) != 0)) {
                                continue;
                            }
                        }
                    } else {
                        if (!vo.getSubarealevelpath().contains("," + user.getAreauserid() + ",")) {
                            continue;
                        }
                    }
                }

                MarketRunInvestorResult mvo = new MarketRunInvestorResult();
                if (2 != vo.getUsertype()) {
                    mvo.setParentusername(vo.getParentusername());
                } else {
                    mvo.setParentusername("");
                }
                mvo.setMemberusername(vo.getMemberusername());
                mvo.setAccountname(vo.getAccountname());
                if (StringUtils.isBlank(mvo.getAccountname())) {
                    mvo.setAccountname(vo.getUseraccountname());
                }
                byte[] valuebts = redisServiceUtil.getBytes("risk:" + str_accountid);
                if (valuebts == null) {
                    continue;
                }
                AccRiskInfo accRiskInfo = AccRiskInfo.newBuilder().mergeFrom(valuebts).build();

                log.debug(accRiskInfo.getACCID() + "accRiskInfo={}", accRiskInfo.toString());

                mvo.setAccountid(accRiskInfo.getACCID());
                mvo.setBalance(BigDecimal.valueOf(accRiskInfo.getBALANCE()));
                mvo.setCurriskrate(BigDecimal.valueOf(accRiskInfo.getCURRISKRATE()).multiply(BigDecimal.valueOf(100d)).setScale(2, RoundingMode.DOWN));
                mvo.setCurrisklv(accRiskInfo.getCURRISKLV());
                mvo.setNetbalance(BigDecimal.valueOf(accRiskInfo.getNetBALANCE()));
                mvo.setCurrisksaferate(BigDecimal.valueOf(accRiskInfo.getCURRISKSAFERATE() * 100));
                mvo.setCurrisksafelv(accRiskInfo.getCURRISKSAFELV());
                mvo.setCredit(BigDecimal.valueOf(accRiskInfo.getCredit()).setScale(0, RoundingMode.HALF_UP));
                mvo.setAvailmargin(BigDecimal.valueOf(accRiskInfo.getAVAILMARGIN()).setScale(2, RoundingMode.HALF_UP));
                mvo.setTotalfloatpl(BigDecimal.valueOf(accRiskInfo.getTOTALFLOATPL()).setScale(2, RoundingMode.HALF_UP));

                double totalfrozen = accRiskInfo.getTOTALFREEZEMARGIN() + accRiskInfo.getTOTALFREEZEFEE()
                        + accRiskInfo.getTOTALOUTAMOUNTFREEZE() + accRiskInfo.getTOTALOTHERMONEYFREEZE();
                mvo.setTotalfrozen(new BigDecimal(totalfrozen).setScale(2, RoundingMode.HALF_UP));

                BigDecimal freezemargin = vo.getFreezemargin();
                mvo.setFreezemargin(freezemargin);

                //占用
                mvo.setUsedmargin(BigDecimal.valueOf(accRiskInfo.getSumMargin()));
                resultList.add(mvo);
            }
        }

        return resultList;
    }
}
