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.extension.plugins.pagination.Page;
import com.muchinfo.mtp.proto.Common;
import com.muchinfo.mtp.proto.NotifyMI1;
import com.muchinfo.mtp3common.vo.ProtoHelper;
import com.muchinfo.mtp3common.enumtype.FunCodeConstants;
import com.muchinfo.mtp3century.service.ICommonService;
import com.muchinfo.mtp3century.service.IGoodsSetUpService;
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.utils.DateTimeUtils;
import com.muchinfo.mtp3common.vo.PageResult;
import com.muchinfo.mtp3interface.mapper.*;
import com.muchinfo.mtp3pojos.entity.*;
import com.muchinfo.mtp3pojos.vo.tradingmarket.goodssetup.*;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.lang3.StringUtils;
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.*;

@Service
public class GoodsSetUpServiceImpl implements IGoodsSetUpService {

    private final Logger log = LoggerFactory.getLogger(this.getClass());
    @Resource
    private ISystemmanagerMapper iSystemmanagerMapper;
    @Resource
    private ICommonService iCommonService;
    @Resource
    private IGoodsMapper iGoodsMapper;
    @Resource
    private IGoodsgroupMapper iGoodsgroupMapper;
    @Resource
    private IQuotesourcegroupMapper iQuotesourcegroupMapper;
    @Resource
    private IMarketMapper iMarketMapper;
    @Resource
    private RedisServiceUtil redisServiceUtil;
    @Resource
    private IEnumdicitemMapper iEnumdicitemMapper;
    @Resource
    private IGoodsgrouptradefeeMapper iGoodsgrouptradefeeMapper;
    @Resource
    private IGoodsgrouptraderuleMapper iGoodsgrouptraderuleMapper;
    @Resource
    private IWrstandardMapper iWrstandardMapper;
    @Resource
    private IDeliverygoodsMapper iDeliverygoodsMapper;
    @Resource
    private IErms2WrsconvertdetailMapper iErms2WrsconvertdetailMapper;
    @Resource
    private IErmsMiddlegoodsMapper iErmsMiddlegoodsMapper;
    @Resource
    private IErmcpGgconvertconfigMapper iErmcpGgconvertconfigMapper;
    @Resource
    private IUseraccountMapper iUseraccountMapper;
    @Resource
    private IArearoleMapper iArearoleMapper;
    @Resource
    private IArearolemarketMapper iArearolemarketMapper;
    @Resource
    private IGoodsmarginconfigMapper iGoodsmarginconfigMapper;
    @Resource
    private IDeliveryrelationMapper iDeliveryrelationMapper;
    @Resource
    private IGoodsoptionpropertyMapper iGoodsoptionpropertyMapper;
    @Resource
    private IGoodsexMapper iGoodsexMapper;
    @Resource
    private IHsbyGoodsexMapper iHsbyGoodsexMapper;
    @Resource
    private IWrcategoryMapper iWrcategoryMapper;
    @Resource
    private IDgfactoryitemtypeMapper iDgfactoryitemtypeMapper;
    @Resource
    private IDgfactoryitemMapper iDgfactoryitemMapper;
    @Resource
    private IDeliveryrelationdetailMapper iDeliveryrelationdetailMapper;
    @Resource
    private IWskhUserinfoMapper IWskhUserinfoMapper;
    @Resource
    private IGoodscloseplanMapper iGoodscloseplanMapper;
    @Resource
    private RabbitTemplate rabbitTemplate;

