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.AccountRedis;
import com.muchinfo.mtp.proto.Common;
import com.muchinfo.mtp.proto.QuoteMI1;
import com.muchinfo.mtp.proto.TkernelMI2;
import com.muchinfo.mtp3century.service.ICommonService;
import com.muchinfo.mtp3century.service.IQueryService;
import com.muchinfo.mtp3century.utils.AjaxResult;
import com.muchinfo.mtp3century.utils.RedisServiceUtil;
import com.muchinfo.mtp3common.enumtype.*;
import com.muchinfo.mtp3common.utils.SerialNumberUtils;
import com.muchinfo.mtp3common.vo.*;
import com.muchinfo.mtp3common.utils.DateTimeUtils;
import com.muchinfo.mtp3common.utils.ExportUtil;
import com.muchinfo.mtp3interface.mapper.*;
import com.muchinfo.mtp3pojos.entity.*;
import com.muchinfo.mtp3pojos.vo.ProtoErrorCodes;
import com.muchinfo.mtp3pojos.vo.common.OrganSelectParam;
import com.muchinfo.mtp3pojos.vo.common.OrganSelectResult;
import com.muchinfo.mtp3pojos.vo.query.accounttransaction.AccountTransactionQueryParam;
import com.muchinfo.mtp3pojos.vo.query.accounttransaction.AccountTransactionQueryResult;
import com.muchinfo.mtp3pojos.vo.query.commission.*;
import com.muchinfo.mtp3pojos.vo.query.contract.*;
import com.muchinfo.mtp3pojos.vo.query.deliveryorder.*;
import com.muchinfo.mtp3pojos.vo.query.goodstrade.GoodsTradeQueryParam;
import com.muchinfo.mtp3pojos.vo.query.goodstrade.GoodsTradeQueryResult;
import com.muchinfo.mtp3pojos.vo.query.investorsum.InvestorSumQueryParam;
import com.muchinfo.mtp3pojos.vo.query.investorsum.InvestorSumQueryResult;
import com.muchinfo.mtp3pojos.vo.query.other.*;
import com.muchinfo.mtp3pojos.vo.query.position.*;
import com.muchinfo.mtp3pojos.vo.query.tradesum.TradeSumQueryParam;
import com.muchinfo.mtp3pojos.vo.query.tradesum.TradeSumQueryResult;
import com.muchinfo.mtp3pojos.vo.query.warehouse.*;
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.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class QueryServiceImpl implements IQueryService {

    private final Logger log = LoggerFactory.getLogger(this.getClass());
    @Resource
    private ITradeOrderdetailMapper iTradeOrderdetailMapper;
    @Resource
    private ISystemmanagerMapper iSystemmanagerMapper;
    @Resource
    private ICommonService iCommonService;
    @Resource
    private IArearoleMapper iArearoleMapper;
    @Resource
    private IUseraccountMapper iUseraccountMapper;
    @Resource
    private IArearolemarketMapper iArearolemarketMapper;
    @Resource
    private IMarketMapper iMarketMapper;
    @Resource
    private RedisServiceUtil redisServiceUtil;
    @Resource
    private IGoodsMapper iGoodsMapper;
    @Resource
    private IGoodsoptionpropertyMapper iGoodsoptionpropertyMapper;
    @Resource
    private IWrtradeOrderdetailMapper iWrtradeOrderdetailMapper;
    @Resource
    private IHisWrtradeOrderdetailMapper iHisWrtradeOrderdetailMapper;
    @Resource
    private IWrfactortypeMapper iWrfactortypeMapper;
    @Resource
    private IWrstandardMapper iWrstandardMapper;
    @Resource
    private IPerformanceplantemplateMapper iPerformanceplantemplateMapper;
    @Resource
    private IHisWrtradeTradedetailMapper iHisWrtradeTradedetailMapper;
    @Resource
    private IWrtradeTradedetailMapper iWrtradeTradedetailMapper;
    @Resource
    private IWarehouseinfoMapper iWarehouseinfoMapper;
    @Resource
    private IMarketrunMapper iMarketrunMapper;
    @Resource
    private IUseresignrecordMapper iUseresignrecordMapper;
    @Resource
    private RabbitTemplate rabbitTemplate;

    @Override
    public PageResult<CommissionSheetResult> commissionSheetQuery(CommissionSheetParam commissionSheetParam, HttpServletRequest request) {
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        PageResult<CommissionSheetResult> pageResult = new PageResult<>();
        //校验
        if (commissionSheetParam.getMarketId() == -1) {
            pageResult.setCode(Constants.Error_Code_Design);
            pageResult.setMessage(AjaxResult.dealMsg(MessageType.QUERY_ERROR_CODE_001.getCode(), request.getHeader("Accept-Language")));
            return pageResult;
        }
        if (commissionSheetParam.getIsHis() == 1 && Strings.isNullOrEmpty(commissionSheetParam.getStartDateHis())) {
            pageResult.setCode(Constants.Error_Code_Design);
            pageResult.setMessage(AjaxResult.dealMsg(MessageType.QUERY_ERROR_CODE_002.getCode(), request.getHeader("Accept-Language")));
            return pageResult;
        }
        if (commissionSheetParam.getIsHis() == 1 && Strings.isNullOrEmpty(commissionSheetParam.getEndDateHis())) {
            pageResult.setCode(Constants.Error_Code_Design);
            pageResult.setMessage(AjaxResult.dealMsg(MessageType.QUERY_ERROR_CODE_003.getCode(), request.getHeader("Accept-Language")));
            return pageResult;
        }
        boolean marketFlag = checkMarketAuth(systemmanager, commissionSheetParam.getMarketId(), commissionSheetParam.getOrgztypes());
        if (marketFlag) {
            commissionSheetParam.setAreaUserid(systemmanager.getAreauserid());
        } else {
            pageResult.setCode(Constants.Error_Code_Design);
            pageResult.setMessage(AjaxResult.dealMsg(MessageType.QUERY_ERROR_CODE_004.getCode(), request.getHeader("Accept-Language")));
            return pageResult;
        }
        if (StringUtils.isNotBlank(commissionSheetParam.getTradeDate())) {
            try {
                Date date = DateTimeUtils.parseDate(commissionSheetParam.getTradeDate());
                commissionSheetParam.setTradeDate(DateTimeUtils.format(date, DateTimeUtils.DATE_CHAR_PATTERN));
            } catch (ParseException e) {
                log.error("日期转换失败,失败原因" + Arrays.toString(e.getStackTrace()));
            }
        }
        if (CollectionUtils.isEmpty(commissionSheetParam.getFilterTrademodeList())) {
            List<Integer> filterTrademodeList = new ArrayList<Integer>();
            filterTrademodeList.add(15);
            filterTrademodeList.add(97);
            filterTrademodeList.add(99);
            commissionSheetParam.setFilterTrademodeList(filterTrademodeList);
        }
        if (StringUtils.isNotBlank(commissionSheetParam.getExcludeAccountIdsStr())) {
            commissionSheetParam.setExcludeAccountIds(commissionSheetParam.getExcludeAccountIdsStr().split(","));
        }
        IPage<CommissionSheetResult> page = new Page<>(commissionSheetParam.getPageNum(), commissionSheetParam.getPageSize());
        IPage<CommissionSheetResult> resultIPage;
        if (commissionSheetParam.getTradeMode() == 36 && commissionSheetParam.getOperateType() == 0) {
            resultIPage = iTradeOrderdetailMapper.queryCoinSheet(page, commissionSheetParam);
        } else {
            resultIPage = iTradeOrderdetailMapper.queryCommissionSheet(page, commissionSheetParam);
        }
        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 commissionExport(CommissionSheetParam commissionSheetParam, HttpServletRequest request) {
        try {
            Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
            //校验
            if (commissionSheetParam.getMarketId() == -1) {
                return AjaxResult.error(Constants.Error_Code_Design, MessageType.QUERY_ERROR_CODE_001.getCode(), request.getHeader("Accept-Language"));
            }
            if (commissionSheetParam.getIsHis() == 1 && Strings.isNullOrEmpty(String.valueOf(commissionSheetParam.getStartDateHis()))) {
                return AjaxResult.error(Constants.Error_Code_Design, MessageType.QUERY_ERROR_CODE_002.getCode(), request.getHeader("Accept-Language"));
            }
            if (commissionSheetParam.getIsHis() == 1 && Strings.isNullOrEmpty(String.valueOf(commissionSheetParam.getEndDateHis()))) {
                return AjaxResult.error(Constants.Error_Code_Design, MessageType.QUERY_ERROR_CODE_003.getCode(), request.getHeader("Accept-Language"));
            }
            boolean marketFlag = checkMarketAuth(systemmanager, commissionSheetParam.getMarketId(), commissionSheetParam.getOrgztypes());
            if (marketFlag) {
                commissionSheetParam.setAreaUserid(systemmanager.getAreauserid());
            } else {
                return AjaxResult.error(Constants.Error_Code_Design, MessageType.QUERY_ERROR_CODE_004.getCode(), request.getHeader("Accept-Language"));
            }
            if (StringUtils.isNotBlank(commissionSheetParam.getTradeDate())) {
                try {
                    Date date = DateTimeUtils.parseDate(commissionSheetParam.getTradeDate());
                    commissionSheetParam.setTradeDate(DateTimeUtils.format(date, DateTimeUtils.DATE_CHAR_PATTERN));
                } catch (ParseException e) {
                    log.error("日期转换失败,失败原因" + Arrays.toString(e.getStackTrace()));
                }
            }
            if (CollectionUtils.isEmpty(commissionSheetParam.getFilterTrademodeList())) {
                List<Integer> filterTrademodeList = new ArrayList<Integer>();
                filterTrademodeList.add(15);
                filterTrademodeList.add(97);
                filterTrademodeList.add(99);
                commissionSheetParam.setFilterTrademodeList(filterTrademodeList);
            }
            String reportName = "委托单";
            if (commissionSheetParam.getOperateType() != null && commissionSheetParam.getOperateType() == 2) {
                reportName = "斩仓记录";
            }
            String fileName = reportName + "_" + DateTimeUtils.getDateTime("yyyyMMdd");
            List<CommissionSheetResult> list = iTradeOrderdetailMapper.queryCommissionSheet(commissionSheetParam);
            if (CollectionUtils.isEmpty(list)) {
                return AjaxResult.error(Constants.Error_Code_Design, MessageType.QUERY_ERROR_CODE_005.getCode(), request.getHeader("Accept-Language"));
            }
            ExportResult exportResult;
            if (commissionSheetParam.getOperateType() != null && commissionSheetParam.getOperateType() == 2) {
                // 斩仓
                List<CommissionZCResult> zcResults = new ArrayList<>();
                for (CommissionSheetResult commissionSheetResult : list) {
                    CommissionZCResult commissionZCResult = new CommissionZCResult();
                    BeanUtils.copyProperties(commissionSheetResult, commissionZCResult);
                    zcResults.add(commissionZCResult);
                }
                exportResult = ExportUtil.write(fileName, CommissionZCResult.class, zcResults);
            } else {
                if (commissionSheetParam.getTradeMode() == 18 || commissionSheetParam.getTradeMode() == 26) {
                    // 期权
                    List<CommissionQQResult> qqResults = new ArrayList<>();
                    for (CommissionSheetResult commissionSheetResult : list) {
                        CommissionQQResult commissionQQResult = new CommissionQQResult();
                        BeanUtils.copyProperties(commissionSheetResult, commissionQQResult);
                        qqResults.add(commissionQQResult);
                    }
                    exportResult = ExportUtil.write(fileName, CommissionQQResult.class, qqResults);
                } else if (commissionSheetParam.getTradeMode() == 46) {
                    // 掉期
                    List<CommissionSwapsResult> swapsResults = new ArrayList<>();
                    for (CommissionSheetResult commissionSheetResult : list) {
                        CommissionSwapsResult commissionSwapsResult = new CommissionSwapsResult();
                        BeanUtils.copyProperties(commissionSheetResult, commissionSwapsResult);
                        swapsResults.add(commissionSwapsResult);
                    }
                    exportResult = ExportUtil.write(fileName, CommissionSwapsResult.class, swapsResults);
                } else if (commissionSheetParam.getTradeMode() == 36) {
                    List<CommissionSheetResult> coinSheet = iTradeOrderdetailMapper.queryCoinSheet(commissionSheetParam);
                    List<CommissionCoinResult> coinResults = new ArrayList<>();
                    for (CommissionSheetResult commissionSheetResult : coinSheet) {
                        CommissionCoinResult coinResult = new CommissionCoinResult();
                        BeanUtils.copyProperties(commissionSheetResult, coinResult);
                        coinResults.add(coinResult);
                    }
                    exportResult = ExportUtil.write(fileName, CommissionCoinResult.class, coinResults);
                } else {
                    List<CommissionResult> commissionResults = new ArrayList<>();
                    for (CommissionSheetResult commissionSheetResult : list) {
                        CommissionResult commissionResult = new CommissionResult();
                        BeanUtils.copyProperties(commissionSheetResult, commissionResult);
                        commissionResults.add(commissionResult);
                    }
                    exportResult = ExportUtil.write(fileName, CommissionResult.class, commissionResults);
                }
            }
            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<CommissionSheetResultDetail> commissionSheetQueryDetail(String orderId, Integer isHis, String tradeDate, HttpServletRequest request) {
        tradeDate = tradeDate.replace("-", "");
        CommissionSheetResultDetail detail = iTradeOrderdetailMapper.commissionSheetQueryDetail(orderId, isHis, tradeDate);
        detail.setMemberaccountname(iTradeOrderdetailMapper.selectMemberUserName(detail.getAccountid()));
        List<TradeResult> tradeResultList = iTradeOrderdetailMapper.queryTradeTradeDetails(orderId);
        List<TradeHisResult> tradeHisResultList = iTradeOrderdetailMapper.queryHisTradeList(orderId);
        detail.setTradeResultList(tradeResultList);
        detail.setTradeHisResultList(tradeHisResultList);
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), detail);
    }

    @Override
    public PageResult<ContractSheetResult> contractSheetQuery(ContractSheetParam contractSheetParam, HttpServletRequest request) {
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        PageResult<ContractSheetResult> pageResult = new PageResult<>();
        //校验
        if (contractSheetParam.getMarketId() == -1) {
            pageResult.setCode(Constants.Error_Code_Design);
            pageResult.setMessage(AjaxResult.dealMsg(MessageType.QUERY_ERROR_CODE_001.getCode(), request.getHeader("Accept-Language")));
            return pageResult;
        }
        if (contractSheetParam.getIsHis() == 1 && Strings.isNullOrEmpty(String.valueOf(contractSheetParam.getStartDateHis()))) {
            pageResult.setCode(Constants.Error_Code_Design);
            pageResult.setMessage(AjaxResult.dealMsg(MessageType.QUERY_ERROR_CODE_002.getCode(), request.getHeader("Accept-Language")));
            return pageResult;
        }
        if (contractSheetParam.getIsHis() == 1 && Strings.isNullOrEmpty(String.valueOf(contractSheetParam.getEndDateHis()))) {
            pageResult.setCode(Constants.Error_Code_Design);
            pageResult.setMessage(AjaxResult.dealMsg(MessageType.QUERY_ERROR_CODE_003.getCode(), request.getHeader("Accept-Language")));
            return pageResult;
        }
        Market market = iMarketMapper.selectOne(new QueryWrapper<Market>().eq("marketid", contractSheetParam.getMarketId()));
        if (market != null && market.getTrademode().equals(46)) {
            // 是否调期市场 -- 用于查询成交单对应点差\会员资金账号，其它模式不需要，历史表数据量大有性能问题
            contractSheetParam.setIsSwap(1);
        }
        boolean marketFlag = checkMarketAuth(systemmanager, contractSheetParam.getMarketId(), contractSheetParam.getOrgztypes());
        if (marketFlag) {
            Object c = redisServiceUtil.getCacheMapValue(Constants.REDIS_HEADER_SYSPARAM, "084");
            if (Objects.nonNull(c)) {
                contractSheetParam.setNameType(Integer.valueOf(c.toString()));
            } else {
                contractSheetParam.setNameType(1);
            }
            contractSheetParam.setAreaUserid(systemmanager.getAreauserid());
        } else {
            pageResult.setCode(Constants.Error_Code_Design);
            pageResult.setMessage(AjaxResult.dealMsg(MessageType.QUERY_ERROR_CODE_004.getCode(), request.getHeader("Accept-Language")));
            return pageResult;
        }
        if (StringUtils.isNotBlank(contractSheetParam.getTradeDate())) {
            try {
                Date date = DateTimeUtils.parseDate(contractSheetParam.getTradeDate());
                contractSheetParam.setTradeDate(DateTimeUtils.format(date, DateTimeUtils.DATE_CHAR_PATTERN));
            } catch (ParseException e) {
                log.error("日期转换失败,失败原因" + Arrays.toString(e.getStackTrace()));
            }
        }
        if (CollectionUtils.isEmpty(contractSheetParam.getFilterTrademodeList())) {
            List<Integer> filterTrademodeList = new ArrayList<Integer>();
            filterTrademodeList.add(15);
            filterTrademodeList.add(97);
            filterTrademodeList.add(99);
            contractSheetParam.setFilterTrademodeList(filterTrademodeList);
        }
        IPage<ContractSheetResult> page = new Page<>(contractSheetParam.getPageNum(), contractSheetParam.getPageSize());
        IPage<ContractSheetResult> resultIPage = iTradeOrderdetailMapper.queryContractSheet(page, contractSheetParam);
        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 contractExport(ContractSheetParam contractSheetParam, HttpServletRequest request) {
        try {
            Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
            //校验
            if (contractSheetParam.getMarketId() == -1) {
                return AjaxResult.error(Constants.Error_Code_Design, MessageType.QUERY_ERROR_CODE_001.getCode(), request.getHeader("Accept-Language"));
            }
            if (contractSheetParam.getIsHis() == 1 && Strings.isNullOrEmpty(String.valueOf(contractSheetParam.getStartDateHis()))) {
                return AjaxResult.error(Constants.Error_Code_Design, MessageType.QUERY_ERROR_CODE_002.getCode(), request.getHeader("Accept-Language"));
            }
            if (contractSheetParam.getIsHis() == 1 && Strings.isNullOrEmpty(String.valueOf(contractSheetParam.getEndDateHis()))) {
                return AjaxResult.error(Constants.Error_Code_Design, MessageType.QUERY_ERROR_CODE_003.getCode(), request.getHeader("Accept-Language"));
            }
            boolean marketFlag = checkMarketAuth(systemmanager, contractSheetParam.getMarketId(), contractSheetParam.getOrgztypes());
            if (marketFlag) {
                Object c = redisServiceUtil.getCacheMapValue(Constants.REDIS_HEADER_SYSPARAM, "084");
                if (Objects.nonNull(c)) {
                    contractSheetParam.setNameType(Integer.valueOf(c.toString()));
                } else {
                    contractSheetParam.setNameType(1);
                }
                contractSheetParam.setAreaUserid(systemmanager.getAreauserid());
            } else {
                return AjaxResult.error(Constants.Error_Code_Design, MessageType.QUERY_ERROR_CODE_004.getCode(), request.getHeader("Accept-Language"));
            }
            if (StringUtils.isNotBlank(contractSheetParam.getTradeDate())) {
                try {
                    Date date = DateTimeUtils.parseDate(contractSheetParam.getTradeDate());
                    contractSheetParam.setTradeDate(DateTimeUtils.format(date, DateTimeUtils.DATE_CHAR_PATTERN));
                } catch (ParseException e) {
                    log.error("日期转换失败,失败原因" + Arrays.toString(e.getStackTrace()));
                }
            }
            Market market = iMarketMapper.selectOne(new QueryWrapper<Market>().eq("marketid", contractSheetParam.getMarketId()));
            if (market != null && market.getTrademode().equals(46)) {
                // 是否调期市场 -- 用于查询成交单对应点差\会员资金账号，其它模式不需要，历史表数据量大有性能问题
                contractSheetParam.setIsSwap(1);
            }
            if (CollectionUtils.isEmpty(contractSheetParam.getFilterTrademodeList())) {
                List<Integer> filterTrademodeList = new ArrayList<Integer>();
                filterTrademodeList.add(15);
                filterTrademodeList.add(97);
                filterTrademodeList.add(99);
                contractSheetParam.setFilterTrademodeList(filterTrademodeList);
            }
            String fileName = "成交单_" + DateTimeUtils.getDateTime("yyyyMMdd");
            List<ContractSheetResult> list = iTradeOrderdetailMapper.queryContractSheet(contractSheetParam);
            if (CollectionUtils.isEmpty(list)) {
                return AjaxResult.error(Constants.Error_Code_Design, MessageType.QUERY_ERROR_CODE_005.getCode(), request.getHeader("Accept-Language"));
            }
            ExportResult exportResult;
            if (contractSheetParam.getTradeMode() == 46) {
                // 掉期
                exportResult = ExportUtil.write(fileName, ContractSheetResult.class, list);
            } else {
                List<ContractResult> contractResults = new ArrayList<>();
                for (ContractSheetResult commissionSheetResult : list) {
                    ContractResult contractResult = new ContractResult();
                    BeanUtils.copyProperties(commissionSheetResult, contractResult);
                    contractResults.add(contractResult);
                }
                exportResult = ExportUtil.write(fileName, CommissionResult.class, contractResults);
            }
            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<ContractSheetResultDetail> contractSheetQueryDetail(String tradeid, Integer buyorsell, Integer ishis, HttpServletRequest request) {
        ContractSheetResultDetail resultDetail = iTradeOrderdetailMapper.contractSheetQueryDetail(tradeid, buyorsell, ishis);
        resultDetail.setMembername(iTradeOrderdetailMapper.selectMemberUserName(resultDetail.getAccountid()));
        Object c = redisServiceUtil.getCacheMapValue(Constants.REDIS_HEADER_SYSPARAM, "084");
        if (Objects.nonNull(c)) {
            resultDetail.setNameType(Integer.valueOf(c.toString()));
        } else {
            resultDetail.setNameType(null);
        }
        resultDetail.setMatchaccountname(iUseraccountMapper.selectUserName(resultDetail.getMatchaccountid()));
        String string = iCommonService.getSysparmById("081") == null ? "0" : iCommonService.getSysparmById("081");
        resultDetail.setTradetype3(Integer.valueOf(string));
        List<ContractTradeResult> contractTradeResults = iTradeOrderdetailMapper.queryTradeClose(tradeid, buyorsell, ishis);
        resultDetail.setResultList(contractTradeResults);
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), resultDetail);
    }

    @Override
    public PageResult<PositionSheetResult> positionSheetQuery(PositionSheetParam param, HttpServletRequest request) {
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        PageResult<PositionSheetResult> pageResult = new PageResult<>();
        // 查询、导出使用统一SQL，避免修改导致不一致； 2024-01-17
        if (param.getTradeDate() != null && !param.getTradeDate().isEmpty()) {
            try {
                Date date = DateTimeUtils.parseDate(param.getTradeDate());
                param.setTradeDate(DateTimeUtils.format(date, DateTimeUtils.DATE_CHAR_PATTERN));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        if (param.getGoodsId() != null && param.getGoodsId() > 0) {    //监控不会传市场id，这边查询一下
            Goods g = iGoodsMapper.selectOne(new QueryWrapper<Goods>().eq("goodsid", param.getGoodsId()));
            if (param.getMarketId() == null) {
                param.setMarketId(g.getMarketid());
            }
        }
        if (param.getMarketId() == -1) {
            pageResult.setCode(Constants.Error_Code_Design);
            pageResult.setMessage(AjaxResult.dealMsg(MessageType.QUERY_ERROR_CODE_001.getCode(), request.getHeader("Accept-Language")));
            return pageResult;
        }
        if (param.getFilterTrademodeList() == null || param.getFilterTrademodeList().size() <= 0) {
            List<Integer> filterTrademodeList = new ArrayList<Integer>();
            filterTrademodeList.add(15);
            filterTrademodeList.add(97);
            filterTrademodeList.add(99);
            param.setFilterTrademodeList(filterTrademodeList);
        }
        boolean marketFlag = checkMarketAuth(systemmanager, param.getMarketId(), param.getOrgztypes());
        IPage<PositionSheetResult> page = new Page<>(param.getPageNum(), param.getPageSize());
        IPage<PositionSheetResult> resultIPage = null;
        if (marketFlag) {
            if (systemmanager.getReletype() != 1) {
                if (("," + param.getOrgztypes() + ",").contains(",3,")) {
                    param.setSelfSupport(3);
                }
                if (systemmanager.getReletype().equals(2)) {
                    param.setAreaUserid(systemmanager.getAreauserid());
                } else if (systemmanager.getReletype().equals(3)) {
                    param.setParentAreaId(systemmanager.getAreauserid());
                }
            }
            if (param.getIsHis() == null || param.getIsHis() == 0) {
                resultIPage = iTradeOrderdetailMapper.queryTradeHolderDetailList(page, param);
                dealAmount(param, resultIPage.getRecords());
            } else if (param.getIsHis() == 1) {
                // 50日清模式查询历史表，其它查询日照表（日清日照表无数据） 2024-01-17
                Market market = iMarketMapper.selectOne(new QueryWrapper<Market>().eq("marketid", param.getMarketId()));
                if (market != null && market.getTrademode() != null && market.getTrademode() == 50
                        && market.getForceclosemode() != null && market.getForceclosemode() == 2) {
                    resultIPage = iTradeOrderdetailMapper.queryHisTradeHolderDetaileList(page, param);
                    dealHisAmount(param, resultIPage.getRecords());
                } else {
                    resultIPage = iTradeOrderdetailMapper.queryHisTradeHolderDetaileByPage(page, param);
                    dealHisAmount(param, resultIPage.getRecords());
                }
            }
            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;
        } else {
            pageResult.setCode(Constants.Error_Code_Design);
            pageResult.setMessage(AjaxResult.dealMsg(MessageType.QUERY_ERROR_CODE_004.getCode(), request.getHeader("Accept-Language")));
            return pageResult;
        }
    }

    @Override
    public AjaxResult positionExport(PositionSheetParam param, HttpServletRequest request) {
        String fileName = "持仓单查询_" + DateTimeUtils.getDateTime("yyyyMMdd");
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        // 查询、导出使用统一SQL，避免修改导致不一致； 2024-01-17
        if (param.getTradeDate() != null && !param.getTradeDate().isEmpty()) {
            try {
                Date date = DateTimeUtils.parseDate(param.getTradeDate());
                param.setTradeDate(DateTimeUtils.format(date, DateTimeUtils.DATE_CHAR_PATTERN));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        if (param.getGoodsId() != null && param.getGoodsId() > 0) {    //监控不会传市场id，这边查询一下
            Goods g = iGoodsMapper.selectOne(new QueryWrapper<Goods>().eq("goodsid", param.getGoodsId()));
            if (param.getMarketId() == null) {
                param.setMarketId(g.getMarketid());
            }
        }
        if (param.getMarketId() == -1) {
            return AjaxResult.error(Constants.Error_Code_Design, MessageType.QUERY_ERROR_CODE_001.getCode(), request.getHeader("Accept-Language"));
        }
        if (param.getFilterTrademodeList() == null || param.getFilterTrademodeList().size() <= 0) {
            List<Integer> filterTrademodeList = new ArrayList<Integer>();
            filterTrademodeList.add(15);
            filterTrademodeList.add(97);
            filterTrademodeList.add(99);
            param.setFilterTrademodeList(filterTrademodeList);
        }
        boolean marketFlag = checkMarketAuth(systemmanager, param.getMarketId(), param.getOrgztypes());
        if (marketFlag) {
            if (systemmanager.getReletype() != 1) {
                if (("," + param.getOrgztypes() + ",").contains(",3,")) {
                    param.setSelfSupport(3);
                }
                if (systemmanager.getReletype().equals(2)) {
                    param.setAreaUserid(systemmanager.getAreauserid());
                } else if (systemmanager.getReletype().equals(3)) {
                    param.setParentAreaId(systemmanager.getAreauserid());
                }
            }
            try {
                ExportResult exportResult = null;
                if (param.getIsHis() == null || param.getIsHis() == 0) {
                    List<PositionSheetResult> results = iTradeOrderdetailMapper.queryTradeHolderDetailList(param);
                    dealAmount(param, results);
                    if (param.getTradeMode() == 18 || param.getTradeMode() == 26) {
                        List<PositionSheetExportQQResult> resultList = new ArrayList<>();
                        for (PositionSheetResult result : results) {
                            PositionSheetExportQQResult sheetExportResult = new PositionSheetExportQQResult();
                            BeanUtils.copyProperties(result, sheetExportResult);
                            resultList.add(sheetExportResult);
                        }
                        exportResult = ExportUtil.write(fileName, PositionSheetExportQQResult.class, resultList);
                    } else {
                        List<PositionSheetExportResult> resultList = new ArrayList<>();
                        for (PositionSheetResult result : results) {
                            PositionSheetExportResult sheetExportResult = new PositionSheetExportResult();
                            BeanUtils.copyProperties(result, sheetExportResult);
                            resultList.add(sheetExportResult);
                        }
                        exportResult = ExportUtil.write(fileName, PositionSheetExportResult.class, resultList);
                    }
                } else if (param.getIsHis() == 1) {
                    // 50日清模式查询历史表，其它查询日照表（日清日照表无数据） 2024-01-17
                    Market market = iMarketMapper.selectOne(new QueryWrapper<Market>().eq("marketid", param.getMarketId()));
                    if (market != null && market.getTrademode() != null && market.getTrademode() == 50
                            && market.getForceclosemode() != null && market.getForceclosemode() == 2) {
                        List<PositionSheetResult> results = iTradeOrderdetailMapper.queryHisTradeHolderDetaileList(param);
                        dealHisAmount(param, results);
                        List<PositionSheetExportHisResult> resultList = new ArrayList<>();
                        for (PositionSheetResult result : results) {
                            PositionSheetExportHisResult sheetExportResult = new PositionSheetExportHisResult();
                            BeanUtils.copyProperties(result, sheetExportResult);
                            resultList.add(sheetExportResult);
                        }
                        exportResult = ExportUtil.write(fileName, PositionSheetExportHisResult.class, resultList);
                    } else {
                        List<PositionSheetResult> results = iTradeOrderdetailMapper.queryHisTradeHolderDetaileByPage(param);
                        dealHisAmount(param, results);
                        if (param.getTradeMode() == 18 || param.getTradeMode() == 26) {
                            List<PositionSheetExportQQHisResult> resultList = new ArrayList<>();
                            for (PositionSheetResult result : results) {
                                PositionSheetExportQQHisResult sheetExportResult = new PositionSheetExportQQHisResult();
                                BeanUtils.copyProperties(result, sheetExportResult);
                                resultList.add(sheetExportResult);
                            }
                            exportResult = ExportUtil.write(fileName, PositionSheetExportQQHisResult.class, resultList);
                        } else {
                            List<PositionSheetExportHisResult> resultList = new ArrayList<>();
                            for (PositionSheetResult result : results) {
                                PositionSheetExportHisResult sheetExportResult = new PositionSheetExportHisResult();
                                BeanUtils.copyProperties(result, sheetExportResult);
                                resultList.add(sheetExportResult);
                            }
                            exportResult = ExportUtil.write(fileName, PositionSheetExportHisResult.class, resultList);
                        }
                    }
                }
                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"));
            }
        } else {
            return AjaxResult.error(Constants.Error_Code_Design, MessageType.QUERY_ERROR_CODE_004.getCode(), request.getHeader("Accept-Language"));
        }
    }

    @Override
    public AjaxResult<PositionSheetResultDetail> positionSheetDetail(String tradeid, Integer buyorsell, Integer ishis, String histradedate, HttpServletRequest request) {
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        PositionSheetResultDetail resultDetail = iTradeOrderdetailMapper.queryTradeHolderDetailById(ishis, tradeid, buyorsell, histradedate);
        if (iCommonService.checkTaAccountReport(systemmanager, resultDetail.getAccountid())) {
            return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), resultDetail);
        } else {
            return AjaxResult.error(Constants.Error_Code_Design, MessageType.QUERY_ERROR_CODE_004.getCode(), request.getHeader("Accept-Language"));
        }
    }

    @Override
    public PageResult<PositionSumSheetResult> positionSumSheet(PositionSumSheetParam param, HttpServletRequest request) {
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        if (systemmanager.getReletype() != 1) {
            param.setAreauserid(systemmanager.getAreauserid());
        }
        if (param.getFilterTrademodeList() == null || param.getFilterTrademodeList().size() <= 0) {
            List<Integer> filterTrademodeList = new ArrayList<Integer>();
            filterTrademodeList.add(15);
            filterTrademodeList.add(97);
            filterTrademodeList.add(99);
            param.setFilterTrademodeList(filterTrademodeList);
        }
        IPage<PositionSumSheetResult> page = new Page<>(param.getPageNum(), param.getPageSize());
        IPage<PositionSumSheetResult> resultIPage = iTradeOrderdetailMapper.queryTradePositionPage(page, param);
        PageResult<PositionSumSheetResult> pageResult = new PageResult<>();
        //处理金额
        dealSunAmount(resultIPage.getRecords());
        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 positionSumSheetExport(PositionSumSheetParam param, HttpServletRequest request) {
        try {
            String fileName = "持仓汇总查询_" + DateTimeUtils.getDateTime("yyyyMMdd");
            List<PositionSumSheetResult> resultIPage = iTradeOrderdetailMapper.queryTradePositionPage(param);
            if (CollectionUtils.isEmpty(resultIPage)) {
                return AjaxResult.error(Constants.Error_Code_Design, MessageType.QUERY_ERROR_CODE_006.getCode(), request.getHeader("Accept-Language"));
            }
            //处理金额
            dealSunAmount(resultIPage);
            ExportResult exportResult = ExportUtil.write(fileName, PositionSumSheetResult.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<WarehouseCommissionResult> warehouseQuery(WarehouseCommissionParam param, HttpServletRequest request) {
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        if (systemmanager.getReletype() != 1) {
            param.setUserid(systemmanager.getAreauserid());
        }
        IPage<WarehouseCommissionResult> page = new Page<>(param.getPageNum(), param.getPageSize());
        IPage<WarehouseCommissionResult> resultIPage = iWrtradeOrderdetailMapper.getAllWrTradeOrderMap(page, param);
        PageResult<WarehouseCommissionResult> pageResult = new PageResult<>();
        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 warehouseExport(WarehouseCommissionParam param, HttpServletRequest request) {
        try {
            Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
            if (systemmanager.getReletype() != 1) {
                param.setUserid(systemmanager.getAreauserid());
            }
            String fileName = "仓单贸易委托单数据_" + DateTimeUtils.getDateTime("yyyyMMdd");
            List<WarehouseCommissionResult> resultIPage = iWrtradeOrderdetailMapper.getAllWrTradeOrderMap(param);
            if (CollectionUtils.isEmpty(resultIPage)) {
                return AjaxResult.error(Constants.Error_Code_Design, MessageType.QUERY_ERROR_CODE_005.getCode(), request.getHeader("Accept-Language"));
            }
            ExportResult exportResult = ExportUtil.write(fileName, WarehouseCommissionResult.class, resultIPage);
            return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), exportResult);
        } catch (Exception e) {
            log.error("仓单贸易委托单数据导出失败，失败原因：" + e);
            return AjaxResult.error(Constants.Error_Code_Design, MessageType.QUERY_ERROR_CODE_006.getCode(), request.getHeader("Accept-Language"));
        }
    }

    @Override
    public AjaxResult<WarehouseCommissionResultDetail> tradeOrderView(Long wrtradeorderid, Integer ishis, HttpServletRequest request) {
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        //赋值
        WarehouseCommissionResultDetail dto = getWRTradeOrderDetailById(wrtradeorderid, ishis);
        if (dto.getWrTradeOrderDetail().getWrtradetype() == 1 && dto.getWrTradeOrderDetail().getBuyorsell() == 1) {
            if (dto.getWrTradeOrderDetail().getPerformancetemplateid() != null && dto.getWrTradeOrderDetail().getPerformancetemplateid() != 0
                    && dto.getWrTradeOrderDetail().getPerformancetemplateid() != -1) {
                getPerformanceTemplateById(dto);
            }
        }
        //是否议价控制按钮
        String sp = iCommonService.getSysparmById(SysConstants.SYSPARAM_CODE_ISYIJIA);
        if (Objects.nonNull(sp)) {
            dto.setIsyijia(Integer.parseInt(sp));
        } else {
            dto.setIsyijia(1);
        }
        //校验
        if (iCommonService.checkTaAccountReport(systemmanager, dto.getWrTradeOrderDetail().getAccountid())) {
            return AjaxResult.error(Constants.Error_Code_Design, MessageType.QUERY_ERROR_CODE_004.getCode(), request.getHeader("Accept-Language"));
        }
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), dto);
    }

    @Override
    public PageResult<WarehouseContractResult> queryTradeOrder(WarehouseContractParam param, HttpServletRequest request) {
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        if (systemmanager.getReletype() != 1) {
            param.setUserid(systemmanager.getAreauserid());
        }
        IPage<WarehouseContractResult> page = new Page<>(param.getPageNum(), param.getPageSize());
        IPage<WarehouseContractResult> resultIPage = iWrtradeOrderdetailMapper.queryTradeDetail(page, param);
        PageResult<WarehouseContractResult> pageResult = new PageResult<>();
        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 tradeOrderExport(WarehouseContractParam param, HttpServletRequest request) {
        try {
            Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
            if (systemmanager.getReletype() != 1) {
                param.setUserid(systemmanager.getAreauserid());
            }
            String fileName = "仓单贸易成交单数据_" + DateTimeUtils.getDateTime("yyyyMMdd");
            List<WarehouseContractResult> resultIPage = iWrtradeOrderdetailMapper.queryTradeDetail(param);
            if (CollectionUtils.isEmpty(resultIPage)) {
                return AjaxResult.error(Constants.Error_Code_Design, MessageType.QUERY_ERROR_CODE_005.getCode(), request.getHeader("Accept-Language"));
            }
            ExportResult exportResult = ExportUtil.write(fileName, WarehouseContractResult.class, resultIPage);
            return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), exportResult);
        } catch (Exception e) {
            log.error("仓单贸易成交单数据导出失败，失败原因：" + e);
            return AjaxResult.error(Constants.Error_Code_Design, MessageType.QUERY_ERROR_CODE_006.getCode(), request.getHeader("Accept-Language"));
        }
    }

    @Override
    public AjaxResult<WarehouseContractDetailParam> tradeTradedView(Long wrtradeorderid, Integer ishis, Integer wrtradetype, HttpServletRequest request) {
        WarehouseContractDetailParam tradeDetail = new WarehouseContractDetailParam();
        WrtradeOrderdetail wr = new WrtradeOrderdetail();
        if (ishis != null && ishis == 1) {
            HisWrtradeTradedetail his = iHisWrtradeTradedetailMapper.selectOne(new QueryWrapper<HisWrtradeTradedetail>()
                    .eq("wrtradedetailid", wrtradeorderid)
                    .eq(wrtradetype != null, "WRTRADETYPE", wrtradetype));
            BeanUtils.copyProperties(his, tradeDetail);
            HisWrtradeOrderdetail hisWrOrder = iHisWrtradeOrderdetailMapper.selectOne(new QueryWrapper<HisWrtradeOrderdetail>()
                    .eq("wrtradeorderid", his.getWrtradeorderid()));
            BeanUtils.copyProperties(hisWrOrder, wr);
        } else {
            WrtradeTradedetail tradeDetailEntity = iWrtradeTradedetailMapper.selectOne(new QueryWrapper<WrtradeTradedetail>()
                    .eq("wrtradedetailid", wrtradeorderid)
                    .eq(wrtradetype != null, "WRTRADETYPE", wrtradetype));
            if (tradeDetailEntity != null) {
                BeanUtils.copyProperties(tradeDetailEntity, tradeDetail);
                wr = iWrtradeOrderdetailMapper.selectOne(new QueryWrapper<WrtradeOrderdetail>()
                        .eq("wrtradeorderid", tradeDetail.getWrtradeorderid()));
                if (wr == null) {
                    wr = new WrtradeOrderdetail();
                    HisWrtradeOrderdetail hisWrOrder = iHisWrtradeOrderdetailMapper.selectOne(new QueryWrapper<HisWrtradeOrderdetail>()
                            .eq("wrtradeorderid", tradeDetail.getWrtradeorderid()));
                    BeanUtils.copyProperties(hisWrOrder, wr);
                }
            }
        }
        Wrfactortype wrs = iWrfactortypeMapper.selectOne(new QueryWrapper<Wrfactortype>().eq("wrfactortypeid", wr.getWrfactortypeid()));
        tradeDetail.setWrTransferUserName(iUseraccountMapper.selectOne(new QueryWrapper<Useraccount>().eq("userid", tradeDetail.getWrtransferuserid())).getAccountname());
        if (wrs != null) {
            if (StringUtils.isNotBlank(wrs.getOptioncompare())) {
                StringBuilder sb = new StringBuilder();
                for (String str : wrs.getOptioncompare().split("\\,")) {
                    if (StringUtils.isBlank(str) || str.split("\\:").length < 2) {
                        continue;
                    }
                    sb.append(str.split("\\:")[1]);
                    sb.append(",");
                }
                sb = sb.deleteCharAt(sb.length() - 1);
                tradeDetail.setWrFactorTypeValue(sb.toString());
            }
            tradeDetail.setMarketName(iMarketMapper.selectOne(new QueryWrapper<Market>().eq("marketid", wr.getMarketid())).getMarketname());
            Wrstandard wRStandard = iWrstandardMapper.selectOne(new QueryWrapper<Wrstandard>().eq("WRSTANDARDID", wrs.getWrstandardid()));
            Map<Object, Object> goodsunitMap = redisServiceUtil.getHash(Constants.REDIS_HEADER_DICT + "goodsunit");
            String goodsUnitName = (String) goodsunitMap.get(wRStandard.getUnitid().toString());
            tradeDetail.setGoodsUnitName(goodsUnitName);
            tradeDetail.setWrstandardcode(wRStandard.getWrstandardcode());
            tradeDetail.setWrstandardname(wRStandard.getWrstandardname());
            if (wRStandard.getRealminivaluedp() != null) {
                double realminivaluedp = Math.pow(10D, wRStandard.getRealminivaluedp().doubleValue());
                if (tradeDetail.getTradeqty() != null) {
                    double tradeQty = tradeDetail.getTradeqty().doubleValue();
                    tradeQty = tradeQty / realminivaluedp;
                    tradeDetail.setTradeqty(BigDecimal.valueOf(tradeQty));
                }
                if (tradeDetail.getRealtradeqty() != null) {
                    double realTradeQty = tradeDetail.getRealtradeqty().doubleValue();
                    realTradeQty = realTradeQty / realminivaluedp;
                    tradeDetail.setRealtradeqty(BigDecimal.valueOf(realTradeQty));
                }
            }
        }
        if (tradeDetail.getRealfirstamount() != null) {
            tradeDetail.setRealfirstamount(tradeDetail.getRealfirstamount().setScale(2, RoundingMode.HALF_UP));
        }
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), tradeDetail);
    }

    @Override
    public AjaxResult<WarehouseInitResult> initWarehouse(HttpServletRequest request) {
        WarehouseInitResult result = new WarehouseInitResult();
        List<Wrstandard> wrstandards = iWrstandardMapper.selectList(new QueryWrapper<Wrstandard>().eq("isvalid", 1));
        result.setWrStandardList(wrstandards);
        List<Warehouseinfo> warehouseinfos = iWarehouseinfoMapper.selectList(new QueryWrapper<Warehouseinfo>());
        result.setWarehouseInfoList(warehouseinfos);
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), result);
    }

    @Override
    public PageResult<WarehouseSumResult> warehouseSum(WarehouseSumParam param, HttpServletRequest request) {
        if (StringUtils.isNotBlank(param.getWrsids())) {
            List<Long> wrstandardids = Arrays.stream(param.getWrsids().split(","))
                    .filter(s -> !s.trim().isEmpty())
                    .map(Long::valueOf).collect(Collectors.toList());
            param.setWrstandardids(wrstandardids);
        }
        if (StringUtils.isNotBlank(param.getWareids())) {
            List<Long> warehouseids = Arrays.stream(param.getWareids().split(","))
                    .filter(s -> !s.trim().isEmpty())
                    .map(Long::valueOf).collect(Collectors.toList());
            param.setWarehouseids(warehouseids);
        }
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        if (systemmanager.getReletype() != 1) {
            param.setMemberuserid(systemmanager.getAreauserid());
        }
        IPage<WarehouseSumResult> page = new Page<>(param.getPageNum(), param.getPageSize());
        IPage<WarehouseSumResult> resultIPage = iWrtradeOrderdetailMapper.querySum(page, param);
        PageResult<WarehouseSumResult> pageResult = new PageResult<>();
        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 PageResult<WarehouseSumDetailResult> summaryQueryDetail(WarehouseSumDetailParam param, HttpServletRequest request) {
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        if (StringUtils.isNotBlank(param.getIds())) {
            List<Long> longList = Arrays.stream(param.getIds().split(","))
                    .filter(s -> !s.trim().isEmpty())
                    .map(Long::valueOf).collect(Collectors.toList());
            param.setUserids(longList);
        }
        if (systemmanager.getReletype() != 1) {
            param.setMemberuserid(systemmanager.getAreauserid());
        }
        IPage<WarehouseSumDetailResult> page = new Page<>(param.getPageNum(), param.getPageSize());
        IPage<WarehouseSumDetailResult> resultIPage = iWrtradeOrderdetailMapper.summaryQueryDetail(page, param);
        PageResult<WarehouseSumDetailResult> pageResult = new PageResult<>();
        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 PageResult<AccountTransactionQueryResult> accountTransactions(AccountTransactionQueryParam param, HttpServletRequest request) {
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        if (Objects.nonNull(systemmanager)) {
            param.setUserid(systemmanager.getAreauserid());
        }
        if (StringUtils.isNotBlank(param.getExcludeaccountidsstr())) {
            param.setExcludeAccountIds(param.getExcludeaccountidsstr().split(","));
        }
        IPage<AccountTransactionQueryResult> page = new Page<>(param.getPageNum(), param.getPageSize());
        IPage<AccountTransactionQueryResult> resultIPage;
        if (param.getSummode() == 1) {
            // 1：按账户汇总
            resultIPage = iTradeOrderdetailMapper.queryByAccount(page, param);
        } else {
            // 2:按账户+日期汇总
            resultIPage = iTradeOrderdetailMapper.queryByAccountDate(page, param);
        }
        PageResult<AccountTransactionQueryResult> pageResult = new PageResult<>();
        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 accountExport(AccountTransactionQueryParam param, HttpServletRequest request) {
        try {
            Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
            if (Objects.nonNull(systemmanager)) {
                param.setUserid(systemmanager.getAreauserid());
            }
            if (StringUtils.isNotBlank(param.getExcludeaccountidsstr())) {
                param.setExcludeAccountIds(param.getExcludeaccountidsstr().split(","));
            }
            List<AccountTransactionQueryResult> results;
            if (param.getSummode() == 1) {
                // 1：按账户汇总
                results = iTradeOrderdetailMapper.queryByAccount(param);
            } else {
                // 2:按账户+日期汇总
                results = iTradeOrderdetailMapper.queryByAccountDate(param);
            }
            String fileName = "账户成交汇总_" + DateTimeUtils.getDateTime("yyyyMMdd");
            if (CollectionUtils.isEmpty(results)) {
                return AjaxResult.error(Constants.Error_Code_Design, MessageType.QUERY_ERROR_CODE_005.getCode(), request.getHeader("Accept-Language"));
            }
            ExportResult exportResult = ExportUtil.write(fileName, AccountTransactionQueryResult.class, results);
            return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), exportResult);
        } catch (Exception e) {
            log.error("账户成交汇总导出失败，失败原因：" + e);
            return AjaxResult.error(Constants.Error_Code_Design, MessageType.QUERY_ERROR_CODE_006.getCode(), request.getHeader("Accept-Language"));
        }
    }

    @Override
    public PageResult<InvestorSumQueryResult> queryInvestorSum(InvestorSumQueryParam param, HttpServletRequest request) {
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        if (Objects.nonNull(systemmanager)) {
            param.setUserid(systemmanager.getAreauserid());
        }
        IPage<InvestorSumQueryResult> page = new Page<>(param.getPageNum(), param.getPageSize());
        IPage<InvestorSumQueryResult> resultIPage = iTradeOrderdetailMapper.queryInvestorSumList(page, param);
        PageResult<InvestorSumQueryResult> pageResult = new PageResult<>();
        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 PageResult<GoodsTradeQueryResult> queryGoodsTrade(GoodsTradeQueryParam param, HttpServletRequest request) {
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        if (Objects.nonNull(systemmanager)) {
            param.setUserid(systemmanager.getAreauserid());
        }
        if (StringUtils.isNotBlank(param.getExcludeaccountidsstr())) {
            param.setExcludeAccountIds(param.getExcludeaccountidsstr().split(","));
        }
        IPage<GoodsTradeQueryResult> page = new Page<>(param.getPageNum(), param.getPageSize());
        IPage<GoodsTradeQueryResult> resultIPage;
        if (param.getSummode() == 1) {
            // 1：按商品汇总
            resultIPage = iTradeOrderdetailMapper.queryByAGoods(page, param);
        } else {
            // 2:按商品+日期汇总
            resultIPage = iTradeOrderdetailMapper.queryByAGoodsDate(page, param);
        }
        PageResult<GoodsTradeQueryResult> pageResult = new PageResult<>();
        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 queryGoodsTradeExport(GoodsTradeQueryParam param, HttpServletRequest request) {
        try {
            Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
            if (Objects.nonNull(systemmanager)) {
                param.setUserid(systemmanager.getAreauserid());
            }
            if (StringUtils.isNotBlank(param.getExcludeaccountidsstr())) {
                param.setExcludeAccountIds(param.getExcludeaccountidsstr().split(","));
            }
            List<GoodsTradeQueryResult> results;
            if (param.getSummode() == 1) {
                // 1：按商品汇总
                results = iTradeOrderdetailMapper.queryByAGoods(param);
            } else {
                // 2:按商品+日期汇总
                results = iTradeOrderdetailMapper.queryByAGoodsDate(param);
            }
            String fileName = "商品成交汇总_" + DateTimeUtils.getDateTime("yyyyMMdd");
            if (CollectionUtils.isEmpty(results)) {
                return AjaxResult.error(Constants.Error_Code_Design, MessageType.QUERY_ERROR_CODE_005.getCode(), request.getHeader("Accept-Language"));
            }
            ExportResult exportResult = ExportUtil.write(fileName, GoodsTradeQueryResult.class, results);
            return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), exportResult);
        } catch (Exception e) {
            log.error("商品成交汇总导出失败，失败原因：" + e);
            return AjaxResult.error(Constants.Error_Code_Design, MessageType.QUERY_ERROR_CODE_006.getCode(), request.getHeader("Accept-Language"));
        }
    }

    @Override
    public AjaxResult<OrganSelectResult> summaryQueryInit(HttpServletRequest request) {
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        OrganSelectParam vo = new OrganSelectParam();
        vo.setUsertype("2");
        Useraccount ua = iUseraccountMapper.selectOne(new QueryWrapper<Useraccount>().eq("userid", systemmanager.getAreauserid()));
        vo.setSubarealevelpath(ua.getSubarealevelpath());
        return iCommonService.queryOrganSelect(vo, request);
    }

    @Override
    public PageResult<TradeSumQueryResult> queryTradeSum(TradeSumQueryParam param, HttpServletRequest request) {
        IPage<TradeSumQueryResult> page = new Page<>(param.getPageNum(), param.getPageSize());
        IPage<TradeSumQueryResult> resultIPage = iTradeOrderdetailMapper.queryTradeSum(page, param);
        PageResult<TradeSumQueryResult> pageResult = new PageResult<>();
        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 exportTradeSum(TradeSumQueryParam param, HttpServletRequest request) {
        try {
            List<TradeSumQueryResult> results = iTradeOrderdetailMapper.queryTradeSum(param);
            String fileName = "成交汇总_" + DateTimeUtils.getDateTime("yyyyMMdd");
            if (CollectionUtils.isEmpty(results)) {
                return AjaxResult.error(Constants.Error_Code_Design, MessageType.QUERY_ERROR_CODE_005.getCode(), request.getHeader("Accept-Language"));
            }
            ExportResult exportResult = ExportUtil.write(fileName, TradeSumQueryResult.class, results);
            return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), exportResult);
        } catch (Exception e) {
            log.error("商品成交汇总导出失败，失败原因：" + e);
            return AjaxResult.error(Constants.Error_Code_Design, MessageType.QUERY_ERROR_CODE_006.getCode(), request.getHeader("Accept-Language"));
        }
    }

    @Override
    public PageResult<DeliveryOrderEntrustResult> queryDeliveryOrder(DeliveryOrderEntrustParam param, HttpServletRequest request) {
        IPage<DeliveryOrderEntrustResult> page = new Page<>(param.getPageNum(), param.getPageSize());
        IPage<DeliveryOrderEntrustResult> resultIPage = iTradeOrderdetailMapper.queryDeliveryOrder(page, param);
        PageResult<DeliveryOrderEntrustResult> pageResult = new PageResult<>();
        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<DeliveryOrderWrsResult> queryWRStandard(DeliveryOrderWrsParam param, HttpServletRequest request) {
        param.setIsvalid(1);
        List<DeliveryOrderWrsResult> results = iWrstandardMapper.queryWRStandard(param);
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), results);
    }

    @Override
    public AjaxResult<DeliveryOrderDetailResult> deliveryOrderDetail(String deliveryorderid, String histradedate, HttpServletRequest request) {
        DeliveryOrderDetailResult deliveryOrderParam = iTradeOrderdetailMapper.queryDeliveryOrderById(deliveryorderid, histradedate);
        deliveryOrderParam.setAccountname(iUseraccountMapper.selectUserName(deliveryOrderParam.getAccountid()));
        deliveryOrderParam.setMatchaccountname(iUseraccountMapper.selectUserName(deliveryOrderParam.getMatchaccountid()));
        List<Wrfactortypeitem> list = iTradeOrderdetailMapper.queryWRFactorTypeItemNew(deliveryOrderParam.getWrfactortypeid());
        deliveryOrderParam.setWrFactorTypeItemList(list);
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), deliveryOrderParam);
    }

    @Override
    public PageResult<SettlementDealResult> querySettlementDeal(SettlementDealParam param, HttpServletRequest request) {
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        if (systemmanager.getReletype() != 1) {
            param.setUserid(systemmanager.getAreauserid());
        }
        //平台只查主单
        if (systemmanager.getReletype() == 1) {
            param.setMainorderflag(1);
        }
        IPage<SettlementDealResult> page = new Page<>(param.getPageNum(), param.getPageSize());
        IPage<SettlementDealResult> resultIPage = iTradeOrderdetailMapper.querySettlementDeal(page, param);
        PageResult<SettlementDealResult> pageResult = new PageResult<>();
        pageResult.setCode(Constants.Success_Code_Design);
        resultIPage.getRecords().forEach(a -> {
            a.setMatchaccountname(iUseraccountMapper.selectUserName(a.getMatchaccountid()));
            a.setAccountname(iUseraccountMapper.selectUserName(a.getAccountid()));
        });
        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<SettlementDealDetailResult> settlementDealDetail(SettlementDealDetailParam param, HttpServletRequest request) {
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        if (!iCommonService.checkUserAccountRole(systemmanager, systemmanager.getAreauserid())) {
            return AjaxResult.error(Constants.Error_Code_Design, MessageType.MESSAGE_ERROR_CODE_SYSTEM003.getCode(), request.getHeader("Accept-Language"));
        }
        SettlementDealDetailResult result = iTradeOrderdetailMapper.settlementDealDetail(param);
        List<Wrfactortypeitem> list = iTradeOrderdetailMapper.queryWRFactorTypeItemNew(result.getWrfactortypeid());
        result.setWrFactorTypeItemList(list);
        result.setMatchaccountname(iUseraccountMapper.selectUserName(result.getMatchaccountid()));
        result.setAccountname(iUseraccountMapper.selectUserName(result.getAccountid()));
        String sysparm089 = iCommonService.getSysparmById(SysConstants.SYPAMAM_CODE_ZHONGJIANG);
        if (StringUtils.isNotBlank(sysparm089)) {
            result.setIszhongjiang(sysparm089);
        } else {
            result.setIszhongjiang("1");
        }
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), result);
    }

    @Override
    public AjaxResult<ApplyOrderDetailResult> applyOrderDetail(String deliveryorderid, String histradedate, HttpServletRequest request) {
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        ApplyOrderDetailResult result;
        List<DeliveryDetailResult> detailResult;
        String sellId = null;
        String buyId = null;
        if (StringUtils.isNotBlank(histradedate)) {
            result = iTradeOrderdetailMapper.applyOrderDetailHis(deliveryorderid);
            if (result.getBuyorsell() == 0) {
                buyId = result.getDeliveryapplyorderid();
            } else {
                sellId = result.getDeliveryapplyorderid();
            }
            detailResult = iTradeOrderdetailMapper.getHisDeliveryDetailByBuyOrSellOrderId(sellId, buyId, result.getBuyorsell());
            detailResult.forEach(a -> {
                a.setMatchaccountname(iUseraccountMapper.selectUserName(a.getMatchaccountid()));
                a.setAccountname(iUseraccountMapper.selectUserName(a.getAccountid()));
            });
        } else {
            result = iTradeOrderdetailMapper.applyOrderDetail(deliveryorderid);
            if (result.getBuyorsell() == 0) {
                buyId = result.getDeliveryapplyorderid();
            } else {
                sellId = result.getDeliveryapplyorderid();
            }
            detailResult = iTradeOrderdetailMapper.getDeliveryDetailByBuyOrSellOrderId(sellId, buyId, result.getBuyorsell());
            detailResult.forEach(a -> {
                a.setMatchaccountname(iUseraccountMapper.selectUserName(a.getMatchaccountid()));
                a.setAccountname(iUseraccountMapper.selectUserName(a.getAccountid()));
            });
        }
        result.setAccountname(iUseraccountMapper.selectUserName(result.getAccountid()));
        result.setDeliveryIds(detailResult);
        if (iCommonService.checkTaaccountReport(systemmanager, result.getAccountid())) {
            return AjaxResult.error(Constants.Error_Code_Design, MessageType.QUERY_ERROR_CODE_004.getCode(), request.getHeader("Accept-Language"));
        }
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), result);
    }

    @Override
    public PageResult<OfflineDeliveryResult> queryoffline(OfflineDeliveryParam param, HttpServletRequest request) {
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        if (systemmanager.getReletype() != 1) {
            // 不是平台，产业会员只查对手为自己的单据
            param.setMatchuserid(systemmanager.getAreauserid());
        }
        IPage<OfflineDeliveryResult> page = new Page<>(param.getPageNum(), param.getPageSize());
        IPage<OfflineDeliveryResult> resultIPage = iTradeOrderdetailMapper.queryDeliveryOfflinePage(page, param);
        PageResult<OfflineDeliveryResult> pageResult = new PageResult<>();
        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<OfflineDeliveryDetailResult> offlineDetail(String deliveryorderid, HttpServletRequest request) {
        OfflineDeliveryDetailResult result = iTradeOrderdetailMapper.queryDeliveryOfflineDetail(deliveryorderid);
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), result);
    }

    @Override
    public AjaxResult offlineclose(String deliveryorderid, Long marketid, HttpServletRequest request) {
        Marketrun marketRun = iMarketrunMapper.selectOne(new QueryWrapper<Marketrun>().eq("marketid", marketid));
        if (Objects.nonNull(marketRun) && marketRun.getRunstatus().equals(2)) {
            int result = closeDeliveryOffline(deliveryorderid);
            if (result == -1) {
                return AjaxResult.error(Constants.Error_Code_Design, MessageType.QUERY_ERROR_CODE_009.getCode(), request.getHeader("Accept-Language"));
            } else {
                return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"));
            }
        } else {
            // 市场错误或市场状态不为开市场状态
            return AjaxResult.error(Constants.Error_Code_Design, MessageType.QUERY_ERROR_CODE_008.getCode(), request.getHeader("Accept-Language"));
        }
    }

    @Override
    public AjaxResult offlinefail(String deliveryorderid, Long marketid, String auditremark, HttpServletRequest request) {
        Marketrun marketRun = iMarketrunMapper.selectOne(new QueryWrapper<Marketrun>().eq("marketid", marketid));
        if (Objects.nonNull(marketRun) && marketRun.getRunstatus().equals(2)) {
            int result = failDeliveryOffline(deliveryorderid, auditremark);
            if (result == -1) {
                return AjaxResult.error(Constants.Error_Code_Design, MessageType.QUERY_ERROR_CODE_009.getCode(), request.getHeader("Accept-Language"));
            } else {
                return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"));
            }
        } else {
            // 市场错误或市场状态不为开市场状态
            return AjaxResult.error(Constants.Error_Code_Design, MessageType.QUERY_ERROR_CODE_008.getCode(), request.getHeader("Accept-Language"));
        }
    }

    @Override
    public AjaxResult offlineexport(OfflineDeliveryParam param, HttpServletRequest request) {
        try {
            List<OfflineDeliveryResult> results = iTradeOrderdetailMapper.queryDeliveryOfflinePage(param);
            String fileName = "线下交收单_" + DateTimeUtils.getDateTime("yyyyMMdd");
            if (CollectionUtils.isEmpty(results)) {
                return AjaxResult.error(Constants.Error_Code_Design, MessageType.QUERY_ERROR_CODE_005.getCode(), request.getHeader("Accept-Language"));
            }
            ExportResult exportResult = ExportUtil.write(fileName, OfflineDeliveryResult.class, results);
            return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), exportResult);
        } catch (Exception e) {
            log.error("线下交收单导出失败，失败原因：" + e);
            return AjaxResult.error(Constants.Error_Code_Design, MessageType.QUERY_ERROR_CODE_006.getCode(), request.getHeader("Accept-Language"));
        }
    }

    @Override
    public PageResult<EsignrecordQueryResult> queryesignrecord(EsignrecordQueryParam param, HttpServletRequest request) {
        IPage<EsignrecordQueryResult> page = new Page<>(param.getPageNum(), param.getPageSize());
        IPage<EsignrecordQueryResult> resultIPage = iTradeOrderdetailMapper.queryesignrecord(page, param);
        // Go查询腾讯电子签子客URL地址\爱签查询
        resultIPage.getRecords().forEach(a -> {
            String sp1005 = iCommonService.getSystemParam(Constants.REDIS_HEADER_SYSPARAM, "1005");
            if (!Strings.isNullOrEmpty(sp1005)) {
                //处理请求url
                if (sp1005.contains("/api/")) {
                    a.setSp1005Url(sp1005 + "Asign/SyncContractStatus");
                } else {
                    a.setSp1005Url(sp1005 + "/Asign/SyncContractStatus");
                }
            }
        });
        PageResult<EsignrecordQueryResult> pageResult = new PageResult<>();
        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 changeStatus(Long recordid, Integer newStatus, HttpServletRequest request) {
        Useresignrecord record = iUseresignrecordMapper.selectOne(new QueryWrapper<Useresignrecord>().eq("recordid", recordid));

        if (record == null) {
            return AjaxResult.error(Constants.Error_Code_Design, MessageType.MESSAGE_ERROR_CODE_SYSTEM002.getCode(), request.getHeader("Accept-Language"));
        }
        if (newStatus == 1L) {
            // 2:签署中\4:签署拒绝的可重置为未签署
            if (!record.getRecordstatus().equals(2L) && !record.getRecordstatus().equals(4L)) {
                return AjaxResult.error(Constants.Error_Code_Design, MessageType.MESSAGE_ERROR_CODE_SYSTEM002.getCode(), request.getHeader("Accept-Language"));
            }
        } else if (newStatus == 3L) {
            // 1:未签署\4:签署拒绝更新为3：已签署
            if (!record.getRecordstatus().equals(1L) && !record.getRecordstatus().equals(4L)) {
                return AjaxResult.error(Constants.Error_Code_Design, MessageType.MESSAGE_ERROR_CODE_SYSTEM002.getCode(), request.getHeader("Accept-Language"));
            }
        } else {
            return AjaxResult.error(Constants.Error_Code_Design, MessageType.MESSAGE_ERROR_CODE_SYSTEM002.getCode(), request.getHeader("Accept-Language"));
        }
        record.setRecordstatus(newStatus);
        record.setUpdatetime(new Date());
        iUseresignrecordMapper.updateById(record);
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"));
    }

    @Override
    public PageResult<InvestorQueryResult> queryinvestor(InvestorQueryParam param, HttpServletRequest request) {
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        if (systemmanager.getReletype() != 1) {
            if (("," + param.getOrgztypes() + ",").contains(",3,")) {
                param.setChangeflag(3);
            }
            param.setAreauserid(systemmanager.getAreauserid());
        }
        IPage<InvestorQueryResult> page = new Page<>(param.getPageNum(), param.getPageSize());
        IPage<InvestorQueryResult> resultIPage = iTradeOrderdetailMapper.queryinvestor(page, param);
        //处理金额
        getRiskFromRedis(resultIPage.getRecords());
        PageResult<InvestorQueryResult> pageResult = new PageResult<>();
        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;
    }

    private void getRiskFromRedis(List<InvestorQueryResult> records) {
        try {
            String floatplFlag = iCommonService.getSystemParam(Constants.REDIS_HEADER_SYSPARAM, "113");
            String creditFlag = iCommonService.getSystemParam(Constants.REDIS_HEADER_SYSPARAM, "946");
            String closeplFlag = iCommonService.getSystemParam(Constants.REDIS_HEADER_SYSPARAM, "112");
            String inamountFlag = iCommonService.getSystemParam(Constants.REDIS_HEADER_SYSPARAM, "111");
            for (InvestorQueryResult record : records) {
                byte[] valuebts = redisServiceUtil.getBytes("risk:" + record.getAccountid());
                AccountRedis.AccRiskInfo accRiskInfo = null;
                if (valuebts != null) {
                    accRiskInfo = AccountRedis.AccRiskInfo.newBuilder().mergeFrom(valuebts).build();
                    log.info("risk:" + record.getAccountid() + "--------------accRiskInfo:" + accRiskInfo);

                    record.setCur_risk_rate(BigDecimal.valueOf(accRiskInfo.getCURRISKRATE()).multiply(BigDecimal.valueOf(100d)).setScale(2, RoundingMode.DOWN));
                    record.setFloatpl(BigDecimal.valueOf(accRiskInfo.getTOTALFLOATPL()));
                } else {
                    // Redis无记录，风险率、浮动盈亏设置为0
                    record.setCur_risk_rate(BigDecimal.ZERO);
                    record.setFloatpl(BigDecimal.ZERO);
                }

                // 更新可用
                setAvaliableAmount(record, floatplFlag);

                // 更新可出
                setAvaliableOutAmount(record, floatplFlag, creditFlag, closeplFlag, inamountFlag);

                // 更新当前净值= 期末余额+浮动盈亏(收益权)
                record.setFloatnetvalue(record.getCurrentbalance().add(record.getFloatpl()));
            }
        } catch (Exception e) {
            log.error("设置风险率失败，请检查！");
        }
    }

    private void setAvaliableOutAmount(InvestorQueryResult vo, String floatplFlag, String creditFlag, String closeplFlag, String inamountFlag) {
        //根据系统参数计算s1(946	是否可设置收益权市场的交易授信 0:不显示 1:显示 默认0)
        //946 = 0：
        //s1=期末余额-交易占用-交易冻结-手续费冻结-出金冻结-其它冻结-授信金额-其它授信金额+浮动盈亏-[平仓盈利(正值)](当日平仓盈利不可出112)-[浮动盈利(正值)](当日浮动盈利不可出113)
        //946 = 1:
        //s1=期末余额-交易占用-交易冻结-手续费冻结-出金冻结-其它冻结-授信金额-其它授信金额+浮动盈亏-[平仓盈利(正值)](当日平仓盈利不可出112)-[浮动盈利(正值)](当日浮动盈利不可出113)
        //s2=期初余额+子账号期初余额汇总+当日出金(负值)-出金冻结+[当日入金](当日入金可出111)
        //可出资金=min(s1,s2)
        BigDecimal s1 = BigDecimal.ZERO;
        if ("1".equals(creditFlag)) {
            s1 = vo.getCurrentbalance().subtract(vo.getUsedmargin())
                    .subtract(vo.getFreezemargin()).subtract(vo.getOtherfreezemargin()).subtract(vo.getFreezecharge())
                    .subtract(vo.getOutamountfreeze()).subtract(vo.getOthercredit()).add(vo.getFloatpl());

        } else {
            s1 = vo.getCurrentbalance().subtract(vo.getUsedmargin())
                    .subtract(vo.getFreezemargin()).subtract(vo.getOtherfreezemargin()).subtract(vo.getFreezecharge())
                    .subtract(vo.getOutamountfreeze()).subtract(vo.getMortgagecredit()).subtract(vo.getOthercredit())
                    .add(vo.getFloatpl());
        }

        if ("0".equals(closeplFlag) && vo.getClosepl().compareTo(BigDecimal.ZERO) > 0) {
            s1 = s1.subtract(vo.getClosepl());
        }
        if ("0".equals(floatplFlag) && vo.getFloatpl().compareTo(BigDecimal.ZERO) > 0) {
            s1 = s1.subtract(vo.getFloatpl());
        }
        BigDecimal s2 = vo.getBalance();
        if (vo.getOutamount().compareTo(BigDecimal.ZERO) < 0) {
            s2 = s2.add(vo.getOutamount());
        }
        s2.subtract(vo.getOutamountfreeze());
        if ("1".equals(inamountFlag)) {
            s2 = s2.add(vo.getInamount());
        }

        if ("0".equals(closeplFlag)) {
            vo.setAvaiableoutmoney(s1.compareTo(s2) > 0 ? s2 : s1);
        } else {
            vo.setAvaiableoutmoney(s1);
        }

        // 减去账户出金阀值
        if (vo.getOutthreshold() != null) {
            if (vo.getOutthreshold().compareTo(vo.getAvaiableoutmoney()) > -1) {
                vo.setAvaiableoutmoney(BigDecimal.ZERO);
            } else {
                vo.setAvaiableoutmoney(vo.getAvaiableoutmoney().subtract(vo.getOutthreshold()));
            }
        }

        // 可出小于0，显示时强制值为0
        if (BigDecimal.ZERO.compareTo(vo.getAvaiableoutmoney()) > -1) {
            vo.setAvaiableoutmoney(BigDecimal.ZERO);
        }
    }

    private void setAvaliableAmount(InvestorQueryResult vo, String floatplFlag) {
        //可用资金：
        //      账户总浮动盈亏为负：
        //      =期末余额+总浮动盈亏（收益权）-占用-冻结-其它冻结-手续费冻结-出金冻结
        //		账户总浮动盈亏为正 且 113 = 0 ：
        //		=期末余额-占用-冻结-其它冻结-手续费冻结-出金冻结
        //		账户总浮动盈亏为正 且 113 = 1 ：
        //		=期末余额+总浮动盈亏（收益权）-占用-冻结-其它冻结-手续费冻结-出金冻结
        //		*系统参数”113“（当日浮动盈利是否可用） 0:不可用 1:可用
        if (vo == null) return;

        if (floatplFlag.equals("1") || vo.getFloatpl().compareTo(new BigDecimal(0)) < 0) {
            vo.setAvaiablemoney(vo.getCurrentbalance().add(vo.getFloatpl()).subtract(vo.getUsedmargin())
                    .subtract(vo.getFreezemargin()).subtract(vo.getOtherfreezemargin()).subtract(vo.getFreezecharge())
                    .subtract(vo.getOutamountfreeze()));
        } else {
            vo.setAvaiablemoney(vo.getCurrentbalance().subtract(vo.getUsedmargin())
                    .subtract(vo.getFreezemargin()).subtract(vo.getOtherfreezemargin()).subtract(vo.getFreezecharge())
                    .subtract(vo.getOutamountfreeze()));
        }
    }

    @Override
    public PageResult<PositionSumSheetResult> queryinvestortradeposition(PositionSumSheetParam param, HttpServletRequest request) {
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        PageResult<PositionSumSheetResult> pageResult = new PageResult<>();
        if (iCommonService.checkTaaccountReport(systemmanager, param.getAccountid())) {
            pageResult.setCode(Constants.Error_Code_Design);
            pageResult.setMessage(AjaxResult.dealMsg(MessageType.QUERY_ERROR_CODE_004.getCode(), request.getHeader("Accept-Language")));
            return pageResult;
        }
        IPage<PositionSumSheetResult> page = new Page<>(param.getPageNum(), param.getPageSize());
        IPage<PositionSumSheetResult> resultIPage = iTradeOrderdetailMapper.queryTradePositionPage(page, param);
        //处理金额
        dealSunAmount(resultIPage.getRecords());
        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 sellGoods(String deliveryorderid, Long marketid, HttpServletRequest request) {
        Marketrun marketRun = iMarketrunMapper.selectOne(new QueryWrapper<Marketrun>().eq("marketid", marketid));
        if (marketRun != null && marketRun.getRunstatus().equals(2)) {
            log.info("支付交收货款处理开始");
            Long uuid = SerialNumberUtils.getNewSerialNumber(SerialNumberUtils.prefix_capacity);
            Calculator ca = new Calculator(uuid, FunCodeConstants.FuncCode_DeliveryProviderPaySellAmountReq);
            SerialNumberUtils.lockMap.put(uuid, ca);

            TkernelMI2.DeliveryProviderPaySellAmountReq.Builder builder = TkernelMI2.DeliveryProviderPaySellAmountReq.newBuilder();
            Common.MessageHead.Builder hd = Common.MessageHead.newBuilder();
            hd.setFunCode(FunCodeConstants.FuncCode_DeliveryProviderPaySellAmountReq);
            hd.setUUID(String.valueOf(uuid));
            hd.setClientTime(System.currentTimeMillis());
            hd.setMarketID(Integer.parseInt(String.valueOf(marketid)));
            builder.setHeader(hd);
            builder.setDeliveryOrderID(Long.parseLong(deliveryorderid));

            byte[] body = ProtoHelper.getNTAS(builder.build().toByteArray(),
                    FunCodeConstants.FuncCode_DeliveryProviderPaySellAmountReq);

            rabbitTemplate.send(SysConstants.TradeCpReq, new Message(body, new MessageProperties()));

            synchronized (ca) {
                try {
                    ca.wait(6000);
                    Object o = ca.obj;
                    if (o != null) {
                        TkernelMI2.DeliveryProviderPaySellAmountRsp rsp_ = (TkernelMI2.DeliveryProviderPaySellAmountRsp) o;
                        if (rsp_.getRetCode() == 0) {
                            return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM012.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) {
                    log.error("DeliveryProviderPaySellAmountRsp 获取响应失败，失败原因：" + e.getMessage());
                } finally {
                    SerialNumberUtils.lockMap.remove(uuid);
                }
            }
        } else {
            return AjaxResult.error(Constants.Error_Code_Design, MessageType.QUERY_ERROR_CODE_008.getCode(), request.getHeader("Accept-Language"));
        }
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"));
    }

    @Override
    public PageResult<HoldtransferQueryResult> holdtransferquery(HoldtransferQueryParam param, HttpServletRequest request) {
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        //协议转让 平台、运营机构有权限，运营机构只查有权限的商品
        if (!systemmanager.getReletype().equals(1)) {
            // 非平台
            param.setYyareauserid(systemmanager.getAreauserid());
        }
        PageResult<HoldtransferQueryResult> pageResult = new PageResult<>();
        IPage<HoldtransferQueryResult> page = new Page<>(param.getPageNum(), param.getPageSize());
        IPage<HoldtransferQueryResult> resultIPage = iTradeOrderdetailMapper.holdtransferquery(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;
    }

    private int failDeliveryOffline(String deliveryorderid, String auditremark) {
        Marketrun mr = iMarketrunMapper.selectOne(new QueryWrapper<Marketrun>().eq("marketid", 0L));
        if (mr != null && deliveryorderid != null) {
            return iTradeOrderdetailMapper.failDeliveryOffline(mr.getTradedate(), deliveryorderid, auditremark);
        }
        return -1;
    }

    private int closeDeliveryOffline(String deliveryorderid) {
        Marketrun mr = iMarketrunMapper.selectOne(new QueryWrapper<Marketrun>().eq("marketid", 0L));
        if (mr != null && deliveryorderid != null) {
            return iTradeOrderdetailMapper.closeDeliveryOffline(mr.getTradedate(), deliveryorderid);
        }
        return -1;
    }

    private void getPerformanceTemplateById(WarehouseCommissionResultDetail dto) {
        Performanceplantemplate plantemplate = iPerformanceplantemplateMapper.selectOne(
                new QueryWrapper<Performanceplantemplate>().eq("autoid", dto.getWrTradeOrderDetail().getPerformancetemplateid()));
        if (Objects.isNull(plantemplate)) {
            return;
        }
        dto.setPerformanceplantemplate(plantemplate);
        List<Performancesteptemplate> pstList = iWrtradeOrderdetailMapper.queryPerformanceStep(dto.getWrTradeOrderDetail().getPerformancetemplateid());
        if (CollectionUtils.isNotEmpty(pstList)) {
            //对List进行排序
            dto.setPerformancesteptemplateList(pstList.stream().sorted(Comparator.comparing(Performancesteptemplate::getStepindex)).collect(Collectors.toList()));
        }
    }

    private WarehouseCommissionResultDetail getWRTradeOrderDetailById(Long wrtradeorderid, Integer ishis) {
        WarehouseCommissionResultDetail dto = new WarehouseCommissionResultDetail();
        WrtradeOrderdetail wr = new WrtradeOrderdetail();
        if (ishis != null && ishis == 1) {
            HisWrtradeOrderdetail hiswrOrde = iHisWrtradeOrderdetailMapper.selectOne(new QueryWrapper<HisWrtradeOrderdetail>().eq("WRTRADEORDERID", wrtradeorderid));
            if (hiswrOrde != null) {
                BeanUtils.copyProperties(hiswrOrde, wr);
            }
        } else {
            WrtradeOrderdetail wrEntity = iWrtradeOrderdetailMapper.selectOne(new QueryWrapper<WrtradeOrderdetail>().eq("wrtradeorderid", wrtradeorderid));
            BeanUtils.copyProperties(wrEntity, wr);
        }

        Wrfactortype wrs = iWrfactortypeMapper.selectOne(new QueryWrapper<Wrfactortype>().eq("wrfactortypeid", wr.getWrfactortypeid()));
        if (wrs != null) {
            dto.setWrFactorTypeName(wrs.getWrfactortypename());
            Wrstandard wRStandard = iWrstandardMapper.selectOne(new QueryWrapper<Wrstandard>().eq("WRSTANDARDID", wrs.getWrstandardid()));
            Map<Object, Object> goodsunitMap = redisServiceUtil.getHash(Constants.REDIS_HEADER_DICT + "goodsunit");
            String goodsUnitName = (String) goodsunitMap.get(wRStandard.getUnitid().toString());
            dto.setGoodsUnitName(goodsUnitName);
            dto.setWrstandardcode(wRStandard.getWrstandardcode());
            dto.setWrstandardname(wRStandard.getWrstandardname());
            if (wRStandard.getRealminivaluedp() != null) {
                double realminivaluedp = Math.pow(10D, wRStandard.getRealminivaluedp().doubleValue());
                if (wr.getTradeqty() != null) {
                    double tradeQty = wr.getTradeqty().doubleValue();
                    tradeQty = tradeQty / realminivaluedp;
                    wr.setTradeqty(BigDecimal.valueOf(tradeQty));
                }
                if (wr.getOrderqty() != null) {
                    double orderQty = wr.getOrderqty().doubleValue();
                    orderQty = orderQty / realminivaluedp;
                    wr.setOrderqty(BigDecimal.valueOf(orderQty));
                }
            }
        }
        dto.setMarketName(iMarketMapper.selectOne(new QueryWrapper<Market>().eq("marketid", wr.getMarketid())).getMarketname());
        dto.setUserName(iUseraccountMapper.selectOne(new QueryWrapper<Useraccount>().eq("userid", wr.getUserid())).getAccountname());
        dto.setWrTradeOrderDetail(wr);
        if (dto.getWrTradeOrderDetail().getFirstratio() != null) {
            BigDecimal firstRation = dto.getWrTradeOrderDetail().getFirstratio();
            dto.getWrTradeOrderDetail().setFirstratio(firstRation.multiply(new BigDecimal(100)).setScale(2, RoundingMode.HALF_UP));
        }
        dto.setWrTradeGoodsConfigs(iWrtradeOrderdetailMapper.getWRTradeGoodsConfigById(wr.getWrtradeorderid()));
        dto.setWrTradeMatchDetails(iWrtradeOrderdetailMapper.getWRTradeMatchDetailById(wr.getWrtradeorderid()));
        return dto;
    }

    private void dealSunAmount(List<PositionSumSheetResult> records) {
        for (PositionSumSheetResult record : records) {
            try {
                int qyt = record.getBuycurpositionqty() - record.getSellcurpositionqty();
                //净持仓量
                record.setQty(qyt);
                //净持仓方向
                if (qyt > 0) {
                    record.setBuyorsell(0);
                } else if (qyt < 0) {
                    record.setBuyorsell(1);
                } else {
                    record.setBuyorsell(null);
                }
                //持仓损益(总)
                record.setFloatPL(record.getBuycurholderamount().subtract(record.getSellcurholderamount()));
                String goodsCode = record.getGoodscode();
                BigDecimal argeeunit = record.getAgreeunit();
                BigDecimal buyFloatPL = null;
                BigDecimal sellFloatPL = null;
                // 计算买浮动盈亏
                if (record.getBuycurpositionqty() > 0) {
                    buyFloatPL = iCommonService.calcFloaPL(goodsCode, argeeunit, 0,
                            record.getBuycurpositionqty(),
                            record.getBuycurholderamount());
                    if (buyFloatPL != null) {
                        record.setBuyFloatPL(buyFloatPL);
                    }
                }
                // 计算卖浮动盈亏
                if (record.getSellcurpositionqty() > 0) {
                    sellFloatPL = iCommonService.calcFloaPL(goodsCode, argeeunit, 1,
                            record.getSellcurpositionqty(),
                            record.getSellcurholderamount());
                    if (sellFloatPL != null) {
                        record.setSellFloatPL(sellFloatPL);
                    }
                }
                // 计算 总浮动盈亏
                if (buyFloatPL != null || sellFloatPL != null) {
                    record.setFloatPL((buyFloatPL == null ? BigDecimal.ZERO : buyFloatPL).add(sellFloatPL == null ? BigDecimal.ZERO : sellFloatPL));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void dealHisAmount(PositionSheetParam param, List<PositionSheetResult> resultIPage) {
        Market market = iMarketMapper.selectOne(new QueryWrapper<Market>().eq("marketid", param.getMarketId()));
        if (market != null && market.getTrademode() == 18) {
            for (PositionSheetResult record : resultIPage) {
                //任务 #67476  定货金总额“(=定货金*成交数量)  中远
                BigDecimal premiumAmount = record.getPremium().multiply(BigDecimal.valueOf(record.getHolderqty()));
                record.setPremiumAmount(premiumAmount);
            }
        }
    }

    private void dealAmount(PositionSheetParam param, List<PositionSheetResult> resultIPage) {
        Market market = iMarketMapper.selectOne(new QueryWrapper<Market>().eq("marketid", param.getMarketId()));
        for (PositionSheetResult record : resultIPage) {
            //浮动盈亏
            BigDecimal actuallYplS = BigDecimal.ZERO;
            if (Objects.nonNull(market)) {
                if (market.getTrademode() == 18 || market.getTrademode() == 26) {
                    // 处理期权商品盈亏
                    setOptionGoodsPL(record);
                } else {
                    //尚志  任务 #67493 ”持仓金额"后添加列“浮动盈亏”
                    String quoteGoodsCode = record.getGoodscode();
                    // 掉期市场使用参考行情商品代码
                    if (market.getTrademode().equals(46)) {
                        quoteGoodsCode = record.getRefgoodscode();
                    }
                    actuallYplS = iCommonService.calcFloaPL(quoteGoodsCode,
                            record.getAgreeUnit(), record.getBuyorsell(),
                            record.getHolderqty(), record.getHolderamount());

                    // 赋值浮动盈亏
                    record.setActuallYplS(actuallYplS);
                }
            }

        }
    }

    /**
     * 浮动盈亏(买) = Min[ Max[ (当前价-行权价)*数量*合约单位*期权类型(认购为1, 认沽为-1), 0 ], 赔付上限值 ]
     * 浮动盈亏(卖) = Max[ Min[ (行权价-当前价)*数量*合约单位*期权类型(认购为1, 认沽为-1), 0 ], 赔付上限值* (-1) ]
     * 实际盈亏(买) = 买持仓浮动盈亏 – 权利金*数量
     * 实际盈亏(卖) = 卖持仓浮动盈亏 + 权利金*数量
     * <p>
     * 赔付上限值(不限)  = 无穷大
     * 赔付上限值(权利金倍数)  = 权利金*数量*赔付权利金倍数
     * <p>
     * 实时盈亏根据浮动盈亏公式计算，实际盈亏根据实际盈亏公式计算；
     */
    private void setOptionGoodsPL(PositionSheetResult tradeHolderDetailParam) {
        // 处理期权商品盈亏
        BigDecimal realTimeYpl = BigDecimal.ZERO;//实时盈亏
        BigDecimal actuallYplL = BigDecimal.ZERO;//实际盈亏
        BigDecimal actuallYplS;//浮动盈亏
        BigDecimal payModeValue = BigDecimal.ZERO;//赔付上限值
        BigDecimal midActuallYpl;//数量*合约单位*期权类型
        BigDecimal midActuallYpl2;//从行情取得当前价-行权价
        BigDecimal midActuallYpl3;//预售申报价格-行权价
        try {
            Goodsoptionproperty goodsOptionProperty = iGoodsoptionpropertyMapper.selectOne(new QueryWrapper<Goodsoptionproperty>().eq("goodsid", tradeHolderDetailParam.getGoodsid()));
            //期权类型(认购为1, 认沽为-1)
            int optionType = tradeHolderDetailParam.getOptiontype() == 1 ? 1 : -1;
            //数量*合约单位*期权类型
            midActuallYpl = tradeHolderDetailParam.getAgreeUnit().multiply(BigDecimal.valueOf(optionType)).multiply(BigDecimal.valueOf(tradeHolderDetailParam.getHolderqty()));
            //预售申报价格-行权价
            midActuallYpl3 = tradeHolderDetailParam.getPreExercisePrice().subtract(tradeHolderDetailParam.getHolderprice());
            //赔付上限值 = 权利金*数量*赔付权利金倍数
            if (goodsOptionProperty.getPaymode() == 2) {
                payModeValue = tradeHolderDetailParam.getPremium().multiply(new BigDecimal(goodsOptionProperty.getPayvalue().toString())).multiply(BigDecimal.valueOf(tradeHolderDetailParam.getHolderqty()));
            }

            if (tradeHolderDetailParam.getIsPreExercise() == 0 && tradeHolderDetailParam.getIsConfirmExercise() == 0) {//未预申报、未确认行权:当前价 = 行情最新价
                byte[] valuebts = redisServiceUtil.getBytes("QUOTE:" + tradeHolderDetailParam.getGoodscode());
                if (valuebts != null) {
                    QuoteMI1.RealtimeQuote goodQuot = QuoteMI1.RealtimeQuote.parseFrom(valuebts);
                    Goods goods = iGoodsMapper.selectOne(new QueryWrapper<Goods>().eq("goodsid", goodQuot.getGoodsID()));
                    BigDecimal pow = BigDecimal.TEN.pow(goods.getDecimalplace());
                    if (goodQuot != null) {
                        if (tradeHolderDetailParam.getBuyorsell() == 0) {//买
                            midActuallYpl2 = (new BigDecimal(goodQuot.getLast()).divide(pow)).subtract(tradeHolderDetailParam.getHolderprice());//从行情取得当前价-行权价
                            actuallYplS = midActuallYpl2.multiply(midActuallYpl);
                            actuallYplS = actuallYplS.compareTo(BigDecimal.ZERO) == 1 ? actuallYplS : BigDecimal.ZERO;//和0比较取大值
                            if (goodsOptionProperty.getPaymode() == 2) {
                                // 赔付上限值(权利金倍数)  = 权利金*数量*赔付权利金倍数
                                // 无限的时候赔付上限值无穷大，不用计算，因为最后是取小值
                                actuallYplS = actuallYplS.compareTo(payModeValue) == 1 ? payModeValue : actuallYplS;//取小值
                            }
                            realTimeYpl = actuallYplS;
                            //实际盈亏(买) = 浮动盈亏 – 权利金*数量
                            actuallYplL = actuallYplS.subtract(tradeHolderDetailParam.getPremium().multiply(BigDecimal.valueOf(tradeHolderDetailParam.getHolderqty())));
                        } else {
                            midActuallYpl2 = tradeHolderDetailParam.getHolderprice().subtract(new BigDecimal(goodQuot.getLast()).divide(pow));//从行情取得行权价-当前价
                            actuallYplS = midActuallYpl2.multiply(midActuallYpl);
                            actuallYplS = actuallYplS.compareTo(BigDecimal.ZERO) == 1 ? BigDecimal.ZERO : actuallYplS;//和0比较取小值
                            if (goodsOptionProperty.getPaymode() == 2) {
                                // 赔付上限值(权利金倍数)  = 权利金*数量*赔付权利金倍数
                                // 无限的时候赔付上限值无穷大，不用计算，因为最后是取小值
                                payModeValue = payModeValue.multiply(BigDecimal.valueOf(-1));
                                actuallYplS = actuallYplS.compareTo(payModeValue) == 1 ? actuallYplS : payModeValue;//取大值
                            }
                            realTimeYpl = actuallYplS;
                            //实际盈亏(买) = 浮动盈亏 + 权利金*数量
                            actuallYplL = actuallYplS.add(tradeHolderDetailParam.getPremium().multiply(BigDecimal.valueOf(tradeHolderDetailParam.getHolderqty())));
                        }
                    }
                }
            } else if (tradeHolderDetailParam.getIsPreExercise() == 1 && tradeHolderDetailParam.getIsConfirmExercise() == 0) {//已预申报、未确认行权:当前价 = 预申报价格
                if (tradeHolderDetailParam.getBuyorsell() == 0) {//买
                    actuallYplS = midActuallYpl3.multiply(midActuallYpl);
                    actuallYplS = actuallYplS.compareTo(BigDecimal.ZERO) == 1 ? actuallYplS : BigDecimal.ZERO;//和0比较取大值
                    if (goodsOptionProperty.getPaymode() == 2) {
                        // 赔付上限值(权利金倍数)  = 权利金*数量*赔付权利金倍数
                        // 无限的时候赔付上限值无穷大，不用计算，因为最后是取小值
                        actuallYplS = actuallYplS.compareTo(payModeValue) == 1 ? payModeValue : actuallYplS;//取小值
                    }
                    realTimeYpl = actuallYplS;
                    //实际盈亏(买) = 浮动盈亏 – 权利金*数量
                    actuallYplL = actuallYplS.subtract(tradeHolderDetailParam.getPremium().multiply(BigDecimal.valueOf(tradeHolderDetailParam.getHolderqty())));
                } else {
                    actuallYplS = midActuallYpl3.multiply(midActuallYpl).multiply(BigDecimal.valueOf(-1));
                    actuallYplS = actuallYplS.compareTo(BigDecimal.ZERO) == 1 ? BigDecimal.ZERO : actuallYplS;//和0比较取小值
                    if (goodsOptionProperty.getPaymode() == 2) {
                        // 赔付上限值(权利金倍数)  = 权利金*数量*赔付权利金倍数
                        // 无限的时候赔付上限值无穷大，不用计算，因为最后是取小值
                        payModeValue = payModeValue.multiply(BigDecimal.valueOf(-1));
                        actuallYplS = actuallYplS.compareTo(payModeValue) == 1 ? actuallYplS : payModeValue;//取大值
                    }
                    realTimeYpl = actuallYplS;
                    //实际盈亏(买) = 浮动盈亏 + 权利金*数量
                    actuallYplL = actuallYplS.add(tradeHolderDetailParam.getPremium().multiply(BigDecimal.valueOf(tradeHolderDetailParam.getHolderqty())));
                }

            } else if (tradeHolderDetailParam.getIsConfirmExercise() == 1) {//已确认行权：买卖浮动盈亏、实际盈亏均为0
                realTimeYpl = BigDecimal.ZERO;
                actuallYplL = BigDecimal.ZERO;
            }
            tradeHolderDetailParam.setRealTimeYpl(realTimeYpl);
            tradeHolderDetailParam.setActuallYpl(actuallYplL);

            //任务 #67475     定货金总额=定货金*持仓数量) -- 期权/挂牌期权 市场
            BigDecimal premiumAmount = null;//定货金总额
            premiumAmount = tradeHolderDetailParam.getPremium().multiply(BigDecimal.valueOf(tradeHolderDetailParam.getHolderqty()));
            tradeHolderDetailParam.setPremiumAmount(premiumAmount);

        } catch (Exception e) {
            e.printStackTrace();
            log.error("金额计算失败，失败原因：" + e);
        }
    }

    /**
     * 判断当前管理员是否有市场权限,只要机构有一个角色有权限就返回true
     * 1、运营机构对市场、商品组，商品修改的权限（其实没有必要的很）
     * 2、查询委托单、成交单、持仓单等的查看权限，经纪会员应该无所谓，就算可以根据市场查询，也查不出数据，运营机构就算看到应该也没关系
     */
    protected boolean checkMarketAuth(Systemmanager systemmanager, Long marketId, String orgztypes) {
        if (systemmanager.getAreauserid() == 0 || systemmanager.getAreauserid() == 1) {
            return true;
        }
        String[] roletyes = {};
        //如果是子机构登陆，查找其父机构角色，查询市场
        Useraccount ua = new Useraccount();
        if (SysConstants.SYS_TYPE_MEMBER.equals(systemmanager.getReletype())) {
            ua = iUseraccountMapper.selectOne(new QueryWrapper<Useraccount>().eq("userid", systemmanager.getAreauserid()));
            String roleids = iArearoleMapper.getRolesByAreaid(ua.getMemberuserid());
            roletyes = roleids.split(",");
        } else {
            roletyes = orgztypes.split(",");
        }
        for (String role : roletyes) {
            if (SysEnums.OrganRole.marketer.getCode().equals(Integer.parseInt(role))
                    || SysEnums.OrganRole.marketing.getCode().equals(Integer.parseInt(role))) {
                return true;
            }
            Long aLong;
            if (SysConstants.SYS_TYPE_MEMBER.equals(systemmanager.getReletype())) {
                aLong = ua.getMemberuserid();
            } else {
                aLong = systemmanager.getAreauserid();
            }
            Arearolemarket arearolemarket = iArearolemarketMapper.selectOne(new QueryWrapper<Arearolemarket>()
                    .eq("marketid", marketId)
                    .eq("roletype", Integer.parseInt(role))
                    .eq("areauserid", aLong)
            );
            if (Objects.nonNull(arearolemarket)) {
                return true;
            }
        }
        return false;
    }
}
