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.muchinfo.mtp3century.service.ICommonService;
import com.muchinfo.mtp3century.service.ITradingWarehouseSetService;
import com.muchinfo.mtp3century.utils.AjaxResult;
import com.muchinfo.mtp3century.utils.RedisServiceUtil;
import com.muchinfo.mtp3common.enumtype.Constants;
import com.muchinfo.mtp3common.enumtype.MessageType;
import com.muchinfo.mtp3common.enumtype.SysConstants;
import com.muchinfo.mtp3common.enumtype.SysEnums;
import com.muchinfo.mtp3common.vo.PageResult;
import com.muchinfo.mtp3interface.mapper.*;
import com.muchinfo.mtp3pojos.entity.*;
import com.muchinfo.mtp3pojos.vo.MarketDto;
import com.muchinfo.mtp3pojos.vo.query.deliveryorder.DeliveryOrderWrsParam;
import com.muchinfo.mtp3pojos.vo.query.deliveryorder.DeliveryOrderWrsResult;
import com.muchinfo.mtp3pojos.vo.tradingmarket.*;
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.util.*;

@Service
public class TradingWarehouseSetServiceImpl implements ITradingWarehouseSetService {

    @Resource
    private ICommonService iCommonService;
    @Resource
    private ISystemmanagerMapper iSystemmanagerMapper;
    @Resource
    private IPerformanceplantemplateMapper iPerformanceplantemplateMapper;
    @Resource
    private IPerformancesteptemplateMapper iPerformancesteptemplateMapper;
    @Resource
    private IMarketMapper iMarketMapper;
    @Resource
    private IMarketrunMapper iMarketrunMapper;
    @Resource
    private IMarketrunstepdetailMapper iMarketrunstepdetailMapper;
    @Resource
    private IMarketcalendarMapper iMarketcalendarMapper;
    @Resource
    private IMarketcalendaryearMapper iMarketcalendaryearMapper;
    @Resource
    private IUseraccountMapper iUseraccountMapper;
    @Resource
    private IMarketcoinconfigMapper iMarketcoinconfigMapper;
    @Resource
    private IMarkettradeconfigMapper iMarkettradeconfigMapper;
    @Resource
    private IScoretypeMapper iScoretypeMapper;
    @Resource
    private IMarketspotgoodsconfigMapper iMarketspotgoodsconfigMapper;
    @Resource
    private IGzCjbsfeeconfigMapper iGzCjbsfeeconfigMapper;
    @Resource
    private IGzCjbsservicefeeconfigMapper iGzCjbsservicefeeconfigMapper;
    @Resource
    private RedisServiceUtil redisServiceUtil;
    @Resource
    private IWrstandardMapper iWrstandardMapper;
    @Resource
    private IEnumdicitemMapper iEnumdicitemMapper;
    @Resource
    private IGoodsMapper iGoodsMapper;
    @Resource
    private IWrtradeOrderdetailMapper iWrtradeOrderdetailMapper;
    @Resource
    private IGoodsgroupMapper iGoodsgroupMapper;
    @Resource
    private ISystemparamMapper iSystemparamMapper;
    @Resource
    private IArearoleMapper iArearoleMapper;
    @Resource
    private IArearolemarketMapper iArearolemarketMapper;
    @Resource
    private ITaaccountmarketMapper iTaaccountmarketMapper;
    @Resource
    private ITaaccountMapper iTaaccountMapper;
    @Resource
    private IRiskratiotypeMapper iRiskratiotypeMapper;