    @Override
    public PageResult<GoodsGroupSetQueryResult> groupSetQuery(GoodsGroupSetQueryParam 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());
        }

        List<Integer> filterTrademodeList = new ArrayList<>();
        filterTrademodeList.add(SysEnums.TradeMode.BJB.getCode());
        param.setFilterTrademodeList(filterTrademodeList);

        PageResult<GoodsGroupSetQueryResult> pageResult = new PageResult<>();
        IPage<GoodsGroupSetQueryResult> page = new Page<>(param.getPageNum(), param.getPageSize());
        IPage<GoodsGroupSetQueryResult> resultIPage = iGoodsMapper.groupSetQuery(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<GoodsGroupSetDetailResult> groupSetDetail(Long goodsgroupid, HttpServletRequest request) {
        GoodsGroupSetDetailResult result = new GoodsGroupSetDetailResult();
        Goodsgroup goodsGroup = iGoodsgroupMapper.selectOne(new QueryWrapper<Goodsgroup>().eq("goodsgroupid", goodsgroupid));
        Market m = iMarketMapper.selectOne(new QueryWrapper<Market>().eq("marketid", goodsGroup.getMarketid()));
        result.setGoodsgroup(goodsGroup);
        result.setMarketName(m.getMarketname());
        result.setTradeMode(m.getTrademode());
        result.setCreatorName(iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("autoid", goodsGroup.getCreatorid())).getUsername());
        if (goodsGroup.getCreatorid() != null && goodsGroup.getCreatorid().equals(goodsGroup.getModifierid())) {
            result.setModifierName(result.getCreatorName());
        } else {
            result.setModifierName(iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("autoid", goodsGroup.getModifierid())).getUsername());
        }
        if (goodsGroup.getQuotesourcegroupid() != null) {
            Quotesourcegroup qsg = iQuotesourcegroupMapper.selectOne(new QueryWrapper<Quotesourcegroup>()
                    .eq("autoid", goodsGroup.getQuotesourcegroupid()));
            if (qsg != null) {
                result.setQuoteSourceGroupName(qsg.getGroupcode() + "(" + qsg.getGroupname() + ")");
            }
        }

        // get rule and fee
        Object o = redisServiceUtil.getCacheMapValue(Constants.REDIS_HEADER_SYSPARAM, "007");
        Integer de = null;
        BigDecimal Cude = null;
        if (o != null && "1".equals(o.toString())) {
            Enumdicitem item = iEnumdicitemMapper.selectOne(new QueryWrapper<Enumdicitem>()
                    .eq("enumdiccode", "currency")
                    .eq("enumitemname", goodsGroup.getCurrencyid()));
            if (item != null && StringUtils.isNotBlank(item.getParam1())) {
                de = Integer.valueOf(item.getParam1());
                Cude = BigDecimal.valueOf(Math.pow(10, de));
            }
        }
        List<Goodsgrouptraderule> rulelist = iGoodsMapper.getTradeRuleByGroupid(goodsGroup.getGoodsgroupid());
        for (Goodsgrouptraderule rule : rulelist) {
            if (rule.getRuleid() == 107 || rule.getRuleid() == 108 || rule.getRuleid() == 110 || rule.getRuleid() == 111) {
                rule.setParamvalue(rule.getParamvalue().multiply(new BigDecimal(100)).setScale(0, RoundingMode.HALF_UP));
            }

            if (rule.getRuleid() >= 101 && rule.getRuleid() <= 104 && o != null && "1".equals(o.toString())) {
                rule.setParamvalue(rule.getParamvalue().divide(BigDecimal.valueOf(Math.pow(10, goodsGroup.getQtydecimalplace()))));
            }
        }
        result.setGroupTradeRule(rulelist);

        // 20250703：52, 54无手续费
        if (m.getTrademode() != 52 && m.getTrademode() != 54) {
            List<Goodsgrouptradefee> feelist = iGoodsMapper.getTradeFeeByGroupid(goodsGroup.getGoodsgroupid());
            //如果费用算法是比率，则值需要乘以10000再展示(同时将积的标度设为0)
            for (Goodsgrouptradefee fee : feelist) {
                if (fee.getFeealgorithm() == 1) {
                    // #6388 商品组、商品：费用比率时支持2位小数
                    fee.setExchangevalue(fee.getExchangevalue().multiply(new BigDecimal(10000)).setScale(2));
                    fee.setMemberdefaultvalue(fee.getMemberdefaultvalue().multiply(new BigDecimal(10000)).setScale(2));
                    fee.setMembermaxvalue(fee.getMembermaxvalue().multiply(new BigDecimal(10000)).setScale(2));
                    fee.setMemberminvalue(fee.getMemberminvalue().multiply(new BigDecimal(10000)).setScale(2));
                } else if (fee.getFeealgorithm() == 2 && de != null) {
                    //根据报价货币小数位放大
                    fee.setExchangevalue(fee.getExchangevalue().divide(Cude));
                    fee.setMemberdefaultvalue(fee.getMemberdefaultvalue().divide(Cude));
                    fee.setMembermaxvalue(fee.getMembermaxvalue().divide(Cude));
                    fee.setMemberminvalue(fee.getMemberminvalue().divide(Cude));
                }
            }
            result.setGroupTradeFee(feelist);
        }
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), result);
    }

    @Override
    public AjaxResult groupDel(Long goodsgroupid, HttpServletRequest request) {
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        // 判断是否商品正在运行
        List<Goods> goodsList = iGoodsMapper.selectList(new QueryWrapper<Goods>().eq("goodsgroupid", goodsgroupid));
        for (Goods g : goodsList) {
            if (SysEnums.GoodsStatus.WORK.getCode().equals(g.getGoodsstatus()) ||
                    SysEnums.GoodsStatus.PENDING_OUT.getCode().equals(g.getGoodsstatus())) {
                return AjaxResult.error(Constants.Error_Code_Design, MessageType.MESSAGE_ERROR_CODE_SYSTEM068.getCode(), request.getHeader("Accept-Language"));
            }
        }
        Goodsgroup gg = iGoodsgroupMapper.selectOne(new QueryWrapper<Goodsgroup>().eq("goodsgroupid", goodsgroupid));
        gg.setGoodsgroupstatus(SysEnums.CommonStatus.DEL.getCode());
        gg.setModifierid(systemmanager.getAutoid());
        gg.setModifytime(new Date());
        iGoodsgroupMapper.updateById(gg);

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

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

        if (param.getGoodsgroup().getMarketid() == null) {
            return AjaxResult.error(Constants.Error_Code_Design, MessageType.QUERY_ERROR_CODE_001.getCode(), request.getHeader("Accept-Language"));
        }

        if (param.getGoodsgroup().getGoodsgroupid() != null && param.getGoodsgroup().getGoodsgroupid() > 0) {
            return groupupdate(param, systemmanager, request);
        } else {
            return groupadd(param, systemmanager, request);
        }
    }

    @Override
    public AjaxResult<Market> listAllInit(HttpServletRequest request, String orgztypes, String filterTrademodeList) {
        //如果即运营机构又是经纪会员会或者金融机构  确实是没办法在一个方法里处理
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        List<Long> markets = null;
        if (!SysConstants.SYS_TYPE_MANAGE.equals(systemmanager.getReletype())) {
            String[] roletyes;
            //如果是子机构登陆，查找其父机构角色，查询市场
            if (SysConstants.SYS_TYPE_MEMBER.equals(systemmanager.getReletype())) {
                Useraccount 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.broker.getCode().equals(Integer.parseInt(role)) || SysEnums.OrganRole.selfsupport.getCode().equals(Integer.parseInt(role))) {
                    //如果是自营会员,经纪会员，自身权限的市场
                    //获取市场id，
                    Integer[] types = (Integer[]) ConvertUtils.convert(roletyes, Integer.class);
                    markets = iArearolemarketMapper.getMarketsNameByUseridAndrole(systemmanager.getAreauserid(), types);
                    //为了界面不出错，取id把市场完整信息查出
                }
            }
        }
        //根据市场id查询市场
        if (markets != null && !markets.isEmpty()) {
            List<Market> marketList = iMarketMapper.selectList(new QueryWrapper<Market>()
                    .in("marketid", markets));
            return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), marketList);
        }

        List<Integer> tradeModes = new ArrayList<>();
        tradeModes.add(SysEnums.TradeMode.MAKER.getCode());
        tradeModes.add(SysEnums.TradeMode.Quoter.getCode());
        tradeModes.add(SysEnums.TradeMode.GPDX.getCode());
        tradeModes.add(SysEnums.TradeMode.DQ.getCode());
        tradeModes.add(SysEnums.TradeMode.QQJY.getCode());
        tradeModes.add(SysEnums.TradeMode.STJJ.getCode());
        tradeModes.add(SysEnums.TradeMode.GPQQ.getCode());
        tradeModes.add(SysEnums.TradeMode.CKHQ.getCode());
        tradeModes.add(SysEnums.TradeMode.BBDH.getCode());
        tradeModes.add(SysEnums.TradeMode.YSYKJ.getCode());
        tradeModes.add(SysEnums.TradeMode.YSJP.getCode());
        tradeModes.add(SysEnums.TradeMode.GPYS.getCode());
        tradeModes.add(SysEnums.TradeMode.SCSC.getCode());
        tradeModes.add(SysEnums.TradeMode.BJB.getCode());
        tradeModes.add(SysEnums.TradeMode.FJYSC.getCode());
        tradeModes.add(SysEnums.TradeMode.DJYSB.getCode());
        tradeModes.add(SysEnums.TradeMode.DJZR.getCode());
        tradeModes.add(SysEnums.TradeMode.DDGP.getCode());
        tradeModes.add(SysEnums.TradeMode.DDZS.getCode());
        tradeModes.add(SysEnums.TradeMode.DJYSZQ.getCode());
        tradeModes.add(SysEnums.TradeMode.DJSC.getCode());
        tradeModes.add(SysEnums.TradeMode.JFSC.getCode());

        List<Market> marketList = iMarketMapper.selectList(new QueryWrapper<Market>()
                .eq("markettype", 2)
                .eq("marketStatus", SysEnums.EnumMarketStatus.NORMAL.getType())
                .in("tradeMode", tradeModes));

        //排除交易模式
        String[] split = filterTrademodeList.split(",");
        List<Integer> list = new ArrayList<>();
        for (String trademode : split) {
            list.add(Integer.valueOf(trademode));
        }

        marketList.removeIf(market -> list.contains(market.getTrademode()));

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

    @Override
    public PageResult<GoodsQueryResult> goodsQuery(GoodsQueryParam 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());
        }
        List<Integer> filterTrademodeList = new ArrayList<>();
        filterTrademodeList.add(SysEnums.TradeMode.BJB.getCode());
        filterTrademodeList.add(SysEnums.TradeMode.YSYKJ.getCode());
        filterTrademodeList.add(SysEnums.TradeMode.YSJP.getCode());
        filterTrademodeList.add(SysEnums.TradeMode.GPYS.getCode());
        filterTrademodeList.add(SysEnums.TradeMode.DJYSB.getCode());
        filterTrademodeList.add(SysEnums.TradeMode.DJYSZQ.getCode());
        param.setFilterTrademodeList(filterTrademodeList);

        if (!"".equals(param.getGoodscode())) {
            param.setGoodscode(param.getGoodscode().trim());
        }
        if (!"".equals(param.getGoodsname())) {
            param.setGoodsname(param.getGoodsname().trim());
        }

        PageResult<GoodsQueryResult> pageResult = new PageResult<>();
        IPage<GoodsQueryResult> page = new Page<>(param.getPageNum(), param.getPageSize());
        IPage<GoodsQueryResult> resultIPage = iGoodsMapper.goodsQuery(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<GoodsQueryDetailResult> goodsview(Long goodsid, HttpServletRequest request) {
        GoodsQueryDetailResult result = new GoodsQueryDetailResult();
        Goods goods = iGoodsMapper.selectOne(new QueryWrapper<Goods>().eq("GOODSID", goodsid));
        result.setGoods(goods);
        // 查询商品保证金
        List<Goodsmarginconfig> margins = iGoodsmarginconfigMapper.selectList(new QueryWrapper<Goodsmarginconfig>()
                .eq("GOODSID", goodsid));
        // 如果保证金计算方式是比率，则值需要乘以100再展示(同时将积的标度设为0)
        for (Goodsmarginconfig gmc : margins) {
            setGoodsMarginConfig(gmc);
        }
        result.setMargins(margins);
        // 查询商品规则

        Object o = redisServiceUtil.getCacheMapValue(Constants.REDIS_HEADER_SYSPARAM, "007");
        Integer de = null;
        BigDecimal Cude = null;
        if (o != null && "1".equals(o.toString())) {
            Enumdicitem item = iEnumdicitemMapper.selectOne(new QueryWrapper<Enumdicitem>()
                    .eq("enumdiccode", "currency")
                    .eq("enumitemname", goods.getCurrencyid()));
            if (item != null && StringUtils.isNotBlank(item.getParam1())) {
                de = Integer.valueOf(item.getParam1());
                Cude = BigDecimal.valueOf(Math.pow(10, de));
            }
        }

        List<Goodstraderule> traderuleList = iGoodsMapper.getTradeRuleByGoodsId(goodsid);
        traderuleList.sort((p1, p2) -> p1.getRuleid() > p2.getRuleid() ? 1 : -1);
        for (Goodstraderule trd : traderuleList) {
            if (trd.getRuleid() == 107 || trd.getRuleid() == 108 || trd.getRuleid() == 110 || trd.getRuleid() == 111) {
                trd.setParamvalue(trd.getParamvalue().multiply(new BigDecimal(100)).setScale(0, RoundingMode.HALF_UP));
            }
            if (o != null && "1".equals(o.toString())) {
                if (trd.getRuleid() >= 101 && trd.getRuleid() <= 104) {
                    trd.setParamvalue(trd.getParamvalue().divide(BigDecimal.valueOf(Math.pow(10, trd.getQtydecimalplace()))));
                }
                if (trd.getRuleid() == 109) {
                    trd.setParamvalue(trd.getParamvalue().divide(BigDecimal.valueOf(Math.pow(10, goods.getDecimalplace()))));
                }
            }
        }
        result.setTraderule(traderuleList);
        // 查询商品费用
        List<Goodstradefee> tradeFeeList = iGoodsMapper.getTradeFeeByGoodsId(goodsid);
        // 如果费用算法是比率，则值需要乘以10000再展示(同时将积的标度设为0)
        for (Goodstradefee fee : tradeFeeList) {
            if (fee.getFeealgorithm() == 1) {
                // #6388 商品组、商品：费用比率时支持2位小数
                fee.setExchangevalue(fee.getExchangevalue().multiply(new BigDecimal(10000)).setScale(2));
                fee.setMemberdefaultvalue(fee.getMemberdefaultvalue().multiply(new BigDecimal(10000)).setScale(2));
                fee.setMembermaxvalue(fee.getMembermaxvalue().multiply(new BigDecimal(10000)).setScale(2));
                fee.setMemberminvalue(fee.getMemberminvalue().multiply(new BigDecimal(10000)).setScale(2));
            } else if (fee.getFeealgorithm() == 2 && de != null) {
                fee.setExchangevalue(fee.getExchangevalue().divide(Cude));
                fee.setMemberdefaultvalue(fee.getMemberdefaultvalue().divide(Cude));
                fee.setMembermaxvalue(fee.getMembermaxvalue().divide(Cude));
                fee.setMemberminvalue(fee.getMemberminvalue().divide(Cude));
            }
        }
        result.setTradefee(tradeFeeList);
        Map<String, Object> map = new HashMap<>();
        map.put("goodsid", goodsid);
        // 查询商品交割相关配置
        if (goods.getDeliveryflag() != null && goods.getDeliveryflag() == 1) {
            // 交割配置
            Deliveryrelation dr = iDeliveryrelationMapper.selectOne(new QueryWrapper<Deliveryrelation>()
                    .eq("GOODSID", goodsid));
            result.setDrelation(dr);

            // 4:线下交收无交收品种
            if (dr != null && dr.getDeliverygoodsid() != null) {
                // 交割升贴水 仓库
                List<WarehouseInfoParam> whlist = IWskhUserinfoMapper.queryWareHouse(dr.getDeliverygoodsid());
                for (WarehouseInfoParam wh : whlist) {
                    Deliveryrelationdetail drd = iDeliveryrelationdetailMapper.selectOne(new QueryWrapper<Deliveryrelationdetail>()
                            .eq("goodsid", goodsid)
                            .eq("dgfactoryitemtypeid", 1L)
                            .eq("dgfactoryitemid", wh.getDgfactoryitemid()));
                    if (drd == null) {
                        wh.setIschecked(0);
                    } else {
                        wh.setIschecked(1);
                        wh.setPremiumvalue(drd.getPremiumvalue());
                    }
                }

                result.setWhlist(whlist);

                // 交割升贴水 其他选择项
                result.setItemtypemode(1);
                List<Dgfactoryitemtype> dgfitlist = iDgfactoryitemtypeMapper.selectList(new QueryWrapper<Dgfactoryitemtype>()
                        .eq("deliverygoodsid", dr.getDeliverygoodsid())
                        .eq("itemtypemode", 1));
                for (Dgfactoryitemtype dgfit : dgfitlist) {
                    if (dgfit.getDgfactoryitemtypeid() != 1) {
                        // 品种选择项定义
                        List<Dgfactoryitem> dgfilist = iDgfactoryitemMapper.selectList(new QueryWrapper<Dgfactoryitem>()
                                .eq("deliverygoodsid", dr.getDeliverygoodsid())
                                .eq("dgfactoryitemtypeid", dgfit.getDgfactoryitemtypeid()));
                        for (int j = 0; j < dgfilist.size(); j++) {
                            Dgfactoryitem dgfi = dgfilist.get(j);
                            Deliveryrelationdetail drd = iDeliveryrelationdetailMapper.selectOne(new QueryWrapper<Deliveryrelationdetail>()
                                    .eq("goodsid", goodsid)
                                    .eq("dgfactoryitemtypeid", dgfit.getDgfactoryitemtypeid())
                                    .eq("dgfactoryitemid", dgfi.getDgfactoryitemid()));

                            if (drd == null) {
                                dgfi.setIschecked(0);
                                dgfilist.remove(j);
                            } else {
                                dgfi.setIschecked(1);
                                dgfi.setPremiumvalue(drd.getPremiumvalue());
                            }
                        }
                        dgfit.setDgfilist(dgfilist);
                    }
                }
                result.setDgfitlist(dgfitlist);
            }
        }

        // 商品期权属性
        Goodsoptionproperty goodsOptionProperty = iGoodsoptionpropertyMapper.selectOne(new QueryWrapper<Goodsoptionproperty>().eq("goodsid", goodsid));
        if (goodsOptionProperty != null) {
            result.setProperty(goodsOptionProperty);
        }
        HsbyGoodsex hge = iHsbyGoodsexMapper.selectOne(new QueryWrapper<HsbyGoodsex>().eq("goodsid", goodsid));
        if (hge != null) {
            if (hge.getMemberratio() != null) {
                hge.setMemberratio(hge.getMemberratio().multiply(new BigDecimal(100)));
            }
            result.setHsbyGoodsex(hge);
            if (hge.getCategoryid() != null) {
                Wrcategory wr = iWrcategoryMapper.selectOne(new QueryWrapper<Wrcategory>().eq("CATEGORYID", hge.getCategoryid()));
                result.setCategoryname(wr.getCategoryname());
                if (wr.getParentcategoryid() != null) {
                    Wrcategory wr2 = iWrcategoryMapper.selectOne(new QueryWrapper<Wrcategory>().eq("CATEGORYID", wr.getParentcategoryid()));
                    result.setIschild(1);
                    result.setPcategoryname(wr2.getCategoryname());
                } else {
                    result.setIschild(0);
                }
            }
        }

        //获取发售方名称
        if (goods.getProvideruserid() != null) {
            Useraccount ua = iUseraccountMapper.selectOne(new QueryWrapper<Useraccount>().eq("userid", goods.getProvideruserid()));
            if (ua != null) {
                result.setProviderusername(ua.getAccountname());
            }
        }

        Goodsex goodsEx = iGoodsexMapper.selectOne(new QueryWrapper<Goodsex>().eq("GOODSID", goodsid));
        if (goodsEx != null) {
            result.setGoodsorder(goodsEx.getGoodsorder());

            // 20241118 TCE 添加字段 #6408
            result.setGoodsnameen(goodsEx.getGoodsnameen());
            result.setGoodsnametw(goodsEx.getGoodsnametw());
            result.setGoodsnameth(goodsEx.getGoodsnameth());
            result.setGoodsnamevi(goodsEx.getGoodsnamevi());
        }

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

    @Override
    public AjaxResult<GoodsUspendedQueryResult> goodsuspended(GoodsUspendedQueryParam 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());
        }
        List<GoodsUspendedQueryResult> results = iGoodsMapper.goodsuspended(param);
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), results);
    }

    @Override
    public PageResult<GoodsSearchQueryResult> sreach(GoodsSearchQueryParam 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());
        }
        PageResult<GoodsSearchQueryResult> pageResult = new PageResult<>();
        IPage<GoodsSearchQueryResult> page = new Page<>(param.getPageNum(), param.getPageSize());
        IPage<GoodsSearchQueryResult> resultIPage = iGoodsMapper.sreach(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<Goodsgroup> goodsGroupList(Long goodsgroupstatus, Long marketid, HttpServletRequest request) {
        List<Goodsgroup> gglist = iGoodsgroupMapper.selectList(new QueryWrapper<Goodsgroup>()
                .eq(marketid != null, "marketid", marketid)
                .eq(goodsgroupstatus != null, "goodsgroupstatus", goodsgroupstatus));
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), gglist);
    }

    @Override
    public AjaxResult<Goods> queryByGoodsgroupId(Long goodsgroupid, Integer goodsstatus, Long marketid, HttpServletRequest request) {
        List<Goods> goodsList = iGoodsMapper.selectList(new QueryWrapper<Goods>()
                .eq(goodsgroupid != null, "goodsgroupid", goodsgroupid)
                .eq(goodsstatus != null, "goodsstatus", goodsstatus)
                .eq(marketid != null, "marketid", marketid));
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), goodsList);
    }

    @Override
    public AjaxResult goodsuspendedadd(GoodsUspendedAddQueryParam param, HttpServletRequest request) {
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        List<Goodscloseplan> gdrList = iGoodscloseplanMapper.selectList(new QueryWrapper<Goodscloseplan>()
                .eq("goodsid", param.getGoodsid()));
        if (CollectionUtils.isNotEmpty(param.getDayRestDto())) {
            return AjaxResult.error(Constants.Error_Code_Design, MessageType.MESSAGE_ERROR_CODE_SYSTEM070.getCode(), request.getHeader("Accept-Language"));
        }
        for (Goodscloseplan goodscloseplan : gdrList) {
            Boolean mark = false;
            Date start = goodscloseplan.getStarttime();
            Date end = goodscloseplan.getEndtime();
            for (DayRestDto drd : param.getDayRestDto()) {
                mark = DateTimeUtils.isOverLaps(start, end, parseDate(drd.getStartdate()),
                        parseDate(drd.getEnddate()));
                if (mark) {
                    return AjaxResult.error(Constants.Error_Code_Design, MessageType.MESSAGE_ERROR_CODE_SYSTEM071.getCode(), request.getHeader("Accept-Language"));
                }
            }
        }

        for (DayRestDto drd : param.getDayRestDto()) {
            Goodscloseplan goodsDayRest = new Goodscloseplan();
            goodsDayRest.setGoodsid(param.getGoodsid());
            try {
                goodsDayRest.setClosedate(getRunDate(drd.getStartdate()));
            } catch (ParseException e) {
                log.error("goodsDayRest 时间格式转换失败");
            }
            goodsDayRest.setStarttime(parseDate(drd.getStartdate()));
            goodsDayRest.setEndtime(parseDate(drd.getEnddate()));
            goodsDayRest.setModifierid(systemmanager.getAutoid());
            goodsDayRest.setModifytime(new Date());
            iGoodscloseplanMapper.insert(goodsDayRest);
        }

        //交易服务需要市场id,先查下
        Goods goods = iGoodsMapper.selectOne(new QueryWrapper<Goods>().eq("goodsid", param.getGoodsid()));
        //再构建消息体
        NotifyMI1.GoodsClosePlanChangeNtf.Builder builder = NotifyMI1.GoodsClosePlanChangeNtf.newBuilder();
        Common.MessageHead.Builder hd = Common.MessageHead.newBuilder();
        hd.setFunCode(FunCodeConstants.FunCode_Trade_GoodsClosePlanChangeNtf);
        hd.setMarketID(goods.getMarketid().intValue());
        builder.setGoodsID(param.getGoodsid().intValue());
        builder.setMarketID(goods.getMarketid().intValue());
        builder.setHeader(hd);
        byte[] body = ProtoHelper.getNTAS(builder.build().toByteArray(), FunCodeConstants.FunCode_Trade_GoodsClosePlanChangeNtf);
        rabbitTemplate.send(SysConstants.RabbitNtfKey, new Message(body, new MessageProperties()));

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

    @Override
    public AjaxResult goodsuspendeddel(Long autoid, HttpServletRequest request) {
        Goodscloseplan goodscloseplan = iGoodscloseplanMapper.selectOne(new QueryWrapper<Goodscloseplan>().eq("autoid", autoid));
        iGoodscloseplanMapper.deleteById(autoid);

        //交易服务需要市场id,先查下
        Goods goods = iGoodsMapper.selectOne(new QueryWrapper<Goods>().eq("goodsid", goodscloseplan.getGoodsid()));
        //再构建消息体
        NotifyMI1.GoodsClosePlanChangeNtf.Builder builder = NotifyMI1.GoodsClosePlanChangeNtf.newBuilder();
        Common.MessageHead.Builder hd = Common.MessageHead.newBuilder();
        hd.setFunCode(FunCodeConstants.FunCode_Trade_GoodsClosePlanChangeNtf);
        hd.setMarketID(goods.getMarketid().intValue());
        builder.setGoodsID(goodscloseplan.getGoodsid().intValue());
        builder.setMarketID(goods.getMarketid().intValue());
        builder.setHeader(hd);
        byte[] body = ProtoHelper.getNTAS(builder.build().toByteArray(), FunCodeConstants.FunCode_Trade_GoodsClosePlanChangeNtf);
        rabbitTemplate.send(SysConstants.RabbitNtfKey, new Message(body, new MessageProperties()));
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"));
    }

    @Override
    public PageResult<DelistGoodsInfoResult> queryDelistGoodsInfo(DelistGoodsInfoParam param, HttpServletRequest request) {
        PageResult<DelistGoodsInfoResult> pageResult = new PageResult<>();
        IPage<DelistGoodsInfoResult> page = new Page<>(param.getPageNum(), param.getPageSize());
        IPage<DelistGoodsInfoResult> resultIPage = iGoodsMapper.queryDelistGoodsInfo(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 void setGoodsMarginConfig(Goodsmarginconfig gmc) {
        if (gmc.getMarginalgorithm() == 1) {
            if (gmc.getMarketmarginvalue() != null) {
                gmc.setMarketmarginvalue(gmc.getMarketmarginvalue().multiply(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_DOWN));
            } else {//页面订金值映射在reckonmarginvalue字段中
                gmc.setMarketmarginvalue(gmc.getReckonmarginvalue().multiply(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_DOWN));
            }
            if (gmc.getReckonmarginvalue() != null) {
                gmc.setReckonmarginvalue(gmc.getReckonmarginvalue().multiply(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_DOWN));
            }

            if (gmc.getLockmarginvalue() != null) {
                gmc.setLockmarginvalue(gmc.getLockmarginvalue().multiply(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_DOWN));
            }
        }
        if (gmc.getRealmarginalgorithm() != null && gmc.getRealmarginalgorithm() == 1
                && gmc.getRealmarginvalue() != null) {
            gmc.setRealmarginvalue(gmc.getRealmarginvalue().multiply(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_DOWN));
        }
    }

    private AjaxResult groupadd(GoodsGroupSetDetailResult param, Systemmanager systemmanager, HttpServletRequest request) {
        Goodsgroup goodsGroup = new Goodsgroup();
        BeanUtils.copyProperties(param.getGoodsgroup(), goodsGroup);
        // 判断商品组代码，同一市场下商品组名称是否唯一
        Goodsgroup nameg = iGoodsgroupMapper.selectOne(new QueryWrapper<Goodsgroup>()
                .eq("marketid", param.getGoodsgroup().getMarketid())
                .eq("goodsgroupname", param.getGoodsgroupname()));
        // 新增时
        if (param.getGoodsgroup().getGoodsgroupid() == null || param.getGoodsgroup().getGoodsgroupid() <= 0) {
            if (nameg != null) {
                return AjaxResult.error(Constants.Error_Code_Design, MessageType.MESSAGE_ERROR_CODE_SYSTEM068.getCode(), request.getHeader("Accept-Language"));
            }
        } else {
            // 修改时 如果code不能修改就不必比较了
            if (nameg != null && !nameg.getGoodsgroupid().equals(param.getGoodsgroup().getGoodsgroupid())) {
                return AjaxResult.error(Constants.Error_Code_Design, MessageType.MESSAGE_ERROR_CODE_SYSTEM068.getCode(), request.getHeader("Accept-Language"));
            }
        }

        goodsGroup.setGoodsgroupstatus(SysEnums.CommonStatus.WORK.getCode());
        // 是否数据库时间？
        goodsGroup.setCreatetime(new Date());
        // 新增要不要 修改人就是 添加人呢？
        goodsGroup.setModifytime(goodsGroup.getCreatetime());
        goodsGroup.setCreatorid(systemmanager.getAutoid());
        goodsGroup.setModifierid(systemmanager.getAutoid());
        iGoodsgroupMapper.insert(goodsGroup);
        // 是否需要验证必填规则？
        Object o = redisServiceUtil.getCacheMapValue(Constants.REDIS_HEADER_SYSPARAM, "007");
        if (param.getGroupTradeRule() != null) {
            for (Goodsgrouptraderule gtrp : param.getGroupTradeRule()) {
                if (gtrp == null || gtrp.getRuleid() == null && gtrp.getParamvalue() == null) {
                    continue;
                }

                Goodsgrouptraderule gtr = new Goodsgrouptraderule();
                BeanUtils.copyProperties(gtrp, gtr);
                gtr.setGoodsgroupid(goodsGroup.getGoodsgroupid());
                if (gtr.getRuleid() == 107 || gtr.getRuleid() == 108 || gtr.getRuleid() == 110 || gtr.getRuleid() == 111) {
                    gtr.setParamvalue(gtr.getParamvalue().divide(new BigDecimal(100)));
                }

                if (gtr.getRuleid() >= 101 && gtr.getRuleid() <= 104 && o != null && "1".equals(o.toString())) {
                    gtr.setParamvalue(gtr.getParamvalue().multiply(new BigDecimal(Math.pow(10, goodsGroup.getQtydecimalplace()))));
                }
                gtr.setMarketid(param.getGoodsgroup().getMarketid());
                iGoodsgrouptraderuleMapper.insert(gtr);
            }
        }
        if (param.getGroupTradeFee() != null) {
            Integer de = null;
            BigDecimal Cude = null;
            if (o != null && "1".equals(o.toString())) {
                Enumdicitem item = iEnumdicitemMapper.selectOne(new QueryWrapper<Enumdicitem>()
                        .eq("enumdiccode", "currency")
                        .eq("enumitemname", param.getGoodsgroup().getCurrencyid()));
                if (item != null && StringUtils.isNotBlank(item.getParam1())) {
                    de = Integer.valueOf(item.getParam1());
                    Cude = BigDecimal.valueOf(Math.pow(10, de));
                }
            }
            for (Goodsgrouptradefee gtfp : param.getGroupTradeFee()) {
                if (gtfp == null || gtfp.getTradefeeid() == null) {
                    continue;
                }
                Goodsgrouptradefee gtf = new Goodsgrouptradefee();
                BeanUtils.copyProperties(gtfp, gtf);
                gtf.setGoodsgroupid(goodsGroup.getGoodsgroupid());
                //如果费用算法是比率，则值需要除以10000再存数据库
                if (gtf.getFeealgorithm() == 1) {
                    gtf.setExchangevalue(gtf.getExchangevalue().divide(new BigDecimal(10000)));
                    gtf.setMemberdefaultvalue(gtf.getMemberdefaultvalue().divide(new BigDecimal(10000)));
                    gtf.setMembermaxvalue(gtf.getMembermaxvalue().divide(new BigDecimal(10000)));
                    gtf.setMemberminvalue(gtf.getMemberminvalue().divide(new BigDecimal(10000)));
                } else if (gtf.getFeealgorithm() == 2 && de != null) {
                    //根据报价货币小数位放大
                    gtf.setExchangevalue(gtf.getExchangevalue().multiply(Cude));
                    gtf.setMemberdefaultvalue(gtf.getMemberdefaultvalue().multiply(Cude));
                    gtf.setMembermaxvalue(gtf.getMembermaxvalue().multiply(Cude));
                    gtf.setMemberminvalue(gtf.getMemberminvalue().multiply(Cude));
                }
                gtf.setMarketid(param.getGoodsgroup().getMarketid());
                iGoodsgrouptradefeeMapper.insert(gtf);
            }
        }

        String sp = iCommonService.getSysparmById(SysConstants.SYSPAMA_CODE_GOODSGROUP);
        if ("1".equals(sp)) {
            //保存ERMS_MiddleGoods
            ErmsMiddlegoods middleGoods = new ErmsMiddlegoods();
            middleGoods.setMiddlegoodsname(goodsGroup.getGoodsgroupname());
            middleGoods.setMiddlegoodscode(goodsGroup.getOutergroupcode());
            middleGoods.setGoodsunitid(goodsGroup.getGoodunitid().intValue());
            middleGoods.setGoodsgroupid(goodsGroup.getGoodsgroupid());
            middleGoods.setIsvalid(1);
            middleGoods.setQtydecimalplace(0);
            middleGoods.setCreatorid(systemmanager.getAutoid());
            middleGoods.setCreatetime(new Date());
            middleGoods.setModifierid(systemmanager.getAutoid());
            middleGoods.setModifytime(new Date());
            middleGoods.setRelatedgoodstype(1);
            middleGoods.setNeedhedgeratio(BigDecimal.ONE);
            middleGoods.setAreauserid(1L);
            middleGoods.setNeedarbitrageratio(BigDecimal.ONE);
            iErmsMiddlegoodsMapper.insert(middleGoods);
            //保存ERMCP_GGConvertConfig
            ErmcpGgconvertconfig gGConvertConfig = new ErmcpGgconvertconfig();
            gGConvertConfig.setSrcgoodsgroupid(goodsGroup.getGoodsgroupid());
            gGConvertConfig.setDestgoodsgroupid(goodsGroup.getGoodsgroupid());
            gGConvertConfig.setConvertratio(BigDecimal.ONE);
            gGConvertConfig.setModifierid(systemmanager.getAutoid());
            gGConvertConfig.setModifytime(new Date());
            iErmcpGgconvertconfigMapper.insert(gGConvertConfig);
            //保存DeliveryGoods
            Deliverygoods deliveryGoods = new Deliverygoods();
            deliveryGoods.setDeliverygoodscode(goodsGroup.getOutergroupcode());
            deliveryGoods.setDeliverygoodsname(goodsGroup.getGoodsgroupname());
            deliveryGoods.setGoodsunitid(Math.toIntExact(goodsGroup.getGoodunitid()));
            deliveryGoods.setDeliverygoodstype(4);
            deliveryGoods.setAuditflag(0);
            deliveryGoods.setIsvalid(1);
            deliveryGoods.setIssplit(0);
            deliveryGoods.setAgreeunit(1L);
            deliveryGoods.setQtydecimalplace(0);
            deliveryGoods.setDgstatus(0);
            deliveryGoods.setAreauserid(1L);
            iDeliverygoodsMapper.insert(deliveryGoods);
            //保存WRStandard
            Wrstandard wRStandard = new Wrstandard();
            wRStandard.setWrstandardcode(goodsGroup.getOutergroupcode());
            wRStandard.setWrstandardname(goodsGroup.getGoodsgroupname());
            wRStandard.setDeliverygoodsid(deliveryGoods.getDeliverygoodsid());
            wRStandard.setUnitid(deliveryGoods.getGoodsunitid());
            wRStandard.setVatrate(BigDecimal.ZERO);
            wRStandard.setMinivalue(1L);
            wRStandard.setMinivaluedp(0L);
            wRStandard.setRealminivalue(1L);
            wRStandard.setRealminivaluedp(0L);
            wRStandard.setWrsstatus(0);
            wRStandard.setCreatorid(systemmanager.getAutoid());
            wRStandard.setCreatetime(new Date());
            wRStandard.setUpdatorid(systemmanager.getAutoid());
            wRStandard.setUpdatetime(new Date());
            wRStandard.setIsvalid(1);
            wRStandard.setAreauserid(1L);
            wRStandard.setConvertfactor(BigDecimal.ONE);
            wRStandard.setVatrate(BigDecimal.ZERO);
            iWrstandardMapper.insert(wRStandard);
            //保存ERMS2_WRSConvertDetail
            Erms2Wrsconvertdetail wRSConvertDetail = new Erms2Wrsconvertdetail();
            wRSConvertDetail.setWrstandardid(wRStandard.getWrstandardid());
            wRSConvertDetail.setDeliverygoodsid(deliveryGoods.getDeliverygoodsid());
            wRSConvertDetail.setMiddlegoodsid(middleGoods.getMiddlegoodsid());
            wRSConvertDetail.setConvertratio(BigDecimal.ONE);
            wRSConvertDetail.setShareratio(BigDecimal.ONE);
            wRSConvertDetail.setCostratio(BigDecimal.ONE);
            wRSConvertDetail.setModifierid(systemmanager.getAutoid());
            wRSConvertDetail.setModifytime(new Date());
            iErms2WrsconvertdetailMapper.insert(wRSConvertDetail);
        }
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"));
    }

    private AjaxResult groupupdate(GoodsGroupSetDetailResult param, Systemmanager systemmanager, HttpServletRequest request) {
        // 判断商品组代码，同一市场下商品组名称是否唯一
        Goodsgroup nameg = iGoodsgroupMapper.selectOne(new QueryWrapper<Goodsgroup>()
                .eq("marketid", param.getGoodsgroup().getMarketid())
                .eq("goodsgroupname", param.getGoodsgroupname()));
        // 新增时
        if (param.getGoodsgroup().getGoodsgroupid() == null || param.getGoodsgroup().getGoodsgroupid() <= 0) {
            if (nameg != null) {
                return AjaxResult.error(Constants.Error_Code_Design, MessageType.MESSAGE_ERROR_CODE_SYSTEM068.getCode(), request.getHeader("Accept-Language"));
            }
        } else {
            // 修改时 如果code不能修改就不必比较了
            if (nameg != null && !nameg.getGoodsgroupid().equals(param.getGoodsgroup().getGoodsgroupid())) {
                return AjaxResult.error(Constants.Error_Code_Design, MessageType.MESSAGE_ERROR_CODE_SYSTEM068.getCode(), request.getHeader("Accept-Language"));
            }
        }

        Goodsgroup ggroup = iGoodsgroupMapper.selectOne(new QueryWrapper<Goodsgroup>()
                .eq("goodsgroupid", param.getGoodsgroup().getGoodsgroupid()));
        ggroup.setQtydecimalplace(param.getGoodsgroup().getQtydecimalplace());
        ggroup.setGoodsgroupname(param.getGoodsgroupname());
        ggroup.setCurrencyid(param.getGoodsgroup().getCurrencyid());
        // ggroup.setMarketid(goodsGroup.getMarketid());
        // //市场应该不能改，不然商品的所属市场就不对了
        ggroup.setModifierid(systemmanager.getAutoid());
        if (param.getGoodsgroup().getQuotesourcegroupid() != null) {
            ggroup.setQuotesourcegroupid(param.getGoodsgroup().getQuotesourcegroupid());
        }
        ggroup.setQuotegear(param.getGoodsgroup().getQuotegear());
        ggroup.setModifytime(new Date());

        ggroup.setOutergroupcode(param.getGoodsgroup().getOutergroupcode());
        ggroup.setCurrencyid(param.getGoodsgroup().getCurrencyid());
        ggroup.setDecimalplace(param.getGoodsgroup().getDecimalplace());
        ggroup.setAgreeunit(param.getGoodsgroup().getAgreeunit());
        ggroup.setQuoteminunit(param.getGoodsgroup().getQuoteminunit());
        ggroup.setSyncgoodsqty(param.getGoodsgroup().getSyncgoodsqty());
        ggroup.setExercisetype(param.getGoodsgroup().getExercisetype());
        ggroup.setPremiumdecimalplace(param.getGoodsgroup().getPremiumdecimalplace());
        ggroup.setPremiumspreadalgorithm(param.getGoodsgroup().getPremiumspreadalgorithm());
        ggroup.setPremiumspreadvalue(param.getGoodsgroup().getPremiumspreadvalue());
        ggroup.setIsbuylimited(param.getGoodsgroup().getIsbuylimited());
        ggroup.setInnerdealmode(param.getGoodsgroup().getInnerdealmode());
        ggroup.setOuterdealmode(param.getGoodsgroup().getOuterdealmode());
        // 添加缩略图
        ggroup.setThumurls(param.getGoodsgroup().getThumurls());
        // 添加分类 20241009 (TCE)
        ggroup.setGroupcategroyid(param.getGoodsgroup().getGroupcategroyid());
        iGoodsgroupMapper.updateById(ggroup);
        // 是否需要验证必填规则？
        Map<String, Object> params = new HashMap<String, Object>();

        //109 小数位放大
        Object o = redisServiceUtil.getCacheMapValue(Constants.REDIS_HEADER_SYSPARAM, "007");
        Integer de = null;
        BigDecimal Cude = null;
        BigDecimal Qtyde = null;
        if (o != null && "1".equals(o.toString())) {
            Qtyde = BigDecimal.valueOf(Math.pow(10, param.getGoodsgroup().getQtydecimalplace()));
            Enumdicitem item = iEnumdicitemMapper.selectOne(new QueryWrapper<Enumdicitem>()
                    .eq("enumdiccode", "currency")
                    .eq("enumitemname", param.getGoodsgroup().getCurrencyid()));
            if (item != null && StringUtils.isNotBlank(item.getParam1())) {
                de = Integer.valueOf(item.getParam1());
                Cude = BigDecimal.valueOf(Math.pow(10, de));
            }
        }

        if (param.getGroupTradeRule() != null) {
            iGoodsgrouptraderuleMapper.delete(new QueryWrapper<Goodsgrouptraderule>().eq("goodsgroupid", param.getGoodsgroup().getGoodsgroupid())); // 全部删了重加
            for (Goodsgrouptraderule gtrp : param.getGroupTradeRule()) {
                Goodsgrouptraderule gtr = new Goodsgrouptraderule();
                BeanUtils.copyProperties(gtrp, gtr);
                gtr.setGoodsgroupid(param.getGoodsgroup().getGoodsgroupid());
                gtr.setMarketid(param.getGoodsgroup().getMarketid());
                if (gtr.getRuleid() == 107 || gtr.getRuleid() == 108 || gtr.getRuleid() == 110 || gtr.getRuleid() == 111) {
                    gtr.setParamvalue(gtr.getParamvalue().divide(new BigDecimal(100)));
                }

                if (gtr.getRuleid() >= 101 && gtr.getRuleid() <= 104 && Qtyde != null) {
                    gtr.setParamvalue(gtr.getParamvalue().multiply(Qtyde));
                }
                iGoodsgrouptraderuleMapper.insert(gtr);
            }
        }
        if (param.getGroupTradeFee() != null) {
            iGoodsgrouptradefeeMapper.delete(new QueryWrapper<Goodsgrouptradefee>().eq("goodsgroupid", param.getGoodsgroup().getGoodsgroupid())); // 全部删了重加
            for (Goodsgrouptradefee gtfp : param.getGroupTradeFee()) {
                Goodsgrouptradefee gtf = new Goodsgrouptradefee();
                BeanUtils.copyProperties(gtfp, gtf);
                gtf.setGoodsgroupid(param.getGoodsgroup().getGoodsgroupid());
                gtf.setMarketid(param.getGoodsgroup().getMarketid());
                //如果是比率，则值需要除以10000再存数据库
                if (gtf.getFeealgorithm() == 1) {
                    gtf.setExchangevalue(gtf.getExchangevalue().divide(new BigDecimal(10000)));
                    gtf.setMemberdefaultvalue(gtf.getMemberdefaultvalue().divide(new BigDecimal(10000)));
                    gtf.setMembermaxvalue(gtf.getMembermaxvalue().divide(new BigDecimal(10000)));
                    gtf.setMemberminvalue(gtf.getMemberminvalue().divide(new BigDecimal(10000)));
                } else if (gtf.getFeealgorithm() == 2 && de != null) {
                    //根据报价货币小数位放大
                    gtf.setExchangevalue(gtf.getExchangevalue().multiply(Cude));
                    gtf.setMemberdefaultvalue(gtf.getMemberdefaultvalue().multiply(Cude));
                    gtf.setMembermaxvalue(gtf.getMembermaxvalue().multiply(Cude));
                    gtf.setMemberminvalue(gtf.getMemberminvalue().multiply(Cude));
                }
                iGoodsgrouptradefeeMapper.insert(gtf);
            }
        }
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"));
    }

    /**
     * @Title: parseDatetime
     * @Description: 格式化时间
     */
    private Date parseDate(String dateStr) {
        //原格式为：yyyyMMdd HH：mm，加上秒才能转化
        String dateString = dateStr + ":00";
        Date date = null;
        try {
            date = DateTimeUtils.parseDatetime(dateString);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }

    /**
     * @Title: getRunDate
     * @Description: 获取运行时间
     */
    private String getRunDate(String dateStr) throws ParseException {
        String rundate = DateTimeUtils.formatStr(dateStr, "yyyyMMdd");
        return rundate;
    }
}
