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.common.base.Strings;
import com.muchinfo.mtp.proto.Common;
import com.muchinfo.mtp.proto.TkernelMI2;
import com.muchinfo.mtp3century.service.ICommonService;
import com.muchinfo.mtp3century.service.IOrderQueryService;
import com.muchinfo.mtp3century.utils.AjaxResult;
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.DateTimeUtils;
import com.muchinfo.mtp3common.utils.ExportUtil;
import com.muchinfo.mtp3common.utils.SerialNumberUtils;
import com.muchinfo.mtp3common.vo.*;
import com.muchinfo.mtp3interface.mapper.ISystemmanagerMapper;
import com.muchinfo.mtp3interface.mapper.ITradeHolderdetailexMapper;
import com.muchinfo.mtp3pojos.entity.Systemmanager;
import com.muchinfo.mtp3pojos.vo.HolderDetailExRedisVo;
import com.muchinfo.mtp3pojos.vo.ProtoErrorCodes;
import com.muchinfo.mtp3pojos.vo.RealtimeQuoteVo;
import com.muchinfo.mtp3pojos.vo.query.order.*;
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 org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class OrderQueryServiceImpl implements IOrderQueryService {

    private final Logger log = LoggerFactory.getLogger(this.getClass());

    @Resource
    private ISystemmanagerMapper iSystemmanagerMapper;
    @Resource
    private ICommonService iCommonService;
    @Resource
    private ITradeHolderdetailexMapper iTradeHolderdetailexMapper;
    @Resource
    private RabbitTemplate rabbitTemplate;

    @Override
    public PageResult<OrderQueryResult> query(OrderQueryParam param, HttpServletRequest request) {
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        if (systemmanager.getReletype() != 1) {
            //经纪会员查询自己下属客户的订单
            param.setAreauserid(systemmanager.getAreauserid());
        }
        PageResult<OrderQueryResult> pageResult = new PageResult<>();
        IPage<OrderQueryResult> page = new Page<>(param.getPageNum(), param.getPageSize());
        IPage<OrderQueryResult> resultIPage = iTradeHolderdetailexMapper.query(page, param);

        List<HolderDetailExRedisVo> redisData = iCommonService.getHolderDetailExFromRedis(new HolderDetailExRedisVo(), 0);

        resultIPage.getRecords().forEach(a -> {
            // 查询Redis数据，获取定金率等数据, flag=0, 忽略DepositRate（定金率\风险率）条件
            if (CollectionUtils.isNotEmpty(redisData)) {
                for (HolderDetailExRedisVo vo : redisData) {
                    if (vo != null && vo.getTradeid() != null && vo.getTradeid().equals(a.getTradeid())) {
                        a.setDepositratedisplay(new BigDecimal(vo.getDepositratedisplay()));
                    }
                }
            }
        });

        pageResult.setCode(Constants.Success_Code_Design);
        pageResult.setMessage(AjaxResult.dealMsg(MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language")));
        pageResult.setPages(resultIPage.getPages());
        pageResult.setCurrent(resultIPage.getCurrent());
        pageResult.setTotal(resultIPage.getTotal());
        pageResult.setPageSize(resultIPage.getSize());
        pageResult.setData(resultIPage.getRecords());
        return pageResult;
    }

    @Override
    public AjaxResult<OrderQueryResult> queryDetail(OrderQueryParam param, HttpServletRequest request) {
        List<OrderQueryResult> result = iTradeHolderdetailexMapper.query(param);
        List<HolderDetailExRedisVo> redisData = iCommonService.getHolderDetailExFromRedis(new HolderDetailExRedisVo(), 0);
        // 查询Redis数据，获取定金率等数据, flag=0, 忽略DepositRate（定金率\风险率）条件
        if (CollectionUtils.isNotEmpty(redisData)) {
            for (HolderDetailExRedisVo vo : redisData) {
                if (vo != null && vo.getTradeid() != null && vo.getTradeid().equals(result.get(0).getTradeid())) {
                    result.get(0).setDepositratedisplay(new BigDecimal(vo.getDepositratedisplay()));
                }
            }
        }

        Integer buyOrSell = result.get(0).getBuyorsell();
        String goodsCode = result.get(0).getGoodscode();
        Integer decimalPlace = result.get(0).getDecimalplace();
        BigDecimal agreeUnit = result.get(0).getAgreeunit();
        Integer holderQty = result.get(0).getHolderqty();
        BigDecimal holderAmount = result.get(0).getHolderamount();
        // 获取时间行情
        RealtimeQuoteVo quoteVo = iCommonService.getRealtimeQuote(goodsCode, decimalPlace);
        if (quoteVo != null) {
            BigDecimal closePrice;
            if (buyOrSell == 0) {
                // 买持仓
                closePrice = new BigDecimal(quoteVo.getBid().toString()).setScale(decimalPlace, RoundingMode.HALF_UP);
            } else {
                // 卖持仓
                closePrice = new BigDecimal(quoteVo.getAsk().toString()).setScale(decimalPlace, RoundingMode.HALF_UP);
            }
            BigDecimal floatPL = iCommonService.calcFloaPL(goodsCode, agreeUnit, buyOrSell, holderQty, holderAmount);

            result.get(0).setCloseprice(closePrice.toString());
            result.get(0).setFloatpl(floatPL == null ? "-" : floatPL.toString());
        } else {
            result.get(0).setCloseprice("-");
            result.get(0).setFloatpl("-");
        }
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), result.get(0));
    }

    @Override
    public AjaxResult export(OrderQueryParam param, HttpServletRequest request) {
        try {
            Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
            if (systemmanager.getReletype() != 1) {
                //经纪会员查询自己下属客户的订单
                param.setAreauserid(systemmanager.getAreauserid());
            }
            String fileName = "订单查询_" + DateTimeUtils.getDateTime("yyyyMMdd");
            List<OrderQueryResult> resultIPage = iTradeHolderdetailexMapper.query(param);
            if (CollectionUtils.isEmpty(resultIPage)) {
                return AjaxResult.error(Constants.Error_Code_Design, MessageType.QUERY_ERROR_CODE_006.getCode(), request.getHeader("Accept-Language"));
            }
            List<HolderDetailExRedisVo> redisData = iCommonService.getHolderDetailExFromRedis(new HolderDetailExRedisVo(), 0);
            resultIPage.forEach(a -> {
                // 查询Redis数据，获取定金率等数据, flag=0, 忽略DepositRate（定金率\风险率）条件
                if (CollectionUtils.isNotEmpty(redisData)) {
                    for (HolderDetailExRedisVo vo : redisData) {
                        if (vo != null && vo.getTradeid() != null && vo.getTradeid().equals(a.getTradeid())) {
                            a.setDepositratedisplay(new BigDecimal(vo.getDepositratedisplay()));
                        }
                    }
                }
            });
            ExportResult exportResult = ExportUtil.write(fileName, OrderQueryResult.class, resultIPage);
            return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), exportResult);
        } catch (Exception e) {
            log.error("订单查询导出失败，失败原因：" + Arrays.toString(e.getStackTrace()));
            return AjaxResult.error(Constants.Error_Code_Design, MessageType.QUERY_ERROR_CODE_006.getCode(), request.getHeader("Accept-Language"));
        }
    }

    @Override
    public PageResult<TerOrderQueryResult> queryTerOrder(TerOrderQueryParam param, HttpServletRequest request) {
        PageResult<TerOrderQueryResult> pageResult = new PageResult<>();
        //校验
        if (param.getIshis() == 1 && Strings.isNullOrEmpty(String.valueOf(param.getStartdate()))) {
            pageResult.setCode(Constants.Error_Code_Design);
            pageResult.setMessage(AjaxResult.dealMsg(MessageType.QUERY_ERROR_CODE_002.getCode(), request.getHeader("Accept-Language")));
            return pageResult;
        }
        if (param.getIshis() == 1 && Strings.isNullOrEmpty(param.getEnddate())) {
            pageResult.setCode(Constants.Error_Code_Design);
            pageResult.setMessage(AjaxResult.dealMsg(MessageType.QUERY_ERROR_CODE_003.getCode(), request.getHeader("Accept-Language")));
            return pageResult;
        }
        //排除交易模式
        List<Integer> filterTrademodeList = new ArrayList<>();
        filterTrademodeList.add(15);
        filterTrademodeList.add(97);
        filterTrademodeList.add(99);
        param.setFilterTrademodeList(filterTrademodeList);

        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        if (systemmanager.getReletype() != 1) {
            // 会员所属机构为自己
            param.setAreauserid(systemmanager.getAreauserid());
        }
        IPage<TerOrderQueryResult> page = new Page<>(param.getPageNum(), param.getPageSize());
        IPage<TerOrderQueryResult> resultIPage = iTradeHolderdetailexMapper.queryYJCloselList(page, param);
        pageResult.setCode(Constants.Success_Code_Design);
        pageResult.setMessage(AjaxResult.dealMsg(MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language")));
        pageResult.setPages(resultIPage.getPages());
        pageResult.setCurrent(resultIPage.getCurrent());
        pageResult.setTotal(resultIPage.getTotal());
        pageResult.setPageSize(resultIPage.getSize());
        pageResult.setData(resultIPage.getRecords());
        return pageResult;
    }

    @Override
    public AjaxResult terOrderExport(TerOrderQueryParam param, HttpServletRequest request) {
        try {
            Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
            if (systemmanager.getReletype() != 1) {
                // 会员所属机构为自己
                param.setAreauserid(systemmanager.getAreauserid());
            }
            //校验
            if (param.getIshis() == 1 && StringUtils.isEmpty(String.valueOf(param.getStartdate()))) {
                return AjaxResult.error(Constants.Error_Code_Design, MessageType.QUERY_ERROR_CODE_002.getCode(), request.getHeader("Accept-Language"));
            }
            if (param.getIshis() == 1 && StringUtils.isEmpty(String.valueOf(param.getEnddate()))) {
                return AjaxResult.error(Constants.Error_Code_Design, MessageType.QUERY_ERROR_CODE_003.getCode(), request.getHeader("Accept-Language"));
            }
            //排除交易模式
            List<Integer> filterTrademodeList = new ArrayList<>();
            filterTrademodeList.add(15);
            filterTrademodeList.add(97);
            filterTrademodeList.add(99);
            param.setFilterTrademodeList(filterTrademodeList);
            String fileName = "终止单查询_" + DateTimeUtils.getDateTime("yyyyMMdd");
            List<TerOrderQueryResult> resultIPage = iTradeHolderdetailexMapper.queryYJCloselList(param);
            if (CollectionUtils.isEmpty(resultIPage)) {
                return AjaxResult.error(Constants.Error_Code_Design, MessageType.QUERY_ERROR_CODE_006.getCode(), request.getHeader("Accept-Language"));
            }
            ExportResult exportResult = ExportUtil.write(fileName, TerOrderQueryResult.class, resultIPage);
            return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), exportResult);
        } catch (Exception e) {
            log.error("终止单查询导出失败，失败原因：" + Arrays.toString(e.getStackTrace()));
            return AjaxResult.error(Constants.Error_Code_Design, MessageType.QUERY_ERROR_CODE_006.getCode(), request.getHeader("Accept-Language"));
        }
    }

    @Override
    public PageResult<DeliveryOrderResult> queryDeliveryOrder(DeliveryOrderParam param, HttpServletRequest request) {
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        if (systemmanager.getReletype() != 1) {
            // 会员所属机构为自己
            param.setMatchuserid(systemmanager.getAreauserid());
        }
        PageResult<DeliveryOrderResult> pageResult = new PageResult<>();
        IPage<DeliveryOrderResult> page = new Page<>(param.getPageNum(), param.getPageSize());
        IPage<DeliveryOrderResult> resultIPage = iTradeHolderdetailexMapper.queryDeliveryOfflinePage(page, param);
        pageResult.setCode(Constants.Success_Code_Design);
        pageResult.setMessage(AjaxResult.dealMsg(MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language")));
        pageResult.setPages(resultIPage.getPages());
        pageResult.setCurrent(resultIPage.getCurrent());
        pageResult.setTotal(resultIPage.getTotal());
        pageResult.setPageSize(resultIPage.getSize());
        pageResult.setData(resultIPage.getRecords());
        return pageResult;
    }

    @Override
    public AjaxResult<DeliveryOrderResult> deliveryOrderDetail(DeliveryOrderParam param, HttpServletRequest request) {
        List<DeliveryOrderResult> resultIPage = iTradeHolderdetailexMapper.queryDeliveryOfflinePage(param);
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), resultIPage.get(0));
    }

    @Override
    public AjaxResult deliveryOrderExport(DeliveryOrderParam param, HttpServletRequest request) {
        try {
            Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
            if (systemmanager.getReletype() != 1) {
                // 会员所属机构为自己
                param.setMatchuserid(systemmanager.getAreauserid());
            }
            String fileName = "线下交收单_" + DateTimeUtils.getDateTime("yyyyMMdd");
            List<DeliveryOrderResult> resultIPage = iTradeHolderdetailexMapper.queryDeliveryOfflinePage(param);
            if (CollectionUtils.isEmpty(resultIPage)) {
                return AjaxResult.error(Constants.Error_Code_Design, MessageType.QUERY_ERROR_CODE_006.getCode(), request.getHeader("Accept-Language"));
            }
            ExportResult exportResult = ExportUtil.write(fileName, OrderQueryResult.class, resultIPage);
            return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), exportResult);
        } catch (Exception e) {
            log.error("线下交收单导出失败，失败原因：" + Arrays.toString(e.getStackTrace()));
            return AjaxResult.error(Constants.Error_Code_Design, MessageType.QUERY_ERROR_CODE_006.getCode(), request.getHeader("Accept-Language"));
        }
    }

    @Override
    public PageResult<OrderDateQueryResult> queryOrderDate(OrderDateQueryParam param, HttpServletRequest request) {
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        if (systemmanager.getReletype() != 1) {
            param.setAreauserid(systemmanager.getAreauserid());
        }
        PageResult<OrderDateQueryResult> pageResult = new PageResult<>();
        IPage<OrderDateQueryResult> page = new Page<>(param.getPageNum(), param.getPageSize());
        IPage<OrderDateQueryResult> resultIPage = iTradeHolderdetailexMapper.queryOrderDate(page, param);
        pageResult.setCode(Constants.Success_Code_Design);
        pageResult.setMessage(AjaxResult.dealMsg(MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language")));
        pageResult.setPages(resultIPage.getPages());
        pageResult.setCurrent(resultIPage.getCurrent());
        pageResult.setTotal(resultIPage.getTotal());
        pageResult.setPageSize(resultIPage.getSize());
        pageResult.setData(resultIPage.getRecords());
        return pageResult;
    }

    @Override
    public AjaxResult orderDateExport(OrderDateQueryParam param, HttpServletRequest request) {
        try {
            Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
            if (systemmanager.getReletype() != 1) {
                param.setAreauserid(systemmanager.getAreauserid());
            }
            String fileName = "订单日报表_" + DateTimeUtils.getDateTime("yyyyMMdd");
            List<OrderDateQueryResult> resultIPage = iTradeHolderdetailexMapper.queryOrderDate(param);
            if (CollectionUtils.isEmpty(resultIPage)) {
                return AjaxResult.error(Constants.Error_Code_Design, MessageType.QUERY_ERROR_CODE_006.getCode(), request.getHeader("Accept-Language"));
            }
            ExportResult exportResult = ExportUtil.write(fileName, OrderDateQueryResult.class, resultIPage);
            return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), exportResult);
        } catch (Exception e) {
            log.error("线下交收单导出失败，失败原因：" + Arrays.toString(e.getStackTrace()));
            return AjaxResult.error(Constants.Error_Code_Design, MessageType.QUERY_ERROR_CODE_006.getCode(), request.getHeader("Accept-Language"));
        }
    }

    @Override
    public PageResult<ForcedOrderResult> queryForcedOrder(ForcedOrderParam param, HttpServletRequest request) {
        PageResult<ForcedOrderResult> pageResult = new PageResult<>();
        if (param.getIshis() == 1) {
            // 历史查询
            if (Strings.isNullOrEmpty(param.getStartdate())) {
                pageResult.setCode(Constants.Error_Code_Design);
                pageResult.setMessage(AjaxResult.dealMsg(MessageType.QUERY_ERROR_CODE_002.getCode(), request.getHeader("Accept-Language")));
                return pageResult;
            }
            if (Strings.isNullOrEmpty(param.getEnddate())) {
                pageResult.setCode(Constants.Error_Code_Design);
                pageResult.setMessage(AjaxResult.dealMsg(MessageType.QUERY_ERROR_CODE_003.getCode(), request.getHeader("Accept-Language")));
                return pageResult;
            }
        }
        IPage<ForcedOrderResult> page = new Page<>(param.getPageNum(), param.getPageSize());
        IPage<ForcedOrderResult> resultIPage = iTradeHolderdetailexMapper.queryForcedOrder(page, param);
        pageResult.setCode(Constants.Success_Code_Design);
        pageResult.setMessage(AjaxResult.dealMsg(MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language")));
        pageResult.setPages(resultIPage.getPages());
        pageResult.setCurrent(resultIPage.getCurrent());
        pageResult.setTotal(resultIPage.getTotal());
        pageResult.setPageSize(resultIPage.getSize());
        pageResult.setData(resultIPage.getRecords());
        return pageResult;
    }

    @Override
    public AjaxResult forcedOrderExport(ForcedOrderParam param, HttpServletRequest request) {
        try {
            String fileName = "强制终止单_" + DateTimeUtils.getDateTime("yyyyMMdd");
            List<ForcedOrderResult> resultIPage = iTradeHolderdetailexMapper.queryForcedOrder(param);
            if (CollectionUtils.isEmpty(resultIPage)) {
                return AjaxResult.error(Constants.Error_Code_Design, MessageType.QUERY_ERROR_CODE_006.getCode(), request.getHeader("Accept-Language"));
            }
            ExportResult exportResult = ExportUtil.write(fileName, ForcedOrderResult.class, resultIPage);
            return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), exportResult);
        } catch (Exception e) {
            log.error("线下交收单导出失败，失败原因：" + Arrays.toString(e.getStackTrace()));
            return AjaxResult.error(Constants.Error_Code_Design, MessageType.QUERY_ERROR_CODE_006.getCode(), request.getHeader("Accept-Language"));
        }
    }

    @Override
    public AjaxResult forcedOrderRecover(String closeid, HttpServletRequest request) {
        ForcedOrderParam param = ForcedOrderParam.builder().closeid(closeid).build();
        List<ForcedOrderResult> results = iTradeHolderdetailexMapper.queryForcedOrder(param);
        for (ForcedOrderResult result : results) {
            //调用52101 服务“斩仓恢复”接口
            Long uuid = SerialNumberUtils.getNewSerialNumber(SerialNumberUtils.prefix_trade);
            Calculator ca = new Calculator(uuid, FunCodeConstants.FuncCode_RiskCloseRecoverReq);
            SerialNumberUtils.lockMap.put(uuid, ca);

            TkernelMI2.RiskCloseRecoverReq.Builder builder = TkernelMI2.RiskCloseRecoverReq.newBuilder();
            // Header
            Common.MessageHead.Builder hd = Common.MessageHead.newBuilder();
            hd.setUUID(String.valueOf(uuid));
            hd.setFunCode(FunCodeConstants.FuncCode_RiskCloseRecoverReq);
            hd.setMarketID(result.getMarketid().intValue());
            hd.setUserID(result.getUserid().intValue());
            hd.setAccountID(result.getAccountid());
            builder.setHeader(hd);

            // Body
            builder.setUserID(result.getUserid().intValue());
            builder.setAccountID(result.getAccountid());
            builder.setTradeID(Long.parseLong(result.getTradeid()));
            builder.setBuyOrSell(result.getBuyorsell());

            byte[] body = ProtoHelper.getNTAS(builder.build().toByteArray(), FunCodeConstants.FuncCode_RiskCloseRecoverReq);
            rabbitTemplate.send(SysConstants.TradeCpReq, new Message(body, new MessageProperties()));

            synchronized (ca) {
                try {
                    ca.wait(6000);
                    Object o = ca.obj;
                    if (o != null) {
                        TkernelMI2.RiskCloseRecoverRsp rsp_ = (TkernelMI2.RiskCloseRecoverRsp) o;
                        if (rsp_.getRetCode() == 0) {
                            return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM011.getCode(), request.getHeader("Accept-Language"));
                        } else {
                            return AjaxResult.error(Constants.Error_Code_Design, ProtoErrorCodes.resultMsg(rsp_.getRetCode()), "", null);
                        }
                    } else {
                        return AjaxResult.error(Constants.Error_Code_Design, MessageType.MESSAGE_ERROR_CODE_SYSTEM006.getCode(), request.getHeader("Accept-Language"));
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    SerialNumberUtils.lockMap.remove(uuid);
                }
            }
        }
        return null;
    }

    @Override
    public AjaxResult<MonitorddjkCountResult> monitorddjkCount(MonitorddjkParam param, HttpServletRequest request) {
        if (param.getRisk() == null) {
            param.setRisk(new BigDecimal("50.0"));
        }

        MonitorddjkCountResult result = new MonitorddjkCountResult();
        HolderDetailExRedisVo build = HolderDetailExRedisVo.builder()
                .risk(param.getRisk())
                .buyorsell(param.getBuyorsell())
                .userfullname(param.getUserfullname())
                .goodsfullname(param.getGoodsfullname())
                .parentusername(param.getParentusername())
                .build();
        //销售总数量
        double sellCount = 0.0;
        //回购总数量
        double buyBackCount = 0.0;
        //持仓总金额
        BigDecimal totalAmount = BigDecimal.valueOf(0);
        //持仓均价
        String avgHolderPrice = "0";
        //总浮动盈亏
        BigDecimal totalFloatPL = BigDecimal.valueOf(0);
        List<HolderDetailExRedisVo> redisData = iCommonService.getHolderDetailExFromRedis(build, 2);

        for (HolderDetailExRedisVo vo : redisData) {
            if (vo.getBuyorsell().equals(0)) {
                buyBackCount = (vo.getHolderqty() * vo.getAgreeunit()) + buyBackCount;
            } else {
                sellCount = (vo.getHolderqty() * vo.getAgreeunit()) + sellCount;
            }
            totalAmount = totalAmount.add(vo.getHolderamount());
            totalFloatPL = totalFloatPL.add(vo.getFloatpl());
        }

        //设置销售、回购总数量
        result.setSellCount(sellCount);
        result.setBuyBackCount(buyBackCount);
        result.setNetcurpositionqty(buyBackCount - sellCount);
        double totalCount = sellCount + buyBackCount;
        avgHolderPrice = totalCount == 0.0 ? "-" : totalAmount.divide(BigDecimal.valueOf(sellCount + buyBackCount), 2, RoundingMode.HALF_UP).toString();
        result.setAvgholderprice(avgHolderPrice);
        result.setFloatpl(totalFloatPL);
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), result);
    }

    @Override
    public PageResult<HolderDetailExRedisVo> monitorddjk(MonitorddjkParam param, HttpServletRequest request) {
        HolderDetailExRedisVo build = HolderDetailExRedisVo.builder()
                .risk(param.getRisk())
                .buyorsell(param.getBuyorsell())
                .userfullname(param.getUserfullname())
                .goodsfullname(param.getGoodsfullname())
                .parentusername(param.getParentusername())
                .build();
        // flag=1:YJ(按定金率，值小风险大  flag=2:交易中心(按风险率，值大风险大)
        List<HolderDetailExRedisVo> resultList = iCommonService.getHolderDetailExFromRedis(build, 2);
        // 排序
        List<HolderDetailExRedisVo> newResult;
        PageResult<HolderDetailExRedisVo> pageResult = new PageResult<>();
        if (CollectionUtils.isNotEmpty(resultList)) {
            newResult = resultList.stream()
                    .sorted(Comparator.comparing(HolderDetailExRedisVo::getDepositrate).reversed())
                    .collect(Collectors.toList());

            // 本页数据汇总
            List<HolderDetailExRedisVo> pageList = new ArrayList<>();

            int index = 0;
            int startIndex = (param.getPageNum() - 1) * param.getPageSize();
            int endIndex = param.getPageNum() * param.getPageSize();
            for (HolderDetailExRedisVo p : newResult) {
                if (index >= startIndex && index < endIndex) {
                    pageList.add(p);
                }
                index++;
            }
            pageResult.setData(pageList);
        }
        //设置分页列表
        pageResult.setCode(Constants.Success_Code_Design);
        pageResult.setMessage(AjaxResult.dealMsg(MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language")));
        pageResult.setCurrent(Long.valueOf(param.getPageNum()));
        pageResult.setTotal((long) resultList.size());
        pageResult.setPageSize(Long.valueOf(param.getPageSize()));
        return pageResult;
    }

}