    @Override
    public PageResult<SpotFulfillmentResult> querySpotFulfillment(Integer pageNum, Integer pageSize, HttpServletRequest request, Integer type) {
        PageResult<SpotFulfillmentResult> pageResult = new PageResult<>();
        IPage<SpotFulfillmentResult> page = new Page<>(pageNum, pageSize);
        IPage<SpotFulfillmentResult> resultIPage = iPerformanceplantemplateMapper.querySpotFulfillment(page, type);
        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<SpotFulfillmentViewResult> spotFulfillmentView(Long autoid, HttpServletRequest request) {
        SpotFulfillmentViewResult param = new SpotFulfillmentViewResult();
        Performanceplantemplate plantemplate = iPerformanceplantemplateMapper.selectById(autoid);
        param.setParam(plantemplate);
        List<Performancesteptemplate> pstList = iPerformanceplantemplateMapper.getPerformanceStepByTmpId(autoid);
        if (CollectionUtils.isNotEmpty(pstList)) {
            pstList.sort(new Comparator<Performancesteptemplate>() {
                @Override
                public int compare(Performancesteptemplate arg0, Performancesteptemplate arg1) {
                    return arg0.getStepindex() - arg1.getStepindex();
                }
            });
            param.setPerformancesteps(pstList);
        }
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), param);
    }

    @Override
    public AjaxResult spotFulfillmentDel(SpotFulfillmentDelParam param, HttpServletRequest request) {
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));

        AjaxResult ajaxResult = check(param, request);
        if (ajaxResult.getCode() == 500) {
            return ajaxResult;
        }
        if (param.getAutoid() == null) {
            Performanceplantemplate plantemplate = new Performanceplantemplate();
            BeanUtils.copyProperties(param, plantemplate);
            plantemplate.setCreatorid(systemmanager.getAutoid());
            plantemplate.setCreatetime(new Date());
            if (plantemplate.getUserid() == null) {
                plantemplate.setUserid(1L);
            }
            iPerformanceplantemplateMapper.insert(plantemplate);
            for (Performancesteptemplate pst : param.getList()) {
                Performancesteptemplate steptemplate = new Performancesteptemplate();
                BeanUtils.copyProperties(pst, steptemplate);
                steptemplate.setTemplateid(plantemplate.getAutoid());
                if (steptemplate.getStepvalue() != null) {
                    steptemplate.setStepvalue(steptemplate.getStepvalue().divide(new BigDecimal(100)));
                }
                if (pst.getIsauto() == null) {
                    steptemplate.setIsauto(0);
                }
                iPerformancesteptemplateMapper.insert(steptemplate);
            }
        } else {
            Performanceplantemplate plantemplate = iPerformanceplantemplateMapper.selectById(param.getAutoid());
            plantemplate.setPaymenttype(param.getPaymenttype());
            plantemplate.setTemplatename(param.getTemplatename());
            plantemplate.setTakemode(param.getTakemode());
            iPerformanceplantemplateMapper.updateById(plantemplate);
            //履约步骤先删除再插入
            iPerformancesteptemplateMapper.delete(new QueryWrapper<Performancesteptemplate>().eq("templateid", param.getAutoid()));
            for (Performancesteptemplate pst : param.getList()) {
                Performancesteptemplate steptemplate = new Performancesteptemplate();
                BeanUtils.copyProperties(pst, steptemplate);
                steptemplate.setTemplateid(plantemplate.getAutoid());
                if (steptemplate.getStepvalue() != null) {
                    steptemplate.setStepvalue(steptemplate.getStepvalue().divide(new BigDecimal(100)));
                }
                if (pst.getIsauto() == null) {
                    steptemplate.setIsauto(0);
                }
                iPerformancesteptemplateMapper.insert(steptemplate);
            }
        }

        return ajaxResult;
    }

    @Override
    public AjaxResult<Market> marketrunsectiion(HttpServletRequest request) {
        List<Integer> status = new ArrayList<>();
        status.add(1);
        status.add(2);
        //处理不同的账户类型查询
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        Long exchareaid = null;
        //如果不是平台管理员
        if (!SysConstants.SYS_TYPE_MANAGE.equals(systemmanager.getReletype())) {
            exchareaid = systemmanager.getAreauserid();
        }
        List<Market> markets = iMarketMapper.getMarketsByTradeMode(exchareaid, status);
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), markets);
    }

    @Override
    public PageResult<MarketRunSectiionResult> querymarketrunsectiion(Integer pageNum, Integer pageSize, Integer trademarkettype, HttpServletRequest request) {
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        Long exchareaid = null;
        //如果不是平台管理员
        if (!SysConstants.SYS_TYPE_MANAGE.equals(systemmanager.getReletype())) {
            exchareaid = systemmanager.getAreauserid();
        }
        PageResult<MarketRunSectiionResult> pageResult = new PageResult<>();
        IPage<MarketRunSectiionResult> page = new Page<>(pageNum, pageSize);
        IPage<MarketRunSectiionResult> resultIPage = iMarketMapper.querymarketrunsectiion(page, trademarkettype, exchareaid);
        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<Map<Integer, List<Marketrunstepdetail>>> queryMarketRunSectiionById(Long markerid, HttpServletRequest request) {
        List<Marketrunstepdetail> list = iMarketrunstepdetailMapper.selectList(new QueryWrapper<Marketrunstepdetail>()
                .eq("marketid", markerid));
        Map<Integer, List<Marketrunstepdetail>> group = new HashMap<>();
        for (Marketrunstepdetail item : list) {
            if (item != null && item.getTradeweekday() != null) {
                if (group.containsKey(item.getTradeweekday())) {
                    group.get(item.getTradeweekday()).add(item);
                } else {
                    List<Marketrunstepdetail> list_ = new ArrayList<>();
                    list_.add(item);
                    group.put(item.getTradeweekday(), list_);
                }
            }
        }
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), group);
    }

    @Override
    public AjaxResult marketRunSectiionCopy(HttpServletRequest request, Long source, Long target) {
        //查出源市场的所有运行计划
        List<Marketrunstepdetail> sourceList = iMarketrunstepdetailMapper.selectList(new QueryWrapper<Marketrunstepdetail>()
                .eq("marketid", source));
        if (CollectionUtils.isEmpty(sourceList)) {
            return AjaxResult.error(Constants.Error_Code_Design, MessageType.MESSAGE_ERROR_CODE_SYSTEM063.getCode(), request.getHeader("Accept-Language"));
        }
        //删除目标市场的所有计划
        iMarketrunstepdetailMapper.delete(new QueryWrapper<Marketrunstepdetail>().eq("marketid", target));
        //查询目标市场的交易模式，若为挂牌点选或者做市，则无集合竞价
        Market market = iMarketMapper.selectOne(new QueryWrapper<Market>().eq("MARKETID", target));
        //循环将源市场的运行计划插入到目标市场
        if (CollectionUtils.isNotEmpty(sourceList)) {
            for (Marketrunstepdetail mrsd : sourceList) {
                Marketrunstepdetail mrs = new Marketrunstepdetail();
                BeanUtils.copyProperties(mrsd, mrs);
                mrs.setMarketid(target);
                if (mrsd.getRunstep() == 1) {
                    if (market.getTrademode() != 10 && market.getTrademode() != 16) {
                        iMarketrunstepdetailMapper.insert(mrs);
                    }
                } else {
                    iMarketrunstepdetailMapper.insert(mrs);
                }
            }
        }
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"));
    }

    @Override
    public AjaxResult editSave(HttpServletRequest request, MarketRunSectiionParam param) {
        //排除空数据影响
        List<Marketrunstepdetail> newList = new ArrayList<>();
        for (int i = 0; i < param.getMarketRunSectiionDet().size(); i++) {
            Marketrunstepdetail mtd = iMarketrunstepdetailMapper.selectById(param.getMarketRunSectiionDet().get(i).getAutoid());
            if (mtd != null && mtd.getTradeweekday() != null) {
                newList.add(mtd);
            }
        }
        param.setMarketRunSectiionDet(newList);

        //删除旧数据
        iMarketrunstepdetailMapper.delete(new QueryWrapper<Marketrunstepdetail>().eq("marketid", param.getMarketid()));

        if (CollectionUtils.isNotEmpty(param.getMarketRunSectiionDet())) {
            //根据归属日分组
            int sectionid = 0; //时间段号
            String s = iCommonService.getSysparmById("980");
            Map<Integer, List<Marketrunstepdetail>> group = new HashMap<>();
            for (Marketrunstepdetail item : param.getMarketRunSectiionDet()) {
                if (item != null && item.getTradeweekday() != null) {
                    item.setMarketid(param.getMarketid());
                    //-1:上日 0:当日 1:次日

                    if (item.getTradeweekday().equals(item.getStartweekday())) {
                        item.setStartflag(0);
                    }
                    if (item.getTradeweekday().equals(item.getEndweekday())) {
                        item.setEndflag(0);
                    }

                    if ("1".equals(s) && item.getTradeweekday() == 1) {
                        //  5 6 0 1 2
                        //上
                        if (item.getStartweekday() == 5) {
                            item.setStartflag(-3);
                        }
                        if (item.getEndweekday() == 5) {
                            item.setEndflag(-3);
                        }

                        if (item.getStartweekday() == 6) {
                            item.setStartflag(-2);
                        }
                        if (item.getEndweekday() == 6) {
                            item.setEndflag(-2);
                        }

                        if (item.getStartweekday() == 0) {
                            item.setStartflag(-1);
                        }
                        if (item.getEndweekday() == 0) {
                            item.setEndflag(-1);
                        }

                        //次
                        if (item.getStartweekday() == 2) {
                            item.setStartflag(1);
                        }
                        if (item.getEndweekday() == 2) {
                            item.setEndflag(1);
                        }
                    } else {
                        if (item.getTradeweekday() == 6) {//5 6 0
                            //上
                            if (item.getStartweekday() == 5) {
                                item.setStartflag(-1);
                            }
                            if (item.getEndweekday() == 5) {
                                item.setEndflag(-1);
                            }

                            //次
                            if (item.getStartweekday() == 0) {
                                item.setStartflag(1);
                            }
                            if (item.getEndweekday() == 0) {
                                item.setEndflag(1);
                            }

                        } else if (item.getTradeweekday() == 0) {//  6 0 1
                            //上
                            if (item.getStartweekday() == 6) {
                                item.setStartflag(-1);
                            }
                            if (item.getEndweekday() == 6) {
                                item.setEndflag(-1);
                            }

                            //次
                            if (item.getStartweekday() == 1) {
                                item.setStartflag(1);
                            }
                            if (item.getEndweekday() == 1) {
                                item.setEndflag(1);
                            }
                        } else {
                            //上
                            if (item.getTradeweekday() > item.getStartweekday()) {
                                item.setStartflag(item.getStartweekday() - item.getTradeweekday());
                            }
                            if (item.getTradeweekday() > item.getEndweekday()) {
                                item.setEndflag(item.getEndweekday() - item.getTradeweekday());
                            }


                            //次
                            if (item.getTradeweekday() < item.getStartweekday()) {
                                item.setStartflag(item.getStartweekday() - item.getTradeweekday());
                            }
                            if (item.getTradeweekday() < item.getEndweekday()) {
                                item.setEndflag(item.getEndweekday() - item.getTradeweekday());
                            }
                        }
                    }

                    if (group.containsKey(item.getTradeweekday())) {
                        item.setSectionid(++sectionid);////每个交易日的时间段号 ，都从1开始，然后递增
                        group.get(item.getTradeweekday()).add(item);
                    } else {
                        List<Marketrunstepdetail> list = new ArrayList<Marketrunstepdetail>();
                        sectionid = 1; //每个交易日的时间段号 ，都从1开始
                        item.setSectionid(sectionid);
                        list.add(item);
                        group.put(item.getTradeweekday(), list);
                    }
                }
            }

            //保存数据，每组都增加 开市、休市记录
            for (Map.Entry<Integer, List<Marketrunstepdetail>> entry : group.entrySet()) {
                List<Marketrunstepdetail> list = entry.getValue();
                int j = list.size() - 1;
                for (int i = 0; i <= j; i++) {
                    Marketrunstepdetail det = list.get(i);


                    iMarketrunstepdetailMapper.insert(det);
                }
            }
        }
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"));
    }

    @Override
    public PageResult<MarketCalendarResult> queryMarketCalendar(Integer pageNum, Integer pageSize, HttpServletRequest request, String marketName, Integer trademarkettype) {
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        Long exchareaid = null;
        if (!SysConstants.SYS_TYPE_MANAGE.equals(systemmanager.getReletype())) {    //如果不是平台管理员
            exchareaid = systemmanager.getAreauserid();
        }
        PageResult<MarketCalendarResult> pageResult = new PageResult<>();
        IPage<MarketCalendarResult> page = new Page<>(pageNum, pageSize);
        IPage<MarketCalendarResult> resultIPage = iMarketMapper.queryMarketCalendar(page, trademarkettype, exchareaid, 99, marketName);
        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 updateSave(HttpServletRequest request, MarketCalendarDelParam param) {
        // 若市场日终处理完成，reckon_pricelog表的下一交易日已确定，若有修改且无交易日，取上一交易日的结算价时会出错
        Marketrun marketRun = iMarketrunMapper.selectOne(new QueryWrapper<Marketrun>().eq("MARKETID", param.getMarketid()));
        if (marketRun != null && (marketRun.getRunstatus().equals(10) || marketRun.getRunstatus().equals(11))) {
            return AjaxResult.error(Constants.Error_Code_Design, MessageType.MESSAGE_ERROR_CODE_SYSTEM064.getCode(), request.getHeader("Accept-Language"));
        }
        //1:先删除此市场此年度的节假日
        iMarketMapper.deleteMarketCanlendarByMap(param);
        String[] spilts = param.getHolidayDateList().split(",");
        //2:重新插入此市场的节假日
        if (spilts.length > 0) {
            for (String date : spilts) {
                Marketcalendar t = new Marketcalendar();
                t.setMarketid(param.getMarketid());
                t.setHolidaydate(date);
                iMarketcalendarMapper.insert(t);
            }
            //删除全年无休的数据
            iMarketcalendaryearMapper.delete(new QueryWrapper<Marketcalendaryear>()
                    .eq("marketid", param.getMarketid())
                    .eq("year", param.getYear()));
        }
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"));
    }

    @Override
    public AjaxResult<MarketCalendarDetailResult> queryMarketCalendarDetail(Long markerid, String year, HttpServletRequest request) {
        MarketCalendarDetailResult result = new MarketCalendarDetailResult();
        List<Market> markets = iMarketMapper.selectList(new QueryWrapper<Market>().eq("editMarketId", markerid));
        result.setMarkets(markets);

        //先查是否全年无休
        List<Marketcalendaryear> mcyList = iMarketcalendaryearMapper.selectList(new QueryWrapper<Marketcalendaryear>()
                .eq("marketid", markerid)
                .eq("year", year)
                .eq("isallyear", 1));
        result.setMcyList(mcyList);

        List<Marketcalendar> marketCalendars = iMarketMapper.queryMarketCalendarById(markerid, year);
        result.setMarketCalendars(marketCalendars);
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"));
    }

    @Override
    public AjaxResult marketCalendarAdd(HttpServletRequest request, MarketCalendarAddParam param) {
        String[] marketids = param.getMarketIds().split(",");
        for (String marketid : marketids) {
            // 若市场日终处理完成，reckon_pricelog表的下一交易日已确定，若有修改且无交易日，取上一交易日的结算价时会出错
            Marketrun marketRun = iMarketrunMapper.selectOne(new QueryWrapper<Marketrun>().eq("MARKETID", marketid));
            if (marketRun != null && (marketRun.getRunstatus().equals(10) || marketRun.getRunstatus().equals(11))) {
                return AjaxResult.error(Constants.Error_Code_Design, MessageType.MESSAGE_ERROR_CODE_SYSTEM064.getCode(), request.getHeader("Accept-Language"));
            }
        }

        if (marketids.length > 0) {
            //先直接删除掉
            for (String marketid : marketids) {
                iMarketcalendarMapper.delete(new QueryWrapper<Marketcalendar>()
                        .eq("marketId", marketid)
                        .eq("holidaydate", param.getHolidaydate()));
            }
            //如果是节假日 ，再插入插入此节假日；
            if (param.getDayType() == 1) {
                for (String marketid : marketids) {
                    Marketcalendar mc = new Marketcalendar();
                    mc.setMarketid(Long.valueOf(marketid));
                    mc.setHolidaydate(param.getHolidaydate());
                    iMarketcalendarMapper.insert(mc);
                    //删除全年无休的数据
                    iMarketcalendaryearMapper.delete(new QueryWrapper<Marketcalendaryear>()
                            .eq("marketid", marketid)
                            .eq("year", param.getHolidaydate().substring(0, 4)));
                }
            }
        }
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"));
    }

    @Override
    public PageResult<MarketManageResult> querymarketmanage(MarketManageParam param, HttpServletRequest request) {
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        if (!SysConstants.SYS_TYPE_MANAGE.equals(systemmanager.getReletype())) {    //如果不是平台管理员
            param.setExchareaid(systemmanager.getAreauserid());
        }
        param.setTrademarkettype(3);
        PageResult<MarketManageResult> pageResult = new PageResult<>();
        IPage<MarketManageResult> page = new Page<>(param.getPageNum(), param.getPageSize());
        IPage<MarketManageResult> resultIPage = iMarketMapper.querymarketmanage(page, param);
        pageResult.setCode(Constants.Success_Code_Design);
        pageResult.setMessage(AjaxResult.dealMsg(MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language")));
        pageResult.setPages(resultIPage.getPages());
        pageResult.setCurrent(resultIPage.getCurrent());
        pageResult.setTotal(resultIPage.getTotal());
        pageResult.setPageSize(resultIPage.getSize());
        pageResult.setData(resultIPage.getRecords());
        return pageResult;
    }

    @Override
    public AjaxResult<MarketManageDetailResult> marketmanagedetail(Long marketid, HttpServletRequest request) {
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));

        MarketManageDetailResult result = new MarketManageDetailResult();
        MarketDto market = getMarketByID(marketid);
        result.setMarketDto(market);
        Map<String, Object> map = redisServiceUtil.getCacheMap(Constants.REDIS_HEADER_DICT + "trademode");
        result.setTrademodeMap(map);

        String sp = iCommonService.getSysparmById(SysConstants.SYSPAMA_CODE_SHOUXIN);
        if (sp != null)
            result.setIsShouXin(sp);
        else
            result.setIsShouXin("0");

        if (market.getTrademode() == 20) {
            String isrebateratio = iCommonService.getSysparmById("090");
            if ("1".equals(isrebateratio)) {
                result.setRebateratio("1");
            }
        } else if (market.getTrademode() == 17 || market.getTrademode() == 67) {
            String contracttmp = iCommonService.getSysparmById("953");
            if ("1".equals(contracttmp)) {
                result.setContracttmp("1");
            }

            //加载仓单标准
            Wrstandard wrStandard = new Wrstandard();
            wrStandard.setIsvalid(1);
            wrStandard.setAreauserid(null);
            DeliveryOrderWrsParam param = new DeliveryOrderWrsParam();
            param.setIsvalid(1);
            List<DeliveryOrderWrsResult> deliveryOrderWrsResults = iWrstandardMapper.queryWRStandard(param);
            result.setWrstandardList(deliveryOrderWrsResults);

            //加载履约模板
            List<Performanceplantemplate> performancePlanTemplateList = iPerformanceplantemplateMapper.selectList(new QueryWrapper<Performanceplantemplate>()
                    .eq("type", 2)
                    .notIn("autoid", -1L)
                    .eq("userid", systemmanager.getAreauserid()));
            performancePlanTemplateList.add(iPerformanceplantemplateMapper.selectOne(new QueryWrapper<Performanceplantemplate>().eq("autoid", -1L)));
            result.setPerformancePlanTemplateList(performancePlanTemplateList);

            //查询仓单贸易类型枚举
            Enumdicitem enumDicItem = iEnumdicitemMapper.selectOne(new QueryWrapper<Enumdicitem>()
                    .eq("enumdiccode", "WRTradeType")
                    .eq("enumitemname", 2L));
            String wRTradeType2 = "0";
            if (enumDicItem != null) {
                wRTradeType2 = "1";
            }
            result.setWRTradeType2(wRTradeType2);
            sp = iCommonService.getSysparmById(SysConstants.SYSPAMA_CODE_PLATEFORM);
            result.setPerformancetempid2(sp == null ? "-1" : (StringUtils.isBlank(sp) ? "-1" : sp));
            String p = null;
            try {
                p = iCommonService.getSystemParam(Constants.REDIS_HEADER_SYSPARAM, SysConstants.SYSPAMA_CODE_PLATEFORM_TYPE);
            } catch (Exception e) {
                p = "0";
            }
            result.setPlateformType(StringUtils.isBlank(p) ? "0" : p);
            //查询履约计划
            List<Integer> list = new ArrayList<>();
            list.add(0);
            list.add(SysEnums.TEMPLATETYPE.get(market.getTrademode() + ""));
            List<Performanceplantemplate> performanceplantemplates = iPerformanceplantemplateMapper.selectList(new QueryWrapper<Performanceplantemplate>()
                    .eq("userid", systemmanager.getAreauserid())
                    .in("type", list));

            result.setPerformanceplantemplate(performanceplantemplates);
        } else if (market.getTrademode() == 78 || market.getTrademode() == 79) {
            MarketDto marketDto = iMarketMapper.queryMarketExtension(marketid);
            if (null != marketDto) {
                result.setMarketDto(marketDto);
            }
        }
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), result);
    }

    @Override
    public AjaxResult deletemarketmanage(Long marketid, HttpServletRequest request) {
        // 1:判断市场下面是否有运行的商品(商品状态不为已退市和已注销)
        Long num = iGoodsMapper.selectCount(new QueryWrapper<Goods>()
                .eq("MARKETID", marketid)
                .in("goodsstatus", 4, 6));
        if (num > 0) {
            return AjaxResult.error(Constants.Error_Code_Design, MessageType.MESSAGE_ERROR_CODE_SYSTEM065.getCode(), request.getHeader("Accept-Language"));
        }
        // 2:注销 市场
        Market market = iMarketMapper.selectOne(new QueryWrapper<Market>().eq("marketid", marketid));
        if (SysEnums.TradeMode.CDMY.getCode().equals(market.getTrademode())) { //仓单贸易市场
            Long onum = iWrtradeOrderdetailMapper.selectCount(new QueryWrapper<WrtradeOrderdetail>().eq("marketid", market.getMarketid()));
            if (onum != null && onum > 0) {
                return AjaxResult.error(Constants.Error_Code_Design, MessageType.MESSAGE_ERROR_CODE_SYSTEM066.getCode(), request.getHeader("Accept-Language"));
            }
        }

        market.setMarketstatus(SysEnums.EnumMarketStatus.DELETE.getType());
        iMarketMapper.update(market, new QueryWrapper<Market>().eq("marketid", marketid));
        // 3:注销市场后，该市场下的商品组也注销
        List<Goodsgroup> ggList = iGoodsgroupMapper.selectList(new QueryWrapper<Goodsgroup>()
                .eq("marketid", marketid)
                .eq("goodsgroupstatus", SysEnums.CommonStatus.WORK.getCode()));
        for (Goodsgroup gg : ggList) {
            gg.setGoodsgroupstatus(SysEnums.CommonStatus.DEL.getCode());
            iGoodsgroupMapper.updateById(gg);
        }

        // 修改系统参数表的市场更新时间
        modifyMarketUpdateTimeToSysParam();
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"));
    }

    @Override
    public AjaxResult<AreaRoleInitResult> areaRoleInit(Long marketid, HttpServletRequest request) {
        AreaRoleInitResult result = new AreaRoleInitResult();

        List<AreaRoleMarketInitResult> marketInitResults = iArearoleMapper.queryMarketArea(marketid);
        result.setMarketInitResultList(marketInitResults);

        List<Arearole> areaRoleResults = iArearoleMapper.selectList(new QueryWrapper<Arearole>()
                .in("roletype", 6, 7));
        result.setAreaRoleResults(areaRoleResults);
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), result);
    }

    @Override
    public AjaxResult saveMemberRight(HttpServletRequest request, AreaRoleInitResult param) {
        Systemmanager user = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));

        // 1:删除此市场下的角色权限关系
        iArearolemarketMapper.delete(new QueryWrapper<Arearolemarket>().eq("marketid", param.getMarketid()));

        // 1.1:删除此市场下的资金账户权限关系taaccountmarket表
        // 多资金账户时其它账户的权限也会被删除，目前交易中心版本无多资金账户问题 -- 20231124 dyp
        iTaaccountmarketMapper.delete(new QueryWrapper<Taaccountmarket>().eq("marketid", param.getMarketid()));

        // 2:插入市场会员权限数据
        if (CollectionUtils.isNotEmpty(param.getMarketInitResultList())) {
            for (AreaRoleMarketInitResult result : param.getMarketInitResultList()) {
                Arearolemarket arearolemarket = new Arearolemarket();
                arearolemarket.setMarketid(param.getMarketid());
                arearolemarket.setModifierid(user.getAutoid());
                arearolemarket.setModifytime(new Date());
                // 默认可摘可挂
                arearolemarket.setSpotrighttype(1);
                arearolemarket.setBuyspotrighttype(1);
                iArearolemarketMapper.insert(arearolemarket);

                if (result.getRoletype().equals(6)) {
                    // 自营会员更新“TAACCOUNTMARKET”表  -- 20231124 dyp
                    Taaccount ta = iTaaccountMapper.selectOne(new QueryWrapper<Taaccount>()
                            .eq("userid", result.getAreauserid())
                            .eq("ismain", 1));
                    if (ta != null) {
                        Taaccountmarket tm = new Taaccountmarket();
                        tm.setAccountid(ta.getAccountid());
                        tm.setMarketid(arearolemarket.getMarketid());
                        tm.setModifytime(new Date());
                        tm.setModifierid(user.getAutoid());
                        // 默认可摘可挂
                        tm.setSpotrighttype(1);
                        tm.setBuyspotrighttype(1);
                        iTaaccountmarketMapper.insert(tm);
                    }
                }
            }
        }
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"));
    }

    @Override
    public PageResult<Riskratiotype> queryRiskRatio(Integer pageNum, Integer pageSize, HttpServletRequest request) {
        PageResult<Riskratiotype> pageResult = new PageResult<>();
        IPage<Riskratiotype> page = new Page<>(pageNum, pageSize);
        IPage<Riskratiotype> resultIPage = iRiskratiotypeMapper.selectPage(page, new QueryWrapper<>());
        for (Riskratiotype record : resultIPage.getRecords()) {
            record.setNotemarginriskratio(record.getNotemarginriskratio().multiply(new BigDecimal(100)));
            record.setAddmarginriskratio(record.getAddmarginriskratio().multiply(new BigDecimal(100)));
            record.setRecovertraderiskratio(record.getRecovertraderiskratio().multiply(new BigDecimal(100)));
            record.setCutbackriskratio(record.getCutbackriskratio().multiply(new BigDecimal(100)));
            record.setCutriskratio(record.getCutriskratio().multiply(new BigDecimal(100)));
            record.setNotesaferatio(record.getNotesaferatio().multiply(new BigDecimal(100)));
            record.setAddsaferatio(record.getAddsaferatio().multiply(new BigDecimal(100)));
            record.setCutsaferatio(record.getCutsaferatio().multiply(new BigDecimal(100)));
            record.setRecoversaferatio(record.getRecoversaferatio().multiply(new BigDecimal(100)));
        }
        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<RiskRatioDetailResult> riskRatiodetail(Integer customertype, Integer riskcontrolmode, HttpServletRequest request) {
        RiskRatioDetailResult result = new RiskRatioDetailResult();
        Riskratiotype riskRatioTypeDetail = queryRiskRatioTypeById(customertype, riskcontrolmode);
        result.setRiskratiotype(riskRatioTypeDetail);
        //查询市场循序
        if (StringUtils.isNotBlank(riskRatioTypeDetail.getCutmarginseq())) {
            String[] mids = riskRatioTypeDetail.getCutmarginseq().split(",");
            List<Long> mid = new ArrayList<>();
            for (String s : mids) {
                mid.add(Long.valueOf(s));
            }
            List<Market> markets = iMarketMapper.selectList(new QueryWrapper<Market>()
                    .in("marketId", mid)
                    .eq("marketStatus", 2));
            //排序
            Map<Integer, Market> tree = new TreeMap<>();
            markets.forEach(p -> {
                tree.put(riskRatioTypeDetail.getCutmarginseq().indexOf(p.getMarketid().toString()), p);
            });
            result.setMarkets(tree);
        }

        Object o = redisServiceUtil.getCacheMapValue(Constants.REDIS_HEADER_SYSPARAM,
                SysConstants.SYSPAMA_CODE_RISK_ISRISK);
        if (o == null || StringUtils.isBlank(o.toString())) {
            result.setRisk128(1);
        } else {
            Object o1 = redisServiceUtil.getCacheMapValue(Constants.REDIS_HEADER_SYSPARAM,
                    SysConstants.SYSPAMA_CODE_RISK_ISSAFERATIO);
            result.setRisk128((Integer) o);
            result.setRisk128((Integer) o1);
        }

        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), result);
    }

    @Override
    public AjaxResult riskRatioUpdate(HttpServletRequest request, Riskratiotype riskRT) {
        Systemmanager user = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));

        if (riskRT.getIsdefault() != null && riskRT.getIsdefault() == 1) {
            // 判断是否存在默认
            Riskratiotype r = iRiskratiotypeMapper.selectOne(new QueryWrapper<Riskratiotype>()
                    .eq("riskcontrolmode", riskRT.getRiskcontrolmode())
                    .eq("isdefault", 1));
            if (r != null) {
                // 存在默认的 ，替换
                r.setIsdefault(0);
                r.setModifytime(new Date());
                r.setModifierid(user.getAutoid());
                iRiskratiotypeMapper.update(r, new QueryWrapper<Riskratiotype>()
                        .eq("riskcontrolmode", riskRT.getRiskcontrolmode())
                        .eq("isdefault", 1));
            }
        }

        BigDecimal cNum = new BigDecimal(100);
        riskRT.setRiskrationame("1");
        if (riskRT.getRecovertraderiskratio() != null) {
            riskRT.setRecovertraderiskratio(riskRT.getRecovertraderiskratio().divide(cNum));
        }
        if (riskRT.getRecoversaferatio() != null) {
            riskRT.setRecoversaferatio(riskRT.getRecoversaferatio().divide(cNum));
        }
        if (riskRT.getNotemarginriskratio() != null) {
            riskRT.setNotemarginriskratio(riskRT.getNotemarginriskratio().divide(cNum));
        }
        if (riskRT.getAddmarginriskratio() != null) {
            riskRT.setAddmarginriskratio(riskRT.getAddmarginriskratio().divide(cNum));
        }
        if (riskRT.getCutriskratio() != null) {
            riskRT.setCutriskratio(riskRT.getCutriskratio().divide(cNum));
        }
        if (riskRT.getCutbackriskratio() != null) {
            riskRT.setCutbackriskratio(riskRT.getCutbackriskratio().divide(cNum));
        }

        //安全度
        if (riskRT.getNotesaferatio() != null) {
            riskRT.setNotesaferatio(riskRT.getNotesaferatio().divide(cNum));
        }
        if (riskRT.getAddsaferatio() != null) {
            riskRT.setAddsaferatio(riskRT.getAddsaferatio().divide(cNum));
        }

        if (riskRT.getCutsaferatio() != null) {
            riskRT.setCutsaferatio(riskRT.getCutsaferatio().divide(cNum));
        }

        riskRT.setModifierid(user.getAutoid());
        riskRT.setModifytime(new Date());
        // 启用净值斩仓标志
        if (riskRT.getCutthreshold() != null) {
            riskRT.setCutthresholdflag(1);
        } else {
            riskRT.setCutthresholdflag(0);
        }

        iRiskratiotypeMapper.update(riskRT, new QueryWrapper<Riskratiotype>()
                .eq("riskcontrolmode", riskRT.getRiskcontrolmode())
                .eq("CUSTOMERTYPE", riskRT.getCustomertype()));
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"));
    }

    @Override
    public AjaxResult<RiskRatioAddInitResult> riskRatioAddInit(HttpServletRequest request) {
        RiskRatioAddInitResult result = new RiskRatioAddInitResult();
        // 判断风控模式是否已有默认设置 flag=1投资者模式1已经有默认，flag=2
        // 做市商模式2已经有默认，flag=3都有默认，flag=0都无默认
        result.setFlag(queryRiskRatioByDefault());

        Object o = redisServiceUtil.getCacheMapValue(Constants.REDIS_HEADER_SYSPARAM,
                SysConstants.SYSPAMA_CODE_RISK_ISRISK);
        if (o == null || StringUtils.isBlank(o.toString())) {
            result.setRisk128(1);
        } else {
            Object o1 = redisServiceUtil.getCacheMapValue(Constants.REDIS_HEADER_SYSPARAM,
                    SysConstants.SYSPAMA_CODE_RISK_ISSAFERATIO);
            result.setRisk128((Integer) o);
            result.setRisk128((Integer) o1);
        }

        // 系统是否有“做市会员” 枚举 roleType 里含 8
        Map<String, Object> roleMap = redisServiceUtil.getCacheMap(Constants.REDIS_HEADER_DICT + "roleType");
        if (roleMap.keySet().contains("8")) {
            result.setHasotc(1);
        } else {
            result.setHasotc(0);
        }

        // 只用于“风险率类型设置” 查询备选市场
        // 过滤10模式收益权 风控方式为 1：按单风控的市场 -- 20240903 dyp
        List<Market> marketList = iMarketMapper.selectList(new QueryWrapper<Market>()
                .eq("marketStatus", SysEnums.EnumMarketStatus.NORMAL.getType())
                .eq("markettype", 2)
                .eq("tradeProperty", SysEnums.TradeProperty.GAIN.getCode()));

        List<Market> markets = new ArrayList<>();
        if (marketList != null) {
            for (Market m : marketList) {
                if (m != null) {
                    // 过滤10模式收益权 风控方式为 1：按单风控的市场 -- 20240903 dyp
                    if (!(m.getTrademode().equals(10) && m.getTradeproperty().equals(1)
                            && m.getRiskcontrolmode() != null && m.getRiskcontrolmode().equals(1))) {
                        markets.add(m);
                    }
                }
            }
        }
        result.setMarkets(markets);
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), result);
    }

    @Override
    public AjaxResult riskRatioAdd(HttpServletRequest request, Riskratiotype riskRT) {
        Systemmanager user = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));

        Riskratiotype riskratiotype = iRiskratiotypeMapper.selectOne(new QueryWrapper<Riskratiotype>()
                .eq("customertype", riskRT.getCustomertype())
                .eq("riskcontrolmode", riskRT.getRiskcontrolmode()));
        if (riskratiotype != null) {
            return AjaxResult.error(Constants.Error_Code_Design, MessageType.MESSAGE_ERROR_CODE_SYSTEM067.getCode(), request.getHeader("Accept-Language"));
        }
        Date time = new Date();
        if (riskRT.getIsdefault() != null && riskRT.getIsdefault() == 1) {
            // 判断是否存在默认
            Riskratiotype r = iRiskratiotypeMapper.selectOne(new QueryWrapper<Riskratiotype>()
                    .eq("riskcontrolmode", riskRT.getRiskcontrolmode())
                    .eq("isdefault", 1));
            if (r != null) {
                // 存在默认的 ，替换
                r.setIsdefault(0);
                r.setModifytime(time);
                r.setModifierid(user.getAutoid());
                iRiskratiotypeMapper.update(r, new QueryWrapper<Riskratiotype>()
                        .eq("riskcontrolmode", riskRT.getRiskcontrolmode())
                        .eq("isdefault", 1));
            }
        } else {
            riskRT.setIsdefault(0);
        }

        BigDecimal cNum = new BigDecimal(100);
        riskRT.setRiskrationame("1");
        if (riskRT.getRecovertraderiskratio() != null) {
            riskRT.setRecovertraderiskratio(riskRT.getRecovertraderiskratio().divide(cNum));
        }
        if (riskRT.getRecoversaferatio() != null) {
            riskRT.setRecoversaferatio(riskRT.getRecoversaferatio().divide(cNum));
        }

        if (riskRT.getNotemarginriskratio() != null) {
            riskRT.setNotemarginriskratio(riskRT.getNotemarginriskratio().divide(cNum));
        }
        if (riskRT.getAddmarginriskratio() != null) {
            riskRT.setAddmarginriskratio(riskRT.getAddmarginriskratio().divide(cNum));
        }
        if (riskRT.getCutriskratio() != null) {
            riskRT.setCutriskratio(riskRT.getCutriskratio().divide(cNum));
        }
        if (riskRT.getCutbackriskratio() != null) {
            riskRT.setCutbackriskratio(riskRT.getCutbackriskratio().divide(cNum));
        }

        //安全度
        if (riskRT.getNotesaferatio() != null) {
            riskRT.setNotesaferatio(riskRT.getNotesaferatio().divide(cNum));
        }
        if (riskRT.getAddsaferatio() != null) {
            riskRT.setAddsaferatio(riskRT.getAddsaferatio().divide(cNum));
        }

        if (riskRT.getCutsaferatio() != null) {
            riskRT.setCutsaferatio(riskRT.getCutsaferatio().divide(cNum));
        }

        riskRT.setCreatorid(user.getAutoid());
        riskRT.setCreatetime(time);
        riskRT.setModifierid(user.getAutoid());
        riskRT.setModifytime(time);
        // 启用净值斩仓标志
        if (riskRT.getCutthreshold() != null) {
            riskRT.setCutthresholdflag(1);
        } else {
            riskRT.setCutthresholdflag(0);
        }
        iRiskratiotypeMapper.insert(riskRT);
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"));
    }

    private Integer queryRiskRatioByDefault() {
        Riskratiotype rrt1 = iRiskratiotypeMapper.selectOne(new QueryWrapper<Riskratiotype>()
                .eq("isdefault", 1)
                .eq("riskcontrolmode", 1));

        Riskratiotype rrt2 = iRiskratiotypeMapper.selectOne(new QueryWrapper<Riskratiotype>()
                .eq("isdefault", 1)
                .eq("riskcontrolmode", 2));
        // 0表示都没默认
        int flag = 0;
        // 投资者模式1 已经有默认
        if (rrt1 != null && rrt2 == null)
            flag = 1;
        // 做市商模式2 已经有默认
        if (rrt2 != null && rrt1 == null)
            flag = 2;
        // 都有默认
        if (rrt2 != null && rrt1 != null)
            flag = 3;
        return flag;
    }

    private Riskratiotype queryRiskRatioTypeById(Integer customertype, Integer riskcontrolmode) {
        Riskratiotype riskRatioType = iRiskratiotypeMapper.selectOne(new QueryWrapper<Riskratiotype>()
                .eq("customertype", customertype)
                .eq("riskcontrolmode", riskcontrolmode));
        if (riskRatioType == null) {
            return null;
        }

        BigDecimal cNum = new BigDecimal(100);
        if (riskRatioType.getRecovertraderiskratio() != null) {
            riskRatioType.setRecovertraderiskratio(riskRatioType.getRecovertraderiskratio()
                    .multiply(cNum).setScale(2, RoundingMode.HALF_UP));
        }
        if (riskRatioType.getNotemarginriskratio() != null) {
            riskRatioType.setNotemarginriskratio(riskRatioType.getNotemarginriskratio()
                    .multiply(cNum).setScale(2, RoundingMode.HALF_UP));
        }
        if (riskRatioType.getAddmarginriskratio() != null) {
            riskRatioType.setAddmarginriskratio(riskRatioType.getAddmarginriskratio()
                    .multiply(cNum).setScale(2, RoundingMode.HALF_UP));
        }
        if (riskRatioType.getCutriskratio() != null) {
            riskRatioType.setCutriskratio(riskRatioType.getCutriskratio().multiply(cNum)
                    .setScale(2, RoundingMode.HALF_UP));
        }
        if (riskRatioType.getCutbackriskratio() != null) {
            riskRatioType.setCutbackriskratio(riskRatioType.getCutbackriskratio()
                    .multiply(cNum).setScale(2, RoundingMode.HALF_UP));
        }

        //安全度
        if (riskRatioType.getNotesaferatio() != null) {
            riskRatioType.setNotesaferatio(riskRatioType.getNotesaferatio().multiply(cNum)
                    .setScale(2, RoundingMode.HALF_UP));
        }
        if (riskRatioType.getAddsaferatio() != null) {
            riskRatioType.setAddsaferatio(riskRatioType.getAddsaferatio().multiply(cNum)
                    .setScale(2, RoundingMode.HALF_UP));
        }
        if (riskRatioType.getRecoversaferatio() != null) {
            riskRatioType.setRecoversaferatio(riskRatioType.getRecoversaferatio()
                    .multiply(cNum).setScale(2, RoundingMode.HALF_UP));
        }
        if (riskRatioType.getCutsaferatio() != null) {
            riskRatioType.setCutsaferatio(riskRatioType.getCutsaferatio()
                    .multiply(cNum).setScale(2, RoundingMode.HALF_UP));
        }

        return riskRatioType;
    }

    private MarketDto getMarketByID(Long marketid) {
        Market market = iMarketMapper.selectOne(new QueryWrapper<Market>().eq("marketId", marketid));
        MarketDto marketDto = new MarketDto();
        BeanUtils.copyProperties(market, marketDto);
        Long orgid = market.getExchareaid();
        if (orgid != null) {
            Useraccount org = iUseraccountMapper.selectOne(new QueryWrapper<Useraccount>().eq("userid", orgid));
            if (org != null) {
                marketDto.setExchAreaName(org.getAccountname());
            }
        }
        if (market.getOtcuserid() != null) {
            Useraccount org = iUseraccountMapper.selectOne(new QueryWrapper<Useraccount>().eq("userid", market.getOtcuserid()));
            if (org != null) {
                marketDto.setOtcareaname(org.getAccountname());
            }
        }
        //仓单贸易市场 扩展的参数 (17仓单贸易  34竞拍-荷兰式 23预售采集)   (20竞拍-竞价式  21竞拍-大宗式 )类似
        if (17 == market.getTrademode()
                || 20 == market.getTrademode()
                || 21 == market.getTrademode()
                || 23 == market.getTrademode()
                || 34 == market.getTrademode()
                || 67 == market.getTrademode()
        ) {
            Markettradeconfig mtc = iMarkettradeconfigMapper.selectOne(new QueryWrapper<Markettradeconfig>().eq("marketid", market.getMarketid()));
            if (mtc != null) {
                BeanUtils.copyProperties(mtc, marketDto);
                if (marketDto.getBuyMarginAlgorithm() != null && marketDto.getBuyMarginAlgorithm() == 1) {    //比率
                    marketDto.setBuyMarginValue(marketDto.getBuyMarginValue().multiply(new BigDecimal(100)).setScale(2));
                }
                if (marketDto.getSellMarginAlgorithm() != null && marketDto.getSellMarginAlgorithm() == 1) {
                    if (marketDto.getSellMarginValue() != null) {
                        marketDto.setSellMarginValue(marketDto.getSellMarginValue().multiply(new BigDecimal(100)).setScale(2));
                    }
                    if (marketDto.getSellmarginvalue2() != null) {
                        marketDto.setSellmarginvalue2(marketDto.getSellmarginvalue2().multiply(new BigDecimal(100)).setScale(2));
                    }
                }
                if (marketDto.getBuyChargeAlgorithm() != null && marketDto.getBuyChargeAlgorithm() == 1) {
                    marketDto.setBuyChargeAlgorithmValue(marketDto.getBuyChargeAlgorithmValue().multiply(new BigDecimal(10000)).setScale(2));
                    if (marketDto.getBuyChargeAlgorithmValue2() != null) {
                        marketDto.setBuyChargeAlgorithmValue2(marketDto.getBuyChargeAlgorithmValue2().multiply(new BigDecimal(10000)).setScale(2));
                    }
                }
                if (marketDto.getSellChargeAlgorithm() != null && marketDto.getSellChargeAlgorithm() == 1) {
                    marketDto.setSellChargeAlgorithmValue(marketDto.getSellChargeAlgorithmValue().multiply(new BigDecimal(10000)).setScale(2));
                    if (marketDto.getSellChargeAlgorithmValue2() != null) {
                        marketDto.setSellChargeAlgorithmValue2(marketDto.getSellChargeAlgorithmValue2().multiply(new BigDecimal(10000)).setScale(2));
                    }
                }

                if (marketDto.getBuyreleaseratio() != null && marketDto.getBuyreleaseratio() != null) {    //买方释放比率
                    marketDto.setBuyreleaseratio(marketDto.getBuyreleaseratio().multiply(new BigDecimal(100)).setScale(2));
                }
                if (marketDto.getSellreleaseratio() != null) { //卖方释放比率
                    marketDto.setSellreleaseratio(marketDto.getSellreleaseratio().multiply(new BigDecimal(100)).setScale(2));
                }
                if (marketDto.getBasisupratio() != null) {
                    marketDto.setBasisupratio(marketDto.getBasisupratio().multiply(new BigDecimal(100)).setScale(2));
                }
                if (marketDto.getBasisdownratio() != null) {
                    marketDto.setBasisdownratio(marketDto.getBasisdownratio().multiply(new BigDecimal(100)).setScale(2));
                }
                //获取履约计划模板名称
                Long performancetempid = mtc.getPerformancetempid();
                if (performancetempid != null) {
                    Performanceplantemplate vo = iPerformanceplantemplateMapper.selectOne(new QueryWrapper<Performanceplantemplate>()
                            .eq("autoid", performancetempid));
                    if (performancetempid != -1) {
                        marketDto.setTemplatename(vo.getTemplatename());
                    } else {
                        marketDto.setTemplatename("立即执行");
                    }
                }
                Long performancetempid2 = mtc.getPerformancetempid2();
                if (performancetempid2 != null) {
                    Performanceplantemplate vo = iPerformanceplantemplateMapper.selectOne(new QueryWrapper<Performanceplantemplate>()
                            .eq("autoid", performancetempid2));
                    if (performancetempid2 != -1) {
                        marketDto.setTemplatename2(vo.getTemplatename());
                    } else {
                        marketDto.setTemplatename2("立即执行");
                    }
                }
                List<String> performancetempidList = new ArrayList<String>();
                if (StringUtils.isNotBlank(mtc.getPerformancetempids())) {
                    for (String p : mtc.getPerformancetempids().split(",")) {
                        if (StringUtils.isNotBlank(p)) {
                            performancetempidList.add(p);
                        }
                    }
                }
                if (StringUtils.isNotBlank(mtc.getPerformancetempid2s())) {
                    for (String p : mtc.getPerformancetempid2s().split(",")) {
                        if (StringUtils.isNotBlank(p)) {
                            performancetempidList.add(p);
                        }
                    }
                }
                marketDto.setPerformancetempidList(performancetempidList);
            }
        }

        //查询市场币交易参数表
        if (36 == market.getTrademode()) {
            Marketcoinconfig marketCoinConfig = iMarketcoinconfigMapper.selectOne(new QueryWrapper<Marketcoinconfig>()
                    .eq("marketid", marketid));
            BeanUtils.copyProperties(marketCoinConfig, marketDto);
            Integer payovertime = marketCoinConfig.getPayovertime();
            marketDto.setPayovertime1((int) (double) (payovertime / 60));
            marketDto.setPayovertime2(payovertime % 60);


            Integer confirmovertime = marketCoinConfig.getConfirmovertime();
            marketDto.setConfirmovertime1((int) (double) (confirmovertime / 60));
            marketDto.setConfirmovertime2(confirmovertime % 60);
        }

        if (77 == market.getTrademode() || 78 == market.getTrademode() || 79 == market.getTrademode()) {
            Markettradeconfig marketTradeConfig = iMarkettradeconfigMapper.selectOne(new QueryWrapper<Markettradeconfig>().eq("marketid", market.getMarketid()));
            if (marketTradeConfig != null) {
                BeanUtils.copyProperties(marketTradeConfig, marketDto);
                if (marketDto.getBuyChargeAlgorithm() == 1) {
                    marketDto.setBuyChargeAlgorithmValue(marketDto.getBuyChargeAlgorithmValue().multiply(new BigDecimal(10000)).setScale(2));
                    marketDto.setBuyChargeAlgorithmValue2(marketDto.getBuyChargeAlgorithmValue2().multiply(new BigDecimal(10000)).setScale(2));
                }
                if (marketDto.getSellChargeAlgorithm() == 1) {
                    marketDto.setSellChargeAlgorithmValue(marketDto.getSellChargeAlgorithmValue().multiply(new BigDecimal(10000)).setScale(2));
                    marketDto.setSellChargeAlgorithmValue2(marketDto.getSellChargeAlgorithmValue2().multiply(new BigDecimal(10000)).setScale(2));
                }
                if (77 == market.getTrademode()) {
                    if (marketDto.getBuyChargeAlgorithm2() != null && marketDto.getBuyChargeAlgorithm2() == 1) {
                        marketDto.setBuyChargeAlgorithmValue3(marketDto.getBuyChargeAlgorithmValue3().multiply(new BigDecimal(10000)).setScale(2));
                        marketDto.setBuyChargeAlgorithmValue4(marketDto.getBuyChargeAlgorithmValue4().multiply(new BigDecimal(10000)).setScale(2));
                    }
                    if (marketDto.getSellChargeAlgorithm2() != null && marketDto.getSellChargeAlgorithm2() == 1) {
                        marketDto.setSellChargeAlgorithmValue3(marketDto.getSellChargeAlgorithmValue3().multiply(new BigDecimal(10000)).setScale(2));
                        marketDto.setSellChargeAlgorithmValue4(marketDto.getSellChargeAlgorithmValue4().multiply(new BigDecimal(10000)).setScale(2));
                    }
                }

            }
        }

        if (17 == market.getTrademode() || 67 == market.getTrademode()) {
            List<Marketspotgoodsconfig> marketSpotGoodsConfigList = iMarketspotgoodsconfigMapper.selectList(new QueryWrapper<Marketspotgoodsconfig>()
                    .eq("marketid", marketid));
            marketDto.setMarketSpotGoodsConfigList(marketSpotGoodsConfigList);
        }

        if (47 == market.getTrademode()
                || 62 == market.getTrademode()
                || 63 == market.getTrademode()
        ) {
            Markettradeconfig marketTradeConfig = iMarkettradeconfigMapper.selectOne(new QueryWrapper<Markettradeconfig>().eq("marketid", market.getMarketid()));
            if (marketTradeConfig != null) {
                BeanUtils.copyProperties(marketTradeConfig, marketDto);
                if (marketDto.getBuyChargeAlgorithm() != null && marketDto.getBuyChargeAlgorithm() == 1) {
                    marketDto.setBuyChargeAlgorithmValue(marketDto.getBuyChargeAlgorithmValue().multiply(new BigDecimal(10000)).setScale(2));
                }
                if (marketDto.getSellChargeAlgorithm() != null && marketDto.getSellChargeAlgorithm() == 1) {
                    marketDto.setSellChargeAlgorithmValue(marketDto.getSellChargeAlgorithmValue().multiply(new BigDecimal(10000)).setScale(2));
                }
            }
        }
        if (66 == market.getTrademode()) { //出境、保税市场
            //出境保税费用设置表
            GzCjbsfeeconfig gZCJBSFeeConfigVo = iGzCjbsfeeconfigMapper.selectOne(new QueryWrapper<GzCjbsfeeconfig>()
                    .eq("marketid", marketid));
            if (gZCJBSFeeConfigVo != null) {
                gZCJBSFeeConfigVo.setVatrate(gZCJBSFeeConfigVo.getVatrate().multiply(new BigDecimal(100)).setScale(2));
                gZCJBSFeeConfigVo.setLogisticspremiumrate(gZCJBSFeeConfigVo.getLogisticspremiumrate().multiply(new BigDecimal(100)).setScale(2));
                gZCJBSFeeConfigVo.setTariffrate(gZCJBSFeeConfigVo.getTariffrate().multiply(new BigDecimal(100)).setScale(2));
                gZCJBSFeeConfigVo.setLogisticsinvoicerate(gZCJBSFeeConfigVo.getLogisticsinvoicerate().multiply(new BigDecimal(100)).setScale(2));
            }
            marketDto.setGzCJBSFeeConfigVo(gZCJBSFeeConfigVo);
            //出境保税综合服务费设置表
            List<GzCjbsservicefeeconfig> gZCJBSServiceFeeConfigList = iGzCjbsservicefeeconfigMapper.selectList(new QueryWrapper<GzCjbsservicefeeconfig>()
                    .eq("marketid", marketid));
            marketDto.setGzCJBSServiceFeeConfigList(gZCJBSServiceFeeConfigList);
        }

        if (64 == market.getTrademode() || 65 == market.getTrademode()) {
            Markettradeconfig marketTradeConfig = iMarkettradeconfigMapper.selectOne(new QueryWrapper<Markettradeconfig>().eq("marketid", market.getMarketid()));
            if (marketTradeConfig != null) {
                BeanUtils.copyProperties(marketTradeConfig, marketDto);
                if (marketDto.getBuyChargeAlgorithm() != null && marketDto.getBuyChargeAlgorithm() == 1) {
                    marketDto.setBuyChargeAlgorithmValue(marketDto.getBuyChargeAlgorithmValue().multiply(new BigDecimal(10000)).setScale(2));
                }
                if (marketDto.getSellChargeAlgorithm() != null && marketDto.getSellChargeAlgorithm() == 1) {
                    marketDto.setSellChargeAlgorithmValue(marketDto.getSellChargeAlgorithmValue().multiply(new BigDecimal(10000)).setScale(2));
                }

                //64模式显示转让手续费
                if (64 == market.getTrademode() && marketDto.getFailedchargealgorithm() != null && marketDto.getFailedchargealgorithm() == 1) {
                    marketDto.setFailedchargevalue(marketDto.getFailedchargevalue().multiply(new BigDecimal(10000)).setScale(2));
                }
            }
        }

        if (54 == market.getTrademode() && market.getScoretypeid() != null) {
            Scoretype scoreType = iScoretypeMapper.selectOne(new QueryWrapper<Scoretype>().eq("scoretypeid", market.getScoretypeid()));
            if (scoreType != null) {
                marketDto.setScoretypename(scoreType.getScoretypename());
            }
        }

        return marketDto;
    }

    private AjaxResult check(SpotFulfillmentDelParam param, HttpServletRequest request) {
        Performanceplantemplate p = iPerformanceplantemplateMapper.selectOne(new QueryWrapper<Performanceplantemplate>()
                .eq("templatename", param.getTemplatename())
                .eq("autoid", param.getAutoid()));
        if (p != null) {
            return AjaxResult.error(Constants.Error_Code_Design, MessageType.MESSAGE_ERROR_CODE_SYSTEM056.getCode(), request.getHeader("Accept-Language"));
        }
        BigDecimal buysum = BigDecimal.ZERO;
        BigDecimal sellsum = BigDecimal.ZERO;
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
        int i = 0;
        for (Performancesteptemplate pst : param.getList()) {
            i++;
            if (pst.getSteptypeid() == 1 || pst.getSteptypeid() == 92) {
                buysum = buysum.add(pst.getStepvalue());
            }
            if (pst.getSteptypeid() == 2) {
                sellsum = sellsum.add(pst.getStepvalue());
            }
            if (sellsum.compareTo(buysum) > 0) {
                Object[] str = {i};
                return AjaxResult.error(Constants.Error_Code_Design, MessageType.MESSAGE_ERROR_CODE_SYSTEM057.getCode(), str, request.getHeader("Accept-Language"));
            }
            if (pst.getSteptypeid() == 5 && !map.containsKey(4)) {
                return AjaxResult.error(Constants.Error_Code_Design, MessageType.MESSAGE_ERROR_CODE_SYSTEM058.getCode(), request.getHeader("Accept-Language"));
            }
            if (pst.getSteptypeid() == 7 && !map.containsKey(6)) {
                return AjaxResult.error(Constants.Error_Code_Design, MessageType.MESSAGE_ERROR_CODE_SYSTEM059.getCode(), request.getHeader("Accept-Language"));
            }
            map.put(pst.getSteptypeid(), pst.getSteptypeid());
        }
        if (buysum.compareTo(BigDecimal.valueOf(100)) != 0) {
            return AjaxResult.error(Constants.Error_Code_Design, MessageType.MESSAGE_ERROR_CODE_SYSTEM060.getCode(), request.getHeader("Accept-Language"));
        }
        if (sellsum.compareTo(BigDecimal.valueOf(100)) != 0) {
            return AjaxResult.error(Constants.Error_Code_Design, MessageType.MESSAGE_ERROR_CODE_SYSTEM061.getCode(), request.getHeader("Accept-Language"));
        }
        i = 0;
        if (map.containsKey(3)) {
            i++;
        }
        if (map.containsKey(4)) {
            i++;
        }
        if (map.containsKey(8)) {
            i++;
        }
        if (i != 1) {
            return AjaxResult.error(Constants.Error_Code_Design, MessageType.MESSAGE_ERROR_CODE_SYSTEM062.getCode(), request.getHeader("Accept-Language"));
        }
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"));
    }

    /**
     * 修改系统参数表的市场更新时间
     */
    private void modifyMarketUpdateTimeToSysParam() {
        Systemparam p = iSystemparamMapper.selectOne(new QueryWrapper<Systemparam>().eq("paramcode", Constants.SYSPARAM_ID_MARKET));
        if (null != p) {
            p.setParamvalue(String.valueOf(System.currentTimeMillis()));
            p.setUpdatetime(new Date());
            iSystemparamMapper.update(p, new QueryWrapper<Systemparam>().eq("paramcode", Constants.SYSPARAM_ID_MARKET));
        }
    }
}
