package com.steerinfo.meterwork.meterworkcaractualfirst.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.jisco.dynamicweight.dynamicbasecamera.factories.ConverterFactories;
import com.steerinfo.baseinfo.combaseinfo.mapper.ComBaseInfoMapper;
import com.steerinfo.baseinfo.combaseinfo.model.ComBaseInfo;
import com.steerinfo.baseinfo.meterbaseaddweight.mapper.MeterBaseAddWeightMapper;
import com.steerinfo.baseinfo.meterbaseaddweight.model.MeterBaseAddWeight;
import com.steerinfo.baseinfo.meterbasecar.mapper.MeterBaseCarMapper;
import com.steerinfo.baseinfo.meterbasecar.model.MeterBaseCar;
import com.steerinfo.baseinfo.meterbasehistaredata.mapper.MeterBaseHisTareDataMapper;
import com.steerinfo.baseinfo.meterbasehistaredata.model.MeterBaseHisTareData;
import com.steerinfo.baseinfo.meterbasehistaredetail.mapper.MeterBaseHisTareDetailMapper;
import com.steerinfo.baseinfo.meterbasehistaredetail.model.MeterBaseHisTareDetail;
import com.steerinfo.baseinfo.meterbasematterinfo.mapper.MeterBaseMatterInfoMapper;
import com.steerinfo.baseinfo.meterbasematterinfo.model.MeterBaseMatterInfo;
import com.steerinfo.baseinfo.meterbasemattermap.mapper.MeterBaseMatterMapMapper;
import com.steerinfo.baseinfo.meterbasemattermap.model.MeterBaseMatterMap;
import com.steerinfo.baseinfo.meterbasematterunit.mapper.MeterBaseMatterUnitMapper;
import com.steerinfo.baseinfo.meterbasematterunit.model.MeterBaseMatterUnit;
import com.steerinfo.baseinfo.meterbasematterunitmixedloadunloadtime.mapper.MeterBaseMatterUnitMixedLoadUnloadTimeMapper;
import com.steerinfo.baseinfo.meterbasematterunitmixedloadunloadtime.model.MeterBaseMatterUnitMixedLoadUnloadTime;
import com.steerinfo.baseinfo.meterbaseoperationlog.mapper.MeterBaseOperationLogMapper;
import com.steerinfo.baseinfo.meterbaseoperationlog.model.MeterBaseOperationLog;
import com.steerinfo.baseinfo.meterbasespotinfo.mapper.MeterBaseSpotInfoMapper;
import com.steerinfo.baseinfo.meterbasespotinfo.model.MeterBaseSpotInfo;
import com.steerinfo.baseinfo.meterbasetermtaredata.mapper.MeterBaseTermTareDataMapper;
import com.steerinfo.baseinfo.meterbasetermtaredata.model.MeterBaseTermTareData;
import com.steerinfo.baseinfo.meterbaseunloadtime.mapper.MeterBaseUnloadTimeMapper;
import com.steerinfo.baseinfo.meterbaseunloadtime.model.MeterBaseUnloadTime;
import com.steerinfo.baseinfo.meterbasevideoinfo.mapper.MeterBaseVideoinfoMapper;
import com.steerinfo.baseinfo.meterbasevideoinfo.model.MeterBaseVideoinfo;
import com.steerinfo.filter.SqlInjectFilter;
import com.steerinfo.framework.controller.RESTfulResult;
import com.steerinfo.framework.mapper.IBaseMapper;
import com.steerinfo.framework.service.impl.BaseServiceImpl;
import com.steerinfo.framework.service.pagehelper.PageHelper;
import com.steerinfo.framework.service.pagehelper.PageList;
import com.steerinfo.framework.user.UserPayload;
import com.steerinfo.framework.utils.collection.ListUtils;
import com.steerinfo.metermonitor.metermonitornote.mapper.MeterMonitorNoteMapper;
import com.steerinfo.metermonitor.metermonitornote.model.MeterMonitorNote;
import com.steerinfo.meterwork.constants.DbConstants;
import com.steerinfo.meterwork.dto.*;
import com.steerinfo.meterwork.except.MarkerMetException;
import com.steerinfo.meterwork.meterworkaddweight.mapper.MeterWorkAddWeightMapper;
import com.steerinfo.meterwork.meterworkaddweight.model.MeterWorkAddWeight;
import com.steerinfo.meterwork.meterworkcaractual.mapper.MeterWorkCarActualMapper;
import com.steerinfo.meterwork.meterworkcaractual.model.MeterWorkCarActual;
import com.steerinfo.meterwork.meterworkcaractualfirst.mapper.MeterWorkCarActualFirstMapper;
import com.steerinfo.meterwork.meterworkcaractualfirst.model.MeterWorkCarActualFirst;
import com.steerinfo.meterwork.meterworkcaractualfirst.service.IMeterWorkCarActualFirstService;
import com.steerinfo.meterwork.meterworkcaractualfirstbak.model.MeterWorkCarActualFirstBak;
import com.steerinfo.meterwork.meterworkcraneactual.mapper.MeterWorkCraneActualMapper;
import com.steerinfo.meterwork.meterworkimage.mapper.MeterWorkImageMapper;
import com.steerinfo.meterwork.meterworkimage.model.MeterWorkImage;
import com.steerinfo.meterwork.meterworkmonitor.mapper.MeterWorkMonitorMapper;
import com.steerinfo.meterwork.meterworkmonitor.model.MeterWorkMonitor;
import com.steerinfo.meterwork.meterworkonline.mapper.MeterWorkOnlineMapper;
import com.steerinfo.meterwork.meterworkonline.model.MeterWorkOnline;
import com.steerinfo.meterwork.meterworkprelink.mapper.MeterWorkPreLinkMapper;
import com.steerinfo.meterwork.meterworkprelink.model.MeterWorkPreLink;
import com.steerinfo.meterwork.meterworkprelink.service.IMeterWorkPreLinkService;
import com.steerinfo.meterwork.meterworkpreprocess.mapper.MeterWorkPreProcessMapper;
import com.steerinfo.meterwork.meterworkpreprocess.model.MeterWorkPreProcess;
import com.steerinfo.meterwork.meterworkprewgttype.mapper.MeterWorkPreWgttypeMapper;
import com.steerinfo.meterwork.meterworkrailwayactfirst.mapper.MeterWorkRailwayActFirstMapper;
import com.steerinfo.meterwork.meterworkrailwayactfirst.model.MeterWorkRailwayActFirst;
import com.steerinfo.meterwork.meterworkrailwayactual.mapper.MeterWorkRailwayActualMapper;
import com.steerinfo.meterwork.meterworkrailwayactual.model.MeterWorkRailwayActual;
import com.steerinfo.pretrack.pretrackscale.mapper.PreTrackScaleMapper;
import com.steerinfo.pretrack.pretrackscale.model.PreTrackScale;
import com.steerinfo.util.*;
import org.apache.http.util.TextUtils;
import org.apache.shiro.crypto.hash.Hash;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;


/**
 * MeterWorkCarActualFirst服务实现：
 *
 * @author generator
 * @version 1.0-SNAPSHORT 2020-09-17 11:28
 * 类描述
 * 修订历史：
 * 日期：2020-09-17
 * 作者：generator
 * 参考：
 * 描述：MeterWorkCarActualFirst服务实现
 * @Copyright 湖南视拓信息技术股份有限公司. All rights reserved.
 * @see null
 */
@Service(value = "meterWorkCarActualFirstService")
public class MeterWorkCarActualFirstServiceImpl extends BaseServiceImpl<MeterWorkCarActualFirst, String> implements IMeterWorkCarActualFirstService {

    private static Logger logger	= LoggerFactory.getLogger( MeterWorkCarActualFirstServiceImpl.class );

    @Resource
    private MeterBaseMatterUnitMixedLoadUnloadTimeMapper meterBaseMatterUnitMixedLoadUnloadTimeMapper;

    @Resource
    private MeterWorkCraneActualMapper craneActualMapper;

    @Resource
    private MeterBaseCarMapper meterBaseCarMapper;

    @Resource
    private MeterBaseOperationLogMapper meterBaseOperationLogMapper;

    @Resource
    private ComBaseInfoMapper comBaseInfoMapper;

    @Resource
    private MeterBaseMatterMapMapper meterBaseMatterMapMapper;

    @Resource
    private MeterBaseSpotInfoMapper meterBaseSpotInfoMapper;

    @Resource
    private MeterWorkCarActualFirstMapper meterWorkCarActualFirstMapper;

    @Resource
    private MeterWorkRailwayActualMapper meterWorkRailwayActualMapper;

    @Resource
    private MeterBaseHisTareDataMapper meterBaseHisTareDataMapper;

    @Resource
    private PreTrackScaleMapper preTrackScaleMapper;

    @Resource
    private MeterWorkPreLinkMapper meterWorkPreLinkMapper;

    @Autowired
    IMeterWorkPreLinkService meterWorkPreLinkService;

    @Resource
    private MeterBaseHisTareDetailMapper meterBaseHisTareDetailMapper;

    @Resource
    private MeterWorkPreWgttypeMapper meterWorkPreWgttypeMapper;

    @Resource
    private MeterWorkImageMapper meterWorkImageMapper;

    @Resource
    private MeterBaseVideoinfoMapper meterBaseVideoinfoMapper;

    @Resource
    private MeterWorkCarActualMapper meterWorkCarActualMapper;

    @Resource
    private MeterWorkPreProcessMapper meterWorkPreProcessMapper;

    @Resource
    private MeterWorkMonitorMapper meterWorkMonitorMapper;

    @Resource
    private MeterWorkOnlineMapper meterWorkOnlineMapper;

    @Resource
    private MeterWorkRailwayActFirstMapper meterWorkRailwayActFirstMapper;

    @Resource
    private MeterMonitorNoteMapper meterMonitorNoteMapper;

    @Resource
    private MeterBaseMatterInfoMapper meterBaseMatterInfoMapper;

    @Resource
    private MeterBaseTermTareDataMapper meterBaseTermTareDataMapper;

    @Resource
    private MeterBaseUnloadTimeMapper meterBaseUnloadTimeMapper;

    @Resource
    private MeterBaseAddWeightMapper meterBaseAddWeightMapper;

    @Resource
    private MeterWorkAddWeightMapper meterWorkAddWeightMapper;

    @Resource
    private MeterBaseMatterUnitMapper meterBaseMatterUnitMapper;

    private static final Logger log = LoggerFactory.getLogger(MeterWorkCarActualFirstServiceImpl.class);

    @Override
    protected IBaseMapper<MeterWorkCarActualFirst, String> getMapper() {
        return meterWorkCarActualFirstMapper;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public RESTfulResult checkandadd(MeterWorkCarActualFirst model, MeterMonitorNote note) throws Exception {
        RESTfulResult rm = new RESTfulResult();
        rm.setFailed();
        try {
            ckeck1(model);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            String afl = sdf.format(new Date());
//            String no = meterWorkCarActualFirstMapper.getNewID(afl);
//            model.setActualFirstNo(sdf.format(new Date()) + no);
            String no = PublicMethod.IdCreate(3);
            model.setActualFirstNo(no);

            if(StringUtils.isNotEmpty(model.getPredictionNo())){
                PreTrackScale pre = new PreTrackScale();
                pre.setPredictionNo(model.getPredictionNo());
                pre.setLineDesc("0");
                preTrackScaleMapper.updateByPrimaryKeySelective(pre);
            }

            //6、存储图片
            //SaveImg(model);

            //7、修改计量监控
            updateMonitor(model.getBaseSpotNo());

            //8、修改监控的计量作业编号
            updateMonitorOver(model.getActualFirstNo(), model.getBaseSpotNo());

            //信息加密
            String str = model.getActualFirstNo() + "," + model.getMeterWeight() + "," + "1";
            String enStr = encryption(str);

            //保存日志
            saveNote(note);

            //当存储一次数据或者结净时，将本车辆的预处理重量改为已使用
            updatePreWeight(model.getCarNo());
            if(StringUtils.isEmpty(model.getValueFlag())){
                model.setValueFlag("1");
            }
            if(StringUtils.isNotEmpty(model.getPredictionNo())){
                model.setIsPreScale("1");
            }
            model.setCreateTime(new Date());
            int num = meterWorkCarActualFirstMapper.insertSelective(model);
            rm.setSucceed();
            rm.setCode("200");
            rm.setData(model.getActualFirstNo());
            rm.setMessage(enStr);
            return rm;
        } catch (MarkerMetException e) {
            throw e;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int checkandupdate(MeterWorkCarActualFirst model) throws MarkerMetException {
        try {
            if (model.getValueFlag().equals(DbConstants.NET)) {
                throw new MarkerMetException(500, "已经结净的数据无法修改！！");
            }
            ckeck(model);
            MeterWorkCarActualFirst first = new MeterWorkCarActualFirst();
            first.setActualFirstNo(model.getActualFirstNo());
            first.setCarNo(model.getCarNo());
            int num = meterWorkCarActualFirstMapper.updateByPrimaryKeySelective(first);
            return num;
        } catch (MarkerMetException e) {
            throw e;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int checkcarandupdate(MeterWorkCarActualFirst model) throws MarkerMetException {
        try {
            ckeckcar(model);

            UserPayload payload = UserPayload.getCurrUser();
            String userId = payload.getUserCode();
            String userName = payload.getUserName();
            model.setUpdateTime(new Date());
            model.setUpdateManNo(userId);
            model.setUpdateManName(userName);

            MeterWorkCarActualFirst modelTemp = meterWorkCarActualFirstMapper.selectByPrimaryKey(model.getActualFirstNo());

            MeterBaseOperationLog logModel = new MeterBaseOperationLog();
            logModel.setId(PublicMethod.IdCreate(2));
            logModel.setCreateManNo(userId);
            logModel.setCreateManName(userName);
            logModel.setCreateTime(new Date());
            logModel.setOperationPage("web端-汽车衡一次数据维护");
            logModel.setOperationFunction("车号修改");
            logModel.setOperationId(model.getActualFirstNo());
            logModel.setOperationPredictionNo(model.getPredictionNo());
            logModel.setOperationCarnNo(model.getCarNo());
            logModel.setOperationBeforeFix(modelTemp.getCarNo());
            logModel.setOperationAfterFix(model.getCarNo());
            meterBaseOperationLogMapper.insertSelective(logModel);
            int num = meterWorkCarActualFirstMapper.updateByPrimaryKeySelective(model);
            return num;
        } catch (MarkerMetException e) {
            throw e;
        }
    }

    @Override
    public RESTfulResult firstDataSupplement(MeterWorkCarActualFirst model) {
        RESTfulResult rm = new RESTfulResult();
        rm.setFailed();
        try {
//            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
//            String afl = sdf.format(new Date());
//            String no = meterWorkCarActualFirstMapper.getNewID(afl);
//            model.setActualFirstNo(sdf.format(new Date()) + no);
            UserPayload payload = UserPayload.getCurrUser();
            String userId = payload.getUserCode();
            String userName = payload.getUserName();
            Assert.isTrue(model.getCreateTime() != null && StringUtils.isNotEmpty(model.getCreateTime().toString()), "计量时间不能为空");
            HashMap<String, Object> obj = new HashMap<>();
            obj.put("baseSpotNo", model.getBaseSpotNo());
            List<MeterBaseSpotInfo> spotModel = meterBaseSpotInfoMapper.selectByParameters(obj);
            Assert.isTrue(spotModel.size() >= 1, "计量点配置表未找到相应的计量点");
            model.setBaseSpotName(spotModel.get(0).getBaseSpotName());
            if(model.getWeightType().equals("毛重")){
                model.setWeightType("0");
            }else if(model.getWeightType().equals("皮重")){
                model.setWeightType("1");
            }else if(model.getWeightType().equals("期限皮重")) {
                model.setWeightType("2");
            }
            String no = PublicMethod.IdCreate(3);
            model.setActualFirstNo(no);
            model.setAddWeight(model.getAddWeight()==null ? new BigDecimal(0): model.getAddWeight());
            BigDecimal meterWeight = model.getMeterWeight().multiply(new BigDecimal(1000));
            model.setMeterWeight(meterWeight);
            model.setValueFlag("1");
            model.setCheckFlag("1");
//            model.setMeterMode("3");
            model.setDataSource("4");
            model.setIsPreScale("0");
            model.setCreateManNo(userId);
            model.setCreateManName(userName);
            meterWorkCarActualFirstMapper.insertSelective(model);
            rm.setSucceed();
            rm.setCode("200");
            rm.setData(model);
        }catch(Exception e) {
            e.printStackTrace();
            rm.setMessage("操作异常，请确认！！>>>>" + e.getMessage());
        }
        return rm;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int abolish(List<MeterWorkCarActualFirst> models) throws MarkerMetException {
        try {
            int num = 0;
            if (models.size() <= 0 || models == null) {
                throw new MarkerMetException(500, "参数为空!!");
            }else {
                for(MeterWorkCarActualFirst model : models) {
                    if (model.getValueFlag().equals(DbConstants.NET)) {
                        throw new MarkerMetException(500, "已结净的数据不可再废除!!");
                    }
                    if (StringUtils.isNotEmpty(model.getPredictionNo())) {
                        throw new MarkerMetException(500, "一次数据已匹配委托，请撤销委托之后再进行作废");
                    }
                }
            }
            String userId = "";
            String userName = "";
            try{
                UserPayload userPayload = UserPayload.getCurrUser();
                userId = userPayload.getUserCode();
                userName = userPayload.getUserName();
            }catch (Exception e) {
                userId = "system";
                userName = "system";
            }
            for (MeterWorkCarActualFirst model : models) {
                ckeck(model);
                model.setValueFlag(DbConstants.INVALID);
                meterWorkCarActualFirstMapper.updateByPrimaryKeySelective(model);
                num++;

                MeterBaseOperationLog logModel = new MeterBaseOperationLog();
                logModel.setId(PublicMethod.IdCreate(2));
                logModel.setCreateManNo(userId);
                logModel.setCreateManName(userName);
                logModel.setCreateTime(new Date());
                logModel.setOperationPage("web端-汽车衡一次数据维护");
                logModel.setOperationFunction("作废");
                logModel.setOperationId(model.getActualFirstNo());
                logModel.setOperationPredictionNo(model.getPredictionNo());
                logModel.setOperationCarnNo(model.getCarNo());
                meterBaseOperationLogMapper.insertSelective(logModel);
            }
//            for (MeterWorkCarActualFirst model : models) {
//                if (StringUtils.isNotEmpty(model.getPredictionNo())
//                        && model.getPredictionNo().length() > 10) {
//                    PreTrackScale ps = new PreTrackScale();
//                    ps.setPredictionNo(model.getPredictionNo());
//                    ps.setValueFlag(DbConstants.Abolish); //没有有效的一次计量记录的时候，预报直接作废，这样检化验那边才能不影响下一车采样 2021年4月18日
//                    ps.setUploadFlag("1");
//                    this.preTrackScaleMapper.updateByPrimaryKeySelective(ps);
//                }
//            }
            /*
            // 2021年5月24日 不需要搞得这么复杂，直接干掉就可以了
            //杨秀东新增逻辑，若预报只有一条有效的一次计量数据，则作废一次计量数据时，将预报置为未使用的状态
            for (MeterWorkCarActualFirst model : models) {
                //必须判断预报是否存在，因为厂内倒运没有预报数据
                if (StringUtils.isNotEmpty(model.getPredictionNo())
                        && model.getPredictionNo().length() > 10) {
                    MeterWorkCarActualFirst myFirt = new MeterWorkCarActualFirst();
                    myFirt.setPredictionNo(model.getPredictionNo());
                    myFirt.setValueFlag(DbConstants.VALID);
                    Map<String, Object> map = FieldsCollector.beanToMap(myFirt);
                    //一次计量数据信息
                    List<MeterWorkCarActualFirst> listFirst = this.meterWorkCarActualFirstMapper.selectByParameters(map);
                    //计量流程表数据
                    List<MeterWorkPreProcess> listPreProcess = this.meterWorkPreProcessMapper.selectByParameters(map);
                    //环节表数据
                    List<MeterWorkPreLink> listPreLink = this.meterWorkPreLinkMapper.selectByParameters(map);
                    if (listFirst != null && listFirst.size() == 0) {
                        //处理预报信息；回退到未使用状态
                        PreTrackScale ps = new PreTrackScale();
                        ps.setPredictionNo(model.getPredictionNo());
//                        ps.setValueFlag(DbConstants.VALID); //没有有效的一次计量记录的时候，预报回退到未使用的状态
                        ps.setValueFlag(DbConstants.Abolish); //没有有效的一次计量记录的时候，预报直接作废，这样检化验那边才能采样 2021年4月18日
                        this.preTrackScaleMapper.updateByPrimaryKeySelective(ps);

                        //处理流程表信息
                        if (listPreProcess != null && listPreProcess.size() > 0) {
                            for (MeterWorkPreProcess myProcess : listPreProcess) {
                                myProcess.setValueFlag(DbConstants.N);
                                this.meterWorkPreProcessMapper.updateByPrimaryKeySelective(myProcess);
                            }
                        }
                        //处理环节信息
                        int mySeqNo = 0;
                        if (listPreLink != null && listPreLink.size() > 0) {
                            for (MeterWorkPreLink myLink : listPreLink) {
                                if ("一次计量".equals(myLink.getLinkName())) {
                                    mySeqNo = myLink.getSeqNo();
                                }
                            }
                            //流程大于“一次计量”的全部都给置位 0
                            for (MeterWorkPreLink myLink : listPreLink) {
                                if (myLink.getSeqNo() > mySeqNo || myLink.getSeqNo() == mySeqNo) {
                                    myLink.setValueFlag(DbConstants.N);
                                    this.meterWorkPreLinkMapper.updateByPrimaryKeySelective(myLink);
                                }
                            }
                        }
                    }
                    if (listFirst != null && listFirst.size() == 1) {
                        //处理预报信息；回退到已使用状态
                        PreTrackScale ps = new PreTrackScale();
                        ps.setPredictionNo(model.getPredictionNo());
                        ps.setValueFlag(DbConstants.Y); //只有一条有效的一次计量记录的时候，预报回退到已使用的状态
                        this.preTrackScaleMapper.updateByPrimaryKeySelective(ps);

                        //处理流程表信息
                        if (listPreProcess != null && listPreProcess.size() > 0) {
                            for (MeterWorkPreProcess myProcess : listPreProcess) {
                                myProcess.setValueFlag(DbConstants.Y);
                                this.meterWorkPreProcessMapper.updateByPrimaryKeySelective(myProcess);
                            }
                        }
                        //处理环节信息
                        int mySeqNo = 0;
                        if (listPreLink != null && listPreLink.size() > 0) {
                            for (MeterWorkPreLink myLink : listPreLink) {
                                if ("一次计量".equals(myLink.getLinkName())) {
                                    mySeqNo = myLink.getSeqNo();
                                }
                            }
                            //流程大于“一次计量”的全部都给置位 0
                            for (MeterWorkPreLink myLink : listPreLink) {
                                if (myLink.getSeqNo() > mySeqNo) {
                                    myLink.setValueFlag(DbConstants.N);
                                    this.meterWorkPreLinkMapper.updateByPrimaryKeySelective(myLink);
                                }
                            }
                        }
                    }
                }

            }
            */
            return num;
        } catch (MarkerMetException e) {
            throw e;
        }
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public int recover(List<MeterWorkCarActualFirst> models) throws MarkerMetException {
        try {
            int num = 0;
            if (models.size() <= 0 || models == null) {
                throw new MarkerMetException(500, "请选择需要启用的数据!!");
            }else {
                for (MeterWorkCarActualFirst model : models) {
                    if (model.getValueFlag().equals(DbConstants.NET)) {
                        throw new MarkerMetException(500, "计量数据已经结净，无法启用");
                    }
                }
            }
            String userId = "";
            String userName = "";
            try{
                UserPayload userPayload = UserPayload.getCurrUser();
                userId = userPayload.getUserCode();
                userName = userPayload.getUserName();
            }catch (Exception e) {
                userId = "system";
                userName = "system";
            }
            for (MeterWorkCarActualFirst model : models) {
                model.setValueFlag(DbConstants.VALID);
                meterWorkCarActualFirstMapper.updateByPrimaryKeySelective(model);

                MeterBaseOperationLog logModel = new MeterBaseOperationLog();
                logModel.setId(PublicMethod.IdCreate(2));
                logModel.setCreateManNo(userId);
                logModel.setCreateManName(userName);
                logModel.setCreateTime(new Date());
                logModel.setOperationPage("web端-汽车衡一次数据维护");
                logModel.setOperationFunction("启用");
                logModel.setOperationId(model.getActualFirstNo());
                logModel.setOperationPredictionNo(model.getPredictionNo());
                logModel.setOperationCarnNo(model.getCarNo());
                meterBaseOperationLogMapper.insertSelective(logModel);

//                if (StringUtils.isNotEmpty(model.getPredictionNo())
//                        && model.getPredictionNo().length() > 10) {
//                    PreTrackScale ps = new PreTrackScale();
//                    ps.setPredictionNo(model.getPredictionNo());
//                    ps.setValueFlag(DbConstants.IN); //预报调整为使用中
//                    ps.setUploadFlag("1");
//                    ps.setMeasureStation(model.getBaseSpotNo());
//                    ps.setMeasureStationName(model.getBaseSpotName());
//                    this.preTrackScaleMapper.updateByPrimaryKeySelective(ps);
//                }
                num++;
            }
            return num;
        } catch (MarkerMetException e) {
            throw e;
        }
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public int audit(MeterWorkCarActualFirst model) throws MarkerMetException {
        try {
            ckeck(model);
            if (model.getCheckFlag().equals("0")) {
                model.setCheckFlag(DbConstants.VALID);
            } else {
                throw new MarkerMetException(500, "当前状态不可审核");
            }
            int num = meterWorkCarActualFirstMapper.updateByPrimaryKeySelective(model);
            return num;
        } catch (MarkerMetException e) {
            throw e;
        }
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public int unaudit(MeterWorkCarActualFirst model) throws MarkerMetException {
        try {
            ckeck(model);
            if (model.getCheckFlag().equals("1")) {
                model.setCheckFlag(DbConstants.INVALID);
            } else {
                throw new MarkerMetException(500, "该数据未审核");
            }
            int num = meterWorkCarActualFirstMapper.updateByPrimaryKeySelective(model);
            return num;
        } catch (MarkerMetException e) {
            throw e;
        }
    }


    @Override
    @Transactional
    public PageList<MeterWorkCarActualFirst> selectView(Map<Objects, String> parmas, Integer pageNum, Integer pageSize) {
        List<MeterWorkCarActualFirst> rowsCount = meterWorkCarActualFirstMapper.selectView(parmas);
        //system.out.println("数据总条数：" + rowsCount.size());
        PageHelper.startPage(pageNum, pageSize);
        List<MeterWorkCarActualFirst> rows = meterWorkCarActualFirstMapper.selectView(parmas);
        //system.out.println("数据分页条数：" + rows.size());
        PageList pageInfo = new PageList(rows);
        return pageInfo;
    }

    /**
     * 一次计量解除结净
     *
     * @param models
     * @return
     * @throws MarkerMetException
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int remove(List<MeterWorkCarActualFirst> models) throws MarkerMetException {
        try {
            String userId = "";
            String userName = "";
            try{
                UserPayload userPayload = UserPayload.getCurrUser();
                userId = userPayload.getUserCode();
                userName = userPayload.getUserName();
            }catch (Exception e) {
                userId = "system";
                userName = "system";
            }

            int num = 0;
            if (models.size() <= 0 || models == null) {
                throw new MarkerMetException(500, "参数为空!!");
            }

            for(MeterWorkCarActualFirst model: models) {
                MeterWorkCarActualFirst modelTemp = meterWorkCarActualFirstMapper.selectByPrimaryKey(model.getActualFirstNo());
                if(modelTemp != null) {
                    if(modelTemp.getValueFlag().equals("0") || modelTemp.getValueFlag().equals("2")) {
                        throw new MarkerMetException(500, "当前一次数据已结净或者已作废，不允许解除托!!");
                    }
                }
                PreTrackScale pls = preTrackScaleMapper.selectByPrimaryKey(model.getPredictionNo());
                if(pls.getValueFlag().equals("9")) {
                    throw new MarkerMetException(500, "一次数据中包含已结算的委托!!");
                }
            }

            for (MeterWorkCarActualFirst model : models) {
                if (model.getPredictionNo() == null && "".equals(model.getPredictionNo())) {
                    throw new MarkerMetException(500, "该条数据还未匹配！！");
                }
                PreTrackScale pls = preTrackScaleMapper.selectByPrimaryKey(model.getPredictionNo());

                /*
                //2021年5月24日 杨秀东注释，没有预报有效次数这个概念了，预报次数检疫的时候，自动生成新的预报编号；
                pls.setPredictionNo(model.getPredictionNo());
                pls.setEffectiveNum(pls.getEffectiveNum() + 1);
                if (pls.getEffectiveNum() == 0) {
                    pls.setValueFlag(DbConstants.UP);
                }
                if (pls.getEffectiveNum() > 0) {
                    pls.setValueFlag(DbConstants.UP);
                }
                 */
                if (pls == null) {
                    throw new MarkerMetException(500, "数据对应的委托不存在！！");
                }
                pls.setUpdateTime(new Date());
                pls.setUpdateManNo(userId);
                pls.setUpdateManName(userName);
                pls.setValueFlag(DbConstants.VALID);
                pls.setUploadFlag("1");
                preTrackScaleMapper.updateByPrimaryKeySelective(pls);

                //回退至预环节的前一状态; 001021003 = 一次计量
                List<MeterWorkPreLink> mwpls = meterWorkPreLinkService.getNext(model.getPredictionNo(), DbConstants.CALCULATE);
                for (MeterWorkPreLink mwpl : mwpls) {
                    mwpl.setValueFlag("0");//未使用
                    meterWorkPreLinkMapper.updateByPrimaryKey(mwpl);
                }

                //操作日志
                MeterBaseOperationLog logModel = new MeterBaseOperationLog();
                logModel.setId(PublicMethod.IdCreate(2));
                logModel.setCreateManNo(userId);
                logModel.setCreateManName(userName);
                logModel.setCreateTime(new Date());
                logModel.setOperationPage("web端-汽车衡一次数据维护");
                logModel.setOperationFunction("撤销委托");
                logModel.setOperationId(model.getActualFirstNo());
                logModel.setOperationPredictionNo(model.getPredictionNo());
                logModel.setOperationCarnNo(model.getCarNo());
                logModel.setOperationBeforeFix(model.toString());

                MeterWorkCarActualFirst mwcaf = meterWorkCarActualFirstMapper.selectAndRemove(model.getActualFirstNo());

                String actualFirstNo = mwcaf.getActualFirstNo();
                //当一次计量数据是已结净的状态时，同时将该结净数据的另一条一次计量数据自动匹配该委托，并将该结净记录也进行委托匹配
                if (mwcaf.getValueFlag() == "2" || "2".equals(mwcaf.getValueFlag())){
                    MeterWorkCarActual meterWorkCarActual = meterWorkCarActualMapper.selectActual(actualFirstNo);
                    String getActualFirstNo = "";
                    //判断传入的是哪条一次记录
                    if (meterWorkCarActual.getActualFirst1No().equals(actualFirstNo)){
                        getActualFirstNo = meterWorkCarActual.getActualFirst2No();
                    }
                    if (meterWorkCarActual.getActualFirst2No().equals(actualFirstNo)){
                        getActualFirstNo = meterWorkCarActual.getActualFirst1No();
                    }
                    //另一条一次数据进行委托解除
                    MeterWorkCarActualFirst meterWorkCarActualFirst1 = meterWorkCarActualFirstMapper.selectAndRemove(getActualFirstNo);
                    meterWorkCarActualFirst1.setIsPreScale("0");
                    meterWorkCarActualFirstMapper.updateByPrimaryKey(meterWorkCarActualFirst1);
                    //将该一次记录的结净数据委托解除
                    MeterWorkCarActual mwca = meterWorkCarActualMapper.cleanPredcition(meterWorkCarActual.getActualNo());
                    mwca.setIsPreScale("0");
                    meterWorkCarActualMapper.updateByPrimaryKey(mwca);
                }

                // 将一次计量数据设置为未匹配状态
                //mwcaf.setValueFlag("2");
                mwcaf.setUpdateManNo(userId);
                mwcaf.setUpdateManName(userName);
                mwcaf.setUpdateTime(new Date());
                mwcaf.setNote("一次数据撤销委托");
                mwcaf.setIsPreScale("0");
                meterWorkCarActualFirstMapper.updateByPrimaryKey(mwcaf);

                logModel.setOperationAfterFix(mwcaf.toString());
                meterBaseOperationLogMapper.insertSelective(logModel);
                num++;
            }
            return num;
        } catch (MarkerMetException e) {
            throw e;
        }
    }


    /**
     * 一次计量数据匹配
     *
     * @param actualFirstNo
     * @param predictionNo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public RESTfulResult match(String actualFirstNo, String predictionNo) {
        RESTfulResult rm = new RESTfulResult();
        rm.setFailed();
        try {
            UserPayload userPayload = UserPayload.getCurrUser();
            String userId = userPayload.getUserCode();
            String userName = userPayload.getUserName();

            Assert.isTrue(StringUtils.isNotEmpty(actualFirstNo), "作业编号为空");
            Assert.isTrue(StringUtils.isNotEmpty(predictionNo), "预报编号为空");
            PreTrackScale pts = preTrackScaleMapper.selectByPrimaryKey(predictionNo);
            Assert.isTrue(pts != null, "委托编号：" + predictionNo + "未查询到有效委托信息");
            Assert.isTrue(!pts.getValueFlag().equals("9"), "委托编号：" + predictionNo + "已结算不允许匹配委托");
            MeterWorkCarActualFirst model = meterWorkCarActualFirstMapper.selectByPrimaryKey(actualFirstNo);
            Assert.isTrue(model != null, "一次数据不存在");
            Assert.isTrue(!model.getValueFlag().equals("2"), "一次数据已结净,不允许匹配委托，请在结净数据维护中进行结净匹配委托");
            Assert.isTrue(model.getPredictionNo() == null && StringUtils.isEmpty(model.getPredictionNo()), "一次数据已匹配,不允许匹配委托");

            //操作日志
            MeterBaseOperationLog logModel = new MeterBaseOperationLog();
            logModel.setId(PublicMethod.IdCreate(2));
            logModel.setCreateManNo(userId);
            logModel.setCreateManName(userName);
            logModel.setCreateTime(new Date());
            logModel.setOperationPage("web端-汽车衡一次数据维护");
            logModel.setOperationFunction("匹配委托");
            logModel.setOperationId(model.getActualFirstNo());
            logModel.setOperationPredictionNo(model.getPredictionNo());
            logModel.setOperationCarnNo(model.getCarNo());
            logModel.setOperationBeforeFix(model.toString());

            //匹配委托操作
            MeterWorkCarActualFirst modelTemp = meterWorkCarActualFirstMapper.selectAndMatch(actualFirstNo, pts.getPredictionNo());
            BeanUtils.copyProperties(modelTemp, model);
            model.setIsPreScale("1");
            model.setUpdateManNo(userId);
            model.setUpdateManName(userName);
            model.setUpdateTime(new Date());
            model.setNote("一次数据匹配委托");
            model.setPredictionNo(pts.getPredictionNo());
            meterWorkCarActualFirstMapper.updateByPrimaryKeySelective(model);

            pts.setUpdateTime(new Date());
            pts.setUpdateManNo(userId);
            pts.setUpdateManName(userName);
            pts.setValueFlag(DbConstants.IN); //2021年5月24日  预报直接就写成【使用中】
            pts.setUploadFlag("1");
            pts.setPredictionType("1");
            pts.setMeasureStation(model.getBaseSpotNo());
            pts.setMeasureStationName(model.getBaseSpotName());
            preTrackScaleMapper.updateByPrimaryKeySelective(pts);

            logModel.setOperationAfterFix(model.toString());
            meterBaseOperationLogMapper.insertSelective(logModel);

            rm.setSucceed();
            rm.setCode("200");
            rm.setMessage("匹配委托成功");
            rm.setData(model);
        }catch (Exception e) {
            e.printStackTrace();
            rm.setMessage("操作异常：>>>" + e.getMessage());
        }
        return rm;

//            if (StringUtils.isEmpty(actualFirstNo)) {
//                throw new MarkerMetException(500, "计量作业编号为空!!");
//            }
//            if (predictionNo == null || "".equals(predictionNo)) {
//                throw new MarkerMetException(500, "预报编号为空!!");
//            }
//            PreTrackScale pts = preTrackScaleMapper.selectByPrimaryKey(predictionNo);
//            if (pts == null) {
//                throw new MarkerMetException(500, "该预报信息不存在");
//            }
//            MeterWorkCarActualFirst meterWorkCarActualFirst = meterWorkCarActualFirstMapper.selectByPrimaryKey(actualFirstNo);
//            if (meterWorkCarActualFirst == null) {
//                throw new MarkerMetException(500, "该计量作业信息不存在");
//            }
//            if (meterWorkCarActualFirst.getPredictionNo() != null && !"".equals(meterWorkCarActualFirst.getPredictionNo())) {
//                throw new MarkerMetException(500, "该计量作业已匹配！！");
//            }
//            MeterWorkCarActualFirst model = meterWorkCarActualFirstMapper.selectAndMatch(actualFirstNo, predictionNo);
//            //区分预报的类型对状态进行修改
//            /*
//            //逻辑异常，此处预报的有效次数默认都是1，在匹配完成后，预报状态应当变为4【使用中】
//            pts.setEffectiveNum(pts.getEffectiveNum() - 1);
//            if (pts.getEffectiveNum() == 0) {
//                pts.setValueFlag(DbConstants.UP);
//            } else {
//                pts.setValueFlag(DbConstants.IN);
//            }
//             */
//            //将预环节的前置包括本环节都使用；001021003 = 一次计量
////            List<MeterWorkPreLink> mwpls = meterWorkPreLinkService.getPer(predictionNo, DbConstants.CALCULATE);
////            for (MeterWorkPreLink mwpl : mwpls) {
////                mwpl.setValueFlag("2");//已使用
////                meterWorkPreLinkMapper.updateByPrimaryKey(mwpl);
////            }
//            //当一次计量数据是已结净的状态时，同时将该结净数据的另一条一次计量数据自动匹配该委托，并将该结净记录也进行委托匹配
//            if ("2".equals(meterWorkCarActualFirst.getValueFlag()) || "0".equals(meterWorkCarActualFirst.getValueFlag())) {
//                throw new MarkerMetException(500, "该计量作业信息已结净或已作废");
//            }
//            if(pts != null) {
//                MeterWorkCarActual meterWorkCarActual = meterWorkCarActualMapper.selectActual(actualFirstNo);
//                String getActualFirstNo = "";
//                //判断传入的是哪条一次记录
//                if (meterWorkCarActual.getActualFirst1No().equals(actualFirstNo)){
//                    getActualFirstNo = meterWorkCarActual.getActualFirst2No();
//                }
//                if (meterWorkCarActual.getActualFirst2No().equals(actualFirstNo)){
//                    getActualFirstNo = meterWorkCarActual.getActualFirst1No();
//                }
//                //另一条一次数据进行委托解除
//                MeterWorkCarActualFirst meterWorkCarActualFirst1 = meterWorkCarActualFirstMapper.selectAndMatch(getActualFirstNo,predictionNo);
//                meterWorkCarActualFirst1.setIsPreScale("1");
//                meterWorkCarActualFirstMapper.updateByPrimaryKey(meterWorkCarActualFirst1);
//                //将该一次记录的结净数据委托解除
//                MeterWorkCarActual mwca = meterWorkCarActualMapper.mathPredcition(meterWorkCarActual.getActualNo(),predictionNo);
//                mwca.setIsPreScale("1");
//                mwca.setUploadFlag("1");
//                meterWorkCarActualMapper.updateByPrimaryKey(mwca);
//
//                pts.setUpdateTime(new Date());
//                pts.setUpdateManNo("system");
//                pts.setUpdateManName("一次计量数据匹配操作");
//                pts.setValueFlag(DbConstants.IN); //2021年5月24日  预报直接就写成【使用中】
//                pts.setUploadFlag("1");
//                pts.setMeasureStation(mwca.getNetSpot3No());
//                pts.setMeasureStationName(mwca.getNetSpot3Name());
//                preTrackScaleMapper.updateByPrimaryKey(pts);
//            }
//            // 设置为已匹配状态
//            //model.setValueFlag("1");
//            model.setIsPreScale("1");
//            meterWorkCarActualFirstMapper.updateByPrimaryKey(model);
//            return model;
//        } catch (MarkerMetException e) {
//            throw e;
//        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public PageList<MeterWorkCarActualFirst> selectTa(Map<String, Object> parmas, String weightType, Integer pageNum, Integer pageSize) {
        parmas.put("weightType", weightType);
        PageHelper.startPage(pageNum, pageSize);
        List<MeterWorkCarActualFirst> mwcafs = meterWorkCarActualFirstMapper.selectTa(parmas);
        PageList pageInfo = new PageList(mwcafs);
        return pageInfo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public PageList<MeterWorkCarActualFirst> selectNet(String weightType, String carNo, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<MeterWorkCarActualFirst> mwcafs = meterWorkCarActualFirstMapper.selectNet(weightType, carNo);
        PageList pageInfo = new PageList(mwcafs);
        return pageInfo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public PageList<StaffPerformanceAnalysis> analysis(String startTime, String endTime, Integer pageNum, Integer pageSize) {
        HashMap<String, Object> obj = new HashMap<>();
        obj.put("startTime", startTime);
        obj.put("endTime", endTime);
        PageHelper.startPage(pageNum, pageSize);
        List<StaffPerformanceAnalysis> list = meterWorkCarActualFirstMapper.analysis(obj);
        PageList pageInfo = new PageList(list);
        return pageInfo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public PageList<UtensilDto> utensil(String startTime, String endTime, Integer pageNum, Integer pageSize) {
        HashMap<String, Object> obj = new HashMap<>();
        obj.put("startTime", startTime);
        obj.put("endTime", endTime);
        PageHelper.startPage(pageNum, pageSize);
        List<UtensilDto> list = meterWorkCarActualFirstMapper.utensil(obj);
        PageList pageInfo = new PageList(list);
        return pageInfo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<MeterTypeDto> meterType(String baseSpotNo, String startTime, String endTime) {
        HashMap<String, Object> obj = new HashMap<>();
        obj.put("baseSpotNo", baseSpotNo);
        obj.put("startTime", startTime);
        obj.put("endTime", endTime);
        List<MeterTypeDto> list = meterWorkCarActualFirstMapper.meterType(obj);
        return list;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<TimesDto> daily(String baseSpotNo, String startTime, String endTime) {
        HashMap<String, Object> obj = new HashMap<>();
        obj.put("baseSpotNo", baseSpotNo);
        obj.put("startTime", startTime);
        obj.put("endTime", endTime);
        List<TimesDto> list = meterWorkCarActualFirstMapper.daily(obj);
        return list;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<TimesDto> period(String baseSpotNo, String startTime, String endTime) {
        HashMap<String, Object> obj = new HashMap<>();
        obj.put("baseSpotNo", baseSpotNo);
        obj.put("startTime", startTime);
        obj.put("endTime", endTime);
        List<TimesDto> list = meterWorkCarActualFirstMapper.period(obj);
        List<TimesDto> tds = new ArrayList<>();
        for (int i = 0; i < 24; i++) {
            TimesDto td = new TimesDto();
            String times1 = String.format("%02d" + ":00:00", i);
            td.setTimes(times1);
            td.setNum(0.0);
            for (TimesDto dto : list) {
                if (td.getTimes().equals(dto.getTimes())) {
                    td.setNum(dto.getNum());
                }
            }
            tds.add(td);
        }
        return tds;
    }

    @Override
    @Transactional
    public List<MeterWorkCarActualFirst> detailed(String times, String num) {
        HashMap<String, Object> obj = new HashMap<>();
        obj.put("spotTypeNo", DbConstants.CAR);
        obj.put("times", times);
        obj.put("num", num);
        List<MeterWorkCarActualFirst> list = meterWorkCarActualFirstMapper.detailed(obj);
        return list;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public PageList<AbnormalDto> abnormal(String baseSpotNo, String startTime, String endTime, Integer pageNum, Integer pageSize) {
        HashMap<String, Object> obj = new HashMap<>();
        obj.put("baseSpotNo", baseSpotNo);
        obj.put("startTime", startTime);
        obj.put("endTime", endTime);
        PageHelper.startPage(pageNum, pageSize);
        List<AbnormalDto> list = meterWorkCarActualFirstMapper.abnormal(obj);
        PageList pageInfo = new PageList(list);
        return pageInfo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public PageList<MeterWorkCarActualFirst> getByAbnormal(String meterReasonNo, String meterReasonName, Integer pageNum, Integer pageSize) {
        HashMap<String, Object> obj = new HashMap<>();
        obj.put("meterReasonNo", meterReasonNo);
        obj.put("meterReasonName", meterReasonName);
        PageHelper.startPage(pageNum, pageSize);
        List<MeterWorkCarActualFirst> list = meterWorkCarActualFirstMapper.getByAbnormal(obj);
        PageList pageInfo = new PageList(list);
        return pageInfo;
    }

    private void ckeck1(MeterWorkCarActualFirst model) throws MarkerMetException {
        if (model.getCarNo() == null || model.getCarNo().equals("")) {
            throw new MarkerMetException(500, "车号不能为空");
        }
        if (model.getBaseSpotNo() == null || model.getBaseSpotNo().equals("")) {
            throw new MarkerMetException(500, "计量点编号不能为空");
        }
        if (model.getBaseSpotName() == null || model.getBaseSpotName().equals("")) {
            throw new MarkerMetException(500, "计量点名称不能为空");
        }

        // 判断是否带有委托
        if (model.getPredictionNo() != null && !"".equals(model.getPredictionNo())) {
            PreTrackScale pre = new PreTrackScale();
            pre.setPredictionNo(model.getPredictionNo());
            pre.setValueFlag("4");
            pre.setUploadFlag("1");
            pre.setMeasureStation(model.getBaseSpotNo());
            pre.setMeasureStationName(model.getBaseSpotName());
            preTrackScaleMapper.updateByPrimaryKeySelective(pre);
        }

        if (StringUtils.isEmpty(model.getActualFirstNo())) {
            model.setValueFlag(DbConstants.VALID);
            model.setCheckFlag(DbConstants.INVALID);
        } else {
            model.setUpdateTime(new Date());
        }
    }


    private void ckeck(MeterWorkCarActualFirst model) throws MarkerMetException {
        if (model.getCarNo() == null || model.getCarNo().equals("")) {
            throw new MarkerMetException(500, "车号不能为空");
        }
//        if (model.getMeterTypeNo() == null || model.getMeterTypeNo().equals("")) {
//            throw new MarkerMetException(500, "业务类型编号不能为空");
//        }
//        if (model.getMeterTypeName() == null || model.getMeterTypeName().equals("")) {
//            throw new MarkerMetException(500, "业务类型名称不能为空");
//        }
        if (model.getBaseSpotNo() == null || model.getBaseSpotNo().equals("")) {
            throw new MarkerMetException(500, "计量点编号不能为空");
        }
        if (model.getBaseSpotName() == null || model.getBaseSpotName().equals("")) {
            throw new MarkerMetException(500, "计量点名称不能为空");
        }
        UserPayload payload = UserPayload.getCurrUser();
        String userId = payload.getUserCode();
        String userName = payload.getUserName();
        if (StringUtils.isEmpty(model.getActualFirstNo())) {
            model.setCreateManNo(userId);
            model.setCreateManName(userName);
            model.setValueFlag(DbConstants.VALID);
            model.setCheckFlag(DbConstants.INVALID);
        } else {
            model.setUpdateTime(new Date());
            model.setUpdateManNo(userId);
            model.setUpdateManName(userName);
        }
    }

    private void ckeckcar(MeterWorkCarActualFirst model) throws MarkerMetException {
        if (model.getActualFirstNo() == null || "".equals(model.getActualFirstNo())) {
            throw new MarkerMetException(500, "操作数据主键不能为空");
        }
        if (model.getValueFlag() == "2") {
            throw new MarkerMetException(500, "已经结净的数据不能进行修改");
        }
        if (model.getPredictionNo() != null || "".equals(model.getPredictionNo())) {
            throw new MarkerMetException(500, "已经匹配委托的数据无法修改车号！！");
        }
        if (model.getCarNo() == null || model.getCarNo().equals("")) {
            throw new MarkerMetException(500, "车号不能为空");
        }
        UserPayload payload = UserPayload.getCurrUser();
        String userId = payload.getUserCode();
        String userName = payload.getUserName();
        model.setUpdateTime(new Date());
        model.setUpdateManNo(userId);
        model.setUpdateManName(userName);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public RESTfulResult doQueryWf(MeterWorkCarActualFirst oci) {
        RESTfulResult rm = new RESTfulResult();
        try {
            rm.setCode("200");
            oci.setMeterWeight(null);
            oci.setAddWeight(null);
            oci.setMeterNum(null);
            oci.setShipmentGrossWeight(null);
            oci.setShipmentNetWeight(null);
            oci.setShipmentNum(null);
            Map<String, Object> map = FieldsCollector.beanToMap(oci);
            rm.setData(meterWorkCarActualFirstMapper.selectByParameters(map));
        } catch (Exception ex) {
            rm.setCode("500");
            rm.setMessage("查询失败：" + ex.getMessage());
        }
        return rm;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public RESTfulResult queryFirst(String carNo) {
        RESTfulResult rm = new RESTfulResult();
        try {
            rm.setCode("200");
            rm.setData(meterWorkCarActualFirstMapper.selectByCarNo(carNo));
        } catch (Exception ex) {
            rm.setCode("500");
            rm.setMessage("查询失败：" + ex.getMessage());
        }
        return rm;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public RESTfulResult doUpdateWf(MeterWorkCarActualFirst oci) {
        RESTfulResult rm = new RESTfulResult();
        try {
            rm.setCode("200");
            meterWorkCarActualFirstMapper.updateByPrimaryKeySelective(oci);
        } catch (Exception ex) {
            rm.setCode("500");
            rm.setMessage("修改数据失败：" + ex.getMessage());
        }
        return rm;
    }

    /**
     * 公共的存储历史皮重
     *
     * @param oci
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void doSaveHisTare(MeterWorkCarActualFirst oci) {
        //获取ID
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
        String afl = formatter.format(oci.getCreateTime());
        //查找相应车辆有效的历史皮重信息
        MeterBaseHisTareData mbtd = new MeterBaseHisTareData();
        mbtd.setCarNo(oci.getCarNo());
        mbtd.setValueFlag("0");
        Map<String, Object> map = FieldsCollector.beanToMap(mbtd);
        List<MeterBaseHisTareData> lmOne = meterBaseHisTareDataMapper.selectByParameters(map);
        if (lmOne != null && lmOne.size() > 0) {
            //说明存在历史皮重，则执行修改操作
            mbtd.setDataNo(lmOne.get(0).getDataNo());
            mbtd.setBaseSpotNo(oci.getBaseSpotNo());
            mbtd.setBaseSpotName(oci.getBaseSpotName());
            mbtd.setMeterWeight(Math.round(oci.getMeterWeight().doubleValue()));
            mbtd.setUpWeight(oci.getMeterWeight().longValue()); //上次皮重
            //查询前几次皮重
            double db = 0.0;
            try {
                MeterBaseHisTareDetail mbhtd = new MeterBaseHisTareDetail();
                mbhtd.setCarNo(oci.getCarNo());
                Map<String, Object> map1 = FieldsCollector.beanToMap(mbhtd);
                List<MeterBaseHisTareDetail> lmd = meterBaseHisTareDetailMapper.selectByParametersTop(map1);
                if(lmd!=null&&lmd.size()!=0){
                    if(lmd.size()>2){//减去最大最小值
                        lmd.remove(0);
                        lmd.remove(lmd.size()-1);
                    }
                    double sum = 0.0;
                    for (MeterBaseHisTareDetail meterBaseHisTareDetail : lmd) {
                        sum+=meterBaseHisTareDetail.getMeterWeight();
                    }
                    db = sum / lmd.size();
                }
            } catch (Exception e) {
                logger.error("计算平均皮重出错", e);
            }
            //  (之前的重量*次数)/(次数+1)
            //double db = (lmOne.get(0).getAvgWeight() * lmOne.get(0).getMeterNum() + lmOne.get(0).getMeterWeight()) / (lmOne.get(0).getMeterNum() + 1);
            mbtd.setAvgWeight(Math.round(db));//平均皮重
            mbtd.setMeterNum(lmOne.get(0).getMeterNum() + 1);
            mbtd.setCreateTime(new Date());
            meterBaseHisTareDataMapper.updateByPrimaryKeySelective(mbtd);
        } else {
            //新增操作
            String no = meterBaseHisTareDataMapper.getNewID(afl);
            mbtd.setDataNo(afl + no);
            mbtd.setBaseSpotNo(oci.getBaseSpotNo());
            mbtd.setBaseSpotName(oci.getBaseSpotName());
            mbtd.setMeterWeight(Math.round(oci.getMeterWeight().doubleValue()));
            mbtd.setUpWeight(oci.getMeterWeight().longValue()); //上次皮重
            mbtd.setAvgWeight(Math.round(oci.getMeterWeight().doubleValue()));//平均皮重
            mbtd.setMeterNum(1l);
            mbtd.setMeterTime(oci.getCreateTime());
            mbtd.setCreateTime(oci.getCreateTime());
            meterBaseHisTareDataMapper.insert(mbtd);
        }
        MeterBaseHisTareDetail mbhtd = new MeterBaseHisTareDetail();
        String no = meterBaseHisTareDetailMapper.getNewID(afl);
        mbhtd.setDetailNo(PublicMethod.IdCreate(3));
        mbhtd.setActualFirstNo(oci.getActualFirstNo());
        mbhtd.setBaseSpotNo(oci.getBaseSpotNo());
        mbhtd.setBaseSpotName(oci.getBaseSpotName());
        mbhtd.setCarNo(oci.getCarNo());
        mbhtd.setMeterOrder("1");
        mbhtd.setMeterTime(oci.getCreateTime());
        mbhtd.setMeterWeight(oci.getMeterWeight().longValue());
        meterBaseHisTareDetailMapper.insert(mbhtd);
    }

    /**
     * 公共的存储历史皮重
     *
     * @param oci
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void doSaveHisTare(MeterWorkCarActualFirst oci, String tareType) {
        //获取ID
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
        String afl = formatter.format(oci.getCreateTime());
        //查找相应车辆有效的历史皮重信息
        MeterBaseHisTareData mbtd = new MeterBaseHisTareData();
        mbtd.setCarNo(oci.getCarNo());
        mbtd.setValueFlag("0");
        mbtd.setTareType(tareType);
        Map<String, Object> map = FieldsCollector.beanToMap(mbtd);
        List<MeterBaseHisTareData> lmOne = meterBaseHisTareDataMapper.selectByParameters(map);
        if (lmOne != null && lmOne.size() > 0) {
            //说明存在历史皮重，则执行修改操作
            mbtd.setDataNo(lmOne.get(0).getDataNo());
            mbtd.setBaseSpotNo(oci.getBaseSpotNo());
            mbtd.setBaseSpotName(oci.getBaseSpotName());
            mbtd.setMeterWeight(Math.round(oci.getMeterWeight().doubleValue()));
            mbtd.setUpWeight(oci.getMeterWeight().longValue()); //上次皮重
            //查询前几次皮重
            double db = 0.0;
            try {
                MeterBaseHisTareDetail mbhtd = new MeterBaseHisTareDetail();
                mbhtd.setCarNo(oci.getCarNo());
                Map<String, Object> map1 = FieldsCollector.beanToMap(mbhtd);
                List<MeterBaseHisTareDetail> lmd = meterBaseHisTareDetailMapper.selectByParametersTop(map1);
                if(lmd!=null&&lmd.size()!=0){
                    if(lmd.size()>2){
                        lmd.remove(0);
                        lmd.remove(lmd.size()-1);
                    }
                    double sum = 0.0;
                    for (MeterBaseHisTareDetail meterBaseHisTareDetail : lmd) {
                        sum+=meterBaseHisTareDetail.getMeterWeight();
                    }
                    db = sum / lmd.size();
                }
            } catch (Exception e) {
                logger.error("计算平均皮重出错", e);
            }
            //  (之前的重量*次数)/(次数+1)
            //double db = (lmOne.get(0).getAvgWeight() * lmOne.get(0).getMeterNum() + lmOne.get(0).getMeterWeight()) / (lmOne.get(0).getMeterNum() + 1);
            mbtd.setAvgWeight(Math.round(db));//平均皮重
            mbtd.setMeterNum(lmOne.get(0).getMeterNum() + 1);
            mbtd.setCreateTime(new Date());
            meterBaseHisTareDataMapper.updateByPrimaryKeySelective(mbtd);
        } else {
            //新增操作
            String no = meterBaseHisTareDataMapper.getNewID(afl);
            mbtd.setDataNo(afl + no);
            mbtd.setBaseSpotNo(oci.getBaseSpotNo());
            mbtd.setBaseSpotName(oci.getBaseSpotName());
            mbtd.setMeterWeight(Math.round(oci.getMeterWeight().doubleValue()));
            mbtd.setUpWeight(oci.getMeterWeight().longValue()); //上次皮重
            mbtd.setAvgWeight(Math.round(oci.getMeterWeight().doubleValue()));//平均皮重
            mbtd.setMeterNum(1l);
            mbtd.setMeterTime(oci.getCreateTime());
            mbtd.setCreateTime(oci.getCreateTime());
            meterBaseHisTareDataMapper.insert(mbtd);
        }
        MeterBaseHisTareDetail mbhtd = new MeterBaseHisTareDetail();
        String no = meterBaseHisTareDetailMapper.getNewID(afl);
        mbhtd.setDetailNo(PublicMethod.IdCreate(3));
        mbhtd.setActualFirstNo(oci.getActualFirstNo());
        mbhtd.setBaseSpotNo(oci.getBaseSpotNo());
        mbhtd.setBaseSpotName(oci.getBaseSpotName());
        mbhtd.setCarNo(oci.getCarNo());
        mbhtd.setMeterOrder("1");
        mbhtd.setMeterTime(oci.getCreateTime());
        mbhtd.setMeterWeight(oci.getMeterWeight().longValue());
        meterBaseHisTareDetailMapper.insert(mbhtd);
    }


    /**
     * 图片保存信息
     *
     * @param oci
     * @throws Exception
     */
    @Transactional(rollbackFor = Exception.class)
    public void SaveImg(MeterWorkCarActualFirst oci) throws Exception {
        //查下当前配置的摄像头有多少个
        MeterBaseVideoinfo mbv = new MeterBaseVideoinfo();
        mbv.setPointid(oci.getBaseSpotNo());
        Map<String, Object> map = FieldsCollector.beanToMap(mbv);
        List<MeterBaseVideoinfo> lmb = meterBaseVideoinfoMapper.selectByParameters(map);
        if (ListUtils.isNotEmpty(lmb) && lmb.size() > 0) {
            MeterBaseVideoinfo mb = lmb.get(0);

            long i = 0;
            //https://www.cnblogs.com/alice-cj/p/10363356.html
            Class clazz = mb.getClass();
            Object obj = clazz.newInstance();
            Field[] fields = clazz.getDeclaredFields();
            for (Field field : fields) {
                if (field.getName().contains("pointname")) {
                    field.setAccessible(true); // 私有属性必须设置访问权限
                    Object resultValue = field.get(obj);
                    if (resultValue != null && resultValue.toString().trim().length() > 0) {
                        i++;
                    }
                }
            }
            MeterWorkImage mw= meterWorkImageMapper.selectByPrimaryKey("C" + oci.getActualFirstNo());
            //METER_WORK_IMAGE
            MeterWorkImage mwi = new MeterWorkImage();
            mwi.setActualFirstNo("C" + oci.getActualFirstNo());
            mwi.setImageTime(oci.getCreateTime());
            mwi.setImageNum(++i);//因为界面上会存储一个界面截图，所以此处比摄像头要多1条
            for (int k = 1; k <= i; k++) {
                Field fName = mwi.getClass().getDeclaredField("imageFile" + i);
                fName.setAccessible(true);
                fName.set(mwi, oci.getBaseSpotNo() + "_" + oci.getActualFirstNo() + "_" + i);
            }
            if(mw != null){
                meterWorkImageMapper.updateByPrimaryKeySelective(mwi);
            }else{
                meterWorkImageMapper.insertSelective(mwi);
            }
        }
    }

    /**
     * 内倒车辆存储一次计量数据
     *
     * @param oci
     * @param saveTare 0 不保存历史皮，1保存历史皮
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(value = "tm", rollbackFor = Exception.class)
    public RESTfulResult doAddInnerWf(MeterWorkCarActualFirst oci, String saveTare, MeterMonitorNote note) throws Exception {
        RESTfulResult rm = new RESTfulResult();
        rm.setFailed();
        try{
            //1、存储一次计量信息
            SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
            String afl = formatter.format(oci.getCreateTime());
//        String no = meterWorkCarActualFirstMapper.getNewID(afl);
//        oci.setActualFirstNo(formatter.format(new Date()) + no);

            String no = PublicMethod.IdCreate(3);
            oci.setActualFirstNo(no);
            oci.setValueFlag("1");
        /*//
        if(oci.getWeightType().equals("0")){

        }
        if(oci.getWeightType().equals("1")){

        }*/
            oci.setCreateTime(new Date());
            meterWorkCarActualFirstMapper.insert(oci);

            //2、存储历史皮重及历史皮重明细信息
            if ("1".equals(saveTare)) {
                doSaveHisTare(oci);
            }
            //3、保存图片
            //SaveImg(oci);
            //4、修改计量监控
            updateMonitor(oci.getBaseSpotNo());

            //保存日志
            saveNote(note);

            updateMonitorOver(oci.getActualFirstNo(), oci.getBaseSpotNo());

            //补充附加重量的数据
            if (StringUtils.isNotEmpty(oci.getAddWgtPk())) {
                insertAddWgtNo(oci.getActualFirstNo(), oci.getAddWgtPk(), oci.getCreateManNo(), oci.getCreateManName());
            }

            //重量类型为毛重则调用接口为
            String flag = "";
        /*
        if("0".equals(oci.getWeightType())){
            flag = transferParamForLims(oci.getCarNo(),oci.getMatterNo(),oci.getReceivingUintName(),oci.getForwardingUnitName(),"",oci.getCreateTime(),oci.getMeterWeight().toString(),oci.getActualFirstNo());
        }
        //*/
            rm.setSucceed();
            rm.setCode("200");
            rm.setData(oci.getActualFirstNo());
            rm.setMessage(flag);
        }catch(Exception e) {
            e.printStackTrace();
            rm.setFailed();
            rm.setMessage("操作异常，请确认！！>>>" + e.getMessage());
        }
        return rm;
    }

    /**
     * 内倒车辆结净
     *
     * @param secondDb 二次计量数据
     * @param netDb    净重数据
     * @param saveTare 0 不保存历史皮，1保存历史皮
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(value = "tm", rollbackFor = Exception.class)
    public RESTfulResult doAddNetInnerWf(MeterWorkCarActualFirst secondDb, MeterWorkCarActual netDb, String saveTare, MeterMonitorNote note) throws Exception {
        RESTfulResult rm = new RESTfulResult();
        rm.setFailed();
        rm.setCode("500");
        try{
            //1、存储当前计量的数据
            SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
            String afl = formatter.format(new Date());
//            String no = meterWorkCarActualFirstMapper.getNewID(afl);
//            secondDb.setActualFirstNo(formatter.format(new Date()) + no);

            String no = PublicMethod.IdCreate(3);
            secondDb.setActualFirstNo(no);

            secondDb.setValueFlag("2");//结净
            secondDb.setCreateTime(new Date());
            meterWorkCarActualFirstMapper.insertSelective(secondDb);

            //修改一次计量数据为结净
            MeterWorkCarActualFirst firstUpdate = new MeterWorkCarActualFirst();
            //2、存储结净数据
            if (secondDb.getMeterWeight().equals(netDb.getTareWeight())) {
                //二次重量如果跟皮重一样
                netDb.setActualFirst2No(secondDb.getActualFirstNo());
                netDb.setTareTime(secondDb.getCreateTime());
                netDb.setBaseSpot2No(secondDb.getBaseSpotNo());
                netDb.setBaseSpot2Name(secondDb.getBaseSpotName());
                MeterWorkCarActualFirst modelTemp = meterWorkCarActualFirstMapper.selectByPrimaryKey(netDb.getActualFirst1No());
                if(modelTemp != null) {
                    netDb.setBaseSpot1No(modelTemp.getBaseSpotNo());
                    netDb.setBaseSpot1Name(modelTemp.getBaseSpotName());
                }
                firstUpdate.setActualFirstNo(netDb.getActualFirst1No());
                firstUpdate.setWeightType("0");
            } else {
                netDb.setActualFirst1No(secondDb.getActualFirstNo());
                netDb.setGrossTime(secondDb.getCreateTime());
                netDb.setBaseSpot1No(secondDb.getBaseSpotNo());
                netDb.setBaseSpot1Name(secondDb.getBaseSpotName());
                MeterWorkCarActualFirst modelTemp = meterWorkCarActualFirstMapper.selectByPrimaryKey(netDb.getActualFirst2No());
                if(modelTemp != null) {
                    netDb.setBaseSpot2No(modelTemp.getBaseSpotNo());
                    netDb.setBaseSpot2Name(modelTemp.getBaseSpotName());
                }
                firstUpdate.setActualFirstNo(netDb.getActualFirst2No());
                firstUpdate.setWeightType("1");
            }

            //3、修改第一次存储的计量数据状态为结净
            if (firstUpdate.getActualFirstNo() != null) {
                firstUpdate.setValueFlag("2");
                meterWorkCarActualFirstMapper.updateByPrimaryKeySelective(firstUpdate);
            }

            //判断结净数据是否匹配委托
            if (StringUtils.isNotEmpty(netDb.getPredictionNo())) {
                MeterWorkCarActualFirst meca1 = meterWorkCarActualFirstMapper.selectAndMatch(netDb.getActualFirst1No(), netDb.getPredictionNo());
                meca1.setIsPreScale("1");
                MeterWorkCarActualFirst meca2 = meterWorkCarActualFirstMapper.selectAndMatch(netDb.getActualFirst2No(), netDb.getPredictionNo());
                meca2.setIsPreScale("1");
                meterWorkCarActualFirstMapper.updateByPrimaryKeySelective(meca1);
                meterWorkCarActualFirstMapper.updateByPrimaryKeySelective(meca2);
                PreTrackScale preTrackScale = new PreTrackScale();
                preTrackScale.setPredictionNo(netDb.getPredictionNo());
                preTrackScale.setValueFlag("2");
                preTrackScale.setUploadFlag("1");
                preTrackScale.setLineDesc("0");
                preTrackScale.setMeasureStation(netDb.getNetSpot3No());
                preTrackScale.setMeasureStationName(netDb.getNetSpot3Name());
                preTrackScaleMapper.updateByPrimaryKeySelective(preTrackScale);
                PreTrackScale pres = preTrackScaleMapper.selectBypredictionNo(netDb.getPredictionNo());
                if(pres != null && pres.getReceiverRemark() != null && (pres.getReceiverRemark().equals("H01") || pres.getReceiverRemark().equals("H02"))){
                    netDb.setPredictionType("7");
                }
            }
            // 判断当前数据是否存在委托
//            if (netDb.getPredictionNo() != null && "".equals(netDb.getPredictionNo())) {
//                MeterWorkCarActualFirst gross = meterWorkCarActualFirstMapper.selectByPrimaryKey(netDb.getActualFirst1No());
//                if ((gross.getPredictionNo() == null || "".equals(gross.getPredictionNo()))) {
//                    // 如果毛重数据还未匹配委托，则匹配委托操作
//                    MeterWorkCarActualFirst meca1 = meterWorkCarActualFirstMapper.selectAndMatch(gross.getActualFirstNo(), netDb.getPredictionNo());
//                    meterWorkCarActualFirstMapper.updateByPrimaryKeySelective(meca1);
//                    PreTrackScale preTrackScale = new PreTrackScale();
//                    preTrackScale.setPredictionNo(netDb.getPredictionNo());
//                    preTrackScale.setValueFlag("2");
//                    preTrackScale.setUploadFlag("1");
//                    preTrackScaleMapper.updateByPrimaryKeySelective(preTrackScale);
//                }
//            }
//            String no1 = meterWorkCarActualMapper.getNewID(afl);
//            netDb.setActualNo(afl + no1);
            String no1 = PublicMethod.IdCreate(3);
            netDb.setActualNo(no1);
            if (netDb != null && netDb.getNetWeight() != null) {
                //2021年3月7日 净重保留两位小数；
                BigDecimal net;
                net = new BigDecimal(String.valueOf(netDb.getNetWeight())).setScale(2, BigDecimal.ROUND_HALF_UP);
                netDb.setNetWeight(net);
            }
            netDb.setUploadFlag("1");
            netDb.setCreateTime(new Date());
            if(netDb.getGrossTime().compareTo(netDb.getTareTime()) >= 0) {
                netDb.setNetSpot3No(netDb.getBaseSpot1No());
                netDb.setNetSpot3Name(netDb.getBaseSpot1Name());
                netDb.setNetManNo(netDb.getGrossManNo());
                netDb.setNetManName(netDb.getGrossManName());
                netDb.setNetTime(netDb.getGrossTime());
                netDb.setCreateTime(netDb.getGrossTime());
                netDb.setCreateManName(netDb.getGrossManName());
            }else {
                netDb.setNetSpot3No(netDb.getBaseSpot2No());
                netDb.setNetSpot3Name(netDb.getBaseSpot2Name());
                netDb.setNetManNo(netDb.getTareManNo());
                netDb.setNetManName(netDb.getTareManName());
                netDb.setNetTime(netDb.getTareTime());
                netDb.setCreateTime(netDb.getTareTime());
                netDb.setCreateManName(netDb.getTareManName());
            }
            try {
                //新增补丁，给净重数据重新赋值一次数据的计量方式2023年10月18日zn
                //查询毛重数据
                MeterWorkCarActualFirst first1 = meterWorkCarActualFirstMapper.selectByPrimaryKey(netDb.getActualFirst1No());
                //查询皮重数据
                MeterWorkCarActualFirst first2 = meterWorkCarActualFirstMapper.selectByPrimaryKey(netDb.getActualFirst2No());
                netDb.setGrossMode(first1.getMeterMode());
                netDb.setTareMode(first2.getMeterMode());
            } catch (Exception e) {
                logger.error("修改计量方式出错", e);
                e.printStackTrace();
            }
            meterWorkCarActualMapper.insert(netDb);

            //4、如果为期限皮重，则将期限皮重转化为一条皮重计量数据保存
            MeterWorkCarActualFirst mwraf = meterWorkCarActualFirstMapper.selectByPrimaryKey(netDb.getActualFirst2No());
            if (mwraf == null) {
                MeterBaseTermTareData mbttd = new MeterBaseTermTareData();
                HashMap mbMap = new HashMap();
                SimpleDateFormat mbsdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                mbMap.put("endTime",mbsdf.format(new Date()));
                if(StringUtils.isNotEmpty(netDb.getActualFirst2No())){
                    mbMap.put("dataNo",netDb.getActualFirst2No());
                    mbttd = meterBaseTermTareDataMapper.selectByDataNo(mbMap);
                }
                else{
                    mbMap.put("carNo",netDb.getCarNo());
                    mbttd = meterBaseTermTareDataMapper.selectByCarNo(mbMap);
                }
                MeterWorkCarActualFirst imTare = new MeterWorkCarActualFirst();
                //补充数据
                String afl1 = formatter.format(new Date());
//                String imTareNO = meterWorkCarActualFirstMapper.getNewID(afl1);
//                imTare.setActualFirstNo(afl1 + imTareNO);
                String imTareNO = PublicMethod.IdCreate(3);
                imTare.setActualFirstNo(imTareNO);
                imTare.setMeterTypeNo(secondDb.getMeterTypeNo());
                imTare.setMeterTypeName(secondDb.getMeterTypeName());
                imTare.setBaseSpotNo(mbttd.getBaseSpotNo());
                imTare.setBaseSpotName(mbttd.getBaseSpotName());
                imTare.setCarNo(mbttd.getCarNo());
                imTare.setCreateTime(mbttd.getCreateTime());
                imTare.setCreateManNo(mbttd.getCreateManNo());
                imTare.setCreateManName(mbttd.getCreateManName());
                imTare.setMeterWeight(netDb.getTareWeight());
                imTare.setWeightType("2");//期限皮重
                imTare.setValueFlag("2");//结净
                meterWorkCarActualFirstMapper.insertSelective(imTare);
                //将结净数据中的皮重编号修改
                MeterWorkCarActual mwca = new MeterWorkCarActual();
                mwca.setActualNo(netDb.getActualNo());
                mwca.setActualFirst2No(imTare.getActualFirstNo());
                meterWorkCarActualMapper.updateByPrimaryKeySelective(mwca);
            }
            //4、存储历史皮重及历史皮重明细信息
            if ("1".equals(saveTare)) {
                MeterWorkCarActualFirst oci = new MeterWorkCarActualFirst();
                oci.setCarNo(netDb.getCarNo());
                oci.setCreateTime(netDb.getTareTime());
                oci.setBaseSpotNo(netDb.getBaseSpot2No());
                oci.setBaseSpotName(netDb.getBaseSpot2Name());
                oci.setMeterWeight(netDb.getTareWeight());
                oci.setActualFirstNo(netDb.getActualFirst2No());
                doSaveHisTare(oci);
            }
            //6、修改计量监控
            updateMonitor(secondDb.getBaseSpotNo());
            //保存日志
            saveNote(note);
            //当存储一次数据或者结净时，将本车辆的预处理重量改为已使用
            updatePreWeight(secondDb.getCarNo());
            updateMonitorOver(secondDb.getActualFirstNo(), secondDb.getBaseSpotNo());
            //重量类型为毛重则调用接口为
            String flag = "";
            //补充附加重量的数据
            if (StringUtils.isNotEmpty(secondDb.getAddWgtPk())) {
                insertAddWgtNo(secondDb.getActualFirstNo(), secondDb.getAddWgtPk(), secondDb.getCreateManNo(), secondDb.getCreateManName());
            }
            rm.setSucceed();
            rm.setCode("200");
            rm.setData(secondDb.getActualFirstNo());
            rm.setMessage(flag);
            return rm;
        }catch (Exception e){
            e.printStackTrace();
            rm.setFailed();
            rm.setMessage(e.getMessage());
            return rm;
        }
    }

    /**
     * 内倒车辆结净
     *
     * @param secondDb 二次计量数据
     * @param netDb    净重数据
     * @param saveTare 0 不保存历史皮，1保存历史皮
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(value = "tm", rollbackFor = Exception.class)
    public RESTfulResult doAddNetNewHZHX(MeterWorkCarActualFirst secondDb, MeterWorkCarActual netDb,MeterWorkCarActualFirst once,String saveTare,  MeterMonitorNote note) throws Exception {
        try{
            RESTfulResult rm = new RESTfulResult();
            rm.setCode("200");

            //1a.查询上一个结净，如果receive_remark不是H01，直接报错
            HashMap<String, Object> obj = new HashMap<>();
            obj.put("carNo", netDb.getCarNo());
            obj.put("receiverRemark", "H01");
            List<MeterWorkCarActual> models = meterWorkCarActualMapper.likeByDesc(obj);
            if(models.size() < 1) {
                rm.setCode("500");
                rm.setData(null);
                rm.setMessage("不存在混装结净数据，请确认！！");
                return rm;
            }
            MeterWorkCarActual upModel = models.get(0);
            MeterWorkCarActualFirst upFirstGross = meterWorkCarActualFirstMapper.selectByPrimaryKey(upModel.getActualFirst1No());
            MeterWorkCarActualFirst upFirstTare = meterWorkCarActualFirstMapper.selectByPrimaryKey(upModel.getActualFirst2No());
            PreTrackScale upScale = preTrackScaleMapper.selectByPrimaryKey(upModel.getPredictionNo());
            upFirstGross.setPredictionCombination(upModel.getPredictionNo() + "," + netDb.getPredictionNo());
            upFirstGross.setPredictionType("7");
            meterWorkCarActualFirstMapper.updateByPrimaryKeySelective(upFirstGross);
            upFirstTare.setPredictionCombination(upModel.getPredictionNo() + "," + netDb.getPredictionNo());
            upFirstTare.setPredictionType("7");
            meterWorkCarActualFirstMapper.updateByPrimaryKeySelective(upFirstTare);
            upModel.setPredictionCombination(upModel.getPredictionNo() + "," + netDb.getPredictionNo());
            upModel.setPredictionType("7");
            meterWorkCarActualMapper.updateByPrimaryKeySelective(upModel);
            upScale.setPredictionType("7");
            upScale.setPredictionCombination(upModel.getPredictionNo() + "," + netDb.getPredictionNo());
            preTrackScaleMapper.updateByPrimaryKeySelective(upScale);

            //1、存储当前计量的数据
            SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
            String afl = formatter.format(new Date());
//            String no = meterWorkCarActualFirstMapper.getNewID(afl);
//            secondDb.setActualFirstNo(formatter.format(new Date()) + no);

            String no = PublicMethod.IdCreate(3);
            secondDb.setActualFirstNo(no);

            secondDb.setValueFlag("2");//结净
            secondDb.setUpdateManNo("system");
            secondDb.setUpdateManName("混装结净更新");
            secondDb.setPredictionType("7");
            secondDb.setCreateTime(new Date());
            secondDb.setPredictionCombination(upModel.getPredictionNo() + "," + netDb.getPredictionNo());
            meterWorkCarActualFirstMapper.insertSelective(secondDb);

            //1、存储当前计量的数据
            SimpleDateFormat formatterHZ = new SimpleDateFormat("yyyyMMdd");
            String aflHZ = formatterHZ.format(new Date());
//            String noHZ = meterWorkCarActualFirstMapper.getNewID(aflHZ);
//            once.setActualFirstNo(formatter.format(new Date()) + noHZ);

            String noHZ = PublicMethod.IdCreate(3);
            once.setActualFirstNo(noHZ);
            once.setValueFlag("2");//结净
            once.setUpdateManNo("system");
            once.setUpdateManName("混装结净更新");
            once.setPredictionType("7");
            once.setCreateTime(secondDb.getCreateTime());
            once.setPredictionCombination(upModel.getPredictionNo() + "," + netDb.getPredictionNo());
            meterWorkCarActualFirstMapper.insertSelective(once);

//            String no1 = meterWorkCarActualMapper.getNewID(afl);
//            netDb.setActualNo(afl + no1);

            String no1 = PublicMethod.IdCreate(3);
            netDb.setActualNo(no1);

            netDb.setActualFirst2No(no);
            netDb.setActualFirst1No(noHZ);
            if (netDb != null && netDb.getNetWeight() != null) {
                //2021年3月7日 净重保留两位小数；
                BigDecimal net;
                net = new BigDecimal(String.valueOf(netDb.getNetWeight())).setScale(2, BigDecimal.ROUND_HALF_UP);
                netDb.setNetWeight(net);
            }
            netDb.setPredictionType("7");
            netDb.setUploadFlag("1");
            // 拿到结净编号B
            netDb.setPredictionCombination(upModel.getPredictionNo() + "," + netDb.getPredictionNo());
            netDb.setCreateTime(new Date());
            if(netDb.getGrossTime().compareTo(netDb.getTareTime()) >= 0) {
                netDb.setNetSpot3No(netDb.getBaseSpot1No());
                netDb.setNetSpot3Name(netDb.getBaseSpot1Name());
                netDb.setNetManNo(netDb.getGrossManNo());
                netDb.setNetManName(netDb.getGrossManName());
                netDb.setNetTime(netDb.getGrossTime());
                netDb.setCreateTime(netDb.getGrossTime());
                netDb.setCreateManName(netDb.getGrossManName());
            }else {
                netDb.setNetSpot3No(netDb.getBaseSpot2No());
                netDb.setNetSpot3Name(netDb.getBaseSpot2Name());
                netDb.setNetManNo(netDb.getTareManNo());
                netDb.setNetManName(netDb.getTareManName());
                netDb.setNetTime(netDb.getTareTime());
                netDb.setCreateTime(netDb.getTareTime());
                netDb.setCreateManName(netDb.getTareManName());
            }
            meterWorkCarActualMapper.insert(netDb);

            //1b.如果receive_remark是H01，拿到委托单号，拿到上一个结净编号A
            //修改上一个委托单

            //修改委托编号
            PreTrackScale scale = preTrackScaleMapper.selectByPrimaryKey(netDb.getPredictionNo());
            scale.setValueFlag(DbConstants.NET);
            scale.setUpdateTime(new Date());
            scale.setUpdateManNo("system");
            scale.setUpdateManName("混装结净更新");
            scale.setUploadFlag("1");
            scale.setPredictionType("7");
            scale.setPredictionCombination(upModel.getPredictionNo() + "," + netDb.getPredictionNo());
            scale.setMeasureStation(netDb.getNetSpot3No());
            scale.setMeasureStationName(netDb.getNetSpot3Name());
            preTrackScaleMapper.updateByPrimaryKeySelective(scale);

            //4、存储历史皮重及历史皮重明细信息
            if ("1".equals(saveTare)) {
                MeterWorkCarActualFirst oci = new MeterWorkCarActualFirst();
                oci.setCarNo(netDb.getCarNo());
                oci.setCreateTime(netDb.getTareTime());
                oci.setBaseSpotNo(netDb.getBaseSpot2No());
                oci.setBaseSpotName(netDb.getBaseSpot2Name());
                oci.setMeterWeight(netDb.getTareWeight());
                oci.setActualFirstNo(netDb.getActualFirst2No());
                doSaveHisTare(oci);
            }



            //5、保存图片
            //SaveImg(secondDb);

            //6、修改计量监控
            updateMonitor(secondDb.getBaseSpotNo());

            //保存日志
            saveNote(note);

            updateMonitorOver(secondDb.getActualFirstNo(), secondDb.getBaseSpotNo());

            //重量类型为毛重则调用接口为
            String flag = "";
            /*
            if("0".equals(secondDb.getWeightType())){
                flag = transferParamForLims(netDb.getCarNo(),netDb.getMatterNo(),netDb.getReceivingUintName(),netDb.getForwardingUnitName(),netDb.getNetWeight().toString(),netDb.getNetTime(),"",netDb.getActualNo());
            }
            //*/

            //补充附加重量的数据
            if (StringUtils.isNotEmpty(secondDb.getAddWgtPk())) {
                insertAddWgtNo(secondDb.getActualFirstNo(), secondDb.getAddWgtPk(), secondDb.getCreateManNo(), secondDb.getCreateManName());
            }



            rm.setData(secondDb.getActualFirstNo());
            rm.setMessage(flag);
            return rm;
        }
        catch (Exception e){
            RESTfulResult rm = new RESTfulResult();
            rm.setCode("500");
            rm.setData(null);
            rm.setMessage(e.getMessage());
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return rm;
        }
    }


    /**
     * 非内倒车辆存储一次计量数据
     *
     * @param oci
     * @param link
     * @param isLock   1 互锁   其它为非互锁  如果是非互锁，且还有预报未使用，则需要留二次计量的信息
     * @param saveTare 0 不保存历史皮，1保存历史皮
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public RESTfulResult doAddWf(MeterWorkCarActualFirst oci, MeterWorkPreLink link, String isLock, String saveTare, MeterMonitorNote note) throws Exception {
        RESTfulResult rm = new RESTfulResult();
        rm.setCode("200");
        if (oci == null || link == null) {
            throw new MarkerMetException(500, "参数！！");
        }
        //0、查询预报信息；判断预报车号的车号与前端传进来的车号是不是一样的；2021年5月16日
        PreTrackScale pts = preTrackScaleMapper.selectByPrimaryKey(oci.getPredictionNo());
        if (StringUtils.isEmpty(pts.getCarNo()) || !pts.getCarNo().equals(oci.getCarNo())) {
            throw new MarkerMetException(500, "预报中的车号【" + pts.getCarNo() + "】与界面车号不一致【" + oci.getCarNo() + "】");
        }

        //1、存储一次计量信息
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
        String afl = formatter.format(oci.getCreateTime());
//        String no = meterWorkCarActualFirstMapper.getNewID(afl);
//        oci.setActualFirstNo(afl + no);

        String no = PublicMethod.IdCreate(3);
        oci.setActualFirstNo(no);

        oci.setValueFlag("1");
        //计算卸货截止时间
        Map<String, Object> obj = new HashMap<>();
        if (StringUtils.isNotEmpty(oci.getBaseSpotNo())) {
            obj.put("baseSpotNo", oci.getBaseSpotNo());
        }
        if (StringUtils.isNotEmpty(oci.getLoadPointNo())) {
            obj.put("loadPointNo", oci.getLoadPointNo());
        }
        if (oci.getWeightType().equals("0")) {
            List<MeterBaseUnloadTime> list1 = meterBaseUnloadTimeMapper.selectByParameters(obj);
            if (list1.size() == 1) {
                Calendar gc = new GregorianCalendar();
                gc.setTime(oci.getCreateTime());
                gc.add(GregorianCalendar.MINUTE, Integer.parseInt(list1.get(0).getLoadTime().toString()));
                oci.setLoadEndTime(gc.getTime());
            }
        }
        oci.setCreateTime(new Date());
        meterWorkCarActualFirstMapper.insertSelective(oci);

        //2、修改预环节为使用
        MeterWorkPreLink mpl = new MeterWorkPreLink();
        mpl.setPreLinkNo(link.getPreLinkNo());
        mpl.setValueFlag("1");
        meterWorkPreLinkMapper.updateByPrimaryKeySelectivePart(mpl);

        //3、获取预流程是否还有未使用的环节，若没有了则修改其状态
        MeterWorkPreLink mplq = new MeterWorkPreLink();
        mplq.setPreProcessNo(link.getPreProcessNo());
        mplq.setValueFlag("0");
        Map<String, Object> map = FieldsCollector.beanToMap(mplq);
        List<MeterWorkPreLink> list = meterWorkPreLinkMapper.selectByParameters(map);
        if (list.size() == 0) {
            MeterWorkPreProcess mpp = new MeterWorkPreProcess();
            mpp.setPreProcessNo(link.getPreProcessNo());
            mpp.setValueFlag("2");
            meterWorkPreProcessMapper.updateByPrimaryKeySelective(mpp);
        }

        //4、修改预报状态  Value_flag 0：未配车；1：未使用；2：已使用；3：已作废；4：正使用
        PreTrackScale ptsU = new PreTrackScale();
        ptsU.setPredictionNo(oci.getPredictionNo());
        if (pts.getPredictionType().equals("2")) {//联运预报
            if ("1".equals(isLock)) {
                ptsU.setValueFlag("4");//一车联运的话，互锁扫码时会将预报改为正使用 下次扫后面的码
            } else {
                ptsU.setValueFlag("2");//一车联运的话，非互锁扫码时预报改为已使用  下次还是扫相同码
            }
        } else {
            //5、存储历史皮重及历史皮重明细信息
            if ("1".equals(saveTare)) {
                doSaveHisTare(oci);
            }
            ptsU.setValueFlag("4");//非一车联运的话，扫码时预报改为正使用  下次还是扫相同码
        }
        ptsU.setUploadFlag("1");
        ptsU.setMeasureStation(oci.getBaseSpotNo());
        ptsU.setMeasureStationName(oci.getBaseSpotName());
        preTrackScaleMapper.updateByPrimaryKeySelective(ptsU);

        //6、存储图片
        //SaveImg(oci);

        //7、修改计量监控
        updateMonitor(oci.getBaseSpotNo());

        //8、修改监控的计量作业编号
        updateMonitorOver(oci.getActualFirstNo(), oci.getBaseSpotNo());

        //9、批次预报重新生成一套预环节   若为批次预报且还未用完
        if (pts.getPredictionType().equals("0") || pts.getPredictionType().equals("3")) {
            meterWorkPreLinkService.batchReset(oci.getPredictionNo());
        }
        //信息加密
        String str = oci.getActualFirstNo() + "," + oci.getMeterWeight() + "," + "1";
        String enStr = encryption(str);

        //保存日志
        saveNote(note);

        //补充附加重量的数据
        if (StringUtils.isNotEmpty(oci.getAddWgtPk())) {
            insertAddWgtNo(oci.getActualFirstNo(), oci.getAddWgtPk(), oci.getCreateManNo(), oci.getCreateManName());
        }

        // eason add 2021-11-25 若进入到这里则要作废期限皮重数据，因为这边如果可以留期限皮则不会留1次皮重计量数据
        if(!oci.getWeightType().equals("0")){
            cancelTermTare(oci.getCarNo());
        }

        rm.setData(oci.getActualFirstNo());
        rm.setMessage(enStr);
        return rm;
    }

    /**
     * 作废期限皮重数据
     */
    private void cancelTermTare(String carNo){
        HashMap<String,Object> mp=new HashMap<>();
        mp.put("carNo",carNo);
        mp.put("valueFlag","0");
        meterBaseTermTareDataMapper.cancelTermTare(mp);
    }

    /**
     * 非内倒车辆结净
     *
     * @param secondDb 二次计量数据
     * @param netDb    净重数据
     * @param link     预报数据
     * @param isLock   1 互锁   其它为非互锁  如果是非互锁，且还有预报未使用，则需要留二次计量的信息
     * @param saveTare 0 不保存历史皮，1保存历史皮
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(value = "tm", rollbackFor = Exception.class)
    public RESTfulResult doAddNetWf(MeterWorkCarActualFirst secondDb, MeterWorkCarActual netDb, MeterMonitorNote note, MeterWorkPreLink link, String isLock, String saveTare) throws Exception {
        String lyFirstNo = "";//联运自动生成的一次计量编号
        RESTfulResult rm = new RESTfulResult();
        rm.setCode("200");
        //先格式化时间
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");

        //0、查询预报信息；判断预报车号的车号与前端传进来的车号是不是一样的；2021年5月16日
        PreTrackScale pts = preTrackScaleMapper.selectByPrimaryKey(secondDb.getPredictionNo());
        if (StringUtils.isEmpty(pts.getCarNo()) || !pts.getCarNo().equals(secondDb.getCarNo())) {
            throw new MarkerMetException(500, "预报中的车号【" + pts.getCarNo() + "】与界面车号不一致【" + secondDb.getCarNo() + "】");
        }

        //1、存储当前计量的数据  1.1先给一个初始状态
        secondDb.setValueFlag("2");//结净

        //2、修改预环节为使用 2.1修改预环节
        MeterWorkPreLink mpl = new MeterWorkPreLink();
        mpl.setPreLinkNo(link.getPreLinkNo());
        mpl.setValueFlag("1");
        meterWorkPreLinkMapper.updateByPrimaryKeySelectivePart(mpl);

        //2、获取预流程是否还有未使用的环节，若没有了则修改其状态  2.2修改预流程
        MeterWorkPreLink mplq = new MeterWorkPreLink();
        mplq.setPreProcessNo(link.getPreProcessNo());
        mplq.setValueFlag("0");
        Map<String, Object> map = FieldsCollector.beanToMap(mplq);
        List<MeterWorkPreLink> list = meterWorkPreLinkMapper.selectByParameters(map);
        if (list.size() == 0) {
            MeterWorkPreProcess mpp = new MeterWorkPreProcess();
            mpp.setPreProcessNo(link.getPreProcessNo());
            mpp.setValueFlag("2");
            meterWorkPreProcessMapper.updateByPrimaryKeySelective(mpp);
        }

        //3、存储历史皮重及历史皮重明细信息  3.1判断皮重信息
        if (secondDb.getMeterWeight().equals(netDb.getTareWeight())) {
            //二次重量如果跟皮重一样
            netDb.setActualFirst2No(secondDb.getActualFirstNo());
        } else {
            netDb.setActualFirst1No(secondDb.getActualFirstNo());
        }
        //3、存储历史皮重及历史皮重明细信息  3.2判断需要保存皮重且不是一车联运预报
        if (!pts.getPredictionType().equals("2")) {//不是一车联运预报
            if ("1".equals(saveTare)) {
                MeterWorkCarActualFirst oci = new MeterWorkCarActualFirst();
                oci.setCarNo(netDb.getCarNo());
                oci.setCreateTime(netDb.getTareTime());
                oci.setBaseSpotNo(netDb.getBaseSpot2No());
                oci.setBaseSpotName(netDb.getBaseSpot2Name());
                oci.setMeterWeight(netDb.getTareWeight());
                oci.setActualFirstNo(netDb.getActualFirst2No());
                doSaveHisTare(oci);
            }
        }

        //4、修改预报信息  包括处理各类预报类型（一车联运多新增一条作为皮重的信息）
        PreTrackScale ptsU = new PreTrackScale();
        ptsU.setPredictionNo(pts.getPredictionNo());
        if (pts.getPredictionType().equals("0")) {
            ptsU.setValueFlag("4");//正使用
            //批次预报 有时间，次数，重量限制
            if (pts.getUsedType().equals("0")) {  //0次数  1时间  2总量
                //次数
                ptsU.setMeterNum(pts.getMeterNum() == null ? 1 : (pts.getMeterNum() + 1));
                if (pts.getEffectiveNum().equals(ptsU.getMeterNum())) {//如果两个值相等
                    ptsU.setValueFlag("2");//用完了则状态改为2
                }
            } else if (pts.getUsedType().equals("1")) {
                //1时间
                if (!"2".equals(pts.getValueFlag()) && pts.getEffectiveEndTime().compareTo(new Date()) <= 0) {
                    ptsU.setValueFlag("2");//当前状态不为2，且结束时间小于当时间
                }
            } else if (pts.getUsedType().equals("2")) {
                //总量
                ptsU.setMeterWeight(pts.getMeterWeight() == null ? netDb.getNetWeight() : (pts.getMeterWeight().add(netDb.getNetWeight())));
                if (pts.getEffectiveWeight().doubleValue() <= ptsU.getMeterWeight().doubleValue()) {//如果总重量小于等于检斤重量则用完了
                    ptsU.setValueFlag("2");//用完了则状态改为2
                }
            }
            ptsU.setUploadFlag("1");
            ptsU.setMeasureStation(netDb.getNetSpot3No());
            ptsU.setMeasureStationName(netDb.getNetSpot3Name());
            preTrackScaleMapper.updateByPrimaryKeySelective(ptsU);
        } else if (pts.getPredictionType().equals("1")) {
            //单次预报 使用1次后将状态设置为已使用
            ptsU.setValueFlag("2");
            ptsU.setUploadFlag("1");
            ptsU.setMeasureStation(netDb.getNetSpot3No());
            ptsU.setMeasureStationName(netDb.getNetSpot3Name());
            preTrackScaleMapper.updateByPrimaryKeySelective(ptsU);
        } else if (pts.getPredictionType().equals("2")) {
            //联运预报 使用1次，但是根据车辆的环节中若是 互锁式则直接结净，否则则看是否还有其它的预报未使用
            //若存在其它未使用的预报则需要留一个二次计量的数据作为下一车的一次计量信息
            if ("1".equals(isLock)) { //互锁搞法：与单次的先皮后毛流程一样
                ptsU.setValueFlag("2"); //修改预报状态为正使用
                ptsU.setUploadFlag("1");
                ptsU.setMeasureStation(netDb.getNetSpot3No());
                ptsU.setMeasureStationName(netDb.getNetSpot3Name());
                preTrackScaleMapper.updateByPrimaryKeySelective(ptsU);
            } else {
                MeterWorkCarActualFirst mwaf = new MeterWorkCarActualFirst();
                String two = formatter.format(secondDb.getCreateTime());
//                String twoNo = meterWorkCarActualFirstMapper.getNewID(two);
//                mwaf.setActualFirstNo(two + twoNo);

                String twoNo = PublicMethod.IdCreate(3);
                mwaf.setActualFirstNo(twoNo);

                //非互锁式 value_flag：1未使用 2已使用状态
                PreTrackScale ptsQ = new PreTrackScale();
                ptsQ.setValueFlag("1");
                ptsQ.setPredictionCombination(secondDb.getPredictionCombination());
                Map<String, Object> map1 = FieldsCollector.beanToMap(ptsQ);
                List<PreTrackScale> lscale = preTrackScaleMapper.selectByParameters(map1);

                int iCount = 0;
                for (PreTrackScale pt : lscale) {
                    //由于预报都已使用的话，不可能进入到服务端而应该在客户端就被抛出异常了，所以这里只可能是还存在未使用的预报
                    //存在未使用，且当前计量编号与未使用编号不一致的情况，那么表示后面还有其他的预报，否则则说明这已经是最后一次计量了
                    if (!secondDb.getPredictionNo().equals(pt.getPredictionNo())) {
                        ++iCount;
                    }
                }
                if (iCount == 0) {
                    //存在未使用预报，但是预报就是当前预报自身，说明已经是最后一车计量了
                    //最后一个预报了
                    //结净的编号与当前计量的编号不一致则说明当前计量扫的是另外一个码需给结净的数据补充一条计量数据，否则则不用补
                    if (!netDb.getPredictionNo().equals(secondDb.getPredictionNo())) {
                        MeterWorkCarActualFirst mwafQ = new MeterWorkCarActualFirst();
                        mwafQ.setPredictionNo(netDb.getPredictionNo());
                        mwafQ.setValueFlag("1");
                        Map<String, Object> map2 = FieldsCollector.beanToMap(mwafQ);
                        List<MeterWorkCarActualFirst> lmwaf = meterWorkCarActualFirstMapper.selectByParameters(map2);
                        if (lmwaf.size() <= 0) {
                            throw new MarkerMetException(500, "操作失败！！");
                        }
                        //给结净数据补充完整二次计量数据(皮重数据)
                        mwaf.setPredictionNo(lmwaf.get(0).getPredictionNo());
                        mwaf.setNoticeNo(lmwaf.get(0).getNoticeNo());
                        mwaf.setCarNo(lmwaf.get(0).getCarNo());
                        mwaf.setTrailerNo(lmwaf.get(0).getTrailerNo());
                        mwaf.setMatterNo(lmwaf.get(0).getMatterNo());
                        mwaf.setMatterName(lmwaf.get(0).getMatterName());
                        mwaf.setContractNo(lmwaf.get(0).getContractNo());
                        mwaf.setBatchNo(lmwaf.get(0).getBatchNo());
                        mwaf.setCustomerSupplierNo(lmwaf.get(0).getCustomerSupplierNo());
                        mwaf.setCustomerSupplierName(lmwaf.get(0).getCustomerSupplierName());
                        mwaf.setForwardingUnitNo(lmwaf.get(0).getForwardingUnitNo());
                        mwaf.setForwardingUnitName(lmwaf.get(0).getForwardingUnitName());
                        mwaf.setReceivingUintNo(lmwaf.get(0).getReceivingUintNo());
                        mwaf.setReceivingUintName(lmwaf.get(0).getReceivingUintName());
                        mwaf.setMaterialNo(lmwaf.get(0).getMaterialNo());
                        mwaf.setMaterialName(lmwaf.get(0).getMaterialName());
                        mwaf.setSpecNo(lmwaf.get(0).getSpecNo());
                        mwaf.setSpecName(lmwaf.get(0).getSpecName());
                        mwaf.setShipmentGrossWeight(lmwaf.get(0).getShipmentGrossWeight());
                        mwaf.setShipmentNetWeight(lmwaf.get(0).getShipmentNetWeight());
                        mwaf.setShipmentNum(lmwaf.get(0).getShipmentNum());
                        mwaf.setBindCardNo(lmwaf.get(0).getBindCardNo());
                        mwaf.setLoadPointNo(lmwaf.get(0).getLoadPointNo());
                        mwaf.setLoadPointName(lmwaf.get(0).getLoadPointName());
                        mwaf.setSampleNo(lmwaf.get(0).getSampleNo());
                        mwaf.setSampleVoucher(lmwaf.get(0).getSampleVoucher());
                        mwaf.setCarrierUnitNo(lmwaf.get(0).getCarrierUnitNo());
                        mwaf.setCarrierUnitName(lmwaf.get(0).getCarrierUnitName());
                        mwaf.setPredictionType(lmwaf.get(0).getPredictionType());
                        mwaf.setPredictionCombination(lmwaf.get(0).getPredictionCombination());
                        mwaf.setMeterTypeNo(lmwaf.get(0).getMeterTypeNo());
                        mwaf.setRailwayNo(lmwaf.get(0).getRailwayNo());
                        mwaf.setMeterTypeName(lmwaf.get(0).getMeterTypeName());
                        mwaf.setMeterProcessEditionNo(lmwaf.get(0).getMeterProcessEditionNo());
                        mwaf.setMeterWeight(secondDb.getMeterWeight());//当前重量
                        mwaf.setAddWeight(new BigDecimal(0));//皮重补充附加重量为0
                        mwaf.setMeterNum(lmwaf.get(0).getMeterNum());
                        mwaf.setWeightType(lmwaf.get(0).getWeightType().equals("0") ? "1" : "0"); //0=毛重；1=常规皮重；2=期限皮重；3=历史皮重；4=标识皮重；5=自重皮重
                        mwaf.setCreateManNo(secondDb.getCreateManNo());
                        mwaf.setCreateManName(secondDb.getCreateManName());
                        mwaf.setCreateTime(secondDb.getCreateTime());
                        mwaf.setMeterClass(secondDb.getMeterClass());
                        mwaf.setMeterGroup(secondDb.getMeterGroup());
                        //mwaf.setWeight_type(secondDb.getWeight_type().equals("0")?"1":"0");//0=毛重；1=常规皮重；2=期限皮重；3=历史皮重；4=标识皮重；5=自重皮重
                        mwaf.setBaseSpotNo(secondDb.getBaseSpotNo());
                        mwaf.setBaseSpotName(secondDb.getBaseSpotName());
                        mwaf.setValueFlag("2");//0=有效，1=作废，2=结净
                        mwaf.setCheckFlag("0");
                        mwaf.setMeterMode(secondDb.getMeterMode());//1：远程计量；2：智能计量；3：手工录入；4：放行智能计量；5：滞后匹配
                        mwaf.setMemo("一车联运自动生成一次计量信息1");
                        //存储补充的需结净的数据
                        meterWorkCarActualFirstMapper.insertSelective(mwaf);
                        lyFirstNo = mwaf.getActualFirstNo();

                        //2021年3月20日；杨秀东对前端传来的实体进行处理;处理state；处理预报
                        secondDb.setWeightType(mwaf.getWeightType().equals("0") ? "1" : "0");
                        PreTrackScale lyScale = new PreTrackScale();
                        lyScale.setPredictionNo(secondDb.getPredictionNo());
                        lyScale.setValueFlag("4");
                        lyScale.setUploadFlag("1");
                        lyScale.setMeasureStation(secondDb.getBaseSpotNo());
                        lyScale.setMeasureStationName(secondDb.getBaseSpotName());
                        preTrackScaleMapper.updateByPrimaryKeySelective(lyScale);

                        //查找到的上个毛重写为结净
                        lmwaf.get(0).setValueFlag("2");//结净
                        meterWorkCarActualFirstMapper.updateByPrimaryKeySelective(lmwaf.get(0));

                        //设置毛重数据数据为有效而非结净
                        secondDb.setValueFlag("1");//有效

                        //将结净数据中的毛重编号修改
                        if (mwaf.getMeterWeight().doubleValue() == netDb.getTareWeight().doubleValue()) {
                            //若此次补充的一次数据重量与结净中的皮重相同,则将这个编号赋值给结净数据的皮重编号
                            netDb.setActualFirst2No(mwaf.getActualFirstNo());
                        } else {
                            netDb.setActualFirst1No(mwaf.getActualFirstNo());
                        }
                    } else {
                        Map<String, Object> hm = new HashMap<>();
                        hm.put("predictionNo", netDb.getPredictionNo());
                        hm.put("valueFlag", "1");
                        List<MeterWorkCarActualFirst> lmwaf = meterWorkCarActualFirstMapper.selectByParameters(hm);
                        if (lmwaf.size() <= 0) {
                            throw new MarkerMetException(500, "操作失败！！");
                        }
                        //查找到的上个毛重写为结净
                        lmwaf.get(0).setValueFlag("2");//结净
                        meterWorkCarActualFirstMapper.updateByPrimaryKeySelective(lmwaf.get(0));
                        //已经是最后一个预报的最后一次结净了
                        ptsU.setValueFlag("2"); //修改预报状态
                        ptsU.setUploadFlag("1");
                        ptsU.setMeasureStation(lmwaf.get(0).getBaseSpotNo());
                        ptsU.setMeasureStationName(lmwaf.get(0).getBaseSpotName());
                        preTrackScaleMapper.updateByPrimaryKeySelective(ptsU);
                    }
                } else {
                    //说明后续还有预报，此时直接将这个预报状态修改为2，同时为当前结净补充一条计量皮重数据
                    Map<String, Object> map3 = new HashMap<>();
                    map3.put("predictionNo", netDb.getPredictionNo());
                    map3.put("valueFlag", "1");
                    List<MeterWorkCarActualFirst> lmwaf = meterWorkCarActualFirstMapper.selectByParameters(map3);
                    if (lmwaf.size() <= 0) {
                        throw new MarkerMetException(500, "操作失败！！");
                    }
                    //给结净数据补充完整二次计量数据
                    mwaf.setPredictionNo(lmwaf.get(0).getPredictionNo());
                    mwaf.setNoticeNo(lmwaf.get(0).getNoticeNo());
                    mwaf.setCarNo(lmwaf.get(0).getCarNo());
                    mwaf.setTrailerNo(lmwaf.get(0).getTrailerNo());
                    mwaf.setMatterNo(lmwaf.get(0).getMatterNo());
                    mwaf.setMatterName(lmwaf.get(0).getMatterName());
                    mwaf.setContractNo(lmwaf.get(0).getContractNo());
                    mwaf.setBatchNo(lmwaf.get(0).getBatchNo());
                    mwaf.setCustomerSupplierNo(lmwaf.get(0).getCustomerSupplierNo());
                    mwaf.setCustomerSupplierName(lmwaf.get(0).getCustomerSupplierName());
                    mwaf.setForwardingUnitNo(lmwaf.get(0).getForwardingUnitNo());
                    mwaf.setForwardingUnitName(lmwaf.get(0).getForwardingUnitName());
                    mwaf.setReceivingUintNo(lmwaf.get(0).getReceivingUintNo());
                    mwaf.setReceivingUintName(lmwaf.get(0).getReceivingUintName());
                    mwaf.setMaterialNo(lmwaf.get(0).getMaterialNo());
                    mwaf.setMaterialName(lmwaf.get(0).getMaterialName());
                    mwaf.setSpecNo(lmwaf.get(0).getSpecNo());
                    mwaf.setSpecName(lmwaf.get(0).getSpecName());
                    mwaf.setShipmentGrossWeight(lmwaf.get(0).getShipmentGrossWeight());
                    mwaf.setShipmentNetWeight(lmwaf.get(0).getShipmentNetWeight());
                    mwaf.setShipmentNum(lmwaf.get(0).getShipmentNum());
                    mwaf.setBindCardNo(lmwaf.get(0).getBindCardNo());
                    mwaf.setLoadPointNo(lmwaf.get(0).getLoadPointNo());
                    mwaf.setLoadPointName(lmwaf.get(0).getLoadPointName());
                    mwaf.setSampleNo(lmwaf.get(0).getSampleNo());
                    mwaf.setSampleVoucher(lmwaf.get(0).getSampleVoucher());
                    mwaf.setCarrierUnitNo(lmwaf.get(0).getCarrierUnitNo());
                    mwaf.setCarrierUnitName(lmwaf.get(0).getCarrierUnitName());
                    mwaf.setPredictionType(lmwaf.get(0).getPredictionType());
                    mwaf.setPredictionCombination(lmwaf.get(0).getPredictionCombination());
                    mwaf.setMeterTypeNo(lmwaf.get(0).getMeterTypeNo());
                    mwaf.setRailwayNo(lmwaf.get(0).getRailwayNo());
                    mwaf.setMeterTypeName(lmwaf.get(0).getMeterTypeName());
                    mwaf.setMeterProcessEditionNo(lmwaf.get(0).getMeterProcessEditionNo());
                    mwaf.setMeterWeight(secondDb.getMeterWeight());//当前重量
                    mwaf.setAddWeight(new BigDecimal(0));//皮重补充附加重量为0
                    mwaf.setMeterNum(lmwaf.get(0).getMeterNum());
                    mwaf.setWeightType(lmwaf.get(0).getWeightType().equals("0") ? "1" : "0");
                    mwaf.setCreateManNo(secondDb.getCreateManNo());
                    mwaf.setCreateManName(secondDb.getCreateManName());
                    mwaf.setCreateTime(secondDb.getCreateTime());
                    mwaf.setMeterClass(secondDb.getMeterClass());
                    mwaf.setMeterGroup(secondDb.getMeterGroup());
                    //mwaf.setWeight_type(secondDb.getWeight_type().equals("0")?"1":"0");//0=毛重；1=常规皮重；2=期限皮重；3=历史皮重；4=标识皮重；5=自重皮重
                    mwaf.setBaseSpotNo(secondDb.getBaseSpotNo());
                    mwaf.setBaseSpotName(secondDb.getBaseSpotName());
                    mwaf.setValueFlag("2");//0=有效，1=作废，2=结净
                    mwaf.setCheckFlag("0");
                    mwaf.setMeterMode(secondDb.getMeterMode());
                    mwaf.setMemo("一车联运自动生成一次计量信息2");
                    //存储补充第二次计量的需结净的皮重数据
                    meterWorkCarActualFirstMapper.insertSelective(mwaf);
                    lyFirstNo = mwaf.getActualFirstNo();

                    ptsU.setValueFlag("2"); //修改当前预报状态
                    ptsU.setUploadFlag("1");
                    ptsU.setMeasureStation(mwaf.getBaseSpotNo());
                    ptsU.setMeasureStationName(mwaf.getBaseSpotName());
                    preTrackScaleMapper.updateByPrimaryKeySelective(ptsU);

                    //查找到的上个毛重写为结净
                    lmwaf.get(0).setValueFlag("2");//结净
                    meterWorkCarActualFirstMapper.updateByPrimaryKeySelective(lmwaf.get(0));

                    //将本次的这一个毛重写为有效
                    secondDb.setValueFlag("1");//有效
                    //=========eason add 2021-03-30==============
                    secondDb.setWeightType(mwaf.getWeightType().equals("0") ? "1" : "0");
                    //===========================================

                    //将结净数据中的毛重编号修改
                    if (mwaf.getMeterWeight().doubleValue() == netDb.getTareWeight().doubleValue()) {
                        //若此次补充的一次数据重量与结净中的皮重相同,则将这个编号赋值给结净数据的皮重编号
                        netDb.setActualFirst2No(mwaf.getActualFirstNo());
                    } else {
                        netDb.setActualFirst1No(mwaf.getActualFirstNo());
                    }
                }
            }
        } else if (pts.getPredictionType().equals("3") && StringUtils.isNotEmpty(pts.getRailwayNo())) {
            //===================火车分检预报处理开始==========================
            //分检预报 有效次数为1；每次计量需要更新火车的重量,前提是火车车号不允许为空***************
            //1.找到轨道衡的同一车的所有数据；重量类型weightType为毛重；状态位为（0,2）的数据(xml中默认)
            HashMap<String, Object> obj = new HashMap<>();
            obj.put("railwayNo", pts.getRailwayNo());
            obj.put("weightType", "0");
            List<MeterWorkRailwayActFirst> mwrafs = meterWorkRailwayActFirstMapper.selectBy(obj);
            if (mwrafs != null && mwrafs.size() > 0) {
                MeterWorkRailwayActFirst meterWorkRailwayActFirst = mwrafs.get(0);
                countForRail(meterWorkRailwayActFirst, netDb.getNetWeight()); //一次计量数据，净重数据
            }

            ptsU.setValueFlag("2");//预报完结
            ptsU.setUploadFlag("1");
            ptsU.setMeasureStation(mwrafs.get(0).getBaseSpotNo());
            ptsU.setMeasureStationName(mwrafs.get(0).getBaseSpotName());
            preTrackScaleMapper.updateByPrimaryKeySelective(ptsU);
            //===================火车分检预报处理结束==========================
        }

        //5、存储当前计量的数据
        String afl = formatter.format(secondDb.getCreateTime());
//        String iActualNo = meterWorkCarActualFirstMapper.getNewID(afl);
//        secondDb.setActualFirstNo(afl + iActualNo);

        String iActualNo = PublicMethod.IdCreate(3);
        secondDb.setActualFirstNo(iActualNo);

        secondDb.setCreateTime(new Date());
        meterWorkCarActualFirstMapper.insertSelective(secondDb);
        if (!secondDb.getPredictionNo().equals(netDb.getPredictionNo())) {
            //杨秀东2021-3-22；一车联运检化验处理;
            // 若一次计量中的预报编号与二次计量的编号不一致，则说明是一车联运；直接新增一条检化验接口数据
        }

        //一次计量的数据修改状态
        MeterWorkCarActualFirst firstUpdate = new MeterWorkCarActualFirst();

        //6、存储结净数据
//        String afl1 = formatter.format(netDb.getNetTime());
//        String no = meterWorkCarActualMapper.getNewID(afl1);
//        netDb.setActualNo(afl + no); //注意：此处生成的编号是下一次的编号；如果是一车联运不能直接返回给客户端这个编号

        String no = PublicMethod.IdCreate(3);
        netDb.setActualNo(no);

        if (secondDb.getMeterWeight().equals(netDb.getTareWeight())) {
            //二次指哪个了如果跟皮重一样
            if (StringUtils.isEmpty(netDb.getActualFirst2No()) || netDb.getActualFirst2No().length() < 10)
                netDb.setActualFirst2No(secondDb.getActualFirstNo()); //皮重编号
            firstUpdate.setActualFirstNo(netDb.getActualFirst1No());
        } else {
            if (StringUtils.isEmpty(netDb.getActualFirst1No()) || netDb.getActualFirst1No().length() < 10)
                netDb.setActualFirst1No(secondDb.getActualFirstNo()); //毛重编号
            firstUpdate.setActualFirstNo(netDb.getActualFirst2No());
        }
        if (netDb != null && netDb.getNetWeight() != null) {
            //2021年3月7日 净重保留两位小数；
            BigDecimal net;
            net = new BigDecimal(String.valueOf(netDb.getNetWeight())).setScale(2, BigDecimal.ROUND_HALF_UP);
            netDb.setNetWeight(net);
        }
        netDb.setUploadFlag("1");
        netDb.setCreateTime(new Date());
        if(netDb.getGrossTime().compareTo(netDb.getTareTime()) >= 0) {
            netDb.setNetSpot3No(netDb.getBaseSpot1No());
            netDb.setNetSpot3Name(netDb.getBaseSpot1Name());
            netDb.setNetManNo(netDb.getGrossManNo());
            netDb.setNetManName(netDb.getGrossManName());
            netDb.setNetTime(netDb.getGrossTime());
            netDb.setCreateTime(netDb.getGrossTime());
            netDb.setCreateManName(netDb.getGrossManName());
        }else {
            netDb.setNetSpot3No(netDb.getBaseSpot2No());
            netDb.setNetSpot3Name(netDb.getBaseSpot2Name());
            netDb.setNetManNo(netDb.getTareManNo());
            netDb.setNetManName(netDb.getTareManName());
            netDb.setNetTime(netDb.getTareTime());
            netDb.setCreateTime(netDb.getTareTime());
            netDb.setCreateManName(netDb.getTareManName());
        }
        meterWorkCarActualMapper.insertSelective(netDb);
        //2023年5月24日张楠修改
        try {
            MeterWorkCarActualFirst meterWorkCarActualFirst1 = meterWorkCarActualFirstMapper.selectByPrimaryKey(netDb.getActualFirst1No());
            if(meterWorkCarActualFirst1!=null){
                meterWorkCarActualFirst1.setValueFlag("2");
                meterWorkCarActualFirstMapper.updateByPrimaryKeySelective(meterWorkCarActualFirst1);
            }
            MeterWorkCarActualFirst meterWorkCarActualFirst2 = meterWorkCarActualFirstMapper.selectByPrimaryKey(netDb.getActualFirst2No());
            if(meterWorkCarActualFirst2!=null){
                meterWorkCarActualFirst2.setValueFlag("2");
                meterWorkCarActualFirstMapper.updateByPrimaryKeySelective(meterWorkCarActualFirst2);
            }
        }catch (Exception e){
            e.printStackTrace();
            log.error("外发结净更改状态失败{}",e);
        }

        //7、修改第一次存储的计量数据状态为结净;预报编号相同时才处理（不是一车联运非互锁式）
        if (firstUpdate.getActualFirstNo() != null
                && netDb.getPredictionNo() != null && secondDb.getPredictionNo() != null
                && netDb.getPredictionNo().equals(secondDb.getPredictionNo())) {
            firstUpdate.setValueFlag("2");
            if (secondDb.getWeightType().equals("0"))//第二次为毛重
            {
                firstUpdate.setWeightType("1");//第一次则为皮重
            } else {
                firstUpdate.setWeightType("0");//否则第一次为毛重
            }
            meterWorkCarActualFirstMapper.updateByPrimaryKeySelective(firstUpdate);
        }


        //8、修改结净的预环节为已使用
        Map<String, Object> updateLink = new HashMap<>();
        updateLink.put("predictionNo", netDb.getPredictionNo());
        updateLink.put("linkCode", "001021005");
        List<MeterWorkPreLink> mwpls = meterWorkPreLinkMapper.selectByParameters(updateLink);
        if (mwpls != null && mwpls.size() > 0) {
            mwpls.get(0).setValueFlag("1");//已使用
            meterWorkPreLinkMapper.updateByPrimaryKeySelective(mwpls.get(0));
        }


        //9、批次预报重新生成一套预环节   若为批次预报且还未用完
        if (pts.getPredictionType().equals("0")) {
            meterWorkPreLinkService.batchReset(netDb.getPredictionNo());
        }
        //yxd 2021年7月6日 对一车联运返回给客户端的的二次编号做处理
        if (pts.getPredictionType().equals("2") && StringUtils.isNotEmpty(lyFirstNo)) {
            secondDb.setActualFirstNo(lyFirstNo);
        }

        //10、存储图片
        //SaveImg(secondDb);

        //11、修改计量监控
        updateMonitor(secondDb.getBaseSpotNo());

        //12、修改监控的计量作业编号
        updateMonitorOver(secondDb.getActualFirstNo(), secondDb.getBaseSpotNo());


        //信息加密
        String str = netDb.getActualNo() + "," + netDb.getNetWeight() + "," + "2";
        String enStr = encryption(str);

        //保存日志
        saveNote(note);

        rm.setData(secondDb.getActualFirstNo());
        rm.setMessage(enStr);
        return rm;
    }


    public void updateMonitor(String baseSpotNo) {
        MeterWorkMonitor mwm = meterWorkMonitorMapper.selectByPrimaryKey(baseSpotNo);
        MeterWorkOnline mwo = meterWorkOnlineMapper.selectByPrimaryKey(mwm.getUserNo());
        //修改计量监控
        /*mwm.setUserNo("");
        meterWorkMonitorMapper.updateByPrimaryKeyNotUserNo(mwm);
        //修改在线状态
        if (mwo != null) {
            mwo.setWorkFlag("0");//未接管
            meterWorkOnlineMapper.updateByPrimaryKey(mwo);
        }*/
    }

    public void updateMonitorOver(String actualFirstNo, String baseSpotNo) {
        if (StringUtils.isEmpty(actualFirstNo)) {
            throw new MarkerMetException(500, "修改监控状态时，计量作业编号为空");
        }
        if (StringUtils.isEmpty(baseSpotNo)) {
            throw new MarkerMetException(500, "修改监控状态时，计量点编号为空");
        }
        MeterWorkMonitor mwm = meterWorkMonitorMapper.selectByPrimaryKey(baseSpotNo);
        mwm.setIsOverWgt(actualFirstNo);
        meterWorkMonitorMapper.updateByPrimaryKeySelective(mwm);
    }

    @Override
    public String encryption(String str) throws Exception {
        String deStr = AESUtil.encrypt(str, "abcdefghijklmnop", "0000000000000000");
        return deStr;
    }

    @Override
    public String encryptionTest(String carNo) throws Exception {
//        String deStr = AESUtil.encrypt(str, "abcdefghijklmnop", "0000000000000000");
//        return deStr;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmm");
        String afl = sdf.format(new Date());
        String message = carNo + "jisco2022" + afl;
        String key = "jiscosec";
        String deStr = DESUtil.toHexString(DESUtil.encrypt(message, key));
        //byte[] deStr = DESUtil.encrypt(message, key);
//        return deStr.toString();s
//        return new String(deStr);
        return deStr;
    }

    @Override
    public RESTfulResult decryptionTest(String str) {
        RESTfulResult rm = new RESTfulResult();
        rm.setFailed();
        try {
            String key = "jiscosec";
            String destr;
            try{
                destr = DESUtil.decrypt(str, key);
            }catch(Exception e) {
                rm.setCode("9");
                rm.setMessage("密文错误");
                return rm;
            }
            String carNo = destr.substring(0, 7);
            String time = destr.substring(16);

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            SimpleDateFormat sdf01 = new SimpleDateFormat("yyyyMMddHHmm");
            Date date = sdf01.parse(time);
            Calendar beforeTime = Calendar.getInstance();
            beforeTime.add(Calendar.MINUTE, -5);// 5分钟之前的时间
            Date startTime = sdf.parse(sdf.format(beforeTime.getTime()));
            Date endTime = sdf.parse(sdf.format(new Date()));

            if(!(date.compareTo(startTime) >= 0 && date.compareTo(endTime) <= 0)) {
                rm.setMessage("二维码已过期");
                rm.setCode("1");
                return rm;
            }

            String carnumRegex = "([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领 A-Z]{1}[A-Z]{1}(([0-9]{5}[DF])|([DF]([A-HJ-NP-Z0-9])[0-9]{4})))|([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领 A-Z]{1}[A-Z]{1}[A-HJ-NP-Z0-9]{4}[A-HJ-NP-Z0-9 挂学警港澳]{1})";
            if (!TextUtils.isEmpty(carNo)) {
                if(carNo.matches(carnumRegex)) {
                    rm.setSucceed();
                    rm.setCode("0");
                    rm.setMessage("操作成功");
                    rm.setData(carNo);
                }else {
                    rm.setMessage("车号不正确");
                    rm.setCode("2");
                }
            }else {
                rm.setMessage("车号为空");
                rm.setCode("2");
            }
        }catch(Exception e) {
            e.printStackTrace();
            rm.setMessage("操作异常>>>" + e.getMessage());
        }
        return rm;
    }

    //两条轨道衡计量实绩的替换
    private MeterWorkRailwayActFirst change(MeterWorkRailwayActFirst one, MeterWorkRailwayActFirst two) {
        //1、为有值的数据，2为0的值  进行替换
        //先判断是否需要修改结净
        if (one.getValueFlag().equals("2")) {
            //已经结净
            //有值的结净数据
            Map<String, Object> map1 = new HashMap<>();
            map1.put("predictionNo", one.getPredictionNo());
            map1.put("valueFlag", "0");
            map1.put("uploadFlag", "0");
            List<MeterWorkRailwayActual> mwra1 = meterWorkRailwayActualMapper.selectByParameters(map1);
            //为0的结净
            Map<String, Object> map2 = new HashMap<>();
            map2.put("predictionNo", two.getPredictionNo());
            map2.put("valueFlag", "0");
            map2.put("uploadFlag", "0");
            List<MeterWorkRailwayActual> mwra2 = meterWorkRailwayActualMapper.selectByParameters(map2);
            mwra2.get(0).setNetWeight(mwra1.get(0).getNetWeight());
            mwra2.get(0).setTareWeight(mwra1.get(0).getTareWeight());
            mwra2.get(0).setGrossWeight(mwra1.get(0).getGrossWeight());
            mwra1.get(0).setNetWeight(new BigDecimal(0));
            mwra1.get(0).setTareWeight(new BigDecimal(0));
            mwra1.get(0).setGrossWeight(new BigDecimal(0));
            //修改数据
            meterWorkRailwayActualMapper.updateByPrimaryKeySelective(mwra1.get(0));
            meterWorkRailwayActualMapper.updateByPrimaryKeySelective(mwra2.get(0));
        }
        two.setMeterBalanceWeight(one.getMeterBalanceWeight());
        two.setMeterWeight(one.getMeterWeight());
        two.setMeterSortWeight(one.getMeterSortWeight());
        meterWorkRailwayActFirstMapper.updateByPrimaryKeySelective(two);
        one.setMeterSortWeight(new BigDecimal(0));
        one.setMeterWeight(new BigDecimal(0));
        one.setMeterBalanceWeight(new BigDecimal(0));
        meterWorkRailwayActFirstMapper.updateByPrimaryKeySelective(one);
        return two;
    }

    /**
     * 改写轨道衡实绩的值（若结净，还要改写结净的值）
     *
     * @param one
     * @param netWeight
     */
    private void countForRail(MeterWorkRailwayActFirst one, BigDecimal netWeight) {
        //有值的数据
        one.setMeterSortWeight(one.getMeterSortWeight().add(netWeight));
        one.setMeterBalanceWeight(one.getMeterWeight().subtract(one.getMeterSortWeight()));
        one.setMemo(one.getMemo() + "分检重量：" + netWeight + ";");
        meterWorkRailwayActFirstMapper.updateByPrimaryKeySelective(one);
        if (one.getValueFlag().equals("2")) {
            //修改结净
            Map<String, Object> map = new HashMap<>();
            map.put("predictionNo", one.getPredictionNo());
            map.put("valueFlag", "0");
            map.put("uploadFlag", "0");
            List<MeterWorkRailwayActual> mwra1 = meterWorkRailwayActualMapper.selectByParameters(map);
            MeterWorkRailwayActual meterWorkRailwayActual = new MeterWorkRailwayActual();
            meterWorkRailwayActual.setActualNo(mwra1.get(0).getActualNo());
            meterWorkRailwayActual.setGrossWeight(one.getMeterBalanceWeight());
            meterWorkRailwayActual.setNetWeight(one.getMeterBalanceWeight().subtract(mwra1.get(0).getTareWeight()));
            meterWorkRailwayActual.setMemo(meterWorkRailwayActual.getMemo() + "分检重量：" + netWeight + ";");
            meterWorkRailwayActualMapper.updateByPrimaryKeySelective(meterWorkRailwayActual);
        }
    }

    private String saveNote(MeterMonitorNote note) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
        String afl = formatter.format(new Date());
        String no = meterMonitorNoteMapper.getNewID(afl);
        note.setNoteNo(PublicMethod.IdCreate(3));
        meterMonitorNoteMapper.insertSelective(note);
        return note.getNoteNo();
    }

    //将附加重量的编号取出，并新增进附加中的表中
    private void insertAddWgtNo(String actualFirstNo, String addWgtPk, String createManNo, String createManName) {
        if (StringUtils.isEmpty(actualFirstNo) || StringUtils.isEmpty(addWgtPk)) {
            throw new MarkerMetException(500, "附加重量异常");
        }
        String[] str = addWgtPk.split(",");
        for (int i = 0; i < str.length; i++) {
            MeterBaseAddWeight mbaw = meterBaseAddWeightMapper.selectByPrimaryKey(str[i]);
            MeterWorkAddWeight mkaw = new MeterWorkAddWeight();
            String no = meterWorkAddWeightMapper.getNewID();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            mkaw.setAddWeightActNo(sdf.format(new Date()) + no);
            mkaw.setActualFirstNo(actualFirstNo);
            mkaw.setAddWeightNo(mbaw.getAddWeightNo());
            mkaw.setUtensilTypeNo(mbaw.getUtensilTypeNo());
            mkaw.setUtensilName(mbaw.getUtensilName());
            mkaw.setUtensilNo(mbaw.getUtensilNo());
            mkaw.setUtensilUtensilName(mbaw.getUtensilUtensilName());
            mkaw.setUtensilWeight(mbaw.getUtensilWeight());
            mkaw.setCreateManNo(createManNo);
            mkaw.setCreateManName(createManName);
            mkaw.setCreateTime(new Date());
            meterWorkAddWeightMapper.insertSelective(mkaw);
        }
    }

    /**
     * 非内倒车辆使用期限皮重结净
     *
     * @param oci
     * @param netDb
     * @param note
     * @return
     */
    @Override
    @Transactional
    public RESTfulResult doAddNetByTermWf(MeterWorkCarActualFirst oci, MeterWorkCarActual netDb, MeterMonitorNote note) {
        RESTfulResult rm = new RESTfulResult();
        rm.setCode("200");

        //0、查询预报信息；判断预报车号的车号与前端传进来的车号是不是一样的；2021年5月16日
        PreTrackScale pts = preTrackScaleMapper.selectByPrimaryKey(oci.getPredictionNo());
        if (StringUtils.isEmpty(pts.getCarNo()) || !pts.getCarNo().equals(oci.getCarNo())) {
            throw new MarkerMetException(500, "预报中的车号【" + pts.getCarNo() + "】与界面车号不一致【" + oci.getCarNo() + "】");
        }

        //先格式化时间
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
        //1、新增一次数据
        //存储当前计量的数据
        String afl = formatter.format(oci.getCreateTime());
//        String iActualNo = meterWorkCarActualFirstMapper.getNewID(afl);
//        oci.setActualFirstNo(afl + iActualNo);

        String iActualNo = PublicMethod.IdCreate(3);
        oci.setActualFirstNo(iActualNo);

        oci.setValueFlag("2");
        oci.setCreateTime(new Date());
        meterWorkCarActualFirstMapper.insertSelective(oci);
        //2、补充期限皮重的数据
        MeterBaseTermTareData mbttd = meterBaseTermTareDataMapper.selectByPrimaryKey(netDb.getActualFirst2No());
        MeterWorkCarActualFirst imTare = new MeterWorkCarActualFirst();
        //补充数据
        String afl1 = formatter.format(new Date());
//        String imTareNO = meterWorkCarActualFirstMapper.getNewID(afl1);
//        imTare.setActualFirstNo(afl1 + imTareNO);

        String imTareNO = PublicMethod.IdCreate(3);
        imTare.setActualFirstNo(imTareNO);

        imTare.setMeterTypeNo(oci.getMeterTypeNo());
        imTare.setMeterTypeName(oci.getMeterTypeName());
        imTare.setBaseSpotNo(mbttd.getBaseSpotNo());
        imTare.setBaseSpotName(mbttd.getBaseSpotName());
        imTare.setCarNo(mbttd.getCarNo());
        imTare.setCreateTime(mbttd.getCreateTime());
        imTare.setCreateManNo(mbttd.getCreateManNo());
        imTare.setCreateManName(mbttd.getCreateManName());
        imTare.setMeterWeight(netDb.getTareWeight());
        imTare.setWeightType("2");//期限皮重
        imTare.setValueFlag("2");//结净
        meterWorkCarActualFirstMapper.insertSelective(imTare);
        //添加历史皮重2023年4月20日--zn
        //doSaveHisTare(imTare,"2");

        //3、新增结净数据
//        String afl2 = formatter.format(netDb.getNetTime());
//        String no = meterWorkCarActualMapper.getNewID(afl2);
//        netDb.setActualNo(afl + no);

        String no = PublicMethod.IdCreate(3);
        netDb.setActualNo(no);

        netDb.setActualFirst2No(imTare.getActualFirstNo());
        netDb.setActualFirst1No(oci.getActualFirstNo());
        if (netDb != null && netDb.getNetWeight() != null) {
            //2021年3月7日 净重保留两位小数；
            BigDecimal net;
            net = new BigDecimal(String.valueOf(netDb.getNetWeight())).setScale(2, BigDecimal.ROUND_HALF_UP);
            netDb.setNetWeight(net);
        }
        netDb.setCreateTime(new Date());
        if(netDb.getGrossTime().compareTo(netDb.getTareTime()) >= 0) {
            netDb.setNetSpot3No(netDb.getBaseSpot1No());
            netDb.setNetSpot3Name(netDb.getBaseSpot1Name());
            netDb.setNetManNo(netDb.getGrossManNo());
            netDb.setNetManName(netDb.getGrossManName());
            netDb.setNetTime(netDb.getGrossTime());
            netDb.setCreateTime(netDb.getGrossTime());
            netDb.setCreateManName(netDb.getGrossManName());
        }else {
            netDb.setNetSpot3No(netDb.getBaseSpot2No());
            netDb.setNetSpot3Name(netDb.getBaseSpot2Name());
            netDb.setNetManNo(netDb.getTareManNo());
            netDb.setNetManName(netDb.getTareManName());
            netDb.setNetTime(netDb.getTareTime());
            netDb.setCreateTime(netDb.getTareTime());
            netDb.setCreateManName(netDb.getTareManName());
        }
        meterWorkCarActualMapper.insertSelective(netDb);

        //4、修改预报
        if (pts.getPredictionType().equals("0")) {
            pts.setValueFlag("4");//正使用
            //批次预报 有时间，次数，重量限制
            if (pts.getUsedType().equals("0")) {  //0次数  1时间  2总量
                //次数
                pts.setMeterNum(pts.getMeterNum() == null ? 1 : (pts.getMeterNum() + 1));
                if (pts.getEffectiveNum().equals(pts.getMeterNum())) {//如果两个值相等
                    pts.setValueFlag("2");//用完了则状态改为2
                }
            } else if (pts.getUsedType().equals("1")) {
                //1时间
                if (!"2".equals(pts.getValueFlag()) && pts.getEffectiveEndTime().compareTo(new Date()) <= 0) {
                    pts.setValueFlag("2");//当前状态不为2，且结束时间小于当时间
                }
            } else if (pts.getUsedType().equals("2")) {
                //总量
                pts.setMeterWeight(pts.getMeterWeight() == null ? netDb.getNetWeight() : (pts.getMeterWeight().add(netDb.getNetWeight())));
                if (pts.getEffectiveWeight().doubleValue() <= pts.getMeterWeight().doubleValue()) {//如果总重量小于等于检斤重量则用完了
                    pts.setValueFlag("2");//用完了则状态改为2
                }
            }
            pts.setUploadFlag("1");
            pts.setMeasureStation(netDb.getNetSpot3No());
            pts.setMeasureStationName(netDb.getNetSpot3Name());
            preTrackScaleMapper.updateByPrimaryKeySelective(pts);
        } else if (pts.getPredictionType().equals("1")) {
            //单次预报 使用1次后将状态设置为已使用
            pts.setValueFlag("2");
            pts.setUploadFlag("1");
            pts.setMeasureStation(netDb.getNetSpot3No());
            pts.setMeasureStationName(netDb.getNetSpot3Name());
            preTrackScaleMapper.updateByPrimaryKeySelective(pts);
        } else if (pts.getPredictionType().equals("3") && StringUtils.isNotEmpty(pts.getRailwayNo())) {
            //===================火车分检预报处理开始==========================
            //分检预报 有效次数为1；每次计量需要更新火车的重量,前提是火车车号不允许为空***************
            //1.找到轨道衡的同一车的所有数据；重量类型weightType为毛重；状态位为（0,2）的数据(xml中默认)
            HashMap<String, Object> obj = new HashMap<>();
            obj.put("railwayNo", pts.getRailwayNo());
            obj.put("weightType", "0");
            List<MeterWorkRailwayActFirst> mwrafs = meterWorkRailwayActFirstMapper.selectBy(obj);
            if (mwrafs != null && mwrafs.size() > 0) {
                MeterWorkRailwayActFirst meterWorkRailwayActFirst = mwrafs.get(0);
                countForRail(meterWorkRailwayActFirst, netDb.getNetWeight()); //一次计量数据，净重数据
            }
            pts.setValueFlag("2");//预报完结
            pts.setUploadFlag("1");
            pts.setMeasureStation(mwrafs.get(0).getBaseSpotNo());
            pts.setMeasureStationName(mwrafs.get(0).getBaseSpotName());
            preTrackScaleMapper.updateByPrimaryKeySelective(pts);
            //===================火车分检预报处理结束==========================
        }
        //5、修改预环节
        //将结净计量以及之前的所有环节都置为已经使用
        List<MeterWorkPreLink> links = meterWorkPreLinkService.getPer(oci.getPredictionNo(), DbConstants.CLEAN); //001021005
        //2021年3月8日杨秀东新增逻辑，对卸货环节[001021004]进行特殊处理;
        if (links != null && links.size() > 1) {
            for (int i = links.size() - 1; i >= 0; i--) {
                //001021004
                if (links.get(i).getLinkCode() != null && DbConstants.unload.equals(links.get(i).getLinkCode())) {
                    links.remove(i);
                }
            }
        }
        meterWorkPreLinkMapper.batchUpdateForUse(links);
        //6、修改预流程
        //获取预流程是否还有未使用的环节，若没有了则修改其状态  2.2修改预流程
        MeterWorkPreLink mplq = new MeterWorkPreLink();
        mplq.setPreProcessNo(links.get(0).getPreProcessNo());
        mplq.setValueFlag("0");
        Map<String, Object> map = FieldsCollector.beanToMap(mplq);
        List<MeterWorkPreLink> list = meterWorkPreLinkMapper.selectByParameters(map);
        if (list.size() == 0) {
            MeterWorkPreProcess mpp = new MeterWorkPreProcess();
            mpp.setPreProcessNo(links.get(0).getPreProcessNo());
            mpp.setValueFlag("2");
            meterWorkPreProcessMapper.updateByPrimaryKeySelective(mpp);
        }
        //7、保存日志
        saveNote(note);

        //8、批次预报重新生成一套预环节  若为批次预报且还未用完
        if (pts.getPredictionType().equals("0")) {
            meterWorkPreLinkService.batchReset(netDb.getPredictionNo());
        }

        //处理检化验委托信息；非内倒车辆使用期限皮重结净
        rm.setData(oci.getActualFirstNo());
        return rm;
    }


    private String transferParamForLims(String carNo, String matterNo, String unloadPlace, String sendPlace, String netWgt,
                                        Date wgtTime, String grossWgt, String cardId) {
        //获取数据索引码（主数据编码）
        MeterBaseMatterInfo mbmi = meterBaseMatterInfoMapper.selectByPrimaryKey(matterNo);
        String matNo = mbmi.getIndexCode();
        //获取账登录deaccessTokens
        Map jsons = new HashMap();
        jsons.put("loginName", DbConstants.loginName);
        jsons.put("password", DbConstants.password);
        String logins = HttpRequest.postJsonMethodParamsEncode(DbConstants.IPFROLOGIN + "/icore.icp.web/pass/auth/login", jsons);
        String accessTokens = JSONObject.parseObject(JSONObject.parseObject(logins).getString("data")).getString("accessToken");
        //system.out.println(accessTokens);
        //调用接口为
        JSONObject json = new JSONObject();
        json.put("carNo", carNo);
        json.put("matNo", matNo);
        json.put("unloadPlace", unloadPlace);
        json.put("sendPlace", sendPlace);
        json.put("netWgt", netWgt);
        json.put("wgtTime", wgtTime);
        json.put("grossWgt", grossWgt);
        json.put("cardId", cardId);
        String result = HttpRequest.postmanAccessToken(DbConstants.IPFORTRAN + "/v1/limstestplans/replacementdata", JSONObject.toJSONString(json), accessTokens);
        String results = JSONObject.parseObject(result).getString("data");
        return results;
    }


    /**
     * 按照时间查询数据
     *
     * @param parmas
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public PageList<MeterWorkCarActualFirst> queryOrderByTime(HashMap parmas, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<MeterWorkCarActualFirst> firstList = meterWorkCarActualFirstMapper.queryOrderByTime(parmas);
        PageList pageInfo = new PageList(firstList);
        return pageInfo;
    }

    /**
     * WGT_TIME
     * 更新预报中的卸货截止时间
     *
     * @param actualFirst
     */
    public void updateTrastUnloadEndTime(MeterWorkCarActualFirst actualFirst) {
        if (actualFirst != null && StringUtils.isNotEmpty(actualFirst.getPredictionNo()) && StringUtils.isNotEmpty(actualFirst.getMatterNo())
                && StringUtils.isNotEmpty(actualFirst.getBaseSpotNo()) && StringUtils.isNotEmpty(actualFirst.getLoadPointNo())) {
            MeterBaseUnloadTime unloadTime = new MeterBaseUnloadTime();
            unloadTime.setBaseSpotNo(actualFirst.getBaseSpotNo());
            unloadTime.setLoadPointNo(actualFirst.getLoadPointNo());
            unloadTime.setMatterNo(actualFirst.getMatterNo());
            Map<String, Object> unloadTimeMap = FieldsCollector.beanToMap(unloadTime);
            List<MeterBaseUnloadTime> unloadTimeList = meterBaseUnloadTimeMapper.selectByParameters(unloadTimeMap);
            if (unloadTimeList != null && unloadTimeList.size() > 0) {
                PreTrackScale scale = new PreTrackScale();
                scale.setPredictionNo(actualFirst.getPredictionNo());
            }
        }
    }

    /**
     * 定期作废【销售出厂】未使用的氢氧化钠的皮重
     */
//    @Scheduled(cron = " 0 */60 * * * ?") //定时任务(每天凌晨两点执行一次)/作废皮重数据；定时服务打包时启用 @Scheduled(cron = " 0 0 2 * * ?")
    public void doInvalidNaOHData() {
        List<MeterWorkCarActualFirst> actFirstList = meterWorkCarActualFirstMapper.selectInvalidNaOHData();
        if (actFirstList != null && actFirstList.size() > 0) {
            for (MeterWorkCarActualFirst firstTare : actFirstList) {
                firstTare.setValueFlag("0");
                firstTare.setUpdateTime(new Date());
                firstTare.setUpdateManNo("system");
                firstTare.setUpdateManName("系统定时作废过期皮重信息");
                meterWorkCarActualFirstMapper.updateByPrimaryKey(firstTare);

                if (StringUtils.isNotEmpty(firstTare.getPredictionNo()) && firstTare.getPredictionNo().length() > 10) {
                    PreTrackScale trackScale = new PreTrackScale();
                    trackScale.setPredictionNo(firstTare.getPredictionNo());
                    trackScale.setValueFlag("3");
                    trackScale.setUpdateTime(new Date());
                    trackScale.setUpdateManNo("system");
                    trackScale.setUploadFlag("1");
                    trackScale.setUpdateManName("系统定时作废过期皮重信息");
                    preTrackScaleMapper.updateByPrimaryKey(trackScale);
                }
            }
        }
    }


    /**
     * 非内倒车辆存储一次计量数据
     *
     * @param oci
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public RESTfulResult doAddLianDaWf(MeterWorkCarActualFirst oci, MeterMonitorNote note) throws Exception {
        RESTfulResult rm = new RESTfulResult();
        rm.setCode("200");
        if (oci == null) {
            throw new MarkerMetException(500, "参数！！");
        }
        //0、查询预报信息；判断预报车号的车号与前端传进来的车号是不是一样的；2021年5月16日
//        PreTrackScale pts = preTrackScaleMapper.selectByPrimaryKey(oci.getPredictionNo().replace("_",""));
//        if (StringUtils.isEmpty(pts.getCarNo()) || !pts.getCarNo().equals(oci.getCarNo())) {
//            throw new MarkerMetException(500, "预报中的车号【" + pts.getCarNo() + "】与界面车号不一致【" + oci.getCarNo() + "】");
//        }

        //1、存储一次计量信息
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
        String afl = formatter.format(oci.getCreateTime());
//        String no = meterWorkCarActualFirstMapper.getNewID(afl);
//        oci.setActualFirstNo(afl + no);

        String no = PublicMethod.IdCreate(3);
        oci.setActualFirstNo(no);

        oci.setValueFlag("1");
        oci.setCreateTime(new Date());
        meterWorkCarActualFirstMapper.insertSelective(oci);

        //6、存储图片
        //SaveImg(oci);

        //7、修改计量监控
        updateMonitor(oci.getBaseSpotNo());

        //8、修改监控的计量作业编号
        updateMonitorOver(oci.getActualFirstNo(), oci.getBaseSpotNo());

        //信息加密
        String str = oci.getActualFirstNo() + "," + oci.getMeterWeight() + "," + "1";
        String enStr = encryption(str);

        //保存日志
        saveNote(note);

        rm.setData(oci.getActualFirstNo());
        rm.setMessage(enStr);
        return rm;
    }

    /**
     * 非内倒车辆结净
     *
     * @param secondDb 二次计量数据
     * @param netDb    净重数据
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(value = "tm", rollbackFor = Exception.class)
    public RESTfulResult doAddNetLianDaWf(MeterWorkCarActualFirst secondDb, MeterWorkCarActual netDb, MeterMonitorNote note) throws Exception {
        String lyFirstNo = "";//联运自动生成的一次计量编号
        RESTfulResult rm = new RESTfulResult();
        rm.setCode("200");
        //先格式化时间
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");

        //0、查询预报信息；判断预报车号的车号与前端传进来的车号是不是一样的；2021年5月16日
        PreTrackScale pts = preTrackScaleMapper.selectByPrimaryKey(secondDb.getPredictionNo().replace("_",""));
        if (StringUtils.isEmpty(pts.getCarNo()) || !pts.getCarNo().equals(secondDb.getCarNo())) {
            throw new MarkerMetException(500, "预报中的车号【" + pts.getCarNo() + "】与界面车号不一致【" + secondDb.getCarNo() + "】");
        }

        //1、存储当前计量的数据  1.1先给一个初始状态
        secondDb.setValueFlag("2");//结净

        //3.1判断皮重信息
        if (secondDb.getMeterWeight().equals(netDb.getTareWeight())) {
            //二次重量如果跟皮重一样
            netDb.setActualFirst2No(secondDb.getActualFirstNo());
        } else {
            netDb.setActualFirst1No(secondDb.getActualFirstNo());
        }



        //5、存储当前计量的数据
        String afl = formatter.format(secondDb.getCreateTime());
//        String iActualNo = meterWorkCarActualFirstMapper.getNewID(afl);
//        secondDb.setActualFirstNo(afl + iActualNo);

        String iActualNo = PublicMethod.IdCreate(3);
        secondDb.setActualFirstNo(iActualNo);

        secondDb.setCreateTime(new Date());
        meterWorkCarActualFirstMapper.insertSelective(secondDb);


        //一次计量的数据修改状态
        MeterWorkCarActualFirst firstUpdate = new MeterWorkCarActualFirst();

        //6、存储结净数据
//        String afl1 = formatter.format(netDb.getNetTime());
//        String no = meterWorkCarActualMapper.getNewID(afl1);
//        netDb.setActualNo(afl + no); //注意：此处生成的编号是下一次的编号；如果是一车联运不能直接返回给客户端这个编号

        String no = PublicMethod.IdCreate(3);
        netDb.setActualNo(no);

        if (secondDb.getMeterWeight().equals(netDb.getTareWeight())) {
            //二次指哪个了如果跟皮重一样
            if (StringUtils.isEmpty(netDb.getActualFirst2No()) || netDb.getActualFirst2No().length() < 10)
                netDb.setActualFirst2No(secondDb.getActualFirstNo()); //皮重编号
            firstUpdate.setActualFirstNo(netDb.getActualFirst1No());
        } else {
            if (StringUtils.isEmpty(netDb.getActualFirst1No()) || netDb.getActualFirst1No().length() < 10)
                netDb.setActualFirst1No(secondDb.getActualFirstNo()); //毛重编号
            firstUpdate.setActualFirstNo(netDb.getActualFirst2No());
        }
        if (netDb != null && netDb.getNetWeight() != null) {
            //2021年3月7日 净重保留两位小数；
            BigDecimal net;
            net = new BigDecimal(String.valueOf(netDb.getNetWeight())).setScale(2, BigDecimal.ROUND_HALF_UP);
            netDb.setNetWeight(net);
        }
        netDb.setUploadFlag("1");
        netDb.setCreateTime(new Date());
        if(netDb.getGrossTime().compareTo(netDb.getTareTime()) >= 0) {
            netDb.setNetSpot3No(netDb.getBaseSpot1No());
            netDb.setNetSpot3Name(netDb.getBaseSpot1Name());
            netDb.setNetManNo(netDb.getGrossManNo());
            netDb.setNetManName(netDb.getGrossManName());
            netDb.setNetTime(netDb.getGrossTime());
            netDb.setCreateTime(netDb.getGrossTime());
            netDb.setCreateManName(netDb.getGrossManName());
        }else {
            netDb.setNetSpot3No(netDb.getBaseSpot2No());
            netDb.setNetSpot3Name(netDb.getBaseSpot2Name());
            netDb.setNetManNo(netDb.getTareManNo());
            netDb.setNetManName(netDb.getTareManName());
            netDb.setNetTime(netDb.getTareTime());
            netDb.setCreateTime(netDb.getTareTime());
            netDb.setCreateManName(netDb.getTareManName());
        }
        meterWorkCarActualMapper.insertSelective(netDb);

        //7、修改第一次存储的计量数据状态为结净;预报编号相同时才处理（不是一车联运非互锁式）
        if (firstUpdate.getActualFirstNo() != null
                && netDb.getPredictionNo() != null && secondDb.getPredictionNo() != null
                && netDb.getPredictionNo().equals(secondDb.getPredictionNo())) {
            firstUpdate.setValueFlag("2");
            if (secondDb.getWeightType().equals("0"))//第二次为毛重
            {
                firstUpdate.setWeightType("1");//第一次则为皮重
            } else {
                firstUpdate.setWeightType("0");//否则第一次为毛重
            }
            meterWorkCarActualFirstMapper.updateByPrimaryKeySelective(firstUpdate);
        }

        //10、存储图片
        //SaveImg(secondDb);

        //11、修改计量监控
        updateMonitor(secondDb.getBaseSpotNo());

        //12、修改监控的计量作业编号
        updateMonitorOver(secondDb.getActualFirstNo(), secondDb.getBaseSpotNo());


        //信息加密
        String str = netDb.getActualNo() + "," + netDb.getNetWeight() + "," + "2";
        String enStr = encryption(str);

        //保存日志
        saveNote(note);

        rm.setData(secondDb.getActualFirstNo());
        rm.setMessage(enStr);
        return rm;
    }

    /**
     * 双委托数据结净
     *
     * @param secondDb 二次计量数据
     * @param netDb1    A-B净重数据
     * @param netDb2    B-C净重数据
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(value = "tm", rollbackFor = Exception.class)
    public RESTfulResult doAddNetDouble(MeterWorkCarActualFirst secondDb, MeterWorkCarActual netDb1, MeterMonitorNote note, MeterWorkCarActual netDb2) throws Exception {
        RESTfulResult rm = new RESTfulResult();
        rm.setCode("200");
        //先格式化时间
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");

        //1、存储当前计量的数据  1.1先给一个初始状态
        secondDb.setValueFlag("2");//结净

        //2、存储三条一次计量数据
        // 第一条结净数据的二次重量数据
        String afl = formatter.format(secondDb.getCreateTime());
//        String iActualNo = meterWorkCarActualFirstMapper.getNewID(afl);
//        secondDb.setActualFirstNo(afl + iActualNo);

        String iActualNo = PublicMethod.IdCreate(3);
        secondDb.setActualFirstNo(iActualNo);
        if (netDb1.getActualFirst1No() == null || "".equals(netDb1.getActualFirst1No())) {
            netDb1.setActualFirst1No(secondDb.getActualFirstNo());
        } else {
            netDb1.setActualFirst2No(secondDb.getActualFirstNo());
        }
        secondDb.setCreateTime(new Date());
        meterWorkCarActualFirstMapper.insertSelective(secondDb);

        // 第二条结净数据的一次重量数据
        MeterWorkCarActualFirst first1 = new MeterWorkCarActualFirst();
        MeterWorkCarActualFirst first2 = new MeterWorkCarActualFirst();

        //一次计量的数据修改状态
        MeterWorkCarActualFirst firstUpdate = new MeterWorkCarActualFirst();

        //6、存储结净数据
//        String afl1 = formatter.format(netDb1.getNetTime());
//        String no = meterWorkCarActualMapper.getNewID(afl1);
//        netDb1.setActualNo(afl + no); //注意：此处生成的编号是下一次的编号；如果是一车联运不能直接返回给客户端这个编号

        String no = PublicMethod.IdCreate(3);
        netDb1.setActualNo(no);

        if (secondDb.getMeterWeight().equals(netDb1.getTareWeight())) {
            //二次指哪个了如果跟皮重一样
            if (StringUtils.isEmpty(netDb1.getActualFirst2No()) || netDb1.getActualFirst2No().length() < 10)
                netDb1.setActualFirst2No(secondDb.getActualFirstNo()); //皮重编号
            firstUpdate.setActualFirstNo(netDb1.getActualFirst1No());
        } else {
            if (StringUtils.isEmpty(netDb1.getActualFirst1No()) || netDb1.getActualFirst1No().length() < 10)
                netDb1.setActualFirst1No(secondDb.getActualFirstNo()); //毛重编号
            firstUpdate.setActualFirstNo(netDb1.getActualFirst2No());
        }
        if (netDb1 != null && netDb1.getNetWeight() != null) {
            //2021年3月7日 净重保留两位小数；
            BigDecimal net;
            net = new BigDecimal(String.valueOf(netDb1.getNetWeight())).setScale(2, BigDecimal.ROUND_HALF_UP);
            netDb1.setNetWeight(net);
        }
        netDb1.setCreateTime(new Date());
        if(netDb1.getGrossTime().compareTo(netDb1.getTareTime()) >= 0) {
            netDb1.setNetSpot3No(netDb1.getBaseSpot1No());
            netDb1.setNetSpot3Name(netDb1.getBaseSpot1Name());
            netDb1.setNetManNo(netDb1.getGrossManNo());
            netDb1.setNetManName(netDb1.getGrossManName());
            netDb1.setNetTime(netDb1.getGrossTime());
            netDb1.setCreateTime(netDb1.getGrossTime());
            netDb1.setCreateManName(netDb1.getGrossManName());
        }else {
            netDb1.setNetSpot3No(netDb1.getBaseSpot2No());
            netDb1.setNetSpot3Name(netDb1.getBaseSpot2Name());
            netDb1.setNetManNo(netDb1.getTareManNo());
            netDb1.setNetManName(netDb1.getTareManName());
            netDb1.setNetTime(netDb1.getTareTime());
            netDb1.setCreateTime(netDb1.getTareTime());
            netDb1.setCreateManName(netDb1.getTareManName());
        }
        meterWorkCarActualMapper.insertSelective(netDb1);



        //10、存储图片
        //(secondDb);

        //11、修改计量监控
        updateMonitor(secondDb.getBaseSpotNo());

        //12、修改监控的计量作业编号
        updateMonitorOver(secondDb.getActualFirstNo(), secondDb.getBaseSpotNo());


        //信息加密
        String str = netDb1.getActualNo() + "," + netDb1.getNetWeight() + "," + "2";
        String enStr = encryption(str);

        //保存日志
        saveNote(note);

        rm.setData(secondDb.getActualFirstNo());
        rm.setMessage(enStr);
        return rm;
    }


    /**
     * 吊钩秤存储一次计量数据
     * @param oci
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public RESTfulResult doCraneDbWf(MeterWorkCarActualFirst oci, MeterMonitorNote note) throws Exception {
        RESTfulResult rm = new RESTfulResult();
        rm.setCode("200");
        if (oci == null) {
            throw new MarkerMetException(500, "参数！！");
        }
        //0、查询预报信息；判断预报车号的车号与前端传进来的车号是不是一样的；2021年5月16日
        PreTrackScale pts = preTrackScaleMapper.selectByPrimaryKey(oci.getPredictionNo());
        if (StringUtils.isEmpty(pts.getCarNo()) || !pts.getCarNo().equals(oci.getCarNo())) {
            throw new MarkerMetException(500, "预报中的车号【" + pts.getCarNo() + "】与界面车号不一致【" + oci.getCarNo() + "】");
        }

        //1、存储一次计量信息
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
        String afl = formatter.format(oci.getCreateTime());
//        String no = meterWorkCarActualFirstMapper.getNewID(afl);
//        oci.setActualFirstNo(afl + no);
        String no = PublicMethod.IdCreate(3);
        oci.setActualFirstNo(no);
        oci.setValueFlag("1");
        oci.setCreateTime(new Date());
        meterWorkCarActualFirstMapper.insertSelective(oci);

        //根据车号加预报编号修改 craneActualMapper
        HashMap<String, Object> obj = new HashMap<>();
        obj.put("predictionNo", oci.getPredictionNo());
        obj.put("carNo", oci.getCarNo());
        obj.put("valueFlag", "2");
        obj.put("weightType","0");
        craneActualMapper.doUpdateFlag(obj);

        //修改预报为已使用，因为车子可能过几天才来过皮，所以预报不能处于正使用状态，否则会使车辆无法继续过磅
        PreTrackScale pre=new PreTrackScale();
        pre.setPredictionNo(oci.getPredictionNo());
        pre.setValueFlag("2");
        pre.setUploadFlag("1");
        pre.setMeasureStation(oci.getBaseSpotNo());
        pre.setMeasureStationName(oci.getBaseSpotName());
        preTrackScaleMapper.updateByPrimaryKeySelective(pre);

        //若有环节信息，还得将环节信息给设置为已使用，不然会影响后续计量的流程
        meterWorkPreLinkMapper.doUpdateFlag(obj);

        //信息加密
        String str = oci.getActualFirstNo() + "," + oci.getMeterWeight() + "," + "1";
        String enStr = encryption(str);

        //保存日志
        saveNote(note);

        rm.setData(oci.getActualFirstNo());
        rm.setMessage(enStr);
        return rm;
    }

    @Override
    @Transactional
    public RESTfulResult doCraneNetDbWf(MeterWorkCarActualFirst oci, MeterWorkCarActual netDB, MeterMonitorNote note) throws Exception {
        RESTfulResult rm = new RESTfulResult();
        rm.setCode("200");
        if (oci == null) {
            throw new MarkerMetException(500, "参数！！");
        }
        //0、查询预报信息；判断预报车号的车号与前端传进来的车号是不是一样的；2021年5月16日
        PreTrackScale pts = preTrackScaleMapper.selectByPrimaryKey(oci.getPredictionNo());
        if (StringUtils.isEmpty(pts.getCarNo()) || !pts.getCarNo().equals(oci.getCarNo())) {
            throw new MarkerMetException(500, "预报中的车号【" + pts.getCarNo() + "】与界面车号不一致【" + oci.getCarNo() + "】");
        }

        //1、存储一次计量信息
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
        String afl = formatter.format(oci.getCreateTime());
//        String no = meterWorkCarActualFirstMapper.getNewID(afl);
//        oci.setActualFirstNo(afl + no);

        String no = PublicMethod.IdCreate(3);
        oci.setActualFirstNo(no);

        oci.setValueFlag("2");
        oci.setCreateTime(new Date());
        meterWorkCarActualFirstMapper.insertSelective(oci);

        netDB.setActualFirst2No(oci.getActualFirstNo());
//        String no1 = meterWorkCarActualMapper.getNewID(afl);
//        netDB.setActualNo(afl + no1);

        String no1 = PublicMethod.IdCreate(3);
        netDB.setActualNo(no1);

        //2、将原有的一次数据结净
        MeterWorkCarActualFirst firstDb=new MeterWorkCarActualFirst();
        firstDb.setActualFirstNo(netDB.getActualFirst1No());
        firstDb.setValueFlag("2");
        meterWorkCarActualFirstMapper.updateByPrimaryKeySelective(firstDb);

        //3、存储数据到结净表
        netDB.setCreateTime(new Date());
        if(netDB.getGrossTime().compareTo(netDB.getTareTime()) >= 0) {
            netDB.setNetSpot3No(netDB.getBaseSpot1No());
            netDB.setNetSpot3Name(netDB.getBaseSpot1Name());
            netDB.setNetManNo(netDB.getGrossManNo());
            netDB.setNetManName(netDB.getGrossManName());
            netDB.setNetTime(netDB.getGrossTime());
            netDB.setCreateTime(netDB.getGrossTime());
            netDB.setCreateManName(netDB.getGrossManName());
        }else {
            netDB.setNetSpot3No(netDB.getBaseSpot2No());
            netDB.setNetSpot3Name(netDB.getBaseSpot2Name());
            netDB.setNetManNo(netDB.getTareManNo());
            netDB.setNetManName(netDB.getTareManName());
            netDB.setNetTime(netDB.getTareTime());
            netDB.setCreateTime(netDB.getTareTime());
            netDB.setCreateManName(netDB.getTareManName());
        }
        meterWorkCarActualMapper.insert(netDB);

        //4、根据车号加预报编号修改 craneActualMapper
        HashMap<String, Object> obj = new HashMap<>();
        obj.put("predictionNo", oci.getPredictionNo());
        obj.put("carNo", oci.getCarNo());
        obj.put("weightType","1");
        obj.put("valueFlag", "2");
        craneActualMapper.doUpdateFlag(obj);

        //信息加密
        String str = oci.getActualFirstNo() + "," + oci.getMeterWeight() + "," + "1";
        String enStr = encryption(str);

        //5、保存日志
        saveNote(note);

        rm.setData(oci.getActualFirstNo());
        rm.setMessage(enStr);
        return rm;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<String> distinctCarNo(HashMap<String, Object> obj) {

        if(obj==null){
            obj = new HashMap<>();
        }
//        HashMap<String, Object> obj = new HashMap<>();
//        obj.put("carNo", carNo);
//        obj.put("startTime", startTime);
//        obj.put("endTime", endTime);
//        obj.put("baseSpotNo", baseSpotNo);
//        obj.put("matterName", matterName);
//        obj.put("predictionNo", predictionNo);
//        obj.put("forwardingUnitName", forwardingUnitName);
//        obj.put("receivingUintName", receivingUintName);
//        obj.put("valueFlag", valueFlag);
        List<String> list = meterWorkCarActualFirstMapper.distinctCarNo(obj).stream().map(MeterWorkCarActualFirst::getCarNo).distinct().collect(Collectors.toList());
        return list;
    }

    @Override
    public RESTfulResult doAddNetHZHX(MeterWorkCarActualFirst first02,MeterWorkCarActual carModel, MeterWorkCarActualFirst first03,  MeterMonitorNote note) throws Exception {
        RESTfulResult rm = new RESTfulResult();
        rm.setFailed();
        try {
            String scaleNo = null;
            if(first02.getMeterProcessNo()!=null && StringUtils.isNotEmpty(first02.getMeterProcessNo())) {
                String[] strList = first02.getMeterProcessNo().split(",");
                if(strList.length >= 1) {
                    if(strList[0].equals("混料")) {
                        scaleNo = strList[1];
                    }
                }
            }
//            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
//            String afl = sdf.format(new Date());

            //存储当前计量的数据
//            String firstNo01 = sdf.format(new Date()) + meterWorkCarActualFirstMapper.getNewID(afl);
//            first02.setActualFirstNo(firstNo01);
            String firstNo01 = PublicMethod.IdCreate(3);
            first02.setActualFirstNo(firstNo01);

            first02.setCreateTime(new Date());
            meterWorkCarActualFirstMapper.insertSelective(first02);

            MeterWorkCarActual actualRow = new MeterWorkCarActual();
            //毛重一次
            MeterWorkCarActualFirst model01 = meterWorkCarActualFirstMapper.selectByPrimaryKey(carModel.getActualFirst1No());
            //皮重一次
            MeterWorkCarActualFirst model02 = meterWorkCarActualFirstMapper.selectByPrimaryKey(carModel.getActualFirst2No());
            PreTrackScale scale = preTrackScaleMapper.selectByPrimaryKey(carModel.getPredictionNo());
            //判断当前一次重量类型、0：毛重，则为混装操作、1：常规皮重，则为混卸操作
            if (first02.getWeightType().equals("0")) {       //混装
                //修改委托状态
                //将委托中的编号和收发货的等数据拷贝进一次数据中
                MeterWorkCarActualFirst first1 = meterWorkCarActualFirstMapper.selectAndMatch(model02.getActualFirstNo(), scale.getPredictionNo());
                BeanUtils.copyProperties(first1, model02);
                MeterWorkCarActualFirst first2 = meterWorkCarActualFirstMapper.selectAndMatch(first02.getActualFirstNo(), scale.getPredictionNo());
                BeanUtils.copyProperties(first2, first02);



                //修改毛重一次数据状态
                first02.setValueFlag(DbConstants.NET);
                first02.setUpdateManNo("system");
                first02.setUpdateManName("混装结净更新");
                first02.setUpdateTime(new Date());
                first02.setWeightType("0");
                first02.setIsPreScale("1");
                first02.setPredictionNo(scale.getPredictionNo());
                first02.setPredictionType("7");
                meterWorkCarActualFirstMapper.updateByPrimaryKeySelective(first02);
                //修改皮重一次数据状态
                model02.setValueFlag(DbConstants.NET);
                model02.setUpdateManNo("system");
                model02.setUpdateManName("混装结净更新");
                model02.setUpdateTime(new Date());
                model02.setWeightType("1");
                model02.setIsPreScale("1");
                model02.setPredictionNo(scale.getPredictionNo());
                model02.setPredictionType("7");
                meterWorkCarActualFirstMapper.updateByPrimaryKeySelective(model02);

                MeterWorkCarActual mwca1 = meterWorkCarActualMapper.manualAddPre(first02.getActualFirstNo(), model02.getActualFirstNo(), scale.getPredictionNo());
                BeanUtils.copyProperties(mwca1, actualRow);
                //保存结净
//                String no = meterWorkCarActualMapper.getNewID(sdf.format(new Date()));
//                actualRow.setActualNo(sdf.format(new Date()) + no);

                String no = PublicMethod.IdCreate(3);
                actualRow.setActualNo(no);
                actualRow.setNetTime(new Date());
                actualRow.setNetMode(DbConstants.TYPE);
                actualRow.setNote("混装匹配结净");
                actualRow.setNetMode("4");
                actualRow.setUploadFlag("1");
                actualRow.setValueFlag("1");
                actualRow.setIsPreScale("1");
                actualRow.setNetManNo(carModel.getNetManNo());
                actualRow.setNetManName(carModel.getNetManName());
                actualRow.setNetSpot3No(carModel.getNetSpot3No());
                actualRow.setNetSpot3Name(carModel.getNetSpot3Name());
                actualRow.setCreateManName(carModel.getCreateManName());
                actualRow.setCreateTime(carModel.getCreateTime());
                actualRow.setUpdateManNo(carModel.getUpdateManNo());
                actualRow.setUpdateManName(carModel.getUpdateManName());
                actualRow.setUpdateTime(carModel.getUpdateTime());
                actualRow.setPredictionNo(scale.getPredictionNo());
                actualRow.setPredictionType("7");
                actualRow.setNetWeight(first02.getMeterWeight().subtract(model02.getMeterWeight()));
                if(actualRow.getGrossTime().compareTo(actualRow.getTareTime()) >= 0) {
                    actualRow.setNetSpot3No(actualRow.getBaseSpot1No());
                    actualRow.setNetSpot3Name(actualRow.getBaseSpot1Name());
                    actualRow.setNetManNo(actualRow.getGrossManNo());
                    actualRow.setNetManName(actualRow.getGrossManName());
                    actualRow.setNetTime(actualRow.getGrossTime());
                    actualRow.setCreateTime(actualRow.getGrossTime());
                    actualRow.setCreateManName(actualRow.getGrossManName());
                }else {
                    actualRow.setNetSpot3No(actualRow.getBaseSpot2No());
                    actualRow.setNetSpot3Name(actualRow.getBaseSpot2Name());
                    actualRow.setNetManNo(actualRow.getTareManNo());
                    actualRow.setNetManName(actualRow.getTareManName());
                    actualRow.setNetTime(actualRow.getTareTime());
                    actualRow.setCreateTime(actualRow.getTareTime());
                    actualRow.setCreateManName(actualRow.getTareManName());
                }
                meterWorkCarActualMapper.insertSelective(actualRow);

                //修改委托编号
                scale.setValueFlag(DbConstants.NET);
                scale.setUpdateTime(new Date());
                scale.setUpdateManNo("system");
                scale.setUpdateManName("混装结净更新");
                scale.setUploadFlag("1");
                scale.setPredictionType("7");
                scale.setMeasureStation(actualRow.getNetSpot3No());
                scale.setMeasureStationName(actualRow.getNetSpot3Name());
                preTrackScaleMapper.updateByPrimaryKeySelective(scale);
            } else if (first02.getWeightType().equals("1")) {         //混卸
                //修改委托状态
                //将委托中的编号和收发货的等数据拷贝进一次数据中
                MeterWorkCarActualFirst first1 = meterWorkCarActualFirstMapper.selectAndMatch(model01.getActualFirstNo(), scale.getPredictionNo());
                BeanUtils.copyProperties(first1, model01);
                MeterWorkCarActualFirst first2 = meterWorkCarActualFirstMapper.selectAndMatch(first02.getActualFirstNo(), scale.getPredictionNo());
                BeanUtils.copyProperties(first2, first02);

                //修改毛重一次数据状态
                first02.setValueFlag(DbConstants.NET);
                first02.setUpdateManNo("system");
                first02.setUpdateManName("混卸结净更新");
                first02.setUpdateTime(new Date());
                first02.setWeightType("0");
                first02.setIsPreScale("1");
                first02.setPredictionNo(scale.getPredictionNo());
                first02.setPredictionType("6");
                meterWorkCarActualFirstMapper.updateByPrimaryKeySelective(first02);
                //修改皮重一次数据状态
                model01.setValueFlag(DbConstants.NET);
                model01.setUpdateManNo("system");
                model01.setUpdateManName("混卸结净更新");
                model01.setUpdateTime(new Date());
                model01.setWeightType("1");
                model01.setIsPreScale("1");
                model01.setPredictionNo(scale.getPredictionNo());
                model01.setPredictionType("6");
                meterWorkCarActualFirstMapper.updateByPrimaryKeySelective(model01);

                MeterWorkCarActual mwca1 = meterWorkCarActualMapper.manualAddPre(model01.getActualFirstNo(), first02.getActualFirstNo(),  scale.getPredictionNo());
                BeanUtils.copyProperties(mwca1, actualRow);

                //保存结净
//                String no = meterWorkCarActualMapper.getNewID(sdf.format(new Date()));
//                actualRow.setActualNo(sdf.format(new Date()) + no);

                String no = PublicMethod.IdCreate(3);
                actualRow.setActualNo(no);
                actualRow.setNetTime(new Date());
                actualRow.setNetMode(DbConstants.TYPE);
                actualRow.setNote("混卸匹配结净");
                actualRow.setNetMode("5");
                actualRow.setUploadFlag("1");
                actualRow.setValueFlag("1");
                actualRow.setIsPreScale("1");
                actualRow.setNetManNo(carModel.getNetManNo());
                actualRow.setNetManName(carModel.getNetManName());
                actualRow.setNetSpot3No(carModel.getNetSpot3No());
                actualRow.setNetSpot3Name(carModel.getNetSpot3Name());
                actualRow.setCreateManName(carModel.getCreateManName());
                actualRow.setCreateTime(carModel.getCreateTime());
                actualRow.setUpdateManNo(carModel.getUpdateManNo());
                actualRow.setUpdateManName(carModel.getUpdateManName());
                actualRow.setUpdateTime(carModel.getUpdateTime());
                actualRow.setPredictionNo(scale.getPredictionNo());
                actualRow.setPredictionType("6");
                actualRow.setNetWeight(model01.getMeterWeight().subtract(first02.getMeterWeight()));
                if(actualRow.getGrossTime().compareTo(actualRow.getTareTime()) >= 0) {
                    actualRow.setNetSpot3No(actualRow.getBaseSpot1No());
                    actualRow.setNetSpot3Name(actualRow.getBaseSpot1Name());
                    actualRow.setNetManNo(actualRow.getGrossManNo());
                    actualRow.setNetManName(actualRow.getGrossManName());
                    actualRow.setNetTime(actualRow.getGrossTime());
                    actualRow.setCreateTime(actualRow.getGrossTime());
                    actualRow.setCreateManName(actualRow.getGrossManName());
                }else {
                    actualRow.setNetSpot3No(actualRow.getBaseSpot2No());
                    actualRow.setNetSpot3Name(actualRow.getBaseSpot2Name());
                    actualRow.setNetManNo(actualRow.getTareManNo());
                    actualRow.setNetManName(actualRow.getTareManName());
                    actualRow.setNetTime(actualRow.getTareTime());
                    actualRow.setCreateTime(actualRow.getTareTime());
                    actualRow.setCreateManName(actualRow.getTareManName());
                }
                meterWorkCarActualMapper.insertSelective(actualRow);

                //修改委托编号
                scale.setValueFlag(DbConstants.NET);
                scale.setUpdateTime(new Date());
                scale.setUpdateManNo("system");
                scale.setUpdateManName("混卸结净更新");
                scale.setUploadFlag("1");
                scale.setPredictionType("6");
                scale.setMeasureStation(actualRow.getNetSpot3No());
                scale.setMeasureStationName(actualRow.getNetSpot3Name());
                preTrackScaleMapper.updateByPrimaryKeySelective(scale);
            }

            //存储当前计量的数据
            if(first03 != null) {
//                String fristNo03 = sdf.format(new Date()) + meterWorkCarActualFirstMapper.getNewID(afl);
//                first03.setActualFirstNo(fristNo03);
                String fristNo03 = PublicMethod.IdCreate(3);
                first03.setActualFirstNo(fristNo03);

                first03.setIsPreScale("0");
                first03.setCreateTime(new Date());
                meterWorkCarActualFirstMapper.insertSelective(first03);
            }else {
                if(scaleNo != null && StringUtils.isNotEmpty(scaleNo)) {
                    //获取
                    MeterWorkCarActualFirst grossModel = meterWorkCarActualFirstMapper.selectByPrimaryKey(actualRow.getActualFirst1No());
                    MeterWorkCarActualFirst tareModel = meterWorkCarActualFirstMapper.selectByPrimaryKey(actualRow.getActualFirst2No());
                    MeterWorkCarActual actualModel = meterWorkCarActualMapper.selectByPrimaryKey(actualRow.getActualNo());
                    PreTrackScale scaleTemp = preTrackScaleMapper.selectByPrimaryKey(scaleNo);

                    grossModel.setPredictionCombination(carModel.getPredictionNo() + "," + scaleTemp.getPredictionNo());
                    tareModel.setPredictionCombination(carModel.getPredictionNo() + "," + scaleTemp.getPredictionNo());
                    actualModel.setPredictionCombination(carModel.getPredictionNo() + "," + scaleTemp.getPredictionNo());

                    meterWorkCarActualFirstMapper.updateByPrimaryKeySelective(grossModel);
                    meterWorkCarActualFirstMapper.updateByPrimaryKeySelective(tareModel);
                    meterWorkCarActualMapper.updateByPrimaryKeySelective(actualModel);

                    HashMap<String, Object> obj = new HashMap<>();
                    obj.put("predictionNo", scaleNo);
                    List<MeterWorkCarActual> modelList = meterWorkCarActualMapper.selectByParameters(obj);
                    if(modelList.size() >= 1) {
                        MeterWorkCarActual preCarActual = modelList.get(0);
                        MeterWorkCarActualFirst preGrossModel = meterWorkCarActualFirstMapper.selectByPrimaryKey(preCarActual.getActualFirst1No());
                        MeterWorkCarActualFirst preTareModel = meterWorkCarActualFirstMapper.selectByPrimaryKey(preCarActual.getActualFirst2No());

                        preGrossModel.setPredictionCombination(carModel.getPredictionNo() + "," + scaleTemp.getPredictionNo());
                        preTareModel.setPredictionCombination(carModel.getPredictionNo() + "," + scaleTemp.getPredictionNo());
                        preCarActual.setPredictionCombination(carModel.getPredictionNo() + "," + scaleTemp.getPredictionNo());

                        meterWorkCarActualFirstMapper.updateByPrimaryKeySelective(preGrossModel);
                        meterWorkCarActualFirstMapper.updateByPrimaryKeySelective(preTareModel);
                        meterWorkCarActualMapper.updateByPrimaryKeySelective(preCarActual);
                    }
                }
            }
            //6、修改计量监控
            updateMonitor(first02.getBaseSpotNo());
            //保存日志
            saveNote(note);
            updateMonitorOver(first02.getActualFirstNo(), first02.getBaseSpotNo());
            //补充附加重量的数据
            if (StringUtils.isNotEmpty(first02.getAddWgtPk())) {
                insertAddWgtNo(first02.getActualFirstNo(), first02.getAddWgtPk(), first02.getCreateManNo(), first02.getCreateManName());
            }
            rm.setSucceed();
            rm.setData(first02.getActualFirstNo());
            rm.setCode("200");
            rm.setMessage("操作成功！！");
            return rm;
        }catch(Exception e) {
            e.printStackTrace();
            rm.setMessage("操作异常，请确认！！>>>>" + e.getMessage());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return rm;
        }
    }

    @Override
    public RESTfulResult doNetAddTwo(MeterWorkCarActualFirst one, MeterWorkCarActual two, PreTrackScale three, PreTrackScale four) throws Exception {
        RESTfulResult rm = new RESTfulResult();
        rm.setFailed();

        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            String afl = sdf.format(new Date());

            //存储当前计量的数据
//            String firstNo01 = sdf.format(new Date()) + meterWorkCarActualFirstMapper.getNewID(afl);
//            one.setActualFirstNo(firstNo01);

            String firstNo01 = PublicMethod.IdCreate(3);
            one.setActualFirstNo(firstNo01);
            one.setCreateTime(new Date());
            meterWorkCarActualFirstMapper.insertSelective(one);

            MeterWorkCarActualFirst model01 = new MeterWorkCarActualFirst();
            MeterWorkCarActualFirst model02 = new MeterWorkCarActualFirst();

            MeterWorkCarActual actualRow1 = new MeterWorkCarActual();
            MeterWorkCarActual actualRow2 = new MeterWorkCarActual();
            if (one.getWeightType().equals("0")) {
                //毛重一次
                model01 = meterWorkCarActualFirstMapper.selectByPrimaryKey(one.getActualFirstNo());
                //皮重一次
                model02 = meterWorkCarActualFirstMapper.selectByPrimaryKey(two.getActualFirst2No());
            } else if (one.getWeightType().equals("1")) {
                //毛重一次
                model01 = meterWorkCarActualFirstMapper.selectByPrimaryKey(two.getActualFirst1No());
                //皮重一次
                model02 = meterWorkCarActualFirstMapper.selectByPrimaryKey(one.getActualFirstNo());
            }
            MeterWorkCarActualFirst model03 = new MeterWorkCarActualFirst();
            MeterWorkCarActualFirst model04 = new MeterWorkCarActualFirst();

            PreTrackScale scale01 = preTrackScaleMapper.selectByPrimaryKey(three.getPredictionNo());
            PreTrackScale scale02 = preTrackScaleMapper.selectByPrimaryKey(four.getPredictionNo());

            //将委托中的编号和收发货的等数据拷贝进一次数据中
            MeterWorkCarActualFirst first1 = meterWorkCarActualFirstMapper.selectAndMatch(model01.getActualFirstNo(), scale01.getPredictionNo());
            BeanUtils.copyProperties(first1, model01);
            MeterWorkCarActualFirst first2 = meterWorkCarActualFirstMapper.selectAndMatch(model02.getActualFirstNo(), scale01.getPredictionNo());
            BeanUtils.copyProperties(first2, model02);
            MeterWorkCarActualFirst first3 = meterWorkCarActualFirstMapper.selectAndMatch(model01.getActualFirstNo(), scale02.getPredictionNo());
            BeanUtils.copyProperties(first3, model03);
            MeterWorkCarActualFirst first4 = meterWorkCarActualFirstMapper.selectAndMatch(model02.getActualFirstNo(), scale02.getPredictionNo());
            BeanUtils.copyProperties(first4, model04);

            //更新一次数据
            //更新第一次毛重数据库
            model01.setValueFlag(DbConstants.NET);
            model01.setUpdateManNo("system");
            model01.setUpdateManName("双委托结净更新");
            model01.setUpdateTime(new Date());
            model01.setWeightType("0");
            model01.setIsPreScale("1");
            model01.setPredictionNo(scale01.getPredictionNo());
            model01.setPredictionType("5");
            model01.setPredictionCombination(scale01.getPredictionNo() + "," + scale02.getPredictionNo());
            meterWorkCarActualFirstMapper.updateByPrimaryKey(model01);
            //更新第一次皮重数据库
            model02.setValueFlag(DbConstants.NET);
            model02.setUpdateManNo("system");
            model02.setUpdateManName("双委托结净更新");
            model02.setUpdateTime(new Date());
            model02.setWeightType("1");
            model02.setIsPreScale("1");
            model02.setPredictionNo(scale01.getPredictionNo());
            model02.setPredictionType("5");
            model02.setPredictionCombination(scale01.getPredictionNo() + "," + scale02.getPredictionNo());
            meterWorkCarActualFirstMapper.updateByPrimaryKeySelective(model02);
            //添加第一次毛重数据库
//            String actualFirstNo = sdf.format(new Date()) + meterWorkCarActualFirstMapper.getNewID(afl);
//            model03.setActualFirstNo(actualFirstNo);
            String actualFirstNo = PublicMethod.IdCreate(3);
            model03.setActualFirstNo(actualFirstNo);

            model03.setValueFlag(DbConstants.NET);
            model03.setUpdateManNo("system");
            model03.setUpdateManName("双委托结净更新");
            model03.setWeightType("0");
            model03.setUpdateTime(new Date());
            model03.setIsPreScale("1");
            model03.setPredictionNo(scale02.getPredictionNo());
            model03.setPredictionType("5");
            model03.setPredictionCombination(scale01.getPredictionNo() + "," + scale02.getPredictionNo());
            meterWorkCarActualFirstMapper.insertSelective(model03);
            //添加第二次皮重数据库
//            String actualSecondNo = sdf.format(new Date()) + meterWorkCarActualFirstMapper.getNewID(afl);
//            model04.setActualFirstNo(actualSecondNo);
            String actualSecondNo = PublicMethod.IdCreate(3);
            model04.setActualFirstNo(actualSecondNo);

            model04.setValueFlag(DbConstants.NET);
            model04.setUpdateManNo("system");
            model04.setUpdateManName("双委托结净更新");
            model04.setWeightType("1");
            model04.setUpdateTime(new Date());
            model04.setIsPreScale("1");
            model04.setPredictionNo(scale02.getPredictionNo());
            model04.setPredictionType("5");
            model04.setPredictionCombination(scale01.getPredictionNo() + "," + scale02.getPredictionNo());
            meterWorkCarActualFirstMapper.insertSelective(model04);

            //将委托中的编号和收发货单位和一次数据等数据拷贝进结净数据中
            MeterWorkCarActual mwca1 = meterWorkCarActualMapper.manualAddPre(model01.getActualFirstNo(), model02.getActualFirstNo(), scale01.getPredictionNo());
            BeanUtils.copyProperties(mwca1, actualRow1);
            MeterWorkCarActual mwca2 = meterWorkCarActualMapper.manualAddPre(model03.getActualFirstNo(), model04.getActualFirstNo(), scale02.getPredictionNo());
            BeanUtils.copyProperties(mwca2, actualRow2);

            //添加结净数据
//            String no = meterWorkCarActualMapper.getNewID(sdf.format(new Date()));
//            actualRow1.setActualNo(sdf.format(new Date()) + no);

            String no = PublicMethod.IdCreate(3);
            actualRow1.setActualNo(no);
            actualRow1.setNetTime(new Date());
            actualRow1.setNetMode(DbConstants.TYPE);
            actualRow1.setNote("双委托匹配结净");
            actualRow1.setNetMode("3");
            actualRow1.setUploadFlag("1");
            actualRow1.setValueFlag("1");
            actualRow1.setIsPreScale("1");
            actualRow1.setNetManNo(two.getNetManNo());
            actualRow1.setNetManName(two.getNetManName());
            actualRow1.setNetSpot3No(two.getNetSpot3No());
            actualRow1.setNetSpot3Name(two.getNetSpot3Name());
            actualRow1.setCreateManName(two.getCreateManName());
            actualRow1.setUpdateManNo(two.getUpdateManNo());
            actualRow1.setUpdateManName(two.getUpdateManName());
            actualRow1.setUpdateTime(two.getUpdateTime());
            actualRow1.setPredictionNo(scale01.getPredictionNo());
            actualRow1.setPredictionType("5");
            actualRow1.setPredictionCombination(scale01.getPredictionNo() + "," + scale02.getPredictionNo());
            actualRow1.setNetWeight(model01.getMeterWeight().subtract(model02.getMeterWeight()));
            if(actualRow1.getGrossTime().compareTo(actualRow1.getTareTime()) >= 0) {
                actualRow1.setNetSpot3No(actualRow1.getBaseSpot1No());
                actualRow1.setNetSpot3Name(actualRow1.getBaseSpot1Name());
                actualRow1.setNetManNo(actualRow1.getGrossManNo());
                actualRow1.setNetManName(actualRow1.getGrossManName());
                actualRow1.setNetTime(actualRow1.getGrossTime());
                actualRow1.setCreateTime(actualRow1.getGrossTime());
                actualRow1.setCreateManName(actualRow1.getGrossManName());
            }else {
                actualRow1.setNetSpot3No(actualRow1.getBaseSpot2No());
                actualRow1.setNetSpot3Name(actualRow1.getBaseSpot2Name());
                actualRow1.setNetManNo(actualRow1.getTareManNo());
                actualRow1.setNetManName(actualRow1.getTareManName());
                actualRow1.setNetTime(actualRow1.getTareTime());
                actualRow1.setCreateTime(actualRow1.getTareTime());
                actualRow1.setCreateManName(actualRow1.getTareManName());
            }
            meterWorkCarActualMapper.insertSelective(actualRow1);

//            String no1 = meterWorkCarActualMapper.getNewID(sdf.format(new Date()));
//            actualRow2.setActualNo(sdf.format(new Date()) + no1);

            String no1 = PublicMethod.IdCreate(3);
            actualRow2.setActualNo(no1);
            actualRow2.setNetTime(new Date());
            actualRow2.setNetMode(DbConstants.TYPE);
            actualRow2.setNote("双委托匹配结净");
            actualRow2.setNetMode("3");
            actualRow2.setValueFlag("1");
            actualRow2.setUploadFlag("1");
            actualRow2.setIsPreScale("1");
            actualRow2.setNetManNo(two.getNetManNo());
            actualRow2.setNetManName(two.getNetManName());
            actualRow2.setNetSpot3No(two.getNetSpot3No());
            actualRow2.setNetSpot3Name(two.getNetSpot3Name());
            actualRow2.setCreateManName(two.getCreateManName());
            actualRow2.setUpdateManNo(two.getUpdateManNo());
            actualRow2.setUpdateManName(two.getUpdateManName());
            actualRow2.setUpdateTime(two.getUpdateTime());
            actualRow2.setPredictionNo(scale02.getPredictionNo());
            actualRow2.setPredictionType("5");
            actualRow2.setPredictionCombination(scale01.getPredictionNo() + "," + scale02.getPredictionNo());
            actualRow2.setNetWeight(model03.getMeterWeight().subtract(model04.getMeterWeight()));
            if(actualRow2.getGrossTime().compareTo(actualRow2.getTareTime()) >= 0) {
                actualRow2.setNetSpot3No(actualRow2.getBaseSpot1No());
                actualRow2.setNetSpot3Name(actualRow2.getBaseSpot1Name());
                actualRow2.setNetManNo(actualRow2.getGrossManNo());
                actualRow2.setNetManName(actualRow2.getGrossManName());
                actualRow2.setNetTime(actualRow2.getGrossTime());
                actualRow2.setCreateTime(actualRow2.getGrossTime());
                actualRow2.setCreateManName(actualRow2.getGrossManName());
            }else {
                actualRow2.setNetSpot3No(actualRow2.getBaseSpot2No());
                actualRow2.setNetSpot3Name(actualRow2.getBaseSpot2Name());
                actualRow2.setNetManNo(actualRow2.getTareManNo());
                actualRow2.setNetManName(actualRow2.getTareManName());
                actualRow2.setNetTime(actualRow2.getTareTime());
                actualRow2.setCreateTime(actualRow2.getTareTime());
                actualRow2.setCreateManName(actualRow2.getTareManName());
            }
            meterWorkCarActualMapper.insertSelective(actualRow2);


            //更新预报数据
            scale01.setValueFlag(DbConstants.NET);
            scale01.setUpdateTime(new Date());
            scale01.setUpdateManNo("system");
            scale01.setUpdateManName("双委托结净更新");
            scale01.setUploadFlag("1");
            scale01.setPredictionType("5");
            scale01.setPredictionCombination(scale01.getPredictionNo() + "," + scale02.getPredictionNo());
            scale01.setMeasureStation(actualRow1.getNetSpot3No());
            scale01.setMeasureStationName(actualRow1.getNetSpot3Name());
            preTrackScaleMapper.updateByPrimaryKeySelective(scale01);

            scale02.setValueFlag(DbConstants.NET);
            scale02.setUpdateTime(new Date());
            scale02.setUpdateManNo("system");
            scale02.setUpdateManName("双委托结净更新");
            scale02.setUploadFlag("1");
            scale02.setPredictionType("5");
            scale02.setPredictionCombination(scale01.getPredictionNo() + "," + scale02.getPredictionNo());
            scale02.setMeasureStation(actualRow2.getNetSpot3No());
            scale02.setMeasureStationName(actualRow2.getNetSpot3Name());

            ////根据收发货单位查询配置信息
            //HashMap<String, Object> map = new HashMap<>();
            //map.put("receivingUintName",scale02.getReceivingUintNo());
            //map.put("receivingUintNo",scale02.getReceivingUintName());
            //map.put("forwardingUnitName",scale02.getForwardingUnitNo());
            //map.put("forwardingUnitNo",scale02.getReceivingUintName());
            //List<MeterBaseMatterUnit> meterBaseMatterUnits = meterBaseMatterUnitMapper.selectByParameters(map);
            ////判断收发货单位是否属于配置，然后修改物料信息
            //if(meterBaseMatterUnits!=null&&meterBaseMatterUnits.size()!=0&&meterBaseMatterUnits.get(0)!=null){
            //    scale02.setMatterNo(meterBaseMatterUnits.get(0).getMatterNo());
            //    scale02.setMatterName(meterBaseMatterUnits.get(0).getMatterName());
            //}

            preTrackScaleMapper.updateByPrimaryKeySelective(scale02);
            //11、修改计量监控
            updateMonitor(one.getBaseSpotNo());
            //12、当存储一次数据或者结净时，将本车辆的预处理重量改为已使用
            updatePreWeight(one.getCarNo());
            updateMonitorOver(one.getActualFirstNo(), one.getBaseSpotNo());
            //补充附加重量的数据
            if (StringUtils.isNotEmpty(one.getAddWgtPk())) {
                insertAddWgtNo(one.getActualFirstNo(), one.getAddWgtPk(), one.getCreateManNo(), one.getCreateManName());
            }

            rm.setSucceed();
            rm.setData(one.getActualFirstNo());
            rm.setCode("200");
            rm.setMessage("操作成功！！");
            return rm;
        }catch(Exception e) {
            e.printStackTrace();
            rm.setMessage("操作异常，请确认！！>>>>" + e.getMessage());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return rm;
    }


    private void updatePreWeight(String CarNo) throws MarkerMetException{
        meterWorkPreWgttypeMapper.updatePreWeight(CarNo);
    }

    @Override
    public String mixedLoading(String actualNo1, String actualNo2, String actualNo3, String predictionNo1, String predictionNo2) {
        try{
            String userId = "";
            String userName = "";
            try{
                UserPayload userPayload = UserPayload.getCurrUser();
                userId = userPayload.getUserCode();
                userName = userPayload.getUserName();
            }catch (Exception e) {
                userId = "system";
                userName = "system";
            }

            //查询所有的一次数据
            MeterWorkCarActualFirst mwcaf1 = meterWorkCarActualFirstMapper.selectByPrimaryKey(actualNo1);
            MeterWorkCarActualFirst mwcaf2 = meterWorkCarActualFirstMapper.selectByPrimaryKey(actualNo2);
            MeterWorkCarActualFirst mwcaf3 = meterWorkCarActualFirstMapper.selectByPrimaryKey(actualNo2);
            MeterWorkCarActualFirst mwcaf4 = meterWorkCarActualFirstMapper.selectByPrimaryKey(actualNo3);
            //查询所有的委托数据
            PreTrackScale pts1 = preTrackScaleMapper.selectByPrimaryKey(predictionNo1);
            PreTrackScale pts2 = preTrackScaleMapper.selectByPrimaryKey(predictionNo2);
            //定义新的结净数据实体
            MeterWorkCarActual actualRow1 = new MeterWorkCarActual();
            MeterWorkCarActual actualRow2 = new MeterWorkCarActual();

            //判断是否为混装逻辑
            if(mwcaf1.getMeterWeight().compareTo(mwcaf2.getMeterWeight()) == 1 ||
                    mwcaf1.getMeterWeight().compareTo(mwcaf4.getMeterWeight()) == 1 ||
                    mwcaf2.getMeterWeight().compareTo(mwcaf4.getMeterWeight()) == 1){
                return "请根据一次数据从小到大的规则，依次选择三条一次数据！！！！";
            }

            /**
             * 2023年10月11日zn
             * 混装混卸配置查询
             */
            HashMap <String,Object> queryCon = new HashMap<>();
            queryCon.put("matterNo",pts2.getMatterNo());
            queryCon.put("matterName",pts2.getMatterName());
            queryCon.put("customerSupplierName",pts2.getForwardingUnitName());
            queryCon.put("customerSupplierNo",pts2.getForwardingUnitNo());
            queryCon.put("validFlag","1");
            queryCon.put("isloadUnload","0");
            List<MeterBaseMatterUnitMixedLoadUnloadTime> lists = meterBaseMatterUnitMixedLoadUnloadTimeMapper.selectByParameters(queryCon);
            if(lists!=null&&lists.size()!=0){
                SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                String fromDate = simpleFormat.format(pts1.getTrustDateTime());
                String toDate = simpleFormat.format(pts2.getTrustDateTime());
                long from = simpleFormat.parse(fromDate).getTime();
                long to = simpleFormat.parse(toDate).getTime();
                int hours = (int) ((to - from) / (1000 * 60 * 60));
                if (pts1.getMatterNo().equals(pts2.getMatterNo()) &&
                        pts1.getForwardingUnitNo().equals(pts2.getForwardingUnitNo()) &&
                        hours <= lists.get(0).getTimeValue().doubleValue()&&
                        lists.get(0).getTimeValue().doubleValue()>0) {
                    return "委托信息不符合混装委托规则(同物料同发货单位委托创建时间不能小于"+lists.get(0)
                            .getTimeValue().doubleValue()+"小时)，请确认!!";
                }
            }
            //SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            //String fromDate = simpleFormat.format(pts1.getCreateTime());
            //String toDate = simpleFormat.format(pts2.getCreateTime());
            //long from = simpleFormat.parse(fromDate).getTime();
            //long to = simpleFormat.parse(toDate).getTime();
            //int hours = (int) ((to - from) / (1000 * 60 * 60));
            //if ( pts1.getMatterNo().equals(pts2.getMatterNo()) &&
            //        pts1.getForwardingUnitNo().equals(pts2.getForwardingUnitNo()) &&
            //        hours < 4) {
            //    return "委托信息不符合混装委托规则(同物料同发货单位委托创建时间不能小于4小时)，请确认!!";
            //}

            //判断一次数据是否存在
            if (mwcaf1 == null || mwcaf2 == null || mwcaf3 == null || mwcaf4 == null) {
                return "未查询到相应的一次数据！！";
            }
            //判断一次数据是否已结净
            if (mwcaf1.getValueFlag().equals("2") || mwcaf2.getValueFlag().equals("2") ||
                    mwcaf3.getValueFlag().equals("2") || mwcaf4.getValueFlag().equals("2")) {
                return "存在已结净的一次数据！！";
            }
            //判断委托数据是否存在
            if (pts1 == null || pts2 == null) {
                return "未查询到相应的委托数据！！";
            }
            //判断委托数据是否已使用
            if (!pts1.getValueFlag().equals("1") || !pts1.getValueFlag().equals("1")) {
                return "委托不是未使用状态！！";
            }

            //将委托中的编号和收发货的等数据拷贝进一次数据中
            MeterWorkCarActualFirst first1 = meterWorkCarActualFirstMapper.selectAndMatch(actualNo1, predictionNo1);
            BeanUtils.copyProperties(first1,mwcaf1);
            MeterWorkCarActualFirst first2 = meterWorkCarActualFirstMapper.selectAndMatch(actualNo2, predictionNo1);
            BeanUtils.copyProperties(first2, mwcaf2);
            MeterWorkCarActualFirst first3 = meterWorkCarActualFirstMapper.selectAndMatch(actualNo2, predictionNo2);
            BeanUtils.copyProperties(first3,mwcaf3);
            MeterWorkCarActualFirst first4 = meterWorkCarActualFirstMapper.selectAndMatch(actualNo3, predictionNo2);
            BeanUtils.copyProperties(first4, mwcaf4);


            //更新一次数据
            //更新第一次皮重数据
            mwcaf1.setValueFlag(DbConstants.NET);
            mwcaf1.setUpdateManNo(userId);
            mwcaf1.setUpdateManName(userName);
            mwcaf1.setNote("手动混装结净更新");
            mwcaf1.setUpdateTime(new Date());
            mwcaf1.setIsPreScale("1");
            mwcaf1.setWeightType("1");
            mwcaf1.setPredictionNo(predictionNo1);
            mwcaf1.setPredictionType("7");
            mwcaf1.setPredictionCombination(predictionNo1 + "," + predictionNo2);
            //添加历史皮重
            doSaveHisTare(mwcaf1,"3");
            meterWorkCarActualFirstMapper.updateByPrimaryKey(mwcaf1);
            //更新第一次毛重数据
            mwcaf2.setValueFlag(DbConstants.NET);
            mwcaf2.setUpdateManNo(userId);
            mwcaf2.setUpdateManName(userName);
            mwcaf2.setNote("手动混装结净更新");
            mwcaf2.setUpdateTime(new Date());
            mwcaf2.setIsPreScale("1");
            mwcaf2.setWeightType("0");
            mwcaf2.setPredictionNo(predictionNo1);
            mwcaf2.setPredictionType("7");
            mwcaf2.setPredictionCombination(predictionNo1 + "," + predictionNo2);
            meterWorkCarActualFirstMapper.updateByPrimaryKey(mwcaf2);
            //添加第二次皮重数据
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            String afl = sdf.format(new Date());
//            String actualFirstNo = sdf.format(new Date()) + meterWorkCarActualFirstMapper.getNewID(afl);
//            mwcaf3.setActualFirstNo(actualFirstNo);
            String actualFirstNo = PublicMethod.IdCreate(3);
            mwcaf3.setActualFirstNo(actualFirstNo);


            mwcaf3.setValueFlag(DbConstants.NET);
            mwcaf3.setUpdateManNo(userId);
            mwcaf3.setUpdateManName(userName);
            mwcaf3.setNote("手动混装结净更新");
            mwcaf3.setUpdateTime(new Date());
            mwcaf3.setIsPreScale("1");
            mwcaf3.setWeightType("1");
            mwcaf3.setPredictionNo(predictionNo2);
            mwcaf3.setPredictionType("7");
            mwcaf3.setPredictionCombination(predictionNo1 + "," + predictionNo2);
            meterWorkCarActualFirstMapper.insertSelective(mwcaf3);
            //更新第二次毛重数据
            mwcaf4.setValueFlag(DbConstants.NET);
            mwcaf4.setUpdateManNo(userId);
            mwcaf4.setUpdateManName(userName);
            mwcaf4.setNote("手动混装结净更新");
            mwcaf4.setUpdateTime(new Date());
            mwcaf4.setIsPreScale("1");
            mwcaf4.setWeightType("0");
            mwcaf4.setPredictionNo(predictionNo2);
            mwcaf4.setPredictionType("7");
            mwcaf4.setPredictionCombination(predictionNo1 + "," + predictionNo2);
            meterWorkCarActualFirstMapper.updateByPrimaryKey(mwcaf4);
            //将委托中的编号和收发货单位和一次数据等数据拷贝进结净数据中
            MeterWorkCarActual mwca1 = meterWorkCarActualMapper.manualAddPre(actualNo2, actualNo1, predictionNo1);
            BeanUtils.copyProperties(mwca1, actualRow1);
            MeterWorkCarActual mwca2 = meterWorkCarActualMapper.manualAddPre(actualNo3, actualFirstNo, predictionNo2);
            BeanUtils.copyProperties(mwca2,actualRow2);

            //添加结净数据
//            String no = meterWorkCarActualMapper.getNewID(sdf.format(new Date()));
//            actualRow1.setActualNo(sdf.format(new Date()) + no);

            String no = PublicMethod.IdCreate(3);
            actualRow1.setActualNo(no);
            actualRow1.setNetMode("4");
            actualRow1.setUploadFlag("1");
            actualRow1.setIsPreScale("1");
            actualRow1.setValueFlag("1");
            actualRow1.setPredictionType("7");
            actualRow1.setPredictionCombination(predictionNo1 + "," + predictionNo2);
            actualRow1.setPredictionNo(predictionNo1);
            actualRow1.setNetWeight(mwcaf2.getMeterWeight().subtract(mwcaf1.getMeterWeight()));
            if(actualRow1.getGrossTime().compareTo(actualRow1.getTareTime()) >= 0) {
                actualRow1.setNetSpot3No(actualRow1.getBaseSpot1No());
                actualRow1.setNetSpot3Name(actualRow1.getBaseSpot1Name());
                actualRow1.setNetManNo(actualRow1.getGrossManNo());
                actualRow1.setNetManName(actualRow1.getGrossManName());
                actualRow1.setNetTime(actualRow1.getGrossTime());
                actualRow1.setCreateTime(actualRow1.getGrossTime());
                actualRow1.setCreateManName(actualRow1.getGrossManName());
            }else {
                actualRow1.setNetSpot3No(actualRow1.getBaseSpot2No());
                actualRow1.setNetSpot3Name(actualRow1.getBaseSpot2Name());
                actualRow1.setNetManNo(actualRow1.getTareManNo());
                actualRow1.setNetManName(actualRow1.getTareManName());
                actualRow1.setNetTime(actualRow1.getTareTime());
                actualRow1.setCreateTime(actualRow1.getTareTime());
                actualRow1.setCreateManName(actualRow1.getTareManName());
            }
            actualRow1.setUpdateManNo(userId);
            actualRow1.setUpdateManName(userName);
            actualRow1.setNote("手动混装匹配结净");
            actualRow1.setUpdateTime(new Date());
            meterWorkCarActualMapper.insertSelective(actualRow1);

//            String no1 = meterWorkCarActualMapper.getNewID(sdf.format(new Date()));
//            actualRow2.setActualNo(sdf.format(new Date()) + no1);

            String no1 = PublicMethod.IdCreate(3);
            actualRow2.setActualNo(no1);
            actualRow2.setNetMode("4");
            actualRow2.setUploadFlag("1");
            actualRow2.setIsPreScale("1");
            actualRow2.setValueFlag("1");
            actualRow2.setPredictionType("7");
            actualRow2.setPredictionCombination(predictionNo1 + "," + predictionNo2);
            actualRow2.setPredictionNo(predictionNo2);
            actualRow2.setNetWeight(mwcaf4.getMeterWeight().subtract(mwcaf3.getMeterWeight()));
            if(actualRow2.getGrossTime().compareTo(actualRow2.getTareTime()) >= 0) {
                actualRow2.setNetSpot3No(actualRow2.getBaseSpot1No());
                actualRow2.setNetSpot3Name(actualRow2.getBaseSpot1Name());
                actualRow2.setNetManNo(actualRow2.getGrossManNo());
                actualRow2.setNetManName(actualRow2.getGrossManName());
                actualRow2.setNetTime(actualRow2.getGrossTime());
                actualRow2.setCreateTime(actualRow2.getGrossTime());
                actualRow2.setCreateManName(actualRow2.getGrossManName());
            }else {
                actualRow2.setNetSpot3No(actualRow2.getBaseSpot2No());
                actualRow2.setNetSpot3Name(actualRow2.getBaseSpot2Name());
                actualRow2.setNetManNo(actualRow2.getTareManNo());
                actualRow2.setNetManName(actualRow2.getTareManName());
                actualRow2.setNetTime(actualRow2.getTareTime());
                actualRow2.setCreateTime(actualRow2.getTareTime());
                actualRow2.setCreateManName(actualRow2.getTareManName());
            }
            actualRow2.setUpdateManNo(userId);
            actualRow2.setUpdateManName(userName);
            actualRow2.setNote("手动混装匹配结净");
            actualRow2.setUpdateTime(new Date());
            meterWorkCarActualMapper.insertSelective(actualRow2);

            //更新预报数据
            PreTrackScale scale = new PreTrackScale();
            scale.setPredictionNo(predictionNo1);
            scale.setValueFlag(DbConstants.NET);
            scale.setUpdateTime(new Date());
            scale.setUpdateManNo(userId);
            scale.setUpdateManName(userName);
            scale.setPredictionType("7");
            scale.setPredictionCombination(predictionNo1 + "," + predictionNo2);
            scale.setUploadFlag("1");
            scale.setMeasureStation(actualRow1.getNetSpot3No());
            scale.setMeasureStationName(actualRow1.getNetSpot3Name());
            preTrackScaleMapper.updateByPrimaryKeySelective(scale);

            PreTrackScale scale1 = new PreTrackScale();
            scale1.setPredictionNo(predictionNo2);
            scale1.setValueFlag(DbConstants.NET);
            scale1.setUpdateTime(new Date());
            scale1.setUpdateManNo(userId);
            scale1.setUpdateManName(userName);
            scale1.setPredictionType("7");
            scale1.setPredictionCombination(predictionNo1 + "," + predictionNo2);
            scale1.setUploadFlag("1");
            scale1.setMeasureStation(actualRow2.getNetSpot3No());
            scale1.setMeasureStationName(actualRow2.getNetSpot3Name());
            preTrackScaleMapper.updateByPrimaryKeySelective(scale1);

            MeterBaseOperationLog logModel01 = new MeterBaseOperationLog();
            logModel01.setId(PublicMethod.IdCreate(2));
            logModel01.setCreateManNo(userId);
            logModel01.setCreateManName(userName);
            logModel01.setCreateTime(new Date());
            logModel01.setOperationPage("web端-汽车衡一次数据维护");
            logModel01.setOperationFunction("混装委托结净");
            logModel01.setOperationId(actualRow1.getActualNo());
            logModel01.setOperationPredictionNo(predictionNo1 + "+" + predictionNo2);
            logModel01.setOperationBeforeFix(actualNo1 + "+" + actualNo2 + "+" + actualNo3);
            logModel01.setOperationCarnNo(actualRow1.getCarNo());
            meterBaseOperationLogMapper.insertSelective(logModel01);

            MeterBaseOperationLog logModel02 = new MeterBaseOperationLog();
            logModel02.setId(PublicMethod.IdCreate(2));
            logModel02.setCreateManNo(userId);
            logModel02.setCreateManName(userName);
            logModel02.setCreateTime(new Date());
            logModel02.setOperationPage("web端-汽车衡一次数据维护");
            logModel02.setOperationFunction("混装委托结净");
            logModel02.setOperationId(actualRow2.getActualNo());
            logModel02.setOperationPredictionNo(predictionNo1 + "+" + predictionNo2);
            logModel02.setOperationBeforeFix(actualNo1 + "+" + actualNo2 + "+" + actualNo3);
            logModel02.setOperationCarnNo(actualRow2.getCarNo());
            meterBaseOperationLogMapper.insertSelective(logModel02);
        }
        catch (Exception e){
            e.printStackTrace();
            return "操作异常，请确认";
        }
        return "";
    }

    @Override
    public String mixedDischarge(String actualNo1, String actualNo2, String actualNo3, String predictionNo1, String predictionNo2) {
        try{
            String userId = "";
            String userName = "";
            try{
                UserPayload userPayload = UserPayload.getCurrUser();
                userId = userPayload.getUserCode();
                userName = userPayload.getUserName();
            }catch (Exception e) {
                userId = "system";
                userName = "system";
            }

            //查询所有的一次数据
            MeterWorkCarActualFirst mwcaf1 = meterWorkCarActualFirstMapper.selectByPrimaryKey(actualNo1);
            MeterWorkCarActualFirst mwcaf2 = meterWorkCarActualFirstMapper.selectByPrimaryKey(actualNo2);
            MeterWorkCarActualFirst mwcaf3 = meterWorkCarActualFirstMapper.selectByPrimaryKey(actualNo2);
            MeterWorkCarActualFirst mwcaf4 = meterWorkCarActualFirstMapper.selectByPrimaryKey(actualNo3);
            //查询所有的委托数据
            PreTrackScale pts1 = preTrackScaleMapper.selectByPrimaryKey(predictionNo1);
            PreTrackScale pts2 = preTrackScaleMapper.selectByPrimaryKey(predictionNo2);
            //定义新的结净数据实体
            MeterWorkCarActual actualRow1 = new MeterWorkCarActual();
            MeterWorkCarActual actualRow2 = new MeterWorkCarActual();
            //判断是否为混装逻辑
            if(mwcaf1.getMeterWeight().compareTo(mwcaf2.getMeterWeight()) == -1 ||
                    mwcaf1.getMeterWeight().compareTo(mwcaf4.getMeterWeight()) == -1 ||
                    mwcaf2.getMeterWeight().compareTo(mwcaf4.getMeterWeight()) == -1){
                return "请根据一次数据从大到小的规则，依次选择三条一次数据！！";
            }

            /**
             * 2023年10月11日zn
             * 混装混卸配置查询
             */
            HashMap <String,Object> queryCon = new HashMap<>();
            queryCon.put("matterNo",pts2.getMatterNo());
            queryCon.put("matterName",pts2.getMatterName());
            queryCon.put("customerSupplierName",pts2.getReceivingUintName());
            queryCon.put("customerSupplierNo",pts2.getReceivingUintNo());
            queryCon.put("validFlag","1");
            queryCon.put("isloadUnload","1");
            List<MeterBaseMatterUnitMixedLoadUnloadTime> lists = meterBaseMatterUnitMixedLoadUnloadTimeMapper.selectByParameters(queryCon);
            if(lists!=null&&lists.size()!=0){
                SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                String fromDate = simpleFormat.format(pts1.getTrustDateTime());
                String toDate = simpleFormat.format(pts2.getTrustDateTime());
                long from = simpleFormat.parse(fromDate).getTime();
                long to = simpleFormat.parse(toDate).getTime();
                int hours = (int) ((to - from) / (1000 * 60 * 60));
                if (pts1.getMatterNo().equals(pts2.getMatterNo()) &&
                        pts1.getForwardingUnitNo().equals(pts2.getForwardingUnitNo()) &&
                        hours <= lists.get(0).getTimeValue().doubleValue()&&
                        lists.get(0).getTimeValue().doubleValue()>0) {
                    return "委托信息不符合混装委托规则(同物料同收货单位委托创建时间不能小于"+lists.get(0)
                            .getTimeValue().doubleValue()+"小时)，请确认!!";
                }
            }

            SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            String fromDate = simpleFormat.format(pts1.getCreateTime());
            String toDate = simpleFormat.format(pts2.getCreateTime());
            long from = simpleFormat.parse(fromDate).getTime();
            long to = simpleFormat.parse(toDate).getTime();
            int minutes = (int) ((to - from) / (1000 * 60));
            //判断混卸 物料相同、AB发货单位相同、收货单位一定不一致：签发时间10分钟内
            if (pts1.getMatterNo().equals(pts2.getMatterNo()) &&
                    pts1.getForwardingUnitNo().equals(pts2.getForwardingUnitNo()) &&
                    !pts1.getReceivingUintNo().equals(pts2.getReceivingUintNo()) &&
                    minutes <= 10) {
                return "委托信息不符合混卸委托规则，请确认!!";
            }
            //判断一次数据是否存在
            if (mwcaf1 == null || mwcaf2 == null || mwcaf3 == null || mwcaf4 == null) {
                return "未查询到相应的一次数据！！";
            }
            //判断一次数据是否已结净
            if (mwcaf1.getValueFlag().equals("2") || mwcaf2.getValueFlag().equals("2") ||
                    mwcaf3.getValueFlag().equals("2") || mwcaf4.getValueFlag().equals("2")) {
                return "存在已结净的一次数据！！";
            }
            //判断委托数据是否存在
            if (pts1 == null || pts2 == null) {
                return "未查询到相应的委托数据！！";
            }
            //判断委托数据是否已使用
            if (!pts1.getValueFlag().equals("1") || !pts1.getValueFlag().equals("1")) {
                return "委托不是未使用状态！！";
            }

            //将委托中的编号和收发货的等数据拷贝进一次数据中
            MeterWorkCarActualFirst first1 = meterWorkCarActualFirstMapper.selectAndMatch(actualNo1, predictionNo1);
            BeanUtils.copyProperties(first1,mwcaf1);
            MeterWorkCarActualFirst first2 = meterWorkCarActualFirstMapper.selectAndMatch(actualNo2, predictionNo1);
            BeanUtils.copyProperties(first2, mwcaf2);
            MeterWorkCarActualFirst first3 = meterWorkCarActualFirstMapper.selectAndMatch(actualNo2, predictionNo2);
            BeanUtils.copyProperties(first3,mwcaf3);
            MeterWorkCarActualFirst first4 = meterWorkCarActualFirstMapper.selectAndMatch(actualNo3, predictionNo2);
            BeanUtils.copyProperties(first4, mwcaf4);

            //更新一次数据
            //更新第一次毛重数据
            mwcaf1.setValueFlag(DbConstants.NET);
            mwcaf1.setUpdateManNo(userId);
            mwcaf1.setUpdateManName(userName);
            mwcaf1.setNote("手动混卸结净更新");
            mwcaf1.setUpdateTime(new Date());
            mwcaf1.setIsPreScale("1");
            mwcaf1.setWeightType("0");
            mwcaf1.setPredictionNo(predictionNo1);
            mwcaf1.setPredictionType("6");
            mwcaf1.setPredictionCombination(predictionNo1 + "," + predictionNo2);
            meterWorkCarActualFirstMapper.updateByPrimaryKey(mwcaf1);
            //更新第一次皮重数据
            mwcaf2.setValueFlag(DbConstants.NET);
            mwcaf2.setUpdateManNo(userId);
            mwcaf2.setUpdateManName(userName);
            mwcaf2.setNote("手动混卸结净更新");
            mwcaf2.setUpdateTime(new Date());
            mwcaf2.setIsPreScale("1");
            mwcaf2.setWeightType("1");
            mwcaf2.setPredictionNo(predictionNo1);
            mwcaf2.setPredictionType("6");
            mwcaf2.setPredictionCombination(predictionNo1 + "," + predictionNo2);
            meterWorkCarActualFirstMapper.updateByPrimaryKey(mwcaf2);
            //添加第二次毛重数据
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            String afl = sdf.format(new Date());
//            String actualFirstNo = sdf.format(new Date()) + meterWorkCarActualFirstMapper.getNewID(afl);
//            mwcaf3.setActualFirstNo(actualFirstNo);
            String actualFirstNo = PublicMethod.IdCreate(3);
            mwcaf3.setActualFirstNo(actualFirstNo);
            mwcaf3.setValueFlag(DbConstants.NET);
            mwcaf3.setUpdateManNo(userId);
            mwcaf3.setUpdateManName(userName);
            mwcaf3.setNote("手动混卸结净更新");
            mwcaf3.setUpdateTime(new Date());
            mwcaf3.setIsPreScale("1");
            mwcaf3.setWeightType("0");
            mwcaf3.setPredictionNo(predictionNo2);
            mwcaf3.setPredictionType("6");
            mwcaf3.setPredictionCombination(predictionNo1 + "," + predictionNo2);
            meterWorkCarActualFirstMapper.insertSelective(mwcaf3);
            //更新第二次皮重数据
            mwcaf4.setValueFlag(DbConstants.NET);
            mwcaf4.setUpdateManNo(userId);
            mwcaf4.setUpdateManName(userName);
            mwcaf4.setNote("手动混卸结净更新");
            mwcaf4.setUpdateTime(new Date());
            mwcaf4.setIsPreScale("1");
            mwcaf4.setWeightType("1");
            mwcaf4.setPredictionNo(predictionNo2);
            mwcaf4.setPredictionType("6");
            mwcaf4.setPredictionCombination(predictionNo1 + "," + predictionNo2);
            meterWorkCarActualFirstMapper.updateByPrimaryKey(mwcaf4);
            //添加历史皮重
            doSaveHisTare(mwcaf4,"4");
            //将委托中的编号和收发货单位和一次数据等数据拷贝进结净数据中
            MeterWorkCarActual mwca1 = meterWorkCarActualMapper.manualAddPre(actualNo1, actualNo2, predictionNo1);
            BeanUtils.copyProperties(mwca1, actualRow1);
            MeterWorkCarActual mwca2 = meterWorkCarActualMapper.manualAddPre(actualFirstNo, actualNo3, predictionNo2);
            BeanUtils.copyProperties(mwca2,actualRow2);

            //添加结净数据
//            String no = meterWorkCarActualMapper.getNewID(sdf.format(new Date()));
//            actualRow1.setActualNo(sdf.format(new Date()) + no);

            String no = PublicMethod.IdCreate(3);
            actualRow1.setActualNo(no);
            actualRow1.setNetMode("5");
            actualRow1.setUploadFlag("1");
            actualRow1.setIsPreScale("1");
            actualRow1.setValueFlag("1");
            actualRow1.setPredictionType("6");
            actualRow1.setPredictionCombination(predictionNo1 + "," + predictionNo2);
            actualRow1.setPredictionNo(predictionNo1);
            actualRow1.setNetWeight(mwcaf1.getMeterWeight().subtract(mwcaf2.getMeterWeight()));
            if(actualRow1.getGrossTime().compareTo(actualRow1.getTareTime()) >= 0) {
                actualRow1.setNetSpot3No(actualRow1.getBaseSpot1No());
                actualRow1.setNetSpot3Name(actualRow1.getBaseSpot1Name());
                actualRow1.setNetManNo(actualRow1.getGrossManNo());
                actualRow1.setNetManName(actualRow1.getGrossManName());
                actualRow1.setNetTime(actualRow1.getGrossTime());
                actualRow1.setCreateTime(actualRow1.getGrossTime());
                actualRow1.setCreateManName(actualRow1.getGrossManName());
            }else {
                actualRow1.setNetSpot3No(actualRow1.getBaseSpot2No());
                actualRow1.setNetSpot3Name(actualRow1.getBaseSpot2Name());
                actualRow1.setNetManNo(actualRow1.getTareManNo());
                actualRow1.setNetManName(actualRow1.getTareManName());
                actualRow1.setNetTime(actualRow1.getTareTime());
                actualRow1.setCreateTime(actualRow1.getTareTime());
                actualRow1.setCreateManName(actualRow1.getTareManName());
            }
            actualRow1.setUpdateManNo(userId);
            actualRow1.setUpdateManName(userName);
            actualRow1.setNote("手动混卸匹配结净");
            actualRow1.setUpdateTime(new Date());
            meterWorkCarActualMapper.insertSelective(actualRow1);
//            String no1 = meterWorkCarActualMapper.getNewID(sdf.format(new Date()));
//            actualRow2.setActualNo(sdf.format(new Date()) + no1);

            String no1 = PublicMethod.IdCreate(3);
            actualRow2.setActualNo(no1);
            actualRow2.setNetMode("5");
            actualRow2.setUploadFlag("1");
            actualRow2.setIsPreScale("1");
            actualRow2.setValueFlag("1");
            actualRow2.setPredictionType("6");
            actualRow2.setPredictionCombination(predictionNo1 + "," + predictionNo2);
            actualRow2.setPredictionNo(predictionNo2);
            actualRow2.setNetWeight(mwcaf3.getMeterWeight().subtract(mwcaf4.getMeterWeight()));
            if(actualRow2.getGrossTime().compareTo(actualRow2.getTareTime()) >= 0) {
                actualRow2.setNetSpot3No(actualRow2.getBaseSpot1No());
                actualRow2.setNetSpot3Name(actualRow2.getBaseSpot1Name());
                actualRow2.setNetManNo(actualRow2.getGrossManNo());
                actualRow2.setNetManName(actualRow2.getGrossManName());
                actualRow2.setNetTime(actualRow2.getGrossTime());
                actualRow2.setCreateTime(actualRow2.getGrossTime());
                actualRow2.setCreateManName(actualRow2.getGrossManName());
            }else {
                actualRow2.setNetSpot3No(actualRow2.getBaseSpot2No());
                actualRow2.setNetSpot3Name(actualRow2.getBaseSpot2Name());
                actualRow2.setNetManNo(actualRow2.getTareManNo());
                actualRow2.setNetManName(actualRow2.getTareManName());
                actualRow2.setNetTime(actualRow2.getTareTime());
                actualRow2.setCreateTime(actualRow2.getTareTime());
                actualRow2.setCreateManName(actualRow2.getTareManName());
            }
            actualRow2.setUpdateManNo(userId);
            actualRow2.setUpdateManName(userName);
            actualRow2.setNote("手动混卸匹配结净");
            actualRow2.setUpdateTime(new Date());
            meterWorkCarActualMapper.insertSelective(actualRow2);

            //更新预报数据
            PreTrackScale scale = new PreTrackScale();
            scale.setPredictionNo(predictionNo1);
            scale.setValueFlag(DbConstants.NET);
            scale.setUpdateTime(new Date());
            scale.setUpdateManNo(userId);
            scale.setUpdateManName(userName);
            scale.setUploadFlag("1");
            scale.setValueFlag("2");
            //预报类型：双委托（5）、预报组合：A预报，B预报
            scale.setPredictionType("6");
            scale.setPredictionCombination(predictionNo1 + "," + predictionNo2);
            scale.setMeasureStation(actualRow1.getNetSpot3No());
            scale.setMeasureStationName(actualRow1.getNetSpot3Name());
            preTrackScaleMapper.updateByPrimaryKeySelective(scale);

            PreTrackScale scale1 = new PreTrackScale();
            scale1.setPredictionNo(predictionNo2);
            scale1.setValueFlag(DbConstants.NET);
            scale1.setUpdateTime(new Date());
            scale1.setUpdateManNo(userId);
            scale1.setUpdateManName(userName);
            scale1.setUploadFlag("1");
            scale1.setValueFlag("2");
            scale1.setPredictionType("6");
            scale1.setPredictionCombination(predictionNo1 + "," + predictionNo2);
            scale1.setMeasureStation(actualRow2.getNetSpot3No());
            scale1.setMeasureStationName(actualRow2.getNetSpot3Name());
            preTrackScaleMapper.updateByPrimaryKeySelective(scale1);

            MeterBaseOperationLog logModel01 = new MeterBaseOperationLog();
            logModel01.setId(PublicMethod.IdCreate(2));
            logModel01.setCreateManNo(userId);
            logModel01.setCreateManName(userName);
            logModel01.setCreateTime(new Date());
            logModel01.setOperationPage("web端-汽车衡一次数据维护");
            logModel01.setOperationFunction("混卸委托结净");
            logModel01.setOperationId(actualRow1.getActualNo());
            logModel01.setOperationPredictionNo(predictionNo1 + "+" + predictionNo2);
            logModel01.setOperationBeforeFix(actualNo1 + "," + actualNo2 + "," + actualNo3);
            logModel01.setOperationCarnNo(actualRow1.getCarNo());
            meterBaseOperationLogMapper.insertSelective(logModel01);

            MeterBaseOperationLog logModel02 = new MeterBaseOperationLog();
            logModel02.setId(PublicMethod.IdCreate(2));
            logModel02.setCreateManNo(userId);
            logModel02.setCreateManName(userName);
            logModel02.setCreateTime(new Date());
            logModel02.setOperationPage("web端-汽车衡一次数据维护");
            logModel02.setOperationFunction("混卸委托结净");
            logModel02.setOperationId(actualRow2.getActualNo());
            logModel02.setOperationPredictionNo(predictionNo1 + "+" + predictionNo2);
            logModel02.setOperationBeforeFix(actualNo1 + "," + actualNo2 + "," + actualNo3);
            logModel02.setOperationCarnNo(actualRow2.getCarNo());
            meterBaseOperationLogMapper.insertSelective(logModel02);
        }
        catch (Exception e){
            e.printStackTrace();
            return "操作异常，请确认";
        }
        return "";
    }

    @Override
    @Transactional
    public RESTfulResult doubleEntrustmentMatch(String actualNo1, String actualNo2, String predictionNo1, String predictionNo2) {
        RESTfulResult rm = new RESTfulResult();
        rm.setFailed();

        try{
            String userId = "";
            String userName = "";
            try{
                UserPayload userPayload = UserPayload.getCurrUser();
                userId = userPayload.getUserCode();
                userName = userPayload.getUserName();
            }catch (Exception e) {
                userId = "system";
                userName = "system";
            }

            //查询出一次计量数据
            MeterWorkCarActualFirst mwcaf01 = meterWorkCarActualFirstMapper.selectByPrimaryKey(actualNo1);
            MeterWorkCarActualFirst mwcaf02 = meterWorkCarActualFirstMapper.selectByPrimaryKey(actualNo1);
            MeterWorkCarActualFirst mwcaf03 = meterWorkCarActualFirstMapper.selectByPrimaryKey(actualNo2);
            MeterWorkCarActualFirst mwcaf04 = meterWorkCarActualFirstMapper.selectByPrimaryKey(actualNo2);
            //查询出所有委托信息
            PreTrackScale pts01 = preTrackScaleMapper.selectByPrimaryKey(predictionNo1);
            PreTrackScale pts02 = preTrackScaleMapper.selectByPrimaryKey(predictionNo2);
            //定义两个结净类
            MeterWorkCarActual actualRow1 = new MeterWorkCarActual();
            MeterWorkCarActual actualRow2 = new MeterWorkCarActual();

            BigDecimal num01 = mwcaf01.getMeterWeight().subtract(mwcaf03.getMeterWeight());
            //判断一次数据和委托信息是否存存在
            if(mwcaf01 == null || mwcaf03 == null ){
                rm.setMessage("未找到相应的一次计量信息,请确认！!");
                return rm;
            }
            if(pts01 == null || pts02 == null){
                rm.setMessage("未找到相应的委托信息,请确认！！");
                return rm;
            }
            //A一次数据重量>B一次数据重量
            if(num01.compareTo(BigDecimal.valueOf(0)) == -1){
                rm.setMessage("请根据一次数据从大到小的规则，依次选择两条一次数据！！");
                return rm;
            }
//            HashMap<String, Object> carMap = new HashMap();
//            carMap.put("carNo", mwcaf01.getCarNo());
//            carMap.put("valueFlag", "1");
//            List<MeterBaseCar> carList = meterBaseCarMapper.selectByParameters(carMap);
//            //判断车辆是否是内倒车辆
//            if(carList.size() >= 1 && carList.get(0).getCarTypeNo().equals("001004003")) {
//                HashMap<String, Object> innerCarMap = new HashMap<>();
//                innerCarMap.put("pBaseCode", "001047");
//                innerCarMap.put("validFlag", "1");
//                innerCarMap.put("baseName", mwcaf01.getCarNo());
//                List<ComBaseInfo> innerCarList = comBaseInfoMapper.selectByParameters(innerCarMap);
//                //判断配置表里是否配置了车辆为内部双委托车辆
//                if(innerCarList.size() >= 1) {
//                    //内部车辆需要查询一下物料映射
//                    HashMap<String, Object> matterMap = new HashMap<>();
//                    matterMap.put("maaterNo1", pts01.getMatterNo());
//                    matterMap.put("maaterNo2", pts02.getMatterNo());
//                    List<MeterBaseMatterMap> matterMapList = meterBaseMatterMapMapper.selectByParameters(matterMap);
//                    if(matterMapList.size() >= 1) {
//                        if(pts01.getReceivingUintNo().equals(pts02.getForwardingUnitNo()) ||
//                                pts01.getForwardingUnitNo().equals(pts02.getReceivingUintNo())) {
//                            rm.setMessage("内部车--委托信息不符合双委托规则，请确认!!");
//                            return rm;
//                        }
//                    }else {
//                        rm.setMessage("内部车--委托信息的物料不存在映射关系，请确认!!");
//                        return rm;
//                    }
//                }else{
//                    rm.setMessage(mwcaf01.getCarNo() + "不是内倒双委托车辆，请确认!!");
//                    return rm;
//                }
//            }else {
//                //外部车辆需要严格控制
//                //判断双委托 物料相同、A委托的收货单位是B委托的发货单位 或者 B委托的收货单位是A委托的发货单位
//                if(!(pts01.getMatterNo().equals(pts02.getMatterNo()) &&
//                        (pts01.getReceivingUintNo().equals(pts02.getForwardingUnitNo()) ||
//                                pts01.getForwardingUnitNo().equals(pts02.getReceivingUintNo())))) {
//                    rm.setMessage("外部车--委托信息不符合双委托规则，请确认!!");
//                    return rm;
//                }
//            }

//            if(!(pts01.getMatterNo().equals(pts02.getMatterNo()) &&
//                    (pts01.getReceivingUintNo().equals(pts02.getForwardingUnitNo()) ||
//                            pts01.getForwardingUnitNo().equals(pts02.getReceivingUintNo())))) {
//                rm.setMessage("委托信息不符合双委托规则，请确认!!");
//                return rm;
//            }
            if(!(pts01.getReceivingUintNo().equals(pts02.getForwardingUnitNo()) ||
                            pts01.getForwardingUnitNo().equals(pts02.getReceivingUintNo()))) {
                rm.setMessage("委托信息不符合双委托规则，请确认!!");
                return rm;
            }
            if(!mwcaf01.getCarNo().equals(mwcaf03.getCarNo())){
                rm.setMessage("两条一次计量数据车号不一致,请确认！！");
                return rm;
            }
            //委托信息是否为有效数据
            if(pts01.getValueFlag().equals("2") || pts02.getValueFlag().equals("2")){
                rm.setMessage("委托信息已使用，请确认！！");
                return rm;
            }
            if(pts01.getValueFlag().equals("3") || pts02.getValueFlag().equals("3")){
                rm.setMessage("委托信息已作废，请确认！！");
                return rm;
            }
            //一次数据是否为有效
            if(mwcaf01.getValueFlag().equals("2") || mwcaf03.getValueFlag().equals("2")){
                rm.setMessage("一次计量数据已结净，请确认！！");
                return rm;
            }
            if(mwcaf01.getValueFlag().equals("0") || mwcaf03.getValueFlag().equals("0")){
                rm.setMessage("一次计量数据已作废，请确认！！");
                return rm;
            }

            //将委托中的编号和收发货的等数据拷贝进一次数据中
            MeterWorkCarActualFirst first1 = meterWorkCarActualFirstMapper.selectAndMatch(actualNo1, predictionNo1);
            //BeanUtils.copyProperties(first1,mwcaf01);
            MeterWorkCarActualFirst first2 = meterWorkCarActualFirstMapper.selectAndMatch(actualNo2, predictionNo1);
            //BeanUtils.copyProperties(first2, mwcaf02);
            MeterWorkCarActualFirst first3 = meterWorkCarActualFirstMapper.selectAndMatch(actualNo1, predictionNo2);
            //BeanUtils.copyProperties(first3,mwcaf03);
            MeterWorkCarActualFirst first4 = meterWorkCarActualFirstMapper.selectAndMatch(actualNo2, predictionNo2);
            //BeanUtils.copyProperties(first4, mwcaf04);

            //更新一次数据
            //更新第一次毛重数据库
            first1.setValueFlag(DbConstants.NET);
            first1.setUpdateManNo(userId);
            first1.setUpdateManName(userName);
            first1.setNote("双委托结净更新");
            first1.setUpdateTime(new Date());
            first1.setIsPreScale("1");
            first1.setWeightType("0");
            first1.setPredictionNo(predictionNo1);
            first1.setPredictionType("5");
            first1.setPredictionCombination(predictionNo1 + "," + predictionNo2);
            meterWorkCarActualFirstMapper.updateByPrimaryKey(first1);
            //更新第一次皮重数据库
            first2.setValueFlag(DbConstants.NET);
            first2.setUpdateManNo(userId);
            first2.setUpdateManName(userName);
            first2.setNote("手动双委托结净更新");
            first2.setUpdateTime(new Date());
            first2.setIsPreScale("1");
            first2.setWeightType("1");
            first2.setPredictionNo(predictionNo1);
            first2.setPredictionType("5");
            first2.setPredictionCombination(predictionNo1 + "," + predictionNo2);
            meterWorkCarActualFirstMapper.updateByPrimaryKey(first2);
            //添加历史皮重
            try {
                doSaveHisTare(first2,"5");
            }catch (Exception e){
                log.error("新增历史皮重异常",e);
                e.printStackTrace();
            }
            //添加第一次毛重数据库
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            String afl = sdf.format(new Date());
//            String actualFirstNo = sdf.format(new Date()) + meterWorkCarActualFirstMapper.getNewID(afl);
//            mwcaf03.setActualFirstNo(actualFirstNo);
            String actualFirstNo = PublicMethod.IdCreate(3);
            first3.setActualFirstNo(actualFirstNo);
            first3.setValueFlag(DbConstants.NET);
            first3.setUpdateManNo(userId);
            first3.setUpdateManName(userName);
            first3.setNote("手动双委托结净更新");
            first3.setUpdateTime(new Date());
            first3.setIsPreScale("1");
            first3.setWeightType("0");
            first3.setPredictionNo(predictionNo2);
            first3.setPredictionType("5");
            first3.setPredictionCombination(predictionNo1 + "," + predictionNo2);
            meterWorkCarActualFirstMapper.insertSelective(first3);
            //添加第二次皮重数据库
            SimpleDateFormat sdf01 = new SimpleDateFormat("yyyyMMdd");
            String afl01 = sdf01.format(new Date());
//            String actualSecondNo = sdf01.format(new Date()) + meterWorkCarActualFirstMapper.getNewID(afl01);
//            mwcaf04.setActualFirstNo(actualSecondNo);
            String actualSecondNo = PublicMethod.IdCreate(3);
            first4.setActualFirstNo(actualSecondNo);
            first4.setValueFlag(DbConstants.NET);
            first4.setUpdateManNo(userId);
            first4.setUpdateManName(userName);
            first4.setNote("手动双委托结净更新");
            first4.setUpdateTime(new Date());
            first4.setIsPreScale("1");
            first4.setWeightType("1");
            first4.setPredictionNo(predictionNo2);
            first4.setPredictionType("5");
            first4.setPredictionCombination(predictionNo1 + "," + predictionNo2);
            meterWorkCarActualFirstMapper.insertSelective(first4);
            //添加历史皮重
            try {
                doSaveHisTare(first4,"5");
            }catch (Exception e){
                log.error("新增历史皮重异常",e);
                e.printStackTrace();
            }

            //将委托中的编号和收发货单位和一次数据等数据拷贝进结净数据中
            MeterWorkCarActual mwca1 = meterWorkCarActualMapper.manualAddPre(actualNo1, actualNo2, predictionNo1);
            BeanUtils.copyProperties(mwca1, actualRow1);
            MeterWorkCarActual mwca2 = meterWorkCarActualMapper.manualAddPre(actualFirstNo, actualSecondNo, predictionNo2);
            BeanUtils.copyProperties(mwca2,actualRow2);

            //添加结净数据
//            String no = meterWorkCarActualMapper.getNewID(sdf.format(new Date()));
//            actualRow1.setActualNo(sdf.format(new Date()) + no);
            String no = PublicMethod.IdCreate(3);
            actualRow1.setActualNo(no);
            actualRow1.setNetTime(new Date());
            actualRow1.setNetMode(DbConstants.TYPE);
            actualRow1.setNetMode("3");
            actualRow1.setUploadFlag("1");
            actualRow1.setIsPreScale("1");
            actualRow1.setValueFlag("1");
            actualRow1.setPredictionNo(predictionNo1);
            actualRow1.setPredictionType("5");
            actualRow1.setPredictionCombination(predictionNo1 + "," + predictionNo2);
            actualRow1.setNetWeight(first1.getMeterWeight().subtract(first2.getMeterWeight()));
            actualRow1.setCreateTime(new Date());
            if(actualRow1.getGrossTime().compareTo(actualRow1.getTareTime()) >= 0) {
                actualRow1.setNetSpot3No(actualRow1.getBaseSpot1No());
                actualRow1.setNetSpot3Name(actualRow1.getBaseSpot1Name());
                actualRow1.setNetManNo(actualRow1.getGrossManNo());
                actualRow1.setNetManName(actualRow1.getGrossManName());
                actualRow1.setNetTime(actualRow1.getGrossTime());
                actualRow1.setCreateTime(actualRow1.getGrossTime());
                actualRow1.setCreateManName(actualRow1.getGrossManName());
            }else {
                actualRow1.setNetSpot3No(actualRow1.getBaseSpot2No());
                actualRow1.setNetSpot3Name(actualRow1.getBaseSpot2Name());
                actualRow1.setNetManNo(actualRow1.getTareManNo());
                actualRow1.setNetManName(actualRow1.getTareManName());
                actualRow1.setNetTime(actualRow1.getTareTime());
                actualRow1.setCreateTime(actualRow1.getTareTime());
                actualRow1.setCreateManName(actualRow1.getTareManName());
            }
            actualRow1.setUpdateManNo(userId);
            actualRow1.setUpdateManName(userName);
            actualRow1.setUpdateTime(new Date());
            actualRow1.setNote("手动双委托匹配结净");
            meterWorkCarActualMapper.insertSelective(actualRow1);

//            String no1 = meterWorkCarActualMapper.getNewID(sdf.format(new Date()));
//            actualRow2.setActualNo(sdf.format(new Date()) + no1);
            String no1 = PublicMethod.IdCreate(3);
            actualRow2.setActualNo(no1);
            actualRow2.setNetTime(new Date());
            actualRow2.setNetMode(DbConstants.TYPE);
            actualRow2.setNetMode("3");
            actualRow2.setUploadFlag("1");
            actualRow2.setIsPreScale("1");
            actualRow2.setValueFlag("1");
            actualRow2.setPredictionNo(predictionNo2);
            actualRow2.setPredictionType("5");
            actualRow2.setPredictionCombination(predictionNo1 + "," + predictionNo2);
            actualRow2.setNetWeight(first3.getMeterWeight().subtract(first4.getMeterWeight()));
            actualRow2.setCreateTime(new Date());
            if(actualRow2.getGrossTime().compareTo(actualRow2.getTareTime()) >= 0) {
                actualRow2.setNetSpot3No(actualRow2.getBaseSpot1No());
                actualRow2.setNetSpot3Name(actualRow2.getBaseSpot1Name());
                actualRow2.setNetManNo(actualRow2.getGrossManNo());
                actualRow2.setNetManName(actualRow2.getGrossManName());
                actualRow2.setNetTime(actualRow2.getGrossTime());
                actualRow2.setCreateTime(actualRow2.getGrossTime());
                actualRow2.setCreateManName(actualRow2.getGrossManName());
            }else {
                actualRow2.setNetSpot3No(actualRow2.getBaseSpot2No());
                actualRow2.setNetSpot3Name(actualRow2.getBaseSpot2Name());
                actualRow2.setNetManNo(actualRow2.getTareManNo());
                actualRow2.setNetManName(actualRow2.getTareManName());
                actualRow2.setNetTime(actualRow2.getTareTime());
                actualRow2.setCreateTime(actualRow2.getTareTime());
                actualRow2.setCreateManName(actualRow2.getTareManName());
            }
            actualRow2.setUpdateManNo(userId);
            actualRow2.setUpdateManName(userName);
            actualRow2.setUpdateTime(new Date());
            actualRow2.setNote("手动双委托匹配结净");
            meterWorkCarActualMapper.insertSelective(actualRow2);

            //更新预报数据
            PreTrackScale scale = new PreTrackScale();
            scale.setPredictionNo(predictionNo1);
            scale.setValueFlag(DbConstants.NET);
            scale.setUpdateTime(new Date());
            scale.setUpdateManNo(userId);
            scale.setUpdateManName(userName);
            scale.setUploadFlag("1");
            scale.setPredictionType("5");
            scale.setPredictionCombination(predictionNo1 + "," + predictionNo2);
            scale.setMeasureStation(actualRow1.getNetSpot3No());
            scale.setMeasureStationName(actualRow1.getNetSpot3Name());
            preTrackScaleMapper.updateByPrimaryKeySelective(scale);

            PreTrackScale scale1 = new PreTrackScale();
            scale1.setPredictionNo(predictionNo2);
            scale1.setValueFlag(DbConstants.NET);
            scale1.setUpdateTime(new Date());
            scale1.setUpdateManNo(userId);
            scale1.setUpdateManName(userName);
            scale1.setUploadFlag("1");
            scale1.setPredictionType("5");
            scale1.setPredictionCombination(predictionNo1 + "," + predictionNo2);
            scale1.setMeasureStation(actualRow2.getNetSpot3No());
            scale1.setMeasureStationName(actualRow2.getNetSpot3Name());
            preTrackScaleMapper.updateByPrimaryKeySelective(scale1);

            MeterBaseOperationLog logModel01 = new MeterBaseOperationLog();
            logModel01.setId(PublicMethod.IdCreate(2));
            logModel01.setCreateManNo(userId);
            logModel01.setCreateManName(userName);
            logModel01.setCreateTime(new Date());
            logModel01.setOperationPage("web端-汽车衡一次数据维护");
            logModel01.setOperationFunction("双委托结净");
            logModel01.setOperationId(actualNo1);
            logModel01.setOperationPredictionNo(predictionNo1 + "+" + predictionNo2);
            logModel01.setOperationBeforeFix(actualRow1.getActualFirst1No() + "," + actualRow1.getActualFirst2No());
            logModel01.setOperationCarnNo(actualRow1.getCarNo());
            meterBaseOperationLogMapper.insertSelective(logModel01);

            MeterBaseOperationLog logModel02 = new MeterBaseOperationLog();
            logModel02.setId(PublicMethod.IdCreate(2));
            logModel02.setCreateManNo(userId);
            logModel02.setCreateManName(userName);
            logModel02.setCreateTime(new Date());
            logModel02.setOperationPage("web端-汽车衡一次数据维护");
            logModel02.setOperationFunction("双委托结净");
            logModel02.setOperationId(actualNo2);
            logModel02.setOperationPredictionNo(predictionNo1 + "+" + predictionNo2);
            logModel02.setOperationBeforeFix(actualRow2.getActualFirst1No() + "," + actualRow2.getActualFirst2No());
            logModel02.setOperationCarnNo(actualRow2.getCarNo());
            meterBaseOperationLogMapper.insertSelective(logModel02);

            rm.setSucceed();
            rm.setMessage("操作成功!!");
            rm.setCode("200");
            return rm;
        }catch(Exception e){
            e.printStackTrace();
            rm.setMessage("操作异常，请确认");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return rm;
        }
    }



    /**
     * 内倒车辆结净
     *
     * @param secondDb 二次计量数据
     * @param netDb    净重数据
     * @param saveTare 0 不保存历史皮，1保存历史皮
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(value = "tm", rollbackFor = Exception.class)
    public RESTfulResult doNetTermTare(MeterWorkCarActualFirst secondDb, MeterWorkCarActual netDb, String saveTare) throws Exception {
        try{
            RESTfulResult rm = new RESTfulResult();
            rm.setCode("200");

            //1、存储当前计量的数据
            SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
            String afl = formatter.format(new Date());
//            String no = meterWorkCarActualFirstMapper.getNewID(afl);
//            secondDb.setActualFirstNo(formatter.format(new Date()) + no);
            String no = PublicMethod.IdCreate(3);
            secondDb.setActualFirstNo(no);

            if(StringUtils.isNotEmpty(secondDb.getPredictionNo())) {
                secondDb.setIsPreScale("1");
            }
            secondDb.setValueFlag("2");//结净
            secondDb.setCreateTime(new Date());
            meterWorkCarActualFirstMapper.insertSelective(secondDb);
//            String no1 = meterWorkCarActualMapper.getNewID(afl);
//            netDb.setActualNo(afl + no1);
            String no1 = PublicMethod.IdCreate(3);
            netDb.setActualNo(no1);
            if (netDb != null && netDb.getNetWeight() != null) {
                //2021年3月7日 净重保留两位小数；
                BigDecimal net;
                net = new BigDecimal(String.valueOf(netDb.getNetWeight())).setScale(2, BigDecimal.ROUND_HALF_UP);
                netDb.setNetWeight(net);
            }
            netDb.setGrossTime(secondDb.getCreateTime());
            netDb.setNetTime(new Date());
            netDb.setUploadFlag("1");
            netDb.setActualFirst1No(secondDb.getActualFirstNo());
            netDb.setCreateTime(new Date());
            if(netDb.getGrossTime().compareTo(netDb.getTareTime()) >= 0) {
                netDb.setNetSpot3No(netDb.getBaseSpot1No());
                netDb.setNetSpot3Name(netDb.getBaseSpot1Name());
                netDb.setNetManNo(netDb.getGrossManNo());
                netDb.setNetManName(netDb.getGrossManName());
                netDb.setNetTime(netDb.getGrossTime());
                netDb.setCreateTime(netDb.getGrossTime());
                netDb.setCreateManName(netDb.getGrossManName());
            }else {
                netDb.setNetSpot3No(netDb.getBaseSpot2No());
                netDb.setNetSpot3Name(netDb.getBaseSpot2Name());
                netDb.setNetManNo(netDb.getTareManNo());
                netDb.setNetManName(netDb.getTareManName());
                netDb.setNetTime(netDb.getTareTime());
                netDb.setCreateTime(netDb.getTareTime());
                netDb.setCreateManName(netDb.getTareManName());
            }
            meterWorkCarActualMapper.insert(netDb);

            //4、将期限皮重转化为一条皮重计量数据保存
            MeterBaseTermTareData mbttd = new MeterBaseTermTareData();
            HashMap mbMap = new HashMap();
            SimpleDateFormat mbsdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            mbMap.put("endTime",mbsdf.format(new Date()));
            if(StringUtils.isNotEmpty(netDb.getActualFirst2No())){
                mbMap.put("dataNo",netDb.getActualFirst2No());
                mbttd = meterBaseTermTareDataMapper.selectByDataNo(mbMap);
            }
            else{
                MeterBaseSpotInfo spotInfo = meterBaseSpotInfoMapper.selectByPrimaryKey(secondDb.getBaseSpotNo());
                mbMap.put("carNo",netDb.getCarNo());
                mbMap.put("spotAreaNo", spotInfo.getSpotAreaNo());
                mbMap.put("spotAreaName", spotInfo.getSpotAreaName());
                mbttd = meterBaseTermTareDataMapper.selectByCarNo(mbMap);
            }
            MeterWorkCarActualFirst imTare = new MeterWorkCarActualFirst();
            //补充数据
            String afl1 = formatter.format(new Date());
//            String imTareNO = meterWorkCarActualFirstMapper.getNewID(afl1);
//            String actualNo = afl1 + imTareNO;
            String actualNo = PublicMethod.IdCreate(3);
            imTare.setActualFirstNo(no);
            imTare.setActualFirstNo(actualNo);
            imTare.setMeterTypeNo(secondDb.getMeterTypeNo());
            imTare.setMeterTypeName(secondDb.getMeterTypeName());
            imTare.setBaseSpotNo(mbttd.getBaseSpotNo());
            imTare.setBaseSpotName(mbttd.getBaseSpotName());
            imTare.setCarNo(mbttd.getCarNo());
            imTare.setCreateTime(mbttd.getMeterTime());
            imTare.setCreateManNo(mbttd.getCreateManNo());
            imTare.setCreateManName(mbttd.getCreateManName());
            imTare.setMeterWeight(mbttd.getMeterWeight());
            imTare.setWeightType("2");//期限皮重
            imTare.setValueFlag("2");//结净
            imTare.setDataSource("1");
            meterWorkCarActualFirstMapper.insertSelective(imTare);
            //将结净数据中的皮重编号修改
            MeterWorkCarActual mwca = new MeterWorkCarActual();
            mwca.setActualNo(netDb.getActualNo());
            mwca.setActualFirst2No(actualNo);
            mwca.setTareWeight(mbttd.getMeterWeight());
            //新增修改结净数据汇总皮重计量点和时间   --20220724杜勇
            mwca.setTareTime(mbttd.getMeterTime());
            mwca.setBaseSpot2No(mbttd.getBaseSpotNo());
            mwca.setBaseSpot2Name(mbttd.getBaseSpotName());
            mwca.setNetWeight(secondDb.getMeterWeight().subtract(imTare.getMeterWeight()));
            meterWorkCarActualMapper.updateByPrimaryKeySelective(mwca);

            //皮重数据匹配委托
            MeterWorkCarActualFirst mwcaf2 = meterWorkCarActualFirstMapper.selectAndMatch(actualNo, netDb.getPredictionNo());
//            String nomwcaf2 = meterWorkCarActualFirstMapper.getNewID(afl);
            String nomwcaf2 = PublicMethod.IdCreate(3);
            mwcaf2.setIsPreScale("1");
            meterWorkCarActualFirstMapper.updateByPrimaryKeySelective(mwcaf2);

            //判断结净数据是否匹配委托
            if (StringUtils.isNotEmpty(netDb.getPredictionNo())) {
                PreTrackScale preTrackScale = new PreTrackScale();
                preTrackScale.setPredictionNo(netDb.getPredictionNo());
                preTrackScale.setValueFlag("2");
                preTrackScale.setLineDesc("0");
                preTrackScale.setUploadFlag("1");
                preTrackScale.setMeasureStation(netDb.getNetSpot3No());
                preTrackScale.setMeasureStationName(netDb.getNetSpot3Name());
                preTrackScaleMapper.updateByPrimaryKeySelective(preTrackScale);
            }

            //4、存储历史皮重及历史皮重明细信息
            if ("1".equals(saveTare)) {
                MeterWorkCarActualFirst oci = new MeterWorkCarActualFirst();
                oci.setCarNo(netDb.getCarNo());
                oci.setCreateTime(mbttd.getCreateTime());
                oci.setBaseSpotNo(mbttd.getBaseSpotNo());
                oci.setBaseSpotName(mbttd.getBaseSpotName());
                oci.setMeterWeight(mbttd.getMeterWeight());
                oci.setActualFirstNo(actualNo);
                doSaveHisTare(oci);
            }

            //5、保存图片
            //SaveImg(secondDb);

            //6、修改计量监控
            updateMonitor(secondDb.getBaseSpotNo());

            //当存储一次数据或者结净时，将本车辆的预处理重量改为已使用
            updatePreWeight(secondDb.getCarNo());

            updateMonitorOver(secondDb.getActualFirstNo(), secondDb.getBaseSpotNo());

            //重量类型为毛重则调用接口为
            String flag = "";
            /*
            if("0".equals(secondDb.getWeightType())){
                flag = transferParamForLims(netDb.getCarNo(),netDb.getMatterNo(),netDb.getReceivingUintName(),netDb.getForwardingUnitName(),netDb.getNetWeight().toString(),netDb.getNetTime(),"",netDb.getActualNo());
            }
            //*/

            //补充附加重量的数据
            if (StringUtils.isNotEmpty(secondDb.getAddWgtPk())) {
                insertAddWgtNo(secondDb.getActualFirstNo(), secondDb.getAddWgtPk(), secondDb.getCreateManNo(), secondDb.getCreateManName());
            }


            rm.setData(secondDb.getActualFirstNo());
            rm.setMessage(flag);
            return rm;
        }
        catch (Exception e){
            RESTfulResult rm = new RESTfulResult();
            rm.setCode("500");
            rm.setData(null);
            rm.setMessage(e.getMessage());
            e.printStackTrace();
            return rm;
        }
    }

    @Override
    public RESTfulResult addEmergency(List<MeterWorkCarActualFirst> meterWorkCarActualFirsts) throws Exception {
        try{
            RESTfulResult rm = new RESTfulResult();
            rm.setCode("200");
            int num = 0;
            for(MeterWorkCarActualFirst model:meterWorkCarActualFirsts){
                if(StringUtils.isNotEmpty(model.getActualFirstNo())){
                    MeterWorkCarActualFirst list = meterWorkCarActualFirstMapper.selectByPrimaryKey(model.getActualFirstNo());
                    if(list != null){
                        continue;
                    }
                }
                SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
//                String afl = formatter.format(new Date());
//                String no = meterWorkCarActualFirstMapper.getNewID(afl);
                String no = PublicMethod.IdCreate(3);
                if(StringUtils.isEmpty(model.getActualFirstNo())){
                    model.setActualFirstNo(formatter.format(new Date()) + no);
                }
                model.setValueFlag("1");
                model.setIsPreScale("0");
                model.setDataSource("3");
                model.setCreateTime(new Date());
                meterWorkCarActualFirstMapper.insertSelective(model);
                num++;
            }
            rm.setData(num);
            rm.setMessage("成功");
            return rm;
        }
        catch (Exception e){
            RESTfulResult rm = new RESTfulResult();
            rm.setCode("500");
            rm.setData(null);
            rm.setMessage(e.getMessage());
            e.printStackTrace();
            return rm;
        }
    }

    @Override
    public RESTfulResult addFirstEmergency(MeterWorkCarActualFirst model) throws Exception {
        try{
            RESTfulResult rm = new RESTfulResult();
            rm.setCode("200");
            int num = 0;
            if(StringUtils.isNotEmpty(model.getActualFirstNo())){
                MeterWorkCarActualFirst list = meterWorkCarActualFirstMapper.selectByPrimaryKey(model.getActualFirstNo());
            }
//            SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
//                String afl = formatter.format(new Date());
//                String no = meterWorkCarActualFirstMapper.getNewID(afl);
            String no = PublicMethod.IdCreate(3);
            if(StringUtils.isEmpty(model.getActualFirstNo())){
                //邓义晶 一次主键多了一个时间
//                model.setActualFirstNo(formatter.format(new Date()) + no);
                model.setActualFirstNo(no);
            }
            model.setValueFlag("1");
            model.setIsPreScale("0");
            model.setDataSource("3");
            model.setCreateTime(new Date());
            meterWorkCarActualFirstMapper.insertSelective(model);
            rm.setData(num);
            rm.setMessage("成功");
            return rm;
        }
        catch (Exception e){
            RESTfulResult rm = new RESTfulResult();
            rm.setCode("500");
            rm.setData(null);
            rm.setMessage(e.getMessage());
            e.printStackTrace();
            return rm;
        }
    }

    @Override
    public RESTfulResult doNetEmergency(MeterWorkCarActual model) throws Exception {
        RESTfulResult rm = new RESTfulResult();
        rm.setFailed();
        try {
            Assert.isTrue(!Objects.isNull(model), "结净数据不能为空");
            Assert.isTrue(!(model.getActualFirst1No() == null || model.getActualFirst2No()==null
                    || StringUtils.isEmpty(model.getActualFirst1No()) || StringUtils.isEmpty(model.getActualFirst2No())), "一次数据编号不能为空");
            MeterWorkCarActualFirst firstTemp = meterWorkCarActualFirstMapper.selectByPrimaryKey(model.getActualFirst1No());
            MeterWorkCarActualFirst secondTemp = meterWorkCarActualFirstMapper.selectByPrimaryKey(model.getActualFirst2No());
            Assert.isTrue(!(Objects.isNull(firstTemp) || Objects.isNull(secondTemp)), "一次数据未查到有效的数据");

            MeterWorkCarActual actualModel = new MeterWorkCarActual();
            BigDecimal meterWeight;
            if(firstTemp.getMeterWeight().compareTo(secondTemp.getMeterWeight()) > 0) {
                MeterWorkCarActual mwca = meterWorkCarActualMapper.manualAdd(firstTemp.getActualFirstNo(), secondTemp.getActualFirstNo());
                BeanUtils.copyProperties(mwca, actualModel);
                firstTemp.setWeightType("0");
                secondTemp.setWeightType("1");
                meterWeight = firstTemp.getMeterWeight().subtract(secondTemp.getMeterWeight());
            }else {
                MeterWorkCarActual mwca = meterWorkCarActualMapper.manualAdd(secondTemp.getActualFirstNo(), firstTemp.getActualFirstNo());
                BeanUtils.copyProperties(mwca, actualModel);
                firstTemp.setWeightType("1");
                secondTemp.setWeightType("0");
                meterWeight = secondTemp.getMeterWeight().subtract(firstTemp.getMeterWeight());
            }
            firstTemp.setValueFlag(DbConstants.NET);
            firstTemp.setUpdateManNo("system");
            firstTemp.setUpdateManName("紧急结净更新");
            firstTemp.setUpdateTime(new Date());
            firstTemp.setIsPreScale("0");
            meterWorkCarActualFirstMapper.updateByPrimaryKey(firstTemp);
            //更新第一次皮重数据库
            secondTemp.setValueFlag(DbConstants.NET);
            secondTemp.setUpdateManNo("system");
            secondTemp.setUpdateManName("紧急结净更新");
            secondTemp.setUpdateTime(new Date());
            secondTemp.setIsPreScale("0");
            meterWorkCarActualFirstMapper.updateByPrimaryKey(secondTemp);

            String no = PublicMethod.IdCreate(3);
            actualModel.setActualNo(no);
            actualModel.setNetTime(new Date());
            actualModel.setNetMode("1");
            actualModel.setNote("紧急结净保存");
            actualModel.setUploadFlag("1");
            actualModel.setIsPreScale("0");
            actualModel.setValueFlag("1");
            actualModel.setNetWeight(meterWeight);
            actualModel.setCreateTime(new Date());
            if(actualModel.getGrossTime().compareTo(actualModel.getTareTime()) >= 0) {
                actualModel.setNetSpot3No(actualModel.getBaseSpot1No());
                actualModel.setNetSpot3Name(actualModel.getBaseSpot1Name());
                actualModel.setNetManNo(actualModel.getGrossManNo());
                actualModel.setNetManName(actualModel.getGrossManName());
                actualModel.setNetTime(actualModel.getGrossTime());
                actualModel.setCreateTime(actualModel.getGrossTime());
                actualModel.setCreateManName(actualModel.getGrossManName());
            }else {
                actualModel.setNetSpot3No(actualModel.getBaseSpot2No());
                actualModel.setNetSpot3Name(actualModel.getBaseSpot2Name());
                actualModel.setNetManNo(actualModel.getTareManNo());
                actualModel.setNetManName(actualModel.getTareManName());
                actualModel.setNetTime(actualModel.getTareTime());
                actualModel.setCreateTime(actualModel.getTareTime());
                actualModel.setCreateManName(actualModel.getTareManName());
            }
            meterWorkCarActualMapper.insertSelective(actualModel);

            rm.setSucceed();
            rm.setCode("200");
            rm.setMessage("操作成功");
            rm.setData(actualModel.getActualNo());
        }catch (Exception e) {
            e.printStackTrace();
            rm.setMessage("操作异常：>>>" + e.getMessage());
        }
        return rm;
    }

    @Override
    public PageList<MeterWorkCarActualFirst> likeByDesc(Map<String, Object> params, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);

        if(params.get("baseSpotNoStr") != null) {
            String[] spotNoStr = params.get("baseSpotNoStr").toString().split(",");
            params.put("spotNoStr", spotNoStr);
        }
        List<MeterWorkCarActualFirst> rows = meterWorkCarActualFirstMapper.likeByDesc(params);
        PageList pageInfo = new PageList(rows);
        return pageInfo;
    }

    @Override
    public List<MeterWorkCarActualFirst> likeByValueFlag(Map<String, Object> params) {
        if(params.get("baseSpotNoStr") != null) {
            String[] spotNoStr = params.get("baseSpotNoStr").toString().split(",");
            params.put("spotNoStr", spotNoStr);
        }
        List<MeterWorkCarActualFirst> rows = meterWorkCarActualFirstMapper.likeByDesc(params);
        return rows;
    }

    @Override
    public List<MeterWorkCarActualFirst> carFirstDataDetail(Map<String, Object> params) {
        List<MeterWorkCarActualFirst> models = meterWorkCarActualFirstMapper.carFirstDataDetail(params);
        return models;
    }

    @Override
    public PageList<MeterWorkCarActualFirst> ApplikeByDesc(Map<String, Object> params, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<MeterWorkCarActualFirst> rows = meterWorkCarActualFirstMapper.likeByDesc(params);
        //移除所有期限皮数据
        if(rows.size() >= 1) {
            for(int i = 0; i < rows.size(); i++){
                if(rows.get(0).getWeightType() != null) {
                    if(rows.get(0).getWeightType().equals("2")) {
                        rows.remove(i);
                    }
                }
            }
            //添加一条期限皮信息
            params.put("weightType", "2");
            List<MeterWorkCarActualFirst> firstList = meterWorkCarActualFirstMapper.likeByDesc(params);
            if(firstList.size() >= 1) {
                rows.add(firstList.get(0));
            }

        /*Collections.sort(rows, new Comparator<MeterWorkCarActualFirst>() {
            @Override
            public int compare(MeterWorkCarActualFirst o1, MeterWorkCarActualFirst o2) {
                //这里使用时间字段排序 如果要用其他字段直接从bean实体中取
                return o2.getCreateTime().compareTo(o1.getCreateTime());
                //上面使用的是降序排序，如果正序 直接使用o1-o2即可
            }
        });*/
        }
        PageList pageInfo = new PageList(rows);
        return pageInfo;
    }

    @Override
    public List<MeterWorkCarActualFirst> queryForTimeInterval(Map<String, Object> params) {
        List<MeterWorkCarActualFirst> rows = meterWorkCarActualFirstMapper.queryForTimeInterval(params);
        return rows;
    }

    @Override
    @Transactional(value = "tm", rollbackFor = Exception.class)
    public RESTfulResult doNetAddMuch(MeterWorkCarActualFirst actualFirst) throws Exception {
        RESTfulResult rm = new RESTfulResult();
        rm.setCode("200");

        try {
            HashMap map = new HashMap();
            map.put("valueFlag","1");
            map.put("carNo",actualFirst.getCarNo());
            List<MeterWorkCarActualFirst> list = meterWorkCarActualFirstMapper.selectByParameters(map);
            int num = 0;
            for (MeterWorkCarActualFirst model:list){
                //存储当前皮重的数据
                SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
                String afl = formatter.format(new Date());
//                String no = meterWorkCarActualFirstMapper.getNewID(afl);
//                actualFirst.setActualFirstNo(formatter.format(new Date()) + no);
                String no = PublicMethod.IdCreate(3);
                actualFirst.setActualFirstNo(no);

                actualFirst.setValueFlag("2");//未结净
                actualFirst.setCreateTime(new Date());
                int i = meterWorkCarActualFirstMapper.insertSelective(actualFirst);

                //将毛重委托匹配到皮重中
                MeterWorkCarActualFirst meterWorkCarActualFirst = meterWorkCarActualFirstMapper.selectAndMatch(actualFirst.getActualFirstNo(), model.getPredictionNo());
                meterWorkCarActualFirst.setIsPreScale("1");
                meterWorkCarActualFirst.setWeightType("1");
                meterWorkCarActualFirstMapper.updateByPrimaryKeySelective(meterWorkCarActualFirst);


                //修改毛重数据状态为结净
                model.setValueFlag("2");
                meterWorkCarActualFirstMapper.updateByPrimaryKeySelective(model);

                MeterWorkCarActual meterWorkCarActual = new MeterWorkCarActual();

                MeterWorkCarActual mwca1 = meterWorkCarActualMapper.manualAddPre(model.getActualFirstNo(), actualFirst.getActualFirstNo(), model.getPredictionNo());
                BeanUtils.copyProperties(mwca1, meterWorkCarActual);

//                String noActual = meterWorkCarActualFirstMapper.getNewID(afl);
//                meterWorkCarActual.setActualNo(formatter.format(new Date()) + noActual);
                String noActual = PublicMethod.IdCreate(3);
                meterWorkCarActual.setActualNo(noActual);
                meterWorkCarActual.setNetTime(new Date());
                meterWorkCarActual.setNetMode(DbConstants.TYPE);
                meterWorkCarActual.setNote("计量数据结净");
                meterWorkCarActual.setUploadFlag("1");
                meterWorkCarActual.setIsPreScale("1");
                meterWorkCarActual.setValueFlag("1");
                meterWorkCarActual.setNetWeight(model.getMeterWeight().subtract(actualFirst.getMeterWeight()));
                meterWorkCarActual.setCreateTime(new Date());
                if(meterWorkCarActual.getGrossTime().compareTo(meterWorkCarActual.getTareTime()) >= 0) {
                    meterWorkCarActual.setNetSpot3No(meterWorkCarActual.getBaseSpot1No());
                    meterWorkCarActual.setNetSpot3Name(meterWorkCarActual.getBaseSpot1Name());
                    meterWorkCarActual.setNetManNo(meterWorkCarActual.getGrossManNo());
                    meterWorkCarActual.setNetManName(meterWorkCarActual.getGrossManName());
                    meterWorkCarActual.setNetTime(meterWorkCarActual.getGrossTime());
                    meterWorkCarActual.setCreateTime(meterWorkCarActual.getGrossTime());
                    meterWorkCarActual.setCreateManName(meterWorkCarActual.getGrossManName());
                }else {
                    meterWorkCarActual.setNetSpot3No(meterWorkCarActual.getBaseSpot2No());
                    meterWorkCarActual.setNetSpot3Name(meterWorkCarActual.getBaseSpot2Name());
                    meterWorkCarActual.setNetManNo(meterWorkCarActual.getTareManNo());
                    meterWorkCarActual.setNetManName(meterWorkCarActual.getTareManName());
                    meterWorkCarActual.setNetTime(meterWorkCarActual.getTareTime());
                    meterWorkCarActual.setCreateTime(meterWorkCarActual.getTareTime());
                    meterWorkCarActual.setCreateManName(meterWorkCarActual.getTareManName());
                }
                meterWorkCarActualMapper.insertSelective(meterWorkCarActual);

                PreTrackScale preTrackScale = new PreTrackScale();
                preTrackScale.setPredictionNo(meterWorkCarActual.getPredictionNo());
                preTrackScale.setValueFlag("2");
                preTrackScale.setUploadFlag("1");
                preTrackScale.setMeasureStation(meterWorkCarActual.getNetSpot3No());
                preTrackScale.setMeasureStationName(meterWorkCarActual.getNetSpot3Name());
                preTrackScaleMapper.updateByPrimaryKeySelective(preTrackScale);
                num++;
            }
            //当存储一次数据或者结净时，将本车辆的预处理重量改为已使用
            updatePreWeight(actualFirst.getCarNo());

            rm.setData(num);
            rm.setMessage("成功");
            return rm;
        }
        catch (Exception e){
            rm.setCode("500");
            rm.setData(null);
            rm.setMessage(e.getMessage());
            e.printStackTrace();
            return rm;
        }
    }


    /**
     * 内倒车辆结净
     *
     * @param secondDb 二次计量数据
     * @param netDb    净重数据
     * @param saveTare 0 不保存历史皮，1保存历史皮
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(value = "tm", rollbackFor = Exception.class)
    public RESTfulResult doAddNetInnerWfError(MeterWorkCarActualFirst secondDb, MeterWorkCarActual netDb, String saveTare, MeterMonitorNote note) throws Exception {
        try{

            RESTfulResult rm = new RESTfulResult();
            rm.setCode("200");

            //1、存储当前计量的数据
            SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
            String afl = formatter.format(new Date());
//            String no = meterWorkCarActualFirstMapper.getNewID(afl);
//            secondDb.setActualFirstNo(formatter.format(new Date()) + no);
            String no = PublicMethod.IdCreate(3);
            secondDb.setActualFirstNo(no);
            secondDb.setValueFlag("2");//结净
            secondDb.setCreateTime(new Date());
            meterWorkCarActualFirstMapper.insertSelective(secondDb);

            //修改一次计量数据为结净
            MeterWorkCarActualFirst firstUpdate = new MeterWorkCarActualFirst();
            //2、存储结净数据
            if (StringUtils.isNotEmpty(netDb.getActualFirst1No())) {
                //二次重量如果跟皮重一样
                netDb.setActualFirst2No(secondDb.getActualFirstNo());
                firstUpdate.setActualFirstNo(netDb.getActualFirst1No());
            } else {
                netDb.setActualFirst1No(secondDb.getActualFirstNo());
                firstUpdate.setActualFirstNo(netDb.getActualFirst2No());
            }

            //3、修改第一次存储的计量数据状态为结净
            if (firstUpdate.getActualFirstNo() != null) {
                firstUpdate.setValueFlag("2");
                meterWorkCarActualFirstMapper.updateByPrimaryKeySelective(firstUpdate);
            }

            //判断结净数据是否匹配委托
            if (StringUtils.isNotEmpty(netDb.getPredictionNo())) {
                MeterWorkCarActualFirst meca1 = meterWorkCarActualFirstMapper.selectAndMatch(firstUpdate.getActualFirstNo(), netDb.getPredictionNo());
                meca1.setIsPreScale("1");
                meterWorkCarActualFirstMapper.updateByPrimaryKeySelective(meca1);
                PreTrackScale preTrackScale = new PreTrackScale();
                preTrackScale.setPredictionNo(netDb.getPredictionNo());
                preTrackScale.setValueFlag("2");
                preTrackScale.setUploadFlag("1");
                preTrackScale.setMeasureStation(firstUpdate.getBaseSpotNo());
                preTrackScale.setMeasureStationName(firstUpdate.getBaseSpotName());
                preTrackScaleMapper.updateByPrimaryKeySelective(preTrackScale);
            }

//            String no1 = meterWorkCarActualMapper.getNewID(afl);
//            netDb.setActualNo(afl + no1);
            String no1 = PublicMethod.IdCreate(3);
            netDb.setActualNo(no1);
            if (netDb != null && netDb.getNetWeight() != null) {
                //2021年3月7日 净重保留两位小数；
                BigDecimal net;
                net = new BigDecimal(String.valueOf(netDb.getNetWeight())).setScale(2, BigDecimal.ROUND_HALF_UP);
                netDb.setNetWeight(net);
            }
            netDb.setUploadFlag("1");
            netDb.setCreateTime(new Date());
            if(netDb.getGrossTime().compareTo(netDb.getTareTime()) >= 0) {
                netDb.setNetSpot3No(netDb.getBaseSpot1No());
                netDb.setNetSpot3Name(netDb.getBaseSpot1Name());
                netDb.setNetManNo(netDb.getGrossManNo());
                netDb.setNetManName(netDb.getGrossManName());
                netDb.setNetTime(netDb.getGrossTime());
                netDb.setCreateTime(netDb.getGrossTime());
                netDb.setCreateManName(netDb.getGrossManName());
            }else {
                netDb.setNetSpot3No(netDb.getBaseSpot2No());
                netDb.setNetSpot3Name(netDb.getBaseSpot2Name());
                netDb.setNetManNo(netDb.getTareManNo());
                netDb.setNetManName(netDb.getTareManName());
                netDb.setNetTime(netDb.getTareTime());
                netDb.setCreateTime(netDb.getTareTime());
                netDb.setCreateManName(netDb.getTareManName());
            }
            meterWorkCarActualMapper.insert(netDb);

            //4、如果为期限皮重，则将期限皮重转化为一条皮重计量数据保存
            MeterWorkCarActualFirst mwraf = meterWorkCarActualFirstMapper.selectByPrimaryKey(netDb.getActualFirst2No());
            if (mwraf == null) {
                MeterBaseTermTareData mbttd = new MeterBaseTermTareData();
                HashMap mbMap = new HashMap();
                SimpleDateFormat mbsdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                mbMap.put("endTime",mbsdf.format(new Date()));
                if(StringUtils.isNotEmpty(netDb.getActualFirst2No())){
                    mbMap.put("dataNo",netDb.getActualFirst2No());
                    mbttd = meterBaseTermTareDataMapper.selectByDataNo(mbMap);
                }
                else{
                    mbMap.put("carNo",netDb.getCarNo());
                    mbttd = meterBaseTermTareDataMapper.selectByCarNo(mbMap);
                }
                MeterWorkCarActualFirst imTare = new MeterWorkCarActualFirst();
                //补充数据
                String afl1 = formatter.format(new Date());
//                String imTareNO = meterWorkCarActualFirstMapper.getNewID(afl1);
//                imTare.setActualFirstNo(afl1 + imTareNO);
                String imTareNO = PublicMethod.IdCreate(3);
                imTare.setActualFirstNo(no);
                imTare.setMeterTypeNo(secondDb.getMeterTypeNo());
                imTare.setMeterTypeName(secondDb.getMeterTypeName());
                imTare.setBaseSpotNo(mbttd.getBaseSpotNo());
                imTare.setBaseSpotName(mbttd.getBaseSpotName());
                imTare.setCarNo(mbttd.getCarNo());
                imTare.setCreateTime(mbttd.getCreateTime());
                imTare.setCreateManNo(mbttd.getCreateManNo());
                imTare.setCreateManName(mbttd.getCreateManName());
                imTare.setMeterWeight(netDb.getTareWeight());
                imTare.setWeightType("2");//期限皮重
                imTare.setValueFlag("2");//结净
                meterWorkCarActualFirstMapper.insertSelective(imTare);
                //将结净数据中的皮重编号修改
                MeterWorkCarActual mwca = new MeterWorkCarActual();
                mwca.setActualNo(netDb.getActualNo());
                mwca.setActualFirst2No(imTare.getActualFirstNo());
                meterWorkCarActualMapper.updateByPrimaryKeySelective(mwca);
            }

            //4、存储历史皮重及历史皮重明细信息
            if ("1".equals(saveTare)) {
                MeterWorkCarActualFirst oci = new MeterWorkCarActualFirst();
                oci.setCarNo(netDb.getCarNo());
                oci.setCreateTime(netDb.getTareTime());
                oci.setBaseSpotNo(netDb.getBaseSpot2No());
                oci.setBaseSpotName(netDb.getBaseSpot2Name());
                oci.setMeterWeight(netDb.getTareWeight());
                oci.setActualFirstNo(netDb.getActualFirst2No());
                doSaveHisTare(oci);
            }

            //5、保存图片
            //SaveImg(secondDb);

            //6、修改计量监控
            updateMonitor(secondDb.getBaseSpotNo());

            //保存日志
            saveNote(note);

            //当存储一次数据或者结净时，将本车辆的预处理重量改为已使用
            updatePreWeight(secondDb.getCarNo());

            updateMonitorOver(secondDb.getActualFirstNo(), secondDb.getBaseSpotNo());

            //重量类型为毛重则调用接口为
            String flag = "";
            /*
            if("0".equals(secondDb.getWeightType())){
                flag = transferParamForLims(netDb.getCarNo(),netDb.getMatterNo(),netDb.getReceivingUintName(),netDb.getForwardingUnitName(),netDb.getNetWeight().toString(),netDb.getNetTime(),"",netDb.getActualNo());
            }
            //*/

            //补充附加重量的数据
            if (StringUtils.isNotEmpty(secondDb.getAddWgtPk())) {
                insertAddWgtNo(secondDb.getActualFirstNo(), secondDb.getAddWgtPk(), secondDb.getCreateManNo(), secondDb.getCreateManName());
            }


            rm.setData(afl + no1);
            rm.setMessage(flag);
            return rm;
        }
        catch (Exception e){
            RESTfulResult rm = new RESTfulResult();
            rm.setCode("500");
            rm.setData(null);
            rm.setMessage(e.getMessage());
            e.printStackTrace();
            return rm;
        }
    }

    @Override
    public RESTfulResult doNetByFirst(MeterWorkCarActualFirst grossModel, MeterWorkCarActualFirst tareModel, PreTrackScale scale) {
        RESTfulResult rm = new RESTfulResult();
        rm.setFailed();

        try {
            String returnNo = "";
            MeterWorkCarActual model = new MeterWorkCarActual();
            if (com.steerinfo.util.StringUtils.isNotEmpty(scale.getPredictionNo())) {
                MeterWorkCarActualFirst mg = meterWorkCarActualFirstMapper.selectByPrimaryKey(grossModel.getActualFirstNo());
                if(mg == null){
                    SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
                    String afl1 = formatter.format(new Date());
//                    String no1 = meterWorkCarActualFirstMapper.getNewID(afl1);
//                    grossModel.setActualFirstNo(formatter.format(new Date()) + no1);
                    String no1 = PublicMethod.IdCreate(3);
                    grossModel.setActualFirstNo(no1);
                    grossModel.setValueFlag("2");//结净
                    grossModel.setCreateTime(new Date());
                    meterWorkCarActualFirstMapper.insertSelective(grossModel);
                    returnNo = grossModel.getActualFirstNo();
                }
                else {
                    SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
                    String afl1 = formatter.format(new Date());
//                    String no1 = meterWorkCarActualFirstMapper.getNewID(afl1);
//                    tareModel.setActualFirstNo(formatter.format(new Date()) + no1);
                    String no1 = PublicMethod.IdCreate(3);
                    tareModel.setActualFirstNo(no1);
                    tareModel.setValueFlag("2");//结净
                    tareModel.setCreateTime(new Date());
                    meterWorkCarActualFirstMapper.insertSelective(tareModel);
                    returnNo = tareModel.getActualFirstNo();
                }


                //将委托信息插入一次数据
                MeterWorkCarActualFirst first1 = meterWorkCarActualFirstMapper.selectAndMatch(grossModel.getActualFirstNo(), scale.getPredictionNo());
                BeanUtils.copyProperties(first1, grossModel);
                MeterWorkCarActualFirst first2 = meterWorkCarActualFirstMapper.selectAndMatch(tareModel.getActualFirstNo(), scale.getPredictionNo());
                BeanUtils.copyProperties(first2, tareModel);

                //更新第一次毛重数据库
                grossModel.setValueFlag(DbConstants.NET);
                grossModel.setUpdateManNo("system");
                grossModel.setUpdateManName("期限皮结净更新");
                grossModel.setUpdateTime(new Date());
                grossModel.setIsPreScale("1");
                grossModel.setPredictionType("1");
                meterWorkCarActualFirstMapper.updateByPrimaryKey(grossModel);
                //更新第一次皮重数据库
                tareModel.setValueFlag(DbConstants.NET);
                tareModel.setUpdateManNo("system");
                tareModel.setUpdateManName("期限皮结净更新");
                tareModel.setUpdateTime(new Date());
                tareModel.setIsPreScale("1");
                tareModel.setWeightType("1");
                tareModel.setPredictionType("1");
                meterWorkCarActualFirstMapper.updateByPrimaryKey(tareModel);
                //将委托信息插入结净数据
                MeterWorkCarActual mwca1 = meterWorkCarActualMapper.manualAddPre(grossModel.getActualFirstNo(), tareModel.getActualFirstNo(), scale.getPredictionNo());
                BeanUtils.copyProperties(mwca1, model);
                //更新结净数据状态
//                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
//                String afl = sdf.format(new Date());
//                String no = meterWorkCarActualMapper.getNewID(sdf.format(new Date()));
//                model.setActualNo(sdf.format(new Date()) + no);

                String no = PublicMethod.IdCreate(3);
                model.setActualNo(no);
                model.setNetTime(new Date());
                model.setNetMode(DbConstants.TYPE);
                model.setNote("期限皮匹配结净");
                model.setUploadFlag("1");
                model.setIsPreScale("1");
                model.setValueFlag("1");
                model.setNetManNo("admin");
                model.setNetManName("admin");
                model.setNetSpot3No(tareModel.getBaseSpotNo());
                model.setNetSpot3Name(tareModel.getBaseSpotName());
                model.setPredictionNo(scale.getPredictionNo());
                model.setPredictionType("1");
                model.setNetWeight(grossModel.getMeterWeight().subtract(tareModel.getMeterWeight()));
                if(model.getGrossTime().compareTo(model.getTareTime()) >= 0) {
                    model.setNetSpot3No(model.getBaseSpot1No());
                    model.setNetSpot3Name(model.getBaseSpot1Name());
                    model.setNetManNo(model.getGrossManNo());
                    model.setNetManName(model.getGrossManName());
                    model.setNetTime(model.getGrossTime());
                    model.setCreateTime(model.getGrossTime());
                    model.setCreateManName(model.getGrossManName());
                }else {
                    model.setNetSpot3No(model.getBaseSpot2No());
                    model.setNetSpot3Name(model.getBaseSpot2Name());
                    model.setNetManNo(model.getTareManNo());
                    model.setNetManName(model.getTareManName());
                    model.setNetTime(model.getTareTime());
                    model.setCreateTime(model.getTareTime());
                    model.setCreateManName(model.getTareManName());
                }
                //新增补丁，给净重数据重新赋值一次数据的计量方式2023年10月18日zn
                try {
                    //查询毛重数据
                    MeterWorkCarActualFirst actualFirst1 = meterWorkCarActualFirstMapper.selectByPrimaryKey(model.getActualFirst1No());
                    //查询皮重数据
                    MeterWorkCarActualFirst actualFirst2 = meterWorkCarActualFirstMapper.selectByPrimaryKey(model.getActualFirst2No());
                    model.setGrossMode(actualFirst1.getMeterMode());
                    model.setTareMode(actualFirst2.getMeterMode());
                } catch (Exception e) {
                    logger.error("修改计量方式出错", e);
                    e.printStackTrace();
                }
                meterWorkCarActualMapper.insertSelective(model);

                //更新委托信息状态
                scale.setValueFlag(DbConstants.NET);
                scale.setUpdateTime(new Date());
                scale.setUpdateManNo("system");
                scale.setUpdateManName("期限皮结净更新");
                scale.setUploadFlag("1");
                scale.setLineDesc("0");
                scale.setPredictionType("1");
                scale.setMeasureStation(model.getNetSpot3No());
                scale.setMeasureStationName(model.getNetSpot3Name());
                preTrackScaleMapper.updateByPrimaryKeySelective(scale);
            } else {
                rm.setMessage("委托信息编号不能为空，请确认！！");
                return rm;
            }

            //新增期限皮重信息
            MeterBaseSpotInfo spotInfo = meterBaseSpotInfoMapper.selectByPrimaryKey(tareModel.getBaseSpotNo());
            HashMap<String, Object> map = new HashMap<>();
            map.put("carNo", tareModel.getCarNo());
            map.put("spotAreaNo", spotInfo.getSpotAreaNo());
            map.put("spotAreaName", spotInfo.getSpotAreaName());
            List<MeterBaseTermTareData> upModels = meterBaseTermTareDataMapper.selectByParameters(map);
            MeterBaseTermTareData termData = new MeterBaseTermTareData();
            if (upModels.size() >= 1) {
                termData = upModels.get(0);
            }
            if (termData.getDataNo() != null) {
                termData.setBaseSpotNo(tareModel.getBaseSpotNo());
                termData.setBaseSpotName(tareModel.getBaseSpotName());
                termData.setSpotAreaNo(spotInfo.getSpotAreaNo());
                termData.setSpotAreaName(spotInfo.getSpotAreaName());
                termData.setCarNo(tareModel.getCarNo());
                termData.setMeterName(tareModel.getCreateManName());
                termData.setMeterTime(tareModel.getCreateTime());
                termData.setStartTime(tareModel.getCreateTime());
                termData.setEndTime(new Date(tareModel.getCreateTime().getTime() + 24 * 60 * 60 * 1000));
                termData.setWarnTime(new Date(tareModel.getCreateTime().getTime() + 12 * 60 * 60 * 1000));
                termData.setValueFlag("0");
                termData.setCreateManNo(tareModel.getCreateManNo());
                termData.setCreateManName(tareModel.getCreateManName());
                termData.setCreateTime(new Date());
                termData.setMeterWeight(tareModel.getMeterWeight());
                meterBaseTermTareDataMapper.updateByPrimaryKeySelective(termData);
                /*
                termData.setUpWeight(termData.getMeterWeight().longValue());
                double db = (termData.getAvgWeight() * termData.getMeterNum() + termData.getMeterWeight().longValue()) / (termData.getMeterNum() + 1);
                termData.setAvgWeight(Math.round(db));
                termData.setMeterNum(termData.getMeterNum()+1);
                */
            } else {
                //新增操作
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
                String no = meterBaseTermTareDataMapper.getNewID(sdf.format(new Date()));
                termData.setDataNo(sdf.format(new Date()) + no);
                termData.setBaseSpotNo(tareModel.getBaseSpotNo());
                termData.setBaseSpotName(tareModel.getBaseSpotName());
                termData.setSpotAreaNo(spotInfo.getSpotAreaNo());
                termData.setSpotAreaName(spotInfo.getSpotAreaName());
                termData.setCarNo(tareModel.getCarNo());
                termData.setMeterName(tareModel.getCreateManName());
                termData.setMeterTime(tareModel.getCreateTime());
                termData.setStartTime(tareModel.getCreateTime());
                termData.setEndTime(new Date(tareModel.getCreateTime().getTime() + 24 * 60 * 60 * 1000));
                termData.setWarnTime(new Date(tareModel.getCreateTime().getTime() + 12 * 60 * 60 * 1000));
                termData.setValueFlag("0");
                termData.setCreateManNo(tareModel.getCreateManNo());
                termData.setCreateManName(tareModel.getCreateManName());
                termData.setCreateTime(new Date());
                termData.setMeterWeight(tareModel.getMeterWeight());
                meterBaseTermTareDataMapper.insertSelective(termData);
            }
            //当存储一次数据或者结净时，将本车辆的预处理重量改为已使用
            updatePreWeight(grossModel.getCarNo());

            MeterWorkCarActualFirst imTare = new MeterWorkCarActualFirst();
            imTare = meterWorkCarActualFirstMapper.selectAndMatch(tareModel.getActualFirstNo(), scale.getPredictionNo());
            SimpleDateFormat formatter1 = new SimpleDateFormat("yyyyMMdd");
            //补充数据
            String afl1 = formatter1.format(new Date());
//            String imTareNO = meterWorkCarActualFirstMapper.getNewID(afl1);
//            String actualNo = afl1 + imTareNO;
            String actualNo = PublicMethod.IdCreate(3);
            imTare.setActualFirstNo(actualNo);
            imTare.setMeterTypeNo(tareModel.getMeterTypeNo());
            imTare.setMeterTypeName(tareModel.getMeterTypeName());
            imTare.setBaseSpotNo(termData.getBaseSpotNo());
            imTare.setBaseSpotName(termData.getBaseSpotName());
            imTare.setCarNo(termData.getCarNo());
            imTare.setCreateTime(termData.getMeterTime());
            imTare.setCreateManNo(termData.getCreateManNo());
            imTare.setCreateManName(termData.getCreateManName());
            imTare.setMeterWeight(termData.getMeterWeight());
            imTare.setWeightType("2");//期限皮重
            imTare.setValueFlag("2");//结净
            imTare.setDataSource("1");
            //期限皮重转为一次数据的时，创建时间应为期限皮开始时间
            //imTare.setCreateTime(new Date());
            meterWorkCarActualFirstMapper.insertSelective(imTare);

            //修改结净皮重编号
            MeterWorkCarActual mca = new MeterWorkCarActual();
            mca.setActualNo(model.getActualNo());
            mca.setActualFirst2No(actualNo);
            mca.setTareTime(termData.getMeterTime());
            mca.setBaseSpot2No(termData.getBaseSpotNo());
            mca.setBaseSpot2Name(termData.getBaseSpotName());
            meterWorkCarActualMapper.updateByPrimaryKeySelective(mca);

            //作废一次计量皮重信息
            tareModel.setValueFlag("0");
            meterWorkCarActualFirstMapper.updateByPrimaryKeySelective(tareModel);
            rm.setSucceed();
            rm.setCode("200");
            rm.setMessage("操作成功！！");
            rm.setData(returnNo);
            return rm;
        } catch (Exception e) {
            e.printStackTrace();
            rm.setMessage("操作异常,请确认！！" + e.getMessage());
            return rm;
        }
    }

    @Override
    public RESTfulResult furConversion(HashMap<String, Object> params) {
        RESTfulResult rm = new RESTfulResult();
        rm.setFailed();

        try{
            String userId = "";
            String userName = "";
            try{
                UserPayload userPayload = UserPayload.getCurrUser();
                userId = userPayload.getUserCode();
                userName = userPayload.getUserName();
            }catch (Exception e) {
                userId = "system";
                userName = "system";
            }
            if(com.steerinfo.util.StringUtils.isNotEmpty(params.get("actualFirstNo").toString())){
                MeterWorkCarActualFirst model = meterWorkCarActualFirstMapper.selectByPrimaryKey(params.get("actualFirstNo").toString());
                if(model != null) {
                    if(model.getValueFlag().equals("1")) {
                        if(model.getValueFlag().equals("2")){
                            rm.setMessage("毛皮转换失败：数据已结净，请确认！！");
                            return rm;
                        }
                        if(model.getWeightType() == null || StringUtils.isEmpty(model.getWeightType())) {
//                            rm.setMessage("毛皮转换失败：重量类型为空，请确认！！");
//                            return rm;
                            model.setUpdateManNo(userId);
                            model.setUpdateManName(userName);
                            model.setUpdateTime(new Date());
                            model.setNote("毛皮转换");
                            model.setWeightType("1");
                            meterWorkCarActualFirstMapper.updateByPrimaryKeySelective(model);

                            MeterBaseOperationLog logModel = new MeterBaseOperationLog();
                            logModel.setId(PublicMethod.IdCreate(2));
                            logModel.setCreateManNo(userId);
                            logModel.setCreateManName(userName);
                            logModel.setCreateTime(new Date());
                            logModel.setOperationPage("web端-汽车衡一次数据维护");
                            logModel.setOperationFunction("毛皮转换");
                            logModel.setOperationId(model.getActualFirstNo());
                            logModel.setOperationPredictionNo(model.getPredictionNo());
                            logModel.setOperationCarnNo(model.getCarNo());
                            meterBaseOperationLogMapper.insertSelective(logModel);
                            rm.setSucceed();
                            rm.setMessage("重量类型为空，毛皮转换成皮重!!");
                            rm.setData(model);
                            rm.setCode("200");
                            return rm;
                        } else {
                            if(model.getWeightType().equals("0")){
                                model.setWeightType("1");
                            }else if (model.getWeightType().equals("1")){
                                model.setWeightType("0");
                            }else{
                                rm.setMessage("毛皮转换失败：毛皮转换只针对毛重和常规皮重，请确认！！");
                                return rm;
                            }
                            model.setUpdateManNo(userId);
                            model.setUpdateManName(userName);
                            model.setUpdateTime(new Date());
                            model.setNote("毛皮转换");
                            meterWorkCarActualFirstMapper.updateByPrimaryKeySelective(model);

                            MeterBaseOperationLog logModel = new MeterBaseOperationLog();
                            logModel.setId(PublicMethod.IdCreate(2));
                            logModel.setCreateManNo(userId);
                            logModel.setCreateManName(userName);
                            logModel.setCreateTime(new Date());
                            logModel.setOperationPage("web端-汽车衡一次数据维护");
                            logModel.setOperationFunction("毛皮转换");
                            logModel.setOperationId(model.getActualFirstNo());
                            logModel.setOperationPredictionNo(model.getPredictionNo());
                            logModel.setOperationCarnNo(model.getCarNo());
                            meterBaseOperationLogMapper.insertSelective(logModel);

                            rm.setSucceed();
                            rm.setMessage("毛皮转换成功!!");
                            rm.setData(model);
                            rm.setCode("200");
                            return rm;
                        }
                    }else{
                        rm.setMessage("毛皮转换失败：毛皮转换只针对有效的毛重和常规皮重，请确认！！");
                    }
                }else {
                    rm.setMessage("未找到相应的一次计量数据，不能毛皮转换！！");
                }
            }else {
                rm.setMessage("实绩编号不能为空！！");
            }
            return rm;
        }catch(Exception e) {
            e.printStackTrace();
            rm.setMessage("操作异常,请确认！！>>>" + e.getMessage());
            return rm;
        }
    }

    @Override
    public RESTfulResult doNetByTermData(HashMap<String, Object> params) {
        RESTfulResult rm = new RESTfulResult();
        rm.setFailed();
        try{
            UserPayload userPayload = UserPayload.getCurrUser();
            String userId;
            String userName;
            try{
               userId  = userPayload.getUserCode();
               userName  = userPayload.getUserName();
            }catch (Exception e) {
                userId = "admin";
                userName = "admins";
            }

            String actualFirstNo = params.get("actualFirstNo") == null ? "": params.get("actualFirstNo").toString();
            Assert.isTrue(StringUtils.isNotEmpty(actualFirstNo), "未选择一次数据");
            MeterWorkCarActualFirst grossModel = meterWorkCarActualFirstMapper.selectByPrimaryKey(actualFirstNo);
            Assert.isTrue(!grossModel.getValueFlag().equals("2"), "一次数据已结净，不允许期限皮结净");
            Assert.isTrue(!grossModel.getValueFlag().equals("0"), "一次数据已作废，不允许期限皮结净");
            String predictionNo = params.get("predictionNo") == null ? "": params.get("predictionNo").toString();
            if(StringUtils.isEmpty(predictionNo)) {
                Assert.isTrue(StringUtils.isNotEmpty(grossModel.getPredictionNo()), "毛重未匹配委托");
                predictionNo = grossModel.getPredictionNo();
            }
            if(grossModel != null) {
                MeterBaseSpotInfo spotInfo = meterBaseSpotInfoMapper.selectByPrimaryKey(grossModel.getBaseSpotNo());
                HashMap<String, Object> map = new HashMap<>();
                map.put("carNo", grossModel.getCarNo());
                map.put("spotAreaNo", spotInfo.getSpotAreaNo());
                map.put("spotAreaName", spotInfo.getSpotAreaName());
                MeterBaseTermTareData termTareModel = meterBaseTermTareDataMapper.getTermTareData(map);
                Assert.isTrue(termTareModel != null, "此车号【" + grossModel.getCarNo() + "】未查询到有效的期限皮重，不允许期限皮结净");
                if(StringUtils.isNotEmpty(predictionNo)) {
                    PreTrackScale scale = preTrackScaleMapper.selectByPrimaryKey(predictionNo);
                    Assert.isTrue(scale != null, "根据委托编号：" + predictionNo + "为查询到有效的委托信息");

                    MeterWorkCarActualFirst tareModel = new MeterWorkCarActualFirst();
                    BeanUtils.copyProperties(grossModel, tareModel);
                    String no = PublicMethod.IdCreate(3);
                    tareModel.setActualFirstNo(no);
                    tareModel.setCreateTime(termTareModel.getCreateTime());
                    tareModel.setMeterWeight(termTareModel.getMeterWeight());
                    tareModel.setBaseSpotNo(termTareModel.getBaseSpotNo());
                    tareModel.setBaseSpotName(termTareModel.getBaseSpotName());
                    tareModel.setCreateManNo(userId);
                    tareModel.setCreateManName(userName);
                    meterWorkCarActualFirstMapper.insertSelective(tareModel);
                    //添加历史皮重
                    doSaveHisTare(tareModel,"2");

                    MeterWorkCarActualFirst grossFirst = meterWorkCarActualFirstMapper.selectAndMatch(grossModel.getActualFirstNo(), scale.getPredictionNo());
                    BeanUtils.copyProperties(grossFirst, grossModel);
                    MeterWorkCarActualFirst tareFirst = meterWorkCarActualFirstMapper.selectAndMatch(tareModel.getActualFirstNo(), scale.getPredictionNo());
                    BeanUtils.copyProperties(tareFirst, tareModel);

                    grossModel.setUpdateManNo(userId);
                    grossModel.setUpdateManName(userName);
                    grossModel.setUpdateTime(new Date());
                    grossModel.setWeightType("0");
                    grossModel.setValueFlag("2");
                    grossModel.setIsPreScale("1");
                    grossModel.setPredictionType("1");
                    grossModel.setPredictionNo(scale.getPredictionNo());
                    grossModel.setNote("期限皮匹配委托结净");
                    meterWorkCarActualFirstMapper.updateByPrimaryKeySelective(grossModel);
                    tareModel.setUpdateManNo(userId);
                    tareModel.setUpdateManName(userName);
                    tareModel.setUpdateTime(new Date());
                    tareModel.setValueFlag("2");
                    tareModel.setWeightType("2");
                    tareModel.setIsPreScale("1");
                    tareModel.setDataSource("2");
                    tareModel.setPredictionType("1");
                    tareModel.setPredictionNo(scale.getPredictionNo());
                    tareModel.setNote("期限皮匹配委托结净");
                    meterWorkCarActualFirstMapper.updateByPrimaryKeySelective(tareModel);

                    MeterWorkCarActual actualRow = meterWorkCarActualMapper.manualAddPre(grossModel.getActualFirstNo(), tareModel.getActualFirstNo(), scale.getPredictionNo());
                    String noActual = PublicMethod.IdCreate(3);
                    actualRow.setActualNo(noActual);
                    actualRow.setNetMode(DbConstants.TYPE);
                    actualRow.setUploadFlag("1");
                    actualRow.setIsPreScale("1");
                    actualRow.setValueFlag("1");
                    actualRow.setPredictionNo(scale.getPredictionNo());
                    actualRow.setPredictionType("1");
                    actualRow.setNote("期限皮匹配委托结净");
                    actualRow.setNetWeight(grossModel.getMeterWeight().subtract(tareModel.getMeterWeight()));
                    if(actualRow.getGrossTime().compareTo(actualRow.getTareTime()) >= 0) {
                        actualRow.setNetSpot3No(actualRow.getBaseSpot1No());
                        actualRow.setNetSpot3Name(actualRow.getBaseSpot1Name());
                        actualRow.setNetManNo(actualRow.getGrossManNo());
                        actualRow.setNetManName(actualRow.getGrossManName());
                        actualRow.setNetTime(actualRow.getGrossTime());
                        actualRow.setCreateTime(actualRow.getGrossTime());
                        actualRow.setCreateManName(actualRow.getGrossManName());
                    }else {
                        actualRow.setNetSpot3No(actualRow.getBaseSpot2No());
                        actualRow.setNetSpot3Name(actualRow.getBaseSpot2Name());
                        actualRow.setNetManNo(actualRow.getTareManNo());
                        actualRow.setNetManName(actualRow.getTareManName());
                        actualRow.setNetTime(actualRow.getTareTime());
                        actualRow.setCreateTime(actualRow.getTareTime());
                        actualRow.setCreateManName(actualRow.getTareManName());
                    }
                    meterWorkCarActualMapper.insertSelective(actualRow);

                    scale.setValueFlag(DbConstants.NET);
                    scale.setUploadFlag("1");
                    scale.setPredictionType("1");
                    scale.setUpdateTime(new Date());
                    scale.setUpdateManNo(userId);
                    scale.setUpdateManName(userName);
                    scale.setMeasureStation(actualRow.getNetSpot3No());
                    scale.setMeasureStationName(actualRow.getNetSpot3Name());
                    preTrackScaleMapper.updateByPrimaryKeySelective(scale);

                    MeterBaseOperationLog logModel = new MeterBaseOperationLog();
                    logModel.setId(PublicMethod.IdCreate(2));
                    logModel.setCreateManNo(userId);
                    logModel.setCreateManName(userName);
                    logModel.setCreateTime(new Date());
                    logModel.setOperationPage("web端-汽车衡一次数据维护");
                    logModel.setOperationFunction("期限皮结净");
                    logModel.setOperationId(grossModel.getActualFirstNo());
                    logModel.setOperationPredictionNo(grossModel.getPredictionNo());
                    logModel.setOperationCarnNo(grossModel.getCarNo());
                    logModel.setOperationBeforeFix("一次数据：" + grossModel.toString());
                    logModel.setOperationAfterFix("结净数据：" + actualRow.toString());
                    meterBaseOperationLogMapper.insertSelective(logModel);

                    rm.setSucceed();
                    rm.setData(actualRow);
                    rm.setMessage("有委托期限皮结净成功");
                    rm.setCode("200");
                }else {
                    MeterWorkCarActualFirst tareModel = new MeterWorkCarActualFirst();
                    BeanUtils.copyProperties(grossModel, tareModel);
                    String no = PublicMethod.IdCreate(3);
                    tareModel.setActualFirstNo(no);
                    tareModel.setCreateTime(termTareModel.getCreateTime());
                    tareModel.setMeterWeight(termTareModel.getMeterWeight());
                    tareModel.setBaseSpotNo(termTareModel.getBaseSpotNo());
                    tareModel.setBaseSpotName(termTareModel.getBaseSpotName());
                    tareModel.setCreateManNo(userId);
                    tareModel.setCreateManName(userName);
                    meterWorkCarActualFirstMapper.insertSelective(tareModel);
                    //添加历史皮重
                    doSaveHisTare(tareModel,"2");
                    grossModel.setUpdateManNo(userId);
                    grossModel.setUpdateManName(userName);
                    grossModel.setUpdateTime(new Date());
                    grossModel.setWeightType("0");
                    grossModel.setValueFlag("2");
                    grossModel.setIsPreScale("0");
                    grossModel.setNote("期限皮结净");
                    meterWorkCarActualFirstMapper.updateByPrimaryKeySelective(grossModel);

                    tareModel.setUpdateManNo(userId);
                    tareModel.setUpdateManName(userName);
                    tareModel.setUpdateTime(new Date());
                    tareModel.setWeightType("2");
                    tareModel.setValueFlag("2");
                    tareModel.setIsPreScale("0");
                    tareModel.setNote("期限皮结净");
                    meterWorkCarActualFirstMapper.updateByPrimaryKeySelective(tareModel);

                    MeterWorkCarActual actualRow = meterWorkCarActualMapper.manualAdd(grossModel.getActualFirstNo(), tareModel.getActualFirstNo());
                    String noActual = PublicMethod.IdCreate(3);
                    actualRow.setActualNo(noActual);
                    actualRow.setNetTime(new Date());
                    actualRow.setNetMode(DbConstants.TYPE);
                    actualRow.setUploadFlag("1");
                    actualRow.setIsPreScale("0");
                    actualRow.setValueFlag("1");
                    actualRow.setNote("期限皮匹配结净");
                    actualRow.setNetWeight(grossModel.getMeterWeight().subtract(tareModel.getMeterWeight()));
                    if(actualRow.getGrossTime().compareTo(actualRow.getTareTime()) >= 0) {
                        actualRow.setNetSpot3No(actualRow.getBaseSpot1No());
                        actualRow.setNetSpot3Name(actualRow.getBaseSpot1Name());
                        actualRow.setNetManNo(actualRow.getGrossManNo());
                        actualRow.setNetManName(actualRow.getGrossManName());
                        actualRow.setNetTime(actualRow.getGrossTime());
                        actualRow.setCreateTime(actualRow.getGrossTime());
                        actualRow.setCreateManName(actualRow.getGrossManName());
                    }else {
                        actualRow.setNetSpot3No(actualRow.getBaseSpot2No());
                        actualRow.setNetSpot3Name(actualRow.getBaseSpot2Name());
                        actualRow.setNetManNo(actualRow.getTareManNo());
                        actualRow.setNetManName(actualRow.getTareManName());
                        actualRow.setNetTime(actualRow.getTareTime());
                        actualRow.setCreateTime(actualRow.getTareTime());
                        actualRow.setCreateManName(actualRow.getTareManName());
                    }
                    meterWorkCarActualMapper.insertSelective(actualRow);

                    MeterBaseOperationLog logModel = new MeterBaseOperationLog();
                    logModel.setId(PublicMethod.IdCreate(2));
                    logModel.setCreateManNo(userId);
                    logModel.setCreateManName(userName);
                    logModel.setCreateTime(new Date());
                    logModel.setOperationPage("web端-汽车衡一次数据维护");
                    logModel.setOperationFunction("期限皮结净");
                    logModel.setOperationId(grossModel.getActualFirstNo());
                    logModel.setOperationPredictionNo(grossModel.getPredictionNo());
                    logModel.setOperationCarnNo(grossModel.getCarNo());
                    logModel.setOperationBeforeFix("一次数据：" + grossModel.toString());
                    logModel.setOperationAfterFix("结净数据：" + actualRow.toString());
                    meterBaseOperationLogMapper.insertSelective(logModel);

                    rm.setSucceed();
                    rm.setData(actualRow);
                    rm.setMessage("无委托期限皮结净成功");
                    rm.setCode("200");
                }
            }
        }catch (Exception e) {
            e.printStackTrace();
            rm.setMessage(e.getMessage());
        }
        return rm;
    }

    //内倒双委托---不使用期限皮结净，保存两条一次毛重
    @Override
    @Transactional(rollbackFor = Exception.class)
    public RESTfulResult doDoubleAdd(MeterWorkCarActualFirst model, PreTrackScale scale01, PreTrackScale scale02) {
        RESTfulResult rm = new RESTfulResult();
        rm.setFailed();
        try{
            //插入一次毛重数据
            model.setActualFirstNo(PublicMethod.IdCreate(3));
            model.setValueFlag("1");
            meterWorkCarActualFirstMapper.insertSelective(model);

            PreTrackScale pre01 = preTrackScaleMapper.selectByPrimaryKey(scale01.getPredictionNo());
            PreTrackScale pre02 = preTrackScaleMapper.selectByPrimaryKey(scale02.getPredictionNo());
            if(pre01 != null && pre02 != null) {
                if(pre01.getValueFlag().equals("2") || pre01.getValueFlag().equals("3")) {
                    rm.setMessage(pre01.getPredictionNo() + "委托信息已使用或已作废");
                    return rm;
                }else if(pre02.getValueFlag().equals("2") || pre02.getValueFlag().equals("3")) {
                    rm.setMessage(pre02.getPredictionNo() + "委托信息已使用或已作废");
                    return rm;
                }
            }else if(pre01 == null){
                rm.setMessage(pre01.getPredictionNo() + "委托信息不存在");
                return rm;
            }else if(pre02 == null) {
                rm.setMessage(pre02.getPredictionNo() + "委托信息不存在");
                return rm;
            }

            MeterWorkCarActualFirst copyFirst01 = new MeterWorkCarActualFirst();
            MeterWorkCarActualFirst copyFirst02 = new MeterWorkCarActualFirst();
            MeterWorkCarActualFirst modelTemp01 = meterWorkCarActualFirstMapper.selectAndMatch(model.getActualFirstNo(), scale01.getPredictionNo());
            BeanUtils.copyProperties(modelTemp01, copyFirst01);
            MeterWorkCarActualFirst modelTemp02 = meterWorkCarActualFirstMapper.selectAndMatch(model.getActualFirstNo(), scale02.getPredictionNo());
            BeanUtils.copyProperties(modelTemp02, copyFirst02);

            copyFirst01.setMeterMode("2");
            copyFirst01.setWeightType("0");
            copyFirst01.setDataSource("1");
            copyFirst01.setValueFlag("1");
            copyFirst01.setIsPreScale("1");
            copyFirst01.setPredictionType("5");
            copyFirst01.setPredictionCombination(scale01.getPredictionNo() + "," + scale02.getPredictionNo());
            copyFirst01.setCreateManNo("system");
            copyFirst01.setCreateManName("system");
            copyFirst01.setCreateTime(new Date());
            meterWorkCarActualFirstMapper.updateByPrimaryKeySelective(copyFirst01);

            copyFirst02.setActualFirstNo(PublicMethod.IdCreate(3));
            copyFirst02.setMeterMode("2");
            copyFirst02.setWeightType("0");
            copyFirst02.setDataSource("1");
            copyFirst02.setValueFlag("1");
            copyFirst02.setIsPreScale("1");
            copyFirst02.setPredictionType("5");
            copyFirst02.setPredictionCombination(scale01.getPredictionNo() + "," + scale02.getPredictionNo());
            copyFirst02.setCreateManNo("system");
            copyFirst02.setCreateManName("system");
            copyFirst02.setCreateTime(new Date());
            copyFirst02.setNote("内倒双委托一次复制:" + copyFirst01.getActualFirstNo());
            meterWorkCarActualFirstMapper.insertSelective(copyFirst02);

            //预约信息重置委托
            pre01.setPredictionType("5");
            pre01.setPredictionCombination(scale01.getPredictionNo() + "," + scale02.getPredictionNo());
            pre01.setMeasureStation(model.getBaseSpotNo());
            pre01.setMeasureStationName(model.getBaseSpotName());
            pre01.setUpdateManNo("system");
            pre01.setUpdateManName("system");
            pre01.setUpdateTime(new Date());
            pre01.setValueFlag("4");
            pre01.setUploadFlag("1");
            pre01.setLineDesc("0");
            preTrackScaleMapper.updateByPrimaryKeySelective(pre01);

            pre02.setPredictionType("5");
            pre02.setPredictionCombination(scale01.getPredictionNo() + "," + scale02.getPredictionNo());
            pre02.setMeasureStation(model.getBaseSpotNo());
            pre02.setMeasureStationName(model.getBaseSpotName());
            pre02.setUpdateManNo("system");
            pre02.setUpdateManName("system");
            pre02.setUpdateTime(new Date());
            pre02.setValueFlag("4");
            pre02.setUploadFlag("1");
            pre02.setLineDesc("0");
            preTrackScaleMapper.updateByPrimaryKeySelective(pre02);

            updatePreWeight(pre01.getCarNo());
            updatePreWeight(pre02.getCarNo());

            rm.setSucceed(true);
            rm.setCode("200");
            rm.setData(model.getActualFirstNo());
            rm.setMessage("操作成功");
        }catch(Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            rm.setMessage("操作异常，" + e.getMessage());
        }
        return rm;
    }

    //内倒双委托---使用期限皮结净,直接保存四条数据和两个结净
    @Override
    @Transactional(rollbackFor = Exception.class)
    public RESTfulResult doTermTareNetDouble(MeterWorkCarActualFirst model, PreTrackScale scale01, PreTrackScale scale02) {
        RESTfulResult rm = new RESTfulResult();
        rm.setFailed();
        try{
            //插入一次毛重数据
            model.setActualFirstNo(PublicMethod.IdCreate(3));
            model.setValueFlag("1");
            meterWorkCarActualFirstMapper.insertSelective(model);

            PreTrackScale pre01 = preTrackScaleMapper.selectByPrimaryKey(scale01.getPredictionNo());
            PreTrackScale pre02 = preTrackScaleMapper.selectByPrimaryKey(scale02.getPredictionNo());
            if(pre01 != null && pre02 != null) {
                if(pre01.getValueFlag().equals("2") || pre01.getValueFlag().equals("3")) {
                    rm.setMessage(pre01.getPredictionNo() + "委托信息已使用或已作废");
                    return rm;
                }else if(pre02.getValueFlag().equals("2") || pre02.getValueFlag().equals("3")) {
                    rm.setMessage(pre02.getPredictionNo() + "委托信息已使用或已作废");
                    return rm;
                }
            }else if(pre01 == null){
                rm.setMessage(pre01.getPredictionNo() + "委托信息不存在");
                return rm;
            }else if(pre02 == null) {
                rm.setMessage(pre02.getPredictionNo() + "委托信息不存在");
                return rm;
            }
            MeterBaseSpotInfo spotInfo = meterBaseSpotInfoMapper.selectByPrimaryKey(model.getBaseSpotNo());
            HashMap<String, Object> obj = new HashMap<>();
            obj.put("carNo", model.getCarNo());
            obj.put("valueFlag", "0");
            obj.put("spotAreaNo", spotInfo.getSpotAreaNo());
            obj.put("spotAreaName", spotInfo.getSpotAreaName());
            List<MeterBaseTermTareData> tareDataList = meterBaseTermTareDataMapper.selectByParameters(obj);
            if(tareDataList.size() < 1) {
                rm.setMessage(model.getCarNo() + "车号期限皮重已过期或者未查找到期限皮中信息，不允许双委托计量");
                return rm;
            }
            MeterBaseTermTareData termData = tareDataList.get(0);

            //插入期限皮重信息
            MeterWorkCarActualFirst tareFirst = new MeterWorkCarActualFirst();
            tareFirst.setActualFirstNo(PublicMethod.IdCreate(3));
            tareFirst.setMeterTypeNo(model.getMeterTypeNo());
            tareFirst.setMeterTypeName(model.getMeterTypeName());
            tareFirst.setBaseSpotNo(termData.getBaseSpotNo());
            tareFirst.setBaseSpotName(termData.getBaseSpotName());
            tareFirst.setCarNo(termData.getCarNo());
            tareFirst.setCreateTime(termData.getMeterTime());
            tareFirst.setCreateManNo(termData.getCreateManNo());
            tareFirst.setCreateManName(termData.getCreateManName());
            tareFirst.setMeterWeight(termData.getMeterWeight());
            tareFirst.setWeightType("2");//期限皮重
            tareFirst.setValueFlag("1");//结净
            tareFirst.setDataSource("1");
            meterWorkCarActualFirstMapper.insertSelective(tareFirst);

            MeterWorkCarActualFirst grossFirst01 = new MeterWorkCarActualFirst();
            MeterWorkCarActualFirst grossFirst02 = new MeterWorkCarActualFirst();

            //期限皮重信息保存
            MeterWorkCarActualFirst tareFirst01 = new MeterWorkCarActualFirst();
            MeterWorkCarActualFirst tareFirst02 = new MeterWorkCarActualFirst();

            MeterWorkCarActual actualRow01 = new MeterWorkCarActual();
            MeterWorkCarActual actualRow02 = new MeterWorkCarActual();

            MeterWorkCarActualFirst modelTemp01 = meterWorkCarActualFirstMapper.selectAndMatch(model.getActualFirstNo(), scale01.getPredictionNo());
            BeanUtils.copyProperties(modelTemp01, grossFirst01);
            MeterWorkCarActualFirst modelTemp02 = meterWorkCarActualFirstMapper.selectAndMatch(model.getActualFirstNo(), scale02.getPredictionNo());
            BeanUtils.copyProperties(modelTemp02, grossFirst02);

            MeterWorkCarActualFirst tareFirstTemp01 = meterWorkCarActualFirstMapper.selectAndMatch(tareFirst.getActualFirstNo(), scale01.getPredictionNo());
            BeanUtils.copyProperties(tareFirstTemp01, tareFirst01);
            MeterWorkCarActualFirst tareFirstTemp02 = meterWorkCarActualFirstMapper.selectAndMatch(tareFirst.getActualFirstNo(), scale02.getPredictionNo());
            BeanUtils.copyProperties(tareFirstTemp02, tareFirst02);

            grossFirst01.setMeterMode("2");
            grossFirst01.setWeightType("0");
            grossFirst01.setDataSource("1");
            grossFirst01.setValueFlag("2");
            grossFirst01.setIsPreScale("1");
            grossFirst01.setPredictionType("5");
            grossFirst01.setPredictionCombination(scale01.getPredictionNo() + "," + scale02.getPredictionNo());
            grossFirst01.setCreateManNo("system");
            grossFirst01.setCreateManName("system");
            grossFirst01.setCreateTime(new Date());
            meterWorkCarActualFirstMapper.updateByPrimaryKeySelective(grossFirst01);

            grossFirst02.setActualFirstNo(PublicMethod.IdCreate(3));
            grossFirst02.setMeterMode("2");
            grossFirst02.setWeightType("0");
            grossFirst02.setDataSource("1");
            grossFirst02.setValueFlag("2");
            grossFirst02.setIsPreScale("1");
            grossFirst02.setPredictionType("5");
            grossFirst02.setPredictionCombination(scale01.getPredictionNo() + "," + scale02.getPredictionNo());
            grossFirst02.setCreateManNo("system");
            grossFirst02.setCreateManName("system");
            grossFirst02.setCreateTime(new Date());
            grossFirst02.setNote("内倒双委托一次复制:" + grossFirst01.getActualFirstNo());
            meterWorkCarActualFirstMapper.insertSelective(grossFirst02);


            tareFirst01.setIsPreScale("1");
            tareFirst01.setMeterMode("2");
            tareFirst01.setValueFlag("2");
            tareFirst01.setPredictionType("5");
            tareFirst01.setPredictionCombination(scale01.getPredictionNo() + "," + scale02.getPredictionNo());
            meterWorkCarActualFirstMapper.updateByPrimaryKeySelective(tareFirst01);

            tareFirst02.setActualFirstNo(PublicMethod.IdCreate(3));
            tareFirst02.setIsPreScale("1");
            tareFirst02.setValueFlag("2");
            tareFirst02.setMeterMode("2");
            tareFirst02.setPredictionType("5");
            tareFirst02.setPredictionCombination(scale01.getPredictionNo() + "," + scale02.getPredictionNo());
            meterWorkCarActualFirstMapper.insertSelective(tareFirst02);

            MeterWorkCarActual actualRowTemp01 = meterWorkCarActualMapper.manualAddPre(grossFirst01.getActualFirstNo(), tareFirst01.getActualFirstNo(), scale01.getPredictionNo());
            BeanUtils.copyProperties(actualRowTemp01, actualRow01);
            MeterWorkCarActual actualRowTemp02 = meterWorkCarActualMapper.manualAddPre(grossFirst02.getActualFirstNo(), tareFirst02.getActualFirstNo(), scale02.getPredictionNo());
            BeanUtils.copyProperties(actualRowTemp02, actualRow02);

            actualRow01.setActualNo(PublicMethod.IdCreate(3));
            actualRow01.setNetMode(DbConstants.TYPE);
            actualRow01.setNote("内倒双委托期限皮匹配结净");
            actualRow01.setUploadFlag("1");
            actualRow01.setIsPreScale("1");
            actualRow01.setValueFlag("1");
            actualRow01.setNetSpot3No(grossFirst01.getBaseSpotNo());
            actualRow01.setNetSpot3Name(grossFirst01.getBaseSpotName());
            actualRow01.setNetTime(grossFirst01.getCreateTime());
            actualRow01.setCreateManName(grossFirst01.getCreateManName());
            actualRow01.setCreateTime(grossFirst01.getCreateTime());
            actualRow01.setPredictionType("5");
            actualRow01.setPredictionNo(grossFirst01.getPredictionNo());
            actualRow01.setPredictionCombination(scale01.getPredictionNo() + "," + scale02.getPredictionNo());
            actualRow01.setNetWeight(grossFirst01.getMeterWeight().subtract(tareFirst01.getMeterWeight()));
            meterWorkCarActualMapper.insertSelective(actualRow01);

            actualRow02.setActualNo(PublicMethod.IdCreate(3));
            actualRow02.setNetMode(DbConstants.TYPE);
            actualRow02.setNote("内倒双委托期限皮匹配结净");
            actualRow02.setUploadFlag("1");
            actualRow02.setIsPreScale("1");
            actualRow02.setValueFlag("1");
            actualRow02.setNetSpot3No(grossFirst02.getBaseSpotNo());
            actualRow02.setNetSpot3Name(grossFirst02.getBaseSpotName());
            actualRow02.setNetTime(grossFirst02.getCreateTime());
            actualRow02.setCreateManName(grossFirst02.getCreateManName());
            actualRow02.setCreateTime(grossFirst02.getCreateTime());
            actualRow02.setPredictionType("5");
            actualRow02.setPredictionNo(grossFirst02.getPredictionNo());
            actualRow02.setPredictionCombination(scale01.getPredictionNo() + "," + scale02.getPredictionNo());
            actualRow02.setNetWeight(grossFirst02.getMeterWeight().subtract(tareFirst02.getMeterWeight()));
            meterWorkCarActualMapper.insertSelective(actualRow02);

            //2023年6月27日张楠修改
            //修改一次数据状态为结净
            try {
                MeterWorkCarActualFirst meterWorkCarActualFirst = meterWorkCarActualFirstMapper.selectByPrimaryKey(actualRow02.getActualFirst1No());
                if(meterWorkCarActualFirst!=null){
                    meterWorkCarActualFirst.setValueFlag("2");
                    meterWorkCarActualFirstMapper.updateByPrimaryKey(meterWorkCarActualFirst);
                }
                MeterWorkCarActualFirst meterWorkCarActualFirst1 = meterWorkCarActualFirstMapper.selectByPrimaryKey(actualRow02.getActualFirst2No());
                if(meterWorkCarActualFirst1!=null){
                    meterWorkCarActualFirst1.setValueFlag("2");
                    meterWorkCarActualFirstMapper.updateByPrimaryKey(meterWorkCarActualFirst1);
                }
            }catch (Exception e){
                e.printStackTrace();
                log.error("修改一次数据出错",e);
            }
            try {
                PreTrackScale preTrackScale = preTrackScaleMapper.selectByPrimaryKey(actualRow02.getPredictionNo());
                if(preTrackScale!=null){
                    preTrackScale.setValueFlag("2");
                    preTrackScaleMapper.updateByPrimaryKey(preTrackScale);
                }
            }catch (Exception e){
                e.printStackTrace();
                log.error("修改委托数据出错",e);
            }

            //预约信息重置委托
            pre01.setPredictionType("5");
            pre01.setPredictionCombination(scale01.getPredictionNo() + "," + scale02.getPredictionNo());
            pre01.setMeasureStation(model.getBaseSpotNo());
            pre01.setMeasureStationName(model.getBaseSpotName());
            pre01.setUpdateManNo("system");
            pre01.setUpdateManName("system");
            pre01.setUpdateTime(new Date());
            pre01.setValueFlag("2");
            pre01.setUploadFlag("1");
            pre01.setLineDesc("0");
            preTrackScaleMapper.updateByPrimaryKeySelective(pre01);

            pre02.setPredictionType("5");
            pre02.setPredictionCombination(scale01.getPredictionNo() + "," + scale02.getPredictionNo());
            pre02.setMeasureStation(model.getBaseSpotNo());
            pre02.setMeasureStationName(model.getBaseSpotName());
            pre02.setUpdateManNo("system");
            pre02.setUpdateManName("system");
            pre02.setUpdateTime(new Date());
            pre02.setValueFlag("2");
            pre02.setUploadFlag("1");
            pre02.setLineDesc("0");
            preTrackScaleMapper.updateByPrimaryKeySelective(pre02);
            updatePreWeight(pre01.getCarNo());
            updatePreWeight(pre02.getCarNo());

            rm.setSucceed(true);
            rm.setCode("200");
            rm.setData(model.getActualFirstNo());
            rm.setMessage("操作成功");
        }catch(Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            rm.setMessage("操作异常，" + e.getMessage());
        }
        return rm;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public RESTfulResult doAddDoubleNet(MeterWorkCarActualFirst grossModel, MeterWorkCarActualFirst tareModel, PreTrackScale scale01, PreTrackScale scale02) {
        RESTfulResult rm = new RESTfulResult();
        rm.setFailed();
        try{
            Boolean grossFlag = false;
            Boolean tareFlag = false;
            //插入一次毛重数据
            MeterWorkCarActualFirst firstTemp01 = meterWorkCarActualFirstMapper.selectByPrimaryKey(grossModel.getActualFirstNo());
            if(firstTemp01 == null) {
                grossFlag = true;
                grossModel.setActualFirstNo(PublicMethod.IdCreate(3));
                grossModel.setValueFlag("1");
                grossModel.setCreateManNo("system");
                grossModel.setCreateManName("system");
                grossModel.setCreateTime(new Date());
                meterWorkCarActualFirstMapper.insertSelective(grossModel);
            }

            //插入一次皮重数据
            MeterWorkCarActualFirst firstTemp02 = meterWorkCarActualFirstMapper.selectByPrimaryKey(tareModel.getActualFirstNo());
            if(firstTemp02 == null) {
                tareFlag = false;
                tareModel.setActualFirstNo(PublicMethod.IdCreate(3));
                tareModel.setValueFlag("1");
                tareModel.setCreateManNo("system");
                tareModel.setCreateManName("system");
                tareModel.setCreateTime(new Date());
                meterWorkCarActualFirstMapper.insertSelective(tareModel);
            }

            PreTrackScale pre01 = preTrackScaleMapper.selectByPrimaryKey(scale01.getPredictionNo());
            PreTrackScale pre02 = preTrackScaleMapper.selectByPrimaryKey(scale02.getPredictionNo());
            if(pre01 != null && pre02 != null) {
                if(pre01.getValueFlag().equals("2") || pre01.getValueFlag().equals("3")) {
                    rm.setMessage(pre01.getPredictionNo() + "委托信息已使用或已作废");
                    return rm;
                }else if(pre02.getValueFlag().equals("2") || pre02.getValueFlag().equals("3")) {
                    rm.setMessage(pre02.getPredictionNo() + "委托信息已使用或已作废");
                    return rm;
                }
            }else if(pre01 == null){
                rm.setMessage(pre01.getPredictionNo() + "委托信息不存在");
                return rm;
            }else if(pre02 == null) {
                rm.setMessage(pre02.getPredictionNo() + "委托信息不存在");
                return rm;
            }

            MeterWorkCarActualFirst grossFirst01 = new MeterWorkCarActualFirst();
            MeterWorkCarActualFirst grossFirst02 = new MeterWorkCarActualFirst();
            //回空皮重信息保存
            MeterWorkCarActualFirst tareFirst01 = new MeterWorkCarActualFirst();
            MeterWorkCarActualFirst tareFirst02 = new MeterWorkCarActualFirst();
            MeterWorkCarActual actualRow01 = new MeterWorkCarActual();
            MeterWorkCarActual actualRow02 = new MeterWorkCarActual();

            MeterWorkCarActualFirst modelTemp01 = meterWorkCarActualFirstMapper.selectAndMatch(grossModel.getActualFirstNo(), scale01.getPredictionNo());
            BeanUtils.copyProperties(modelTemp01, grossFirst01);
            MeterWorkCarActualFirst modelTemp02 = meterWorkCarActualFirstMapper.selectAndMatch(grossModel.getActualFirstNo(), scale02.getPredictionNo());
            BeanUtils.copyProperties(modelTemp02, grossFirst02);

            MeterWorkCarActualFirst tareFirstTemp01 = meterWorkCarActualFirstMapper.selectAndMatch(tareModel.getActualFirstNo(), scale01.getPredictionNo());
            BeanUtils.copyProperties(tareFirstTemp01, tareFirst01);
            MeterWorkCarActualFirst tareFirstTemp02 = meterWorkCarActualFirstMapper.selectAndMatch(tareModel.getActualFirstNo(), scale02.getPredictionNo());
            BeanUtils.copyProperties(tareFirstTemp02, tareFirst02);

            grossFirst01.setMeterMode("2");
            grossFirst01.setWeightType("0");
            grossFirst01.setDataSource("1");
            grossFirst01.setValueFlag("2");
            grossFirst01.setIsPreScale("1");
            grossFirst01.setPredictionType("5");
            grossFirst01.setPredictionCombination(scale01.getPredictionNo() + "," + scale02.getPredictionNo());
            grossFirst01.setUpdateManNo("system");
            grossFirst01.setUpdateManName("system");
            grossFirst01.setUpdateTime(new Date());
            grossFirst01.setNote("内倒双委托一次结净");
            meterWorkCarActualFirstMapper.updateByPrimaryKeySelective(grossFirst01);

            grossFirst02.setActualFirstNo(PublicMethod.IdCreate(3));
            grossFirst02.setMeterMode("2");
            grossFirst02.setWeightType("0");
            grossFirst02.setDataSource("1");
            grossFirst02.setValueFlag("2");
            grossFirst02.setIsPreScale("1");
            grossFirst02.setPredictionType("5");
            grossFirst02.setPredictionCombination(scale01.getPredictionNo() + "," + scale02.getPredictionNo());
            grossFirst02.setUpdateManNo("system");
            grossFirst02.setUpdateManName("system");
            grossFirst02.setUpdateTime(new Date());
            grossFirst02.setNote("内倒双委托一次结净");
            meterWorkCarActualFirstMapper.insertSelective(grossFirst02);


            tareFirst01.setMeterMode("2");
            tareFirst01.setWeightType("1");
            tareFirst01.setDataSource("1");
            tareFirst01.setValueFlag("2");
            tareFirst01.setIsPreScale("1");
            tareFirst01.setPredictionType("5");
            tareFirst01.setPredictionCombination(scale01.getPredictionNo() + "," + scale02.getPredictionNo());
            tareFirst01.setUpdateManNo("system");
            tareFirst01.setUpdateManName("system");
            tareFirst01.setUpdateTime(new Date());
            tareFirst01.setNote("内倒双委托一次结净");
            meterWorkCarActualFirstMapper.updateByPrimaryKeySelective(tareFirst01);

            tareFirst02.setActualFirstNo(PublicMethod.IdCreate(3));
            tareFirst02.setMeterMode("2");
            tareFirst02.setWeightType("1");
            tareFirst02.setDataSource("1");
            tareFirst02.setValueFlag("2");
            tareFirst02.setIsPreScale("1");
            tareFirst02.setPredictionType("5");
            tareFirst02.setPredictionCombination(scale01.getPredictionNo() + "," + scale02.getPredictionNo());
            tareFirst02.setUpdateManNo("system");
            tareFirst02.setUpdateManName("system");
            tareFirst02.setUpdateTime(new Date());
            tareFirst01.setNote("内倒双委托一次结净");
            meterWorkCarActualFirstMapper.insertSelective(tareFirst02);

            //保存历史皮重信息
            doSaveHisTare(tareFirst01);

            MeterWorkCarActual actualRowTemp01 = meterWorkCarActualMapper.manualAddPre(grossFirst01.getActualFirstNo(), tareFirst01.getActualFirstNo(), scale01.getPredictionNo());
            BeanUtils.copyProperties(actualRowTemp01, actualRow01);
            MeterWorkCarActual actualRowTemp02 = meterWorkCarActualMapper.manualAddPre(grossFirst02.getActualFirstNo(), tareFirst02.getActualFirstNo(), scale02.getPredictionNo());
            BeanUtils.copyProperties(actualRowTemp02, actualRow02);

            actualRow01.setActualNo(PublicMethod.IdCreate(3));
            actualRow01.setNetMode(DbConstants.TYPE);
            actualRow01.setNote("内倒双委托一次匹配结净");
            actualRow01.setUploadFlag("1");
            actualRow01.setIsPreScale("1");
            actualRow01.setValueFlag("1");
            if(actualRow01.getGrossTime().compareTo(actualRow01.getTareTime()) >= 0) {
                actualRow01.setNetSpot3No(actualRow01.getBaseSpot1No());
                actualRow01.setNetSpot3Name(actualRow01.getBaseSpot1Name());
                actualRow01.setNetManNo(actualRow01.getGrossManNo());
                actualRow01.setNetManName(actualRow01.getGrossManName());
                actualRow01.setNetTime(actualRow01.getGrossTime());
                actualRow01.setCreateTime(actualRow01.getGrossTime());
                actualRow01.setCreateManName(actualRow01.getGrossManName());
            }else {
                actualRow01.setNetSpot3No(actualRow01.getBaseSpot2No());
                actualRow01.setNetSpot3Name(actualRow01.getBaseSpot2Name());
                actualRow01.setNetManNo(actualRow01.getTareManNo());
                actualRow01.setNetManName(actualRow01.getTareManName());
                actualRow01.setNetTime(actualRow01.getTareTime());
                actualRow01.setCreateTime(actualRow01.getTareTime());
                actualRow01.setCreateManName(actualRow01.getTareManName());
            }
            actualRow01.setPredictionType("5");
            actualRow01.setPredictionNo(grossFirst01.getPredictionNo());
            actualRow01.setPredictionCombination(scale01.getPredictionNo() + "," + scale02.getPredictionNo());
            actualRow01.setNetWeight(grossFirst01.getMeterWeight().subtract(tareFirst01.getMeterWeight()));
            meterWorkCarActualMapper.insertSelective(actualRow01);

            actualRow02.setActualNo(PublicMethod.IdCreate(3));
            actualRow02.setNetMode(DbConstants.TYPE);
            actualRow02.setNote("内倒双委托一次匹配结净");
            actualRow02.setUploadFlag("1");
            actualRow02.setIsPreScale("1");
            actualRow02.setValueFlag("1");
            if(actualRow02.getGrossTime().compareTo(actualRow02.getTareTime()) >= 0) {
                actualRow02.setNetSpot3No(actualRow02.getBaseSpot1No());
                actualRow02.setNetSpot3Name(actualRow02.getBaseSpot1Name());
                actualRow02.setNetManNo(actualRow02.getGrossManNo());
                actualRow02.setNetManName(actualRow02.getGrossManName());
                actualRow02.setNetTime(actualRow02.getGrossTime());
                actualRow02.setCreateTime(actualRow02.getGrossTime());
                actualRow02.setCreateManName(actualRow02.getGrossManName());
            }else {
                actualRow02.setNetSpot3No(actualRow02.getBaseSpot2No());
                actualRow02.setNetSpot3Name(actualRow02.getBaseSpot2Name());
                actualRow02.setNetManNo(actualRow02.getTareManNo());
                actualRow02.setNetManName(actualRow02.getTareManName());
                actualRow02.setNetTime(actualRow02.getTareTime());
                actualRow02.setCreateTime(actualRow02.getTareTime());
                actualRow02.setCreateManName(actualRow02.getTareManName());
            }
            actualRow02.setPredictionType("5");
            actualRow02.setPredictionNo(grossFirst02.getPredictionNo());
            actualRow02.setPredictionCombination(scale01.getPredictionNo() + "," + scale02.getPredictionNo());
            actualRow02.setNetWeight(grossFirst02.getMeterWeight().subtract(tareFirst02.getMeterWeight()));
            meterWorkCarActualMapper.insertSelective(actualRow02);

            //预约信息重置委托
            pre01.setPredictionType("5");
            pre01.setPredictionCombination(scale01.getPredictionNo() + "," + scale02.getPredictionNo());
            pre01.setMeasureStation(actualRow01.getNetSpot3No());
            pre01.setMeasureStationName(actualRow01.getNetSpot3Name());
            pre01.setUpdateManNo("system");
            pre01.setUpdateManName("system");
            pre01.setUpdateTime(new Date());
            pre01.setValueFlag("2");
            pre01.setUploadFlag("1");
            pre01.setLineDesc("0");
            preTrackScaleMapper.updateByPrimaryKeySelective(pre01);

            pre02.setPredictionType("5");
            pre02.setPredictionCombination(scale01.getPredictionNo() + "," + scale02.getPredictionNo());
            pre02.setMeasureStation(actualRow02.getNetSpot3No());
            pre02.setMeasureStationName(actualRow02.getNetSpot3Name());
            pre02.setUpdateManNo("system");
            pre02.setUpdateManName("system");
            pre02.setUpdateTime(new Date());
            pre02.setValueFlag("2");
            pre02.setUploadFlag("1");
            pre02.setLineDesc("0");
            preTrackScaleMapper.updateByPrimaryKeySelective(pre02);
            updatePreWeight(pre01.getCarNo());
            updatePreWeight(pre02.getCarNo());

            rm.setSucceed(true);
            rm.setCode("200");
            if(grossFlag) {
                rm.setData(grossModel.getActualFirstNo());
            }
            if(tareFlag) {
                rm.setData(tareModel.getActualFirstNo());
            }
            rm.setMessage("操作成功");
        }catch(Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            rm.setMessage("操作异常，" + e.getMessage());
        }
        return rm;
    }

    @Override
    public RESTfulResult doTermTareNetDoubleRetain(MeterWorkCarActualFirst grossModel, MeterWorkCarActualFirst tareModel, PreTrackScale scale01, PreTrackScale scale02) {
        RESTfulResult rm = new RESTfulResult();
        rm.setFailed();
        try{
            Boolean grossFlag = false;
            Boolean tareFlag = false;
            //插入一次毛重数据
            MeterWorkCarActualFirst firstTemp01 = meterWorkCarActualFirstMapper.selectByPrimaryKey(grossModel.getActualFirstNo());
            if(firstTemp01 == null) {
                grossFlag = true;
                grossModel.setActualFirstNo(PublicMethod.IdCreate(3));
                grossModel.setValueFlag("1");
                grossModel.setCreateManNo("system");
                grossModel.setCreateManName("system");
                grossModel.setCreateTime(new Date());
                meterWorkCarActualFirstMapper.insertSelective(grossModel);
            }

            //插入一次皮重数据
            MeterWorkCarActualFirst firstTemp02 = meterWorkCarActualFirstMapper.selectByPrimaryKey(tareModel.getActualFirstNo());
            if(firstTemp02 == null) {
                tareFlag = false;
                tareModel.setActualFirstNo(PublicMethod.IdCreate(3));
                tareModel.setValueFlag("1");
                tareModel.setCreateManNo("system");
                tareModel.setCreateManName("system");
                tareModel.setCreateTime(new Date());
                meterWorkCarActualFirstMapper.insertSelective(tareModel);
            }

            PreTrackScale pre01 = preTrackScaleMapper.selectByPrimaryKey(scale01.getPredictionNo());
            PreTrackScale pre02 = preTrackScaleMapper.selectByPrimaryKey(scale02.getPredictionNo());
            if(pre01 != null && pre02 != null) {
                if(pre01.getValueFlag().equals("2") || pre01.getValueFlag().equals("3")) {
                    rm.setMessage(pre01.getPredictionNo() + "委托信息已使用或已作废");
                    return rm;
                }else if(pre02.getValueFlag().equals("2") || pre02.getValueFlag().equals("3")) {
                    rm.setMessage(pre02.getPredictionNo() + "委托信息已使用或已作废");
                    return rm;
                }
            }else if(pre01 == null){
                rm.setMessage(pre01.getPredictionNo() + "委托信息不存在");
                return rm;
            }else if(pre02 == null) {
                rm.setMessage(pre02.getPredictionNo() + "委托信息不存在");
                return rm;
            }

            MeterWorkCarActualFirst grossFirst01 = new MeterWorkCarActualFirst();
            MeterWorkCarActualFirst grossFirst02 = new MeterWorkCarActualFirst();
            //回空皮重信息保存
            MeterWorkCarActualFirst tareFirst01 = new MeterWorkCarActualFirst();
            MeterWorkCarActualFirst tareFirst02 = new MeterWorkCarActualFirst();
            MeterWorkCarActual actualRow01 = new MeterWorkCarActual();
            MeterWorkCarActual actualRow02 = new MeterWorkCarActual();

            MeterWorkCarActualFirst modelTemp01 = meterWorkCarActualFirstMapper.selectAndMatch(grossModel.getActualFirstNo(), scale01.getPredictionNo());
            BeanUtils.copyProperties(modelTemp01, grossFirst01);
            MeterWorkCarActualFirst modelTemp02 = meterWorkCarActualFirstMapper.selectAndMatch(grossModel.getActualFirstNo(), scale02.getPredictionNo());
            BeanUtils.copyProperties(modelTemp02, grossFirst02);

            MeterWorkCarActualFirst tareFirstTemp01 = meterWorkCarActualFirstMapper.selectAndMatch(tareModel.getActualFirstNo(), scale01.getPredictionNo());
            BeanUtils.copyProperties(tareFirstTemp01, tareFirst01);
            MeterWorkCarActualFirst tareFirstTemp02 = meterWorkCarActualFirstMapper.selectAndMatch(tareModel.getActualFirstNo(), scale02.getPredictionNo());
            BeanUtils.copyProperties(tareFirstTemp02, tareFirst02);

            grossFirst01.setMeterMode("2");
            grossFirst01.setWeightType("0");
            grossFirst01.setDataSource("1");
            grossFirst01.setValueFlag("2");
            grossFirst01.setIsPreScale("1");
            grossFirst01.setPredictionType("5");
            grossFirst01.setPredictionCombination(scale01.getPredictionNo() + "," + scale02.getPredictionNo());
            grossFirst01.setUpdateManNo("system");
            grossFirst01.setUpdateManName("system");
            grossFirst01.setUpdateTime(new Date());
            grossFirst01.setNote("内倒双委托一次保存期限皮结净");
            meterWorkCarActualFirstMapper.updateByPrimaryKeySelective(grossFirst01);

            grossFirst02.setActualFirstNo(PublicMethod.IdCreate(3));
            grossFirst02.setMeterMode("2");
            grossFirst02.setWeightType("0");
            grossFirst02.setDataSource("1");
            grossFirst02.setValueFlag("2");
            grossFirst02.setIsPreScale("1");
            grossFirst02.setPredictionType("5");
            grossFirst02.setPredictionCombination(scale01.getPredictionNo() + "," + scale02.getPredictionNo());
            grossFirst02.setUpdateManNo("system");
            grossFirst02.setUpdateManName("system");
            grossFirst02.setUpdateTime(new Date());
            grossFirst02.setNote("内倒双委托一次保存期限皮结净");
            meterWorkCarActualFirstMapper.insertSelective(grossFirst02);

            tareFirst01.setActualFirstNo(PublicMethod.IdCreate(3));
            tareFirst01.setMeterMode("2");
            tareFirst01.setWeightType("2");
            tareFirst01.setDataSource("1");
            tareFirst01.setValueFlag("2");
            tareFirst01.setIsPreScale("1");
            tareFirst01.setPredictionType("5");
            tareFirst01.setPredictionCombination(scale01.getPredictionNo() + "," + scale02.getPredictionNo());
            tareFirst01.setUpdateManNo("system");
            tareFirst01.setUpdateManName("system");
            tareFirst01.setUpdateTime(new Date());
            tareFirst01.setNote("内倒双委托一次保存期限皮结净");
            meterWorkCarActualFirstMapper.insertSelective(tareFirst01);

            tareFirst02.setActualFirstNo(PublicMethod.IdCreate(3));
            tareFirst02.setMeterMode("2");
            tareFirst02.setWeightType("2");
            tareFirst02.setDataSource("1");
            tareFirst02.setValueFlag("2");
            tareFirst02.setIsPreScale("1");
            tareFirst02.setPredictionType("5");
            tareFirst02.setPredictionCombination(scale01.getPredictionNo() + "," + scale02.getPredictionNo());
            tareFirst02.setUpdateManNo("system");
            tareFirst02.setUpdateManName("system");
            tareFirst02.setUpdateTime(new Date());
            tareFirst02.setNote("内倒双委托一次保存期限皮结净");
            meterWorkCarActualFirstMapper.insertSelective(tareFirst02);

            //作废一次皮重
            tareModel.setValueFlag("0");
            meterWorkCarActualFirstMapper.updateByPrimaryKeySelective(tareModel);
            //保存历史皮重信息
            doSaveHisTare(tareFirst01);

            //保存期限皮重信息
            MeterBaseSpotInfo spotInfo = meterBaseSpotInfoMapper.selectByPrimaryKey(tareModel.getBaseSpotNo());
            HashMap<String, Object> map = new HashMap<>();
            map.put("carNo", tareModel.getCarNo());
            map.put("spotAreaNo", spotInfo.getSpotAreaNo());
            map.put("spotAreaName", spotInfo.getSpotAreaName());
            List<MeterBaseTermTareData> upModels = meterBaseTermTareDataMapper.selectByParameters(map);
            MeterBaseTermTareData termData = new MeterBaseTermTareData();
            if (upModels.size() >= 1) {
                termData = upModels.get(0);
            }
            if (termData.getDataNo() != null) {
                termData.setBaseSpotNo(tareModel.getBaseSpotNo());
                termData.setBaseSpotName(tareModel.getBaseSpotName());
                termData.setSpotAreaNo(spotInfo.getSpotAreaNo());
                termData.setSpotAreaName(spotInfo.getSpotAreaName());
                termData.setCarNo(tareModel.getCarNo());
                termData.setMeterName(tareModel.getCreateManName());
                termData.setMeterTime(tareModel.getCreateTime());
                termData.setStartTime(tareModel.getCreateTime());
                termData.setEndTime(new Date(tareModel.getCreateTime().getTime() + 24 * 60 * 60 * 1000));
                termData.setWarnTime(new Date(tareModel.getCreateTime().getTime() + 12 * 60 * 60 * 1000));
                termData.setValueFlag("0");
                termData.setCreateManNo(tareModel.getCreateManNo());
                termData.setCreateManName(tareModel.getCreateManName());
                termData.setCreateTime(new Date());
                termData.setMeterWeight(tareModel.getMeterWeight());
                meterBaseTermTareDataMapper.updateByPrimaryKeySelective(termData);
            } else {
                //新增操作
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
                String no1 = meterBaseTermTareDataMapper.getNewID(sdf.format(new Date()));
                termData.setDataNo(sdf.format(new Date()) + no1);
                termData.setBaseSpotNo(tareModel.getBaseSpotNo());
                termData.setBaseSpotName(tareModel.getBaseSpotName());
                termData.setSpotAreaNo(spotInfo.getSpotAreaNo());
                termData.setSpotAreaName(spotInfo.getSpotAreaName());
                termData.setCarNo(tareModel.getCarNo());
                termData.setMeterName(tareModel.getCreateManName());
                termData.setMeterTime(tareModel.getCreateTime());
                termData.setStartTime(tareModel.getCreateTime());
                termData.setEndTime(new Date(tareModel.getCreateTime().getTime() + 24 * 60 * 60 * 1000));
                termData.setWarnTime(new Date(tareModel.getCreateTime().getTime() + 12 * 60 * 60 * 1000));
                termData.setValueFlag("0");
                termData.setCreateManNo(tareModel.getCreateManNo());
                termData.setCreateManName(tareModel.getCreateManName());
                termData.setCreateTime(new Date());
                termData.setMeterWeight(tareModel.getMeterWeight());
                meterBaseTermTareDataMapper.insertSelective(termData);
            }

            MeterWorkCarActual actualRowTemp01 = meterWorkCarActualMapper.manualAddPre(grossFirst01.getActualFirstNo(), tareFirst01.getActualFirstNo(), scale01.getPredictionNo());
            BeanUtils.copyProperties(actualRowTemp01, actualRow01);
            MeterWorkCarActual actualRowTemp02 = meterWorkCarActualMapper.manualAddPre(grossFirst02.getActualFirstNo(), tareFirst02.getActualFirstNo(), scale02.getPredictionNo());
            BeanUtils.copyProperties(actualRowTemp02, actualRow02);

            actualRow01.setActualNo(PublicMethod.IdCreate(3));
            actualRow01.setNetMode(DbConstants.TYPE);
            actualRow01.setNote("内倒双委托一次保存期限皮匹配结净");
            actualRow01.setUploadFlag("1");
            actualRow01.setIsPreScale("1");
            actualRow01.setValueFlag("1");
            if(actualRow01.getGrossTime().compareTo(actualRow01.getTareTime()) >= 0) {
                actualRow01.setNetSpot3No(actualRow01.getBaseSpot1No());
                actualRow01.setNetSpot3Name(actualRow01.getBaseSpot1Name());
                actualRow01.setNetManNo(actualRow01.getGrossManNo());
                actualRow01.setNetManName(actualRow01.getGrossManName());
                actualRow01.setNetTime(actualRow01.getGrossTime());
                actualRow01.setCreateTime(actualRow01.getGrossTime());
                actualRow01.setCreateManName(actualRow01.getGrossManName());
            }else {
                actualRow01.setNetSpot3No(actualRow01.getBaseSpot2No());
                actualRow01.setNetSpot3Name(actualRow01.getBaseSpot2Name());
                actualRow01.setNetManNo(actualRow01.getTareManNo());
                actualRow01.setNetManName(actualRow01.getTareManName());
                actualRow01.setNetTime(actualRow01.getTareTime());
                actualRow01.setCreateTime(actualRow01.getTareTime());
                actualRow01.setCreateManName(actualRow01.getTareManName());
            }
            actualRow01.setPredictionType("5");
            actualRow01.setPredictionNo(grossFirst01.getPredictionNo());
            actualRow01.setPredictionCombination(scale01.getPredictionNo() + "," + scale02.getPredictionNo());
            actualRow01.setNetWeight(grossFirst01.getMeterWeight().subtract(tareFirst01.getMeterWeight()));
            meterWorkCarActualMapper.insertSelective(actualRow01);

            actualRow02.setActualNo(PublicMethod.IdCreate(3));
            actualRow02.setNetMode(DbConstants.TYPE);
            actualRow02.setNote("内倒双委托一次保存期限皮匹配结净");
            actualRow02.setUploadFlag("1");
            actualRow02.setIsPreScale("1");
            actualRow02.setValueFlag("1");
            if(actualRow02.getGrossTime().compareTo(actualRow02.getTareTime()) >= 0) {
                actualRow02.setNetSpot3No(actualRow02.getBaseSpot1No());
                actualRow02.setNetSpot3Name(actualRow02.getBaseSpot1Name());
                actualRow02.setNetManNo(actualRow02.getGrossManNo());
                actualRow02.setNetManName(actualRow02.getGrossManName());
                actualRow02.setNetTime(actualRow02.getGrossTime());
                actualRow02.setCreateTime(actualRow02.getGrossTime());
                actualRow02.setCreateManName(actualRow02.getGrossManName());
            }else {
                actualRow02.setNetSpot3No(actualRow02.getBaseSpot2No());
                actualRow02.setNetSpot3Name(actualRow02.getBaseSpot2Name());
                actualRow02.setNetManNo(actualRow02.getTareManNo());
                actualRow02.setNetManName(actualRow02.getTareManName());
                actualRow02.setNetTime(actualRow02.getTareTime());
                actualRow02.setCreateTime(actualRow02.getTareTime());
                actualRow02.setCreateManName(actualRow02.getTareManName());
            }
            actualRow02.setPredictionType("5");
            actualRow02.setPredictionNo(grossFirst02.getPredictionNo());
            actualRow02.setPredictionCombination(scale01.getPredictionNo() + "," + scale02.getPredictionNo());
            actualRow02.setNetWeight(grossFirst02.getMeterWeight().subtract(tareFirst02.getMeterWeight()));
            meterWorkCarActualMapper.insertSelective(actualRow02);

            //预约信息重置委托
            pre01.setPredictionType("5");
            pre01.setPredictionCombination(scale01.getPredictionNo() + "," + scale02.getPredictionNo());
            pre01.setMeasureStation(actualRow01.getNetSpot3No());
            pre01.setMeasureStationName(actualRow01.getNetSpot3Name());
            pre01.setUpdateManNo("system");
            pre01.setUpdateManName("system");
            pre01.setUpdateTime(new Date());
            pre01.setValueFlag("2");
            pre01.setUploadFlag("1");
            pre01.setLineDesc("0");
            preTrackScaleMapper.updateByPrimaryKeySelective(pre01);

            pre02.setPredictionType("5");
            pre02.setPredictionCombination(scale01.getPredictionNo() + "," + scale02.getPredictionNo());
            pre02.setMeasureStation(actualRow02.getNetSpot3No());
            pre02.setMeasureStationName(actualRow02.getNetSpot3Name());
            pre02.setUpdateManNo("system");
            pre02.setUpdateManName("system");
            pre02.setUpdateTime(new Date());
            pre02.setValueFlag("2");
            pre02.setUploadFlag("1");
            pre02.setLineDesc("0");
            preTrackScaleMapper.updateByPrimaryKeySelective(pre02);
            updatePreWeight(pre01.getCarNo());
            updatePreWeight(pre02.getCarNo());

            rm.setSucceed(true);
            rm.setCode("200");
            if(grossFlag) {
                rm.setData(grossModel.getActualFirstNo());
            }
            if(tareFlag) {
                rm.setData(tareModel.getActualFirstNo());
            }
            rm.setMessage("操作成功");
        }catch(Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            rm.setMessage("操作异常，" + e.getMessage());
        }
        return rm;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public RESTfulResult doAddDoubleMuchNet(List<MeterWorkCarActualFirst> grossModels, MeterWorkCarActualFirst tareModel) {
        RESTfulResult rm = new RESTfulResult();
        rm.setFailed();
        try{
            String no = "";
            //将皮重数据新增
            tareModel.setActualFirstNo(PublicMethod.IdCreate(3));
            tareModel.setValueFlag("1");
            tareModel.setCreateManNo("system");
            tareModel.setCreateManName("system");
            tareModel.setCreateTime(new Date());
            meterWorkCarActualFirstMapper.insertSelective(tareModel);

            no = tareModel.getActualFirstNo();

            for (MeterWorkCarActualFirst grossModel: grossModels){
                //将毛重数据结净
                grossModel.setValueFlag("2");
                grossModel.setUpdateManNo("system");
                grossModel.setUpdateManName("system");
                grossModel.setUpdateTime(new Date());
                grossModel.setNote("内倒多毛一皮匹配委托结净");
                meterWorkCarActualFirstMapper.updateByPrimaryKeySelective(grossModel);

                tareModel = meterWorkCarActualFirstMapper.selectAndMatch(tareModel.getActualFirstNo(), grossModel.getPredictionNo());
                //多毛回空皮结净
                tareModel.setActualFirstNo(PublicMethod.IdCreate(3));
                tareModel.setMeterMode("2");
                tareModel.setWeightType("1");
                tareModel.setDataSource("1");
                tareModel.setValueFlag("2");
                tareModel.setIsPreScale("1");
                tareModel.setPredictionType("1");
                tareModel.setUpdateManNo("system");
                tareModel.setUpdateManName("system");
                tareModel.setUpdateTime(new Date());
                tareModel.setNote("内倒多毛一皮匹配委托结净");
                meterWorkCarActualFirstMapper.insertSelective(tareModel);

                //将委托信息插入结净数据
                MeterWorkCarActual mwca = meterWorkCarActualMapper.manualAddPre(grossModel.getActualFirstNo(), tareModel.getActualFirstNo(), grossModel.getPredictionNo());
                //更新结净数据状态
                mwca.setActualNo(PublicMethod.IdCreate(3));
                mwca.setNetMode(DbConstants.TYPE);
                mwca.setNote("内倒多毛一皮匹配委托结净");
                mwca.setUploadFlag("1");
                mwca.setIsPreScale("1");
                mwca.setValueFlag("1");
                if(mwca.getGrossTime().compareTo(mwca.getTareTime()) >= 0) {
                    mwca.setNetSpot3No(mwca.getBaseSpot1No());
                    mwca.setNetSpot3Name(mwca.getBaseSpot1Name());
                    mwca.setNetManNo(mwca.getGrossManNo());
                    mwca.setNetManName(mwca.getGrossManName());
                    mwca.setNetTime(mwca.getGrossTime());
                    mwca.setCreateTime(mwca.getGrossTime());
                    mwca.setCreateManName(mwca.getGrossManName());
                }else {
                    mwca.setNetSpot3No(mwca.getBaseSpot2No());
                    mwca.setNetSpot3Name(mwca.getBaseSpot2Name());
                    mwca.setNetManNo(mwca.getTareManNo());
                    mwca.setNetManName(mwca.getTareManName());
                    mwca.setNetTime(mwca.getTareTime());
                    mwca.setCreateTime(mwca.getTareTime());
                    mwca.setCreateManName(mwca.getTareManName());
                }
                mwca.setPredictionType("5");
                mwca.setPredictionCombination(grossModel.getPredictionCombination());
                mwca.setPredictionNo(mwca.getPredictionNo());
                mwca.setNetWeight(grossModel.getMeterWeight().subtract(tareModel.getMeterWeight()));
                meterWorkCarActualMapper.insertSelective(mwca);

                //修改委托
                PreTrackScale scale = preTrackScaleMapper.selectBypredictionNo(grossModel.getPredictionNo());
                scale.setPredictionType("1");
                scale.setMeasureStation(mwca.getNetSpot3No());
                scale.setMeasureStationName(mwca.getNetSpot3Name());
                scale.setUpdateManNo("system");
                scale.setUpdateManName("system");
                scale.setUpdateTime(new Date());
                scale.setValueFlag("2");
                scale.setUploadFlag("1");
                scale.setLineDesc("0");
                preTrackScaleMapper.updateByPrimaryKeySelective(scale);
                updatePreWeight(scale.getCarNo());
            }
            doSaveHisTare(tareModel);

            meterWorkCarActualFirstMapper.deleteByPrimaryKey(no);

            rm.setSucceed();
            rm.setMessage("多毛一皮结净完成!!");
            rm.setData(tareModel.getActualFirstNo());
            rm.setCode("200");
            return rm;
        }
        catch (Exception e){
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            rm.setMessage("操作异常,请确认！！>>>" + e.getMessage());
            return rm;
        }
    }

    @Override
    public RESTfulResult countFirstByCar(HashMap<String, Object> params) {
        RESTfulResult rm = new RESTfulResult();
        rm.setFailed();
        try{
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String afl = sdf.format(new Date());
            String startTime = afl + " 00:00:00";
            String endTime = afl + " 23:59:59";
            params.put("startTime", startTime);
            params.put("endTime", endTime);
            int countFirst = meterWorkCarActualFirstMapper.countFirstByCar(params);
            rm.setSucceed(true);
            rm.setCode("200");
            rm.setData(countFirst);
            rm.setMessage("操作成功");
        }catch(Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            rm.setMessage("操作异常，" + e.getMessage());
        }
        return rm;
    }

    @Override
    public RESTfulResult doNetAddMuchGrossDouble(List<MeterWorkCarActualFirst> gross, MeterWorkCarActualFirst tare, MeterMonitorNote note) throws Exception {
        RESTfulResult rm = new RESTfulResult();
        rm.setFailed();
        try{
            //将皮重数据新增
            String no = PublicMethod.IdCreate(3);
            tare.setActualFirstNo(no);

            tare.setValueFlag("0");//结净
            tare.setWeightType("1");
            tare.setCreateTime(new Date());
            meterWorkCarActualFirstMapper.insertSelective(tare);

            //将皮重数据保存或更新到期限皮中
            MeterBaseSpotInfo spotInfo = meterBaseSpotInfoMapper.selectByPrimaryKey(tare.getBaseSpotNo());
            HashMap<String, Object> map = new HashMap<>();
            map.put("carNo", tare.getCarNo());
            map.put("spotAreaNo", spotInfo.getSpotAreaNo());
            map.put("spotAreaName", spotInfo.getSpotAreaName());
            List<MeterBaseTermTareData> upModels = meterBaseTermTareDataMapper.selectByParameters(map);
            MeterBaseTermTareData termData = new MeterBaseTermTareData();
            if (upModels.size() >= 1) {
                termData = upModels.get(0);
            }
            if (termData.getDataNo() != null) {
                termData.setBaseSpotNo(tare.getBaseSpotNo());
                termData.setBaseSpotName(tare.getBaseSpotName());
                termData.setSpotAreaNo(spotInfo.getSpotAreaNo());
                termData.setSpotAreaName(spotInfo.getSpotAreaName());
                termData.setCarNo(tare.getCarNo());
                termData.setMeterName(tare.getCreateManName());
                termData.setMeterTime(tare.getCreateTime());
                termData.setStartTime(tare.getCreateTime());
                termData.setEndTime(new Date(tare.getCreateTime().getTime() + 24 * 60 * 60 * 1000));
                termData.setWarnTime(new Date(tare.getCreateTime().getTime() + 12 * 60 * 60 * 1000));
                termData.setValueFlag("0");
                termData.setCreateManNo(tare.getCreateManNo());
                termData.setCreateManName(tare.getCreateManName());
                termData.setCreateTime(new Date());
                termData.setMeterWeight(tare.getMeterWeight());
                meterBaseTermTareDataMapper.updateByPrimaryKeySelective(termData);
            } else {
                //新增操作
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
                String no1 = meterBaseTermTareDataMapper.getNewID(sdf.format(new Date()));
                termData.setDataNo(sdf.format(new Date()) + no1);
                termData.setBaseSpotNo(tare.getBaseSpotNo());
                termData.setBaseSpotName(tare.getBaseSpotName());
                termData.setSpotAreaNo(spotInfo.getSpotAreaNo());
                termData.setSpotAreaName(spotInfo.getSpotAreaName());
                termData.setCarNo(tare.getCarNo());
                termData.setMeterName(tare.getCreateManName());
                termData.setMeterTime(tare.getCreateTime());
                termData.setStartTime(tare.getCreateTime());
                termData.setEndTime(new Date(tare.getCreateTime().getTime() + 24 * 60 * 60 * 1000));
                termData.setWarnTime(new Date(tare.getCreateTime().getTime() + 12 * 60 * 60 * 1000));
                termData.setValueFlag("0");
                termData.setCreateManNo(tare.getCreateManNo());
                termData.setCreateManName(tare.getCreateManName());
                termData.setCreateTime(new Date());
                termData.setMeterWeight(tare.getMeterWeight());
                meterBaseTermTareDataMapper.insertSelective(termData);
            }

            for (MeterWorkCarActualFirst model:gross){
                //将皮重数据新增
                model.setValueFlag("2");//结净
                meterWorkCarActualFirstMapper.updateByPrimaryKeySelective(model);

                MeterWorkCarActualFirst imTare = new MeterWorkCarActualFirst();
                imTare = meterWorkCarActualFirstMapper.selectAndMatch(tare.getActualFirstNo(), model.getPredictionNo());
                SimpleDateFormat formatter1 = new SimpleDateFormat("yyyyMMdd");
                //补充数据
                String afl1 = formatter1.format(new Date());
//                String imTareNO = meterWorkCarActualFirstMapper.getNewID(afl1);
//                String actualNo = afl1 + imTareNO;
                String actualNo = PublicMethod.IdCreate(3);

                imTare.setActualFirstNo(actualNo);
                imTare.setMeterTypeNo(tare.getMeterTypeNo());
                imTare.setMeterTypeName(tare.getMeterTypeName());
                imTare.setBaseSpotNo(termData.getBaseSpotNo());
                imTare.setBaseSpotName(termData.getBaseSpotName());
                imTare.setCarNo(termData.getCarNo());
                //杜勇 20220724修改
                imTare.setCreateTime(termData.getMeterTime());
                imTare.setCreateManNo(termData.getCreateManNo());
                imTare.setCreateManName(termData.getCreateManName());
                imTare.setMeterWeight(termData.getMeterWeight());
                imTare.setWeightType("2");//期限皮重
                imTare.setValueFlag("2");//结净
                imTare.setDataSource("1");
                imTare.setIsPreScale("1");
                imTare.setMeterTypeNo(model.getMeterTypeNo());
                imTare.setMeterTypeName(model.getMeterTypeName());
                imTare.setCreateTime(new Date());
                imTare.setUpdateManNo("system");
                imTare.setUpdateManName("system");
                imTare.setUpdateTime(new Date());
                imTare.setPredictionType("5");
                imTare.setPredictionNo(model.getPredictionNo());
                imTare.setPredictionCombination(model.getPredictionCombination());
                meterWorkCarActualFirstMapper.insertSelective(imTare);

                //将委托信息插入结净数据
                MeterWorkCarActual mwca = meterWorkCarActualMapper.manualAddPre(model.getActualFirstNo(), imTare.getActualFirstNo(), model.getPredictionNo());
                //更新结净数据状态
                String noActual = PublicMethod.IdCreate(3);
                mwca.setActualNo(noActual);
                mwca.setNetTime(new Date());
                mwca.setNetMode(DbConstants.TYPE);
                mwca.setNote("期限皮匹配结净");
                mwca.setUploadFlag("1");
                mwca.setIsPreScale("1");
                mwca.setValueFlag("1");
                mwca.setNetManNo("admin");
                mwca.setNetManName("admin");
                mwca.setNetSpot3No(model.getBaseSpotNo());
                mwca.setNetSpot3Name(model.getBaseSpotName());
                mwca.setNetWeight(model.getMeterWeight().subtract(imTare.getMeterWeight()));
                mwca.setCreateTime(new Date());
                if(mwca.getGrossTime().compareTo(mwca.getTareTime()) >= 0) {
                    mwca.setNetSpot3No(mwca.getBaseSpot1No());
                    mwca.setNetSpot3Name(mwca.getBaseSpot1Name());
                    mwca.setNetManNo(mwca.getGrossManNo());
                    mwca.setNetManName(mwca.getGrossManName());
                    mwca.setNetTime(mwca.getGrossTime());
                    mwca.setCreateTime(mwca.getGrossTime());
                    mwca.setCreateManName(mwca.getGrossManName());
                }else {
                    mwca.setNetSpot3No(mwca.getBaseSpot2No());
                    mwca.setNetSpot3Name(mwca.getBaseSpot2Name());
                    mwca.setNetManNo(mwca.getTareManNo());
                    mwca.setNetManName(mwca.getTareManName());
                    mwca.setNetTime(mwca.getTareTime());
                    mwca.setCreateTime(mwca.getTareTime());
                    mwca.setCreateManName(mwca.getTareManName());
                }
                mwca.setUpdateManNo("system");
                mwca.setUpdateManName("system");
                mwca.setUpdateTime(new Date());
                mwca.setPredictionType("5");
                mwca.setPredictionNo(model.getPredictionNo());
                mwca.setPredictionCombination(model.getPredictionCombination());
                meterWorkCarActualMapper.insertSelective(mwca);

                //修改委托
                PreTrackScale scale = preTrackScaleMapper.selectBypredictionNo(model.getPredictionNo());
                scale.setValueFlag(DbConstants.NET);
                scale.setUpdateTime(new Date());
                scale.setUpdateManNo("system");
                scale.setUpdateManName("期限皮结净更新");
                scale.setUploadFlag("1");
                scale.setLineDesc("0");
                scale.setMeasureStation(mwca.getNetSpot3No());
                scale.setMeasureStationName(mwca.getNetSpot3Name());
                scale.setPredictionType("5");
                scale.setPredictionCombination(model.getPredictionCombination());
                preTrackScaleMapper.updateByPrimaryKeySelective(scale);
            }

            //当存储一次数据或者结净时，将本车辆的预处理重量改为已使用
            updatePreWeight(tare.getCarNo());

            //保存或更新历史皮重
            MeterWorkCarActualFirst oci = new MeterWorkCarActualFirst();
            oci.setCarNo(tare.getCarNo());
            oci.setCreateTime(new Date());
            oci.setBaseSpotNo(tare.getBaseSpotNo());
            oci.setBaseSpotName(tare.getBaseSpotName());
            oci.setMeterWeight(tare.getMeterWeight());
            oci.setActualFirstNo(tare.getActualFirstNo());
            doSaveHisTare(oci);

            rm.setSucceed();
            rm.setMessage("多毛期限皮结净完成!!");
            rm.setData(tare.getActualFirstNo());
            rm.setCode("200");
        } catch (Exception e){
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            rm.setMessage("操作异常,请确认！！>>>" + e.getMessage());
        }
        return rm;
    }

    @Override
    public PageList<MeterWorkCarActualFirst> allStateView(HashMap<String, Object> params, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<MeterWorkCarActualFirst> firstList = meterWorkCarActualFirstMapper.allStateView(params);
        PageList pageInfo = new PageList(firstList);
        return pageInfo;
    }

    @Override
    public RESTfulResult doNetAddMuchGross(List<MeterWorkCarActualFirst> gross, MeterWorkCarActualFirst tare, MeterMonitorNote note) throws Exception {
        RESTfulResult rm = new RESTfulResult();
        rm.setFailed();
        try{
            //将皮重数据新增
            SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
            String afl = formatter.format(new Date());
//            String no = meterWorkCarActualFirstMapper.getNewID(afl);
//            tare.setActualFirstNo(formatter.format(new Date()) + no);

            String no = PublicMethod.IdCreate(3);
            tare.setActualFirstNo(no);

            tare.setValueFlag("0");//结净
            tare.setWeightType("1");
            tare.setCreateTime(new Date());
            meterWorkCarActualFirstMapper.insertSelective(tare);

            //将皮重数据保存或更新到期限皮中
            MeterBaseSpotInfo spotInfo = meterBaseSpotInfoMapper.selectByPrimaryKey(tare.getBaseSpotNo());
            HashMap<String, Object> map = new HashMap<>();
            map.put("carNo", tare.getCarNo());
            map.put("spotAreaNo", spotInfo.getSpotAreaNo());
            map.put("spotAreaName", spotInfo.getSpotAreaName());
            List<MeterBaseTermTareData> upModels = meterBaseTermTareDataMapper.selectByParameters(map);
            MeterBaseTermTareData termData = new MeterBaseTermTareData();
            if (upModels.size() >= 1) {
                termData = upModels.get(0);
            }
            if (termData.getDataNo() != null) {
                termData.setBaseSpotNo(tare.getBaseSpotNo());
                termData.setBaseSpotName(tare.getBaseSpotName());
                termData.setSpotAreaNo(spotInfo.getSpotAreaNo());
                termData.setSpotAreaName(spotInfo.getSpotAreaName());
                termData.setCarNo(tare.getCarNo());
                termData.setMeterName(tare.getCreateManName());
                termData.setMeterTime(tare.getCreateTime());
                termData.setStartTime(tare.getCreateTime());
                termData.setEndTime(new Date(tare.getCreateTime().getTime() + 24 * 60 * 60 * 1000));
                termData.setWarnTime(new Date(tare.getCreateTime().getTime() + 12 * 60 * 60 * 1000));
                termData.setValueFlag("0");
                termData.setCreateManNo(tare.getCreateManNo());
                termData.setCreateManName(tare.getCreateManName());
                termData.setCreateTime(new Date());
                termData.setMeterWeight(tare.getMeterWeight());
                meterBaseTermTareDataMapper.updateByPrimaryKeySelective(termData);
            } else {
                //新增操作
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
                String no1 = meterBaseTermTareDataMapper.getNewID(sdf.format(new Date()));
                termData.setDataNo(sdf.format(new Date()) + no1);
                termData.setBaseSpotNo(tare.getBaseSpotNo());
                termData.setBaseSpotName(tare.getBaseSpotName());
                termData.setSpotAreaNo(spotInfo.getSpotAreaNo());
                termData.setSpotAreaName(spotInfo.getSpotAreaName());
                termData.setCarNo(tare.getCarNo());
                termData.setMeterName(tare.getCreateManName());
                termData.setMeterTime(tare.getCreateTime());
                termData.setStartTime(tare.getCreateTime());
                termData.setEndTime(new Date(tare.getCreateTime().getTime() + 24 * 60 * 60 * 1000));
                termData.setWarnTime(new Date(tare.getCreateTime().getTime() + 12 * 60 * 60 * 1000));
                termData.setValueFlag("0");
                termData.setCreateManNo(tare.getCreateManNo());
                termData.setCreateManName(tare.getCreateManName());
                termData.setCreateTime(new Date());
                termData.setMeterWeight(tare.getMeterWeight());
                meterBaseTermTareDataMapper.insertSelective(termData);
            }

            for (MeterWorkCarActualFirst model:gross){
                //将皮重数据新增
                model.setValueFlag("2");//结净
                meterWorkCarActualFirstMapper.updateByPrimaryKeySelective(model);

                MeterWorkCarActualFirst imTare = new MeterWorkCarActualFirst();
                imTare = meterWorkCarActualFirstMapper.selectAndMatch(tare.getActualFirstNo(), model.getPredictionNo());
                SimpleDateFormat formatter1 = new SimpleDateFormat("yyyyMMdd");
                //补充数据
                String afl1 = formatter1.format(new Date());
//                String imTareNO = meterWorkCarActualFirstMapper.getNewID(afl1);
//                String actualNo = afl1 + imTareNO;
                String actualNo = PublicMethod.IdCreate(3);
                imTare.setActualFirstNo(actualNo);
                imTare.setMeterTypeNo(tare.getMeterTypeNo());
                imTare.setMeterTypeName(tare.getMeterTypeName());
                imTare.setBaseSpotNo(termData.getBaseSpotNo());
                imTare.setBaseSpotName(termData.getBaseSpotName());
                imTare.setCarNo(termData.getCarNo());
                //杜勇 20220724修改
                imTare.setCreateTime(termData.getMeterTime());
                imTare.setCreateManNo(termData.getCreateManNo());
                imTare.setCreateManName(termData.getCreateManName());
                imTare.setMeterWeight(termData.getMeterWeight());
                imTare.setWeightType("2");//期限皮重
                imTare.setValueFlag("2");//结净
                imTare.setDataSource("1");
                imTare.setIsPreScale("1");
                imTare.setMeterTypeNo(model.getMeterTypeNo());
                imTare.setMeterTypeName(model.getMeterTypeName());
                imTare.setCreateTime(new Date());
                meterWorkCarActualFirstMapper.insertSelective(imTare);

                //将委托信息插入结净数据
                MeterWorkCarActual mwca = meterWorkCarActualMapper.manualAddPre(model.getActualFirstNo(), imTare.getActualFirstNo(), model.getPredictionNo());
                //更新结净数据状态
                String noActual = PublicMethod.IdCreate(3);
                mwca.setActualNo(noActual);
                mwca.setNetMode(DbConstants.TYPE);
                mwca.setNote("期限皮匹配结净");
                mwca.setUploadFlag("1");
                mwca.setIsPreScale("1");
                mwca.setValueFlag("1");
                mwca.setNetManNo("system");
                mwca.setNetManName("system");
                mwca.setNetTime(new Date());
                mwca.setNetSpot3No(model.getBaseSpotNo());
                mwca.setNetSpot3Name(model.getBaseSpotName());
                mwca.setPredictionNo(model.getPredictionNo());
                mwca.setPredictionType("1");
                mwca.setNetWeight(model.getMeterWeight().subtract(imTare.getMeterWeight()));
                mwca.setCreateTime(new Date());
                if(mwca.getGrossTime().compareTo(mwca.getTareTime()) >= 0) {
                    mwca.setNetSpot3No(mwca.getBaseSpot1No());
                    mwca.setNetSpot3Name(mwca.getBaseSpot1Name());
                    mwca.setNetManNo(mwca.getGrossManNo());
                    mwca.setNetManName(mwca.getGrossManName());
                    mwca.setNetTime(mwca.getGrossTime());
                    mwca.setCreateTime(mwca.getGrossTime());
                    mwca.setCreateManName(mwca.getGrossManName());
                }else {
                    mwca.setNetSpot3No(mwca.getBaseSpot2No());
                    mwca.setNetSpot3Name(mwca.getBaseSpot2Name());
                    mwca.setNetManNo(mwca.getTareManNo());
                    mwca.setNetManName(mwca.getTareManName());
                    mwca.setNetTime(mwca.getTareTime());
                    mwca.setCreateTime(mwca.getTareTime());
                    mwca.setCreateManName(mwca.getTareManName());
                }
                meterWorkCarActualMapper.insertSelective(mwca);

                //修改委托
                PreTrackScale scale = preTrackScaleMapper.selectBypredictionNo(model.getPredictionNo());
                scale.setValueFlag(DbConstants.NET);
                scale.setUpdateTime(new Date());
                scale.setUpdateManNo("system");
                scale.setUpdateManName("期限皮结净更新");
                scale.setUploadFlag("1");
                scale.setLineDesc("0");
                scale.setPredictionType("1");
                scale.setMeasureStation(mwca.getNetSpot3No());
                scale.setMeasureStationName(mwca.getNetSpot3Name());
                preTrackScaleMapper.updateByPrimaryKeySelective(scale);
            }

            //当存储一次数据或者结净时，将本车辆的预处理重量改为已使用
            updatePreWeight(tare.getCarNo());

            //保存或更新历史皮重
            MeterWorkCarActualFirst oci = new MeterWorkCarActualFirst();
            oci.setCarNo(tare.getCarNo());
            oci.setCreateTime(new Date());
            oci.setBaseSpotNo(tare.getBaseSpotNo());
            oci.setBaseSpotName(tare.getBaseSpotName());
            oci.setMeterWeight(tare.getMeterWeight());
            oci.setActualFirstNo(tare.getActualFirstNo());
            doSaveHisTare(oci);

            rm.setSucceed();
            rm.setMessage("多毛结净完成!!");
            rm.setData(tare.getActualFirstNo());
            rm.setCode("200");
            return rm;
        }
        catch (Exception e){
            e.printStackTrace();
            rm.setMessage("操作异常,请确认！！>>>" + e.getMessage());
            return rm;
        }
    }

    @Override
    @Transactional
    public RESTfulResult localCleanByFirstNo(MeterWorkCarActual actualModel) {
        RESTfulResult rm = new RESTfulResult();
        rm.setFailed();
        try{
            if(StringUtils.isEmpty(actualModel.getActualFirst1No()) || StringUtils.isEmpty(actualModel.getActualFirst2No())) {
                rm.setMessage("两个一次作业编号不能为空！");
                return rm;
            }
            MeterWorkCarActualFirst grossModel = meterWorkCarActualFirstMapper.selectByPrimaryKey(actualModel.getActualFirst1No());
            if(grossModel == null) {
                rm.setMessage("毛重一次作业编号【" + actualModel.getActualFirst1No() +"】未查询到一次计量数据！");
                return rm;
            }
            MeterWorkCarActualFirst tareModel = meterWorkCarActualFirstMapper.selectByPrimaryKey(actualModel.getActualFirst2No());
            if(tareModel == null) {
                rm.setMessage("皮重一次作业编号【" + actualModel.getActualFirst2No() +"】未查询到一次计量数据！");
                return rm;
            }
            //判断委托编号是否带委托，结净数据未带委托，再去两个一次数据去取委托
            String predictionNo = "";
            if(StringUtils.isNotEmpty(actualModel.getPredictionNo())) {
                predictionNo = actualModel.getPredictionNo();
            }else {
                if(StringUtils.isNotEmpty(grossModel.getPredictionNo())) {
                    predictionNo = grossModel.getPredictionNo();
                }else if(StringUtils.isNotEmpty(tareModel.getPredictionNo())) {
                    predictionNo = tareModel.getPredictionNo();
                }
            }

            String userId = actualModel.getUpdateManNo();
            String userName = actualModel.getUpdateManName();
            String note = actualModel.getNote();
            if(StringUtils.isNotEmpty(predictionNo)) {
                grossModel = meterWorkCarActualFirstMapper.selectAndMatch(grossModel.getActualFirstNo(), predictionNo);
                grossModel.setWeightType("0");
                grossModel.setValueFlag("2");
                grossModel.setIsPreScale("1");
                grossModel.setPredictionType("1");
                grossModel.setUpdateManNo(userId);
                grossModel.setUpdateManName(userName);
                grossModel.setUpdateTime(new Date());
                grossModel.setNote(note);
                meterWorkCarActualFirstMapper.updateByPrimaryKeySelective(grossModel);

                tareModel = meterWorkCarActualFirstMapper.selectAndMatch(tareModel.getActualFirstNo(), predictionNo);
                tareModel.setWeightType("1");
                tareModel.setValueFlag("2");
                tareModel.setIsPreScale("1");
                tareModel.setPredictionType("1");
                tareModel.setUpdateManNo(userId);
                tareModel.setUpdateManName(userName);
                tareModel.setUpdateTime(new Date());
                tareModel.setNote(note);
                meterWorkCarActualFirstMapper.updateByPrimaryKeySelective(tareModel);

                MeterWorkCarActual mwca = meterWorkCarActualMapper.manualAddPre(grossModel.getActualFirstNo(), tareModel.getActualFirstNo(), predictionNo);
                //更新结净数据状态
                mwca.setActualNo(PublicMethod.IdCreate(3));
                mwca.setNetMode(DbConstants.TYPE);
                mwca.setUpdateManNo(userId);
                mwca.setUpdateManName(userName);
                mwca.setNote(note);
                mwca.setUploadFlag("1");
                mwca.setIsPreScale("1");
                mwca.setValueFlag("1");
                if(mwca.getGrossTime().compareTo(mwca.getTareTime()) >= 0) {
                    mwca.setNetSpot3No(mwca.getBaseSpot1No());
                    mwca.setNetSpot3Name(mwca.getBaseSpot1Name());
                    mwca.setNetManNo(mwca.getGrossManNo());
                    mwca.setNetManName(mwca.getGrossManName());
                    mwca.setNetTime(mwca.getGrossTime());
                    mwca.setCreateTime(mwca.getGrossTime());
                    mwca.setCreateManName(mwca.getGrossManName());
                }else {
                    mwca.setNetSpot3No(mwca.getBaseSpot2No());
                    mwca.setNetSpot3Name(mwca.getBaseSpot2Name());
                    mwca.setNetManNo(mwca.getTareManNo());
                    mwca.setNetManName(mwca.getTareManName());
                    mwca.setNetTime(mwca.getTareTime());
                    mwca.setCreateTime(mwca.getTareTime());
                    mwca.setCreateManName(mwca.getTareManName());
                }
                mwca.setPredictionType("1");
                mwca.setNetWeight(grossModel.getMeterWeight().subtract(tareModel.getMeterWeight()));
                meterWorkCarActualMapper.insertSelective(mwca);

                MeterBaseOperationLog logModel = new MeterBaseOperationLog();
                logModel.setId(PublicMethod.IdCreate(2));
                logModel.setCreateManNo(userId);
                logModel.setCreateManName(userName);
                logModel.setCreateTime(new Date());
                logModel.setOperationPage("C#端-本地计量一次数据维护");
                logModel.setOperationFunction("一次数据结净");
                logModel.setOperationId(mwca.getActualNo());
                logModel.setOperationPredictionNo(mwca.getPredictionNo());
                logModel.setOperationCarnNo(mwca.getCarNo());
                logModel.setOperationBeforeFix(mwca.getActualFirst1No() + "+" + mwca.getActualFirst2No());
                logModel.setOperationAfterFix("");
                meterBaseOperationLogMapper.insertSelective(logModel);
            }else {
                grossModel.setWeightType("0");
                grossModel.setValueFlag("2");
                grossModel.setIsPreScale("0");
                grossModel.setUpdateManNo(userId);
                grossModel.setUpdateManName(userName);
                grossModel.setUpdateTime(new Date());
                grossModel.setNote(note);
                meterWorkCarActualFirstMapper.updateByPrimaryKeySelective(grossModel);

                tareModel.setWeightType("1");
                tareModel.setValueFlag("2");
                tareModel.setIsPreScale("0");
                tareModel.setUpdateManNo(userId);
                tareModel.setUpdateManName(userName);
                tareModel.setUpdateTime(new Date());
                tareModel.setNote(note);
                meterWorkCarActualFirstMapper.updateByPrimaryKeySelective(tareModel);

                MeterWorkCarActual mwca = meterWorkCarActualMapper.manualAdd(grossModel.getActualFirstNo(), tareModel.getActualFirstNo());
                //更新结净数据状态
                mwca.setActualNo(PublicMethod.IdCreate(3));
                mwca.setNetMode(DbConstants.TYPE);
                mwca.setUpdateManNo(userId);
                mwca.setUpdateManName(userName);
                mwca.setNote(note);
                mwca.setUploadFlag("1");
                mwca.setIsPreScale("0");
                mwca.setValueFlag("1");
                if(mwca.getGrossTime().compareTo(mwca.getTareTime()) >= 0) {
                    mwca.setNetSpot3No(mwca.getBaseSpot1No());
                    mwca.setNetSpot3Name(mwca.getBaseSpot1Name());
                    mwca.setNetManNo(mwca.getGrossManNo());
                    mwca.setNetManName(mwca.getGrossManName());
                    mwca.setNetTime(mwca.getGrossTime());
                    mwca.setCreateTime(mwca.getGrossTime());
                    mwca.setCreateManName(mwca.getGrossManName());
                }else {
                    mwca.setNetSpot3No(mwca.getBaseSpot2No());
                    mwca.setNetSpot3Name(mwca.getBaseSpot2Name());
                    mwca.setNetManNo(mwca.getTareManNo());
                    mwca.setNetManName(mwca.getTareManName());
                    mwca.setNetTime(mwca.getTareTime());
                    mwca.setCreateTime(mwca.getTareTime());
                    mwca.setCreateManName(mwca.getTareManName());
                }
                mwca.setNetWeight(grossModel.getMeterWeight().subtract(tareModel.getMeterWeight()));
                meterWorkCarActualMapper.insertSelective(mwca);

                MeterBaseOperationLog logModel = new MeterBaseOperationLog();
                logModel.setId(PublicMethod.IdCreate(2));
                logModel.setCreateManNo(userId);
                logModel.setCreateManName(userName);
                logModel.setCreateTime(new Date());
                logModel.setOperationPage("C#端-本地计量一次数据维护");
                logModel.setOperationFunction("一次数据结净");
                logModel.setOperationId(mwca.getActualNo());
                logModel.setOperationPredictionNo(mwca.getPredictionNo());
                logModel.setOperationCarnNo(mwca.getCarNo());
                logModel.setOperationBeforeFix(mwca.getActualFirst1No() + "+" + mwca.getActualFirst2No());
                logModel.setOperationAfterFix("");
                meterBaseOperationLogMapper.insertSelective(logModel);
            }
            rm.setSucceed(true);
            rm.setMessage("操作成功");
            rm.setCode("200");
        }catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            rm.setMessage("操作异常：>>>>" + e.getMessage());
        }
        return rm;
    }

    @Override
    @Transactional
    public RESTfulResult localRecoveryOrAbolishByFirstNo(MeterWorkCarActualFirst firstModel) {
        RESTfulResult rm = new RESTfulResult();
        rm.setFailed();
        try{
            if(StringUtils.isEmpty(firstModel.getActualFirstNo())) {
                rm.setMessage("一次作业编号不能为空！");
                return rm;
            }
            MeterWorkCarActualFirst first = meterWorkCarActualFirstMapper.selectByPrimaryKey(firstModel.getActualFirstNo());
            MeterWorkCarActualFirst firstTemp = first;
            if(first == null) {
                rm.setMessage("根据一次作业编号【" + firstModel.getActualFirstNo() + "】未查询到有效的一次数据！");
                return rm;
            }

            String userId = firstModel.getUpdateManNo();
            String userName = firstModel.getUpdateManName();
            String note = firstModel.getNote();
            String flag = firstModel.getMemo();
            if(flag.contains("启用")) {
                first.setValueFlag("1");
                first.setUpdateManNo(userId);
                first.setUpdateManName(userName);
                first.setUpdateTime(new Date());
                first.setNote(note);
                meterWorkCarActualFirstMapper.updateByPrimaryKeySelective(first);

                MeterBaseOperationLog logModel = new MeterBaseOperationLog();
                logModel.setId(PublicMethod.IdCreate(2));
                logModel.setCreateManNo(userId);
                logModel.setCreateManName(userName);
                logModel.setCreateTime(new Date());
                logModel.setOperationPage("C#端-本地计量一次数据维护");
                logModel.setOperationFunction("启用");
                logModel.setOperationId(first.getActualFirstNo());
                logModel.setOperationPredictionNo(first.getPredictionNo());
                logModel.setOperationCarnNo(first.getCarNo());
                logModel.setOperationBeforeFix(firstTemp.toString());
                logModel.setOperationAfterFix(first.toString());
                meterBaseOperationLogMapper.insertSelective(logModel);
            }else if (flag.contains("作废")) {
                if(StringUtils.isNotEmpty(first.getPredictionNo())) {
                    rm.setMessage("一次作业编号【" + first.getActualFirstNo() + "】所对应的一次数据已匹配委托不能进行作废，请撤销委托之后在进行此操作！");
                    return rm;
                }
                first.setValueFlag("0");
                first.setUpdateManNo(userId);
                first.setUpdateManName(userName);
                first.setUpdateTime(new Date());
                first.setNote(note);
                meterWorkCarActualFirstMapper.updateByPrimaryKeySelective(first);

                MeterBaseOperationLog logModel = new MeterBaseOperationLog();
                logModel.setId(PublicMethod.IdCreate(2));
                logModel.setCreateManNo(userId);
                logModel.setCreateManName(userName);
                logModel.setCreateTime(new Date());
                logModel.setOperationPage("C#端-本地计量一次数据维护");
                logModel.setOperationFunction("作废");
                logModel.setOperationId(first.getActualFirstNo());
                logModel.setOperationPredictionNo(first.getPredictionNo());
                logModel.setOperationCarnNo(first.getCarNo());
                logModel.setOperationBeforeFix(firstTemp.toString());
                logModel.setOperationAfterFix(first.toString());
                meterBaseOperationLogMapper.insertSelective(logModel);
            }
            rm.setSucceed(true);
            rm.setMessage("操作成功");
            rm.setCode("200");
        }catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            rm.setMessage("操作异常：>>>>" + e.getMessage());
        }
        return rm;
    }

    @Override
    public RESTfulResult localMatch(String actualFirstNo, String predictionNo, String updateManNo, String updateManName) {
        RESTfulResult rm = new RESTfulResult();
        rm.setFailed();
        try {
            String userId = updateManNo;
            String userName = updateManName;

            Assert.isTrue(StringUtils.isNotEmpty(actualFirstNo), "作业编号为空");
            Assert.isTrue(StringUtils.isNotEmpty(predictionNo), "预报编号为空");
            PreTrackScale pts = preTrackScaleMapper.selectByPrimaryKey(predictionNo);
            Assert.isTrue(pts != null, "委托编号：" + predictionNo + "未查询到有效委托信息");
            Assert.isTrue(!pts.getValueFlag().equals("9"), "委托编号：" + predictionNo + "已结算不允许匹配委托");
            MeterWorkCarActualFirst model = meterWorkCarActualFirstMapper.selectByPrimaryKey(actualFirstNo);
            Assert.isTrue(model != null, "一次数据不存在");
            Assert.isTrue(!model.getValueFlag().equals("2"), "一次数据已结净,不允许匹配委托，请在结净数据维护中进行结净匹配委托");
            Assert.isTrue(model.getPredictionNo() == null && StringUtils.isEmpty(model.getPredictionNo()), "一次数据已匹配,不允许匹配委托");

            //操作日志
            MeterBaseOperationLog logModel = new MeterBaseOperationLog();
            logModel.setId(PublicMethod.IdCreate(2));
            logModel.setCreateManNo(userId);
            logModel.setCreateManName(userName);
            logModel.setCreateTime(new Date());
            logModel.setOperationPage("C#端-本地计量一次数据维护");
            logModel.setOperationFunction("匹配委托");
            logModel.setOperationId(model.getActualFirstNo());
            logModel.setOperationPredictionNo(model.getPredictionNo());
            logModel.setOperationCarnNo(model.getCarNo());
            logModel.setOperationBeforeFix(model.toString());

            //匹配委托操作
            MeterWorkCarActualFirst modelTemp = meterWorkCarActualFirstMapper.selectAndMatch(actualFirstNo, pts.getPredictionNo());
            BeanUtils.copyProperties(modelTemp, model);
            model.setIsPreScale("1");
            model.setUpdateManNo(userId);
            model.setUpdateManName(userName);
            model.setUpdateTime(new Date());
            model.setNote("一次数据匹配委托");
            model.setPredictionNo(pts.getPredictionNo());
            meterWorkCarActualFirstMapper.updateByPrimaryKeySelective(model);

            pts.setUpdateTime(new Date());
            pts.setUpdateManNo(userId);
            pts.setUpdateManName(userName);
            pts.setValueFlag(DbConstants.IN); //2021年5月24日  预报直接就写成【使用中】
            pts.setUploadFlag("1");
            pts.setPredictionType("1");
            pts.setMeasureStation(model.getBaseSpotNo());
            pts.setMeasureStationName(model.getBaseSpotName());
            preTrackScaleMapper.updateByPrimaryKeySelective(pts);

            logModel.setOperationAfterFix(model.toString());
            meterBaseOperationLogMapper.insertSelective(logModel);

            rm.setSucceed();
            rm.setCode("200");
            rm.setMessage("匹配委托成功");
            rm.setData(model);
        }catch (Exception e) {
            e.printStackTrace();
            rm.setMessage("操作异常：>>>" + e.getMessage());
        }
        return rm;
    }

    @Override
    @Transactional
    public int localRemove(List<MeterWorkCarActualFirst> models){
        try {
            String userId = models.get(0).getUpdateManNo();
            String userName = models.get(0).getUpdateManName();
            String note = models.get(0).getNote();

            int num = 0;
            Assert.isTrue(models != null && models.size() >= 1, "参数为空!!");

            for(MeterWorkCarActualFirst model: models) {
                MeterWorkCarActualFirst modelTemp = meterWorkCarActualFirstMapper.selectByPrimaryKey(model.getActualFirstNo());
                if(modelTemp != null) {
                    if(modelTemp.getValueFlag().equals("0") || modelTemp.getValueFlag().equals("2")) {
                        throw new MarkerMetException(500, "当前一次数据已结净或者已作废，不允许解除托!!");
                    }
                }
                PreTrackScale pls = preTrackScaleMapper.selectByPrimaryKey(model.getPredictionNo());
                Assert.isTrue(!pls.getValueFlag().equals("9"), "一次数据中包含已结算的委托!!");
            }

            for (MeterWorkCarActualFirst model : models) {
                Assert.isTrue(StringUtils.isNotEmpty(model.getPredictionNo()), "该条数据还未匹配！！");
                PreTrackScale pls = preTrackScaleMapper.selectByPrimaryKey(model.getPredictionNo());
                Assert.isTrue(pls != null, "数据对应的委托不存在!!");
                pls.setUpdateTime(new Date());
                pls.setUpdateManNo(userId);
                pls.setUpdateManName(userName);
                pls.setValueFlag(DbConstants.VALID);
                pls.setUploadFlag("1");
                preTrackScaleMapper.updateByPrimaryKeySelective(pls);

                //操作日志
                MeterBaseOperationLog logModel = new MeterBaseOperationLog();
                logModel.setId(PublicMethod.IdCreate(2));
                logModel.setCreateManNo(userId);
                logModel.setCreateManName(userName);
                logModel.setCreateTime(new Date());
                logModel.setOperationPage("C#端-本地计量一次数据维护");
                logModel.setOperationFunction("撤销委托");
                logModel.setOperationId(model.getActualFirstNo());
                logModel.setOperationPredictionNo(model.getPredictionNo());
                logModel.setOperationCarnNo(model.getCarNo());
                logModel.setOperationBeforeFix(model.toString());

                MeterWorkCarActualFirst mwcaf = meterWorkCarActualFirstMapper.selectAndRemove(model.getActualFirstNo());
                String actualFirstNo = mwcaf.getActualFirstNo();
                //当一次计量数据是已结净的状态时，同时将该结净数据的另一条一次计量数据自动匹配该委托，并将该结净记录也进行委托匹配
                if (mwcaf.getValueFlag().equals("2")){
                    MeterWorkCarActual meterWorkCarActual = meterWorkCarActualMapper.selectActual(actualFirstNo);
                    String getActualFirstNo = "";
                    //判断传入的是哪条一次记录
                    if (meterWorkCarActual.getActualFirst1No().equals(actualFirstNo)){
                        getActualFirstNo = meterWorkCarActual.getActualFirst2No();
                    }
                    if (meterWorkCarActual.getActualFirst2No().equals(actualFirstNo)){
                        getActualFirstNo = meterWorkCarActual.getActualFirst1No();
                    }
                    //另一条一次数据进行委托解除
                    MeterWorkCarActualFirst meterWorkCarActualFirst1 = meterWorkCarActualFirstMapper.selectAndRemove(getActualFirstNo);
                    meterWorkCarActualFirst1.setIsPreScale("0");
                    meterWorkCarActualFirstMapper.updateByPrimaryKey(meterWorkCarActualFirst1);
                    //将该一次记录的结净数据委托解除
                    MeterWorkCarActual mwca = meterWorkCarActualMapper.cleanPredcition(meterWorkCarActual.getActualNo());
                    mwca.setIsPreScale("0");
                    meterWorkCarActualMapper.updateByPrimaryKey(mwca);
                }

                // 将一次计量数据设置为未匹配状态
                //mwcaf.setValueFlag("2");
                mwcaf.setUpdateManNo(userId);
                mwcaf.setUpdateManName(userName);
                mwcaf.setUpdateTime(new Date());
                mwcaf.setNote(note);
                mwcaf.setIsPreScale("0");
                meterWorkCarActualFirstMapper.updateByPrimaryKey(mwcaf);

                logModel.setOperationAfterFix(mwcaf.toString());
                meterBaseOperationLogMapper.insertSelective(logModel);
                num++;
            }
            return num;
        } catch (MarkerMetException e) {
            throw e;
        }
    }

    //===========================eason add 2023-04-10 针对单机计量=================================
    @Override
    @Transactional(rollbackFor = Exception.class)
    public RESTfulResult addDj(MeterWorkCarActualFirst model, MeterMonitorNote note) throws Exception {
        RESTfulResult rm = new RESTfulResult();
        rm.setFailed();
        try {
            ckeck1(model);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            String afl = sdf.format(new Date());
//            String no = meterWorkCarActualFirstMapper.getNewID(afl);
//            model.setActualFirstNo(sdf.format(new Date()) + no);
            String no = PublicMethod.IdCreate(3);
            model.setActualFirstNo(no);

            if(StringUtils.isNotEmpty(model.getPredictionNo())){
                PreTrackScale pre = new PreTrackScale();
                pre.setPredictionNo(model.getPredictionNo());
                pre.setLineDesc("0");
                preTrackScaleMapper.updateByPrimaryKeySelective(pre);
            }

            //6、存储图片
            //SaveImg(model);

            //7、修改计量监控
            //updateMonitor(model.getBaseSpotNo());

            //8、修改监控的计量作业编号
            //updateMonitorOver(model.getActualFirstNo(), model.getBaseSpotNo());

            //信息加密
            String str = model.getActualFirstNo() + "," + model.getMeterWeight() + "," + "1";
            String enStr = encryption(str);

            //保存日志
            saveNote(note);

            //当存储一次数据或者结净时，将本车辆的预处理重量改为已使用
            updatePreWeight(model.getCarNo());
            if(StringUtils.isEmpty(model.getValueFlag())){
                model.setValueFlag("1");
            }
            if(StringUtils.isNotEmpty(model.getPredictionNo())){
                model.setIsPreScale("1");
            }
            model.setCreateTime(new Date());
            int num = meterWorkCarActualFirstMapper.insertSelective(model);
            rm.setSucceed();
            rm.setCode("200");
            rm.setData(model.getActualFirstNo());
            rm.setMessage(enStr);
            return rm;
        } catch (MarkerMetException e) {
            throw e;
        }
    }


    @Override
    @Transactional(value = "tm", rollbackFor = Exception.class)
    public RESTfulResult doAddNetDj(MeterWorkCarActualFirst secondDb, MeterWorkCarActual netDb, String saveTare, MeterMonitorNote note) throws Exception {
        RESTfulResult rm = new RESTfulResult();
        rm.setFailed();
        rm.setCode("500");
        try{
            //1、存储当前计量的数据
            SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
            String no = PublicMethod.IdCreate(3);
            secondDb.setActualFirstNo(no);

            secondDb.setValueFlag("2");//结净
            secondDb.setCreateTime(new Date());
            meterWorkCarActualFirstMapper.insertSelective(secondDb);

            //修改一次计量数据为结净
            MeterWorkCarActualFirst firstUpdate = new MeterWorkCarActualFirst();
            //2、存储结净数据
            if (secondDb.getMeterWeight().equals(netDb.getTareWeight())) {
                //二次重量如果跟皮重一样
                netDb.setActualFirst2No(secondDb.getActualFirstNo());
                netDb.setTareTime(secondDb.getCreateTime());
                netDb.setBaseSpot2No(secondDb.getBaseSpotNo());
                netDb.setBaseSpot2Name(secondDb.getBaseSpotName());
                MeterWorkCarActualFirst modelTemp = meterWorkCarActualFirstMapper.selectByPrimaryKey(netDb.getActualFirst1No());
                if(modelTemp != null) {
                    netDb.setBaseSpot1No(modelTemp.getBaseSpotNo());
                    netDb.setBaseSpot1Name(modelTemp.getBaseSpotName());
                }
                firstUpdate.setActualFirstNo(netDb.getActualFirst1No());
                firstUpdate.setWeightType("0");
            } else {
                netDb.setActualFirst1No(secondDb.getActualFirstNo());
                netDb.setGrossTime(secondDb.getCreateTime());
                netDb.setBaseSpot1No(secondDb.getBaseSpotNo());
                netDb.setBaseSpot1Name(secondDb.getBaseSpotName());
                MeterWorkCarActualFirst modelTemp = meterWorkCarActualFirstMapper.selectByPrimaryKey(netDb.getActualFirst2No());
                if(modelTemp != null) {
                    netDb.setBaseSpot2No(modelTemp.getBaseSpotNo());
                    netDb.setBaseSpot2Name(modelTemp.getBaseSpotName());
                }
                firstUpdate.setActualFirstNo(netDb.getActualFirst2No());
                firstUpdate.setWeightType("1");
            }

            //3、修改第一次存储的计量数据状态为结净
            if (firstUpdate.getActualFirstNo() != null) {
                firstUpdate.setValueFlag("2");
                meterWorkCarActualFirstMapper.updateByPrimaryKeySelective(firstUpdate);
            }

            //判断结净数据是否匹配委托
            if (StringUtils.isNotEmpty(netDb.getPredictionNo())) {
                MeterWorkCarActualFirst meca1 = meterWorkCarActualFirstMapper.selectAndMatch(netDb.getActualFirst1No(), netDb.getPredictionNo());
                meca1.setIsPreScale("1");
                MeterWorkCarActualFirst meca2 = meterWorkCarActualFirstMapper.selectAndMatch(netDb.getActualFirst2No(), netDb.getPredictionNo());
                meca2.setIsPreScale("1");
                meterWorkCarActualFirstMapper.updateByPrimaryKeySelective(meca1);
                meterWorkCarActualFirstMapper.updateByPrimaryKeySelective(meca2);

                PreTrackScale preTrackScale = new PreTrackScale();
                preTrackScale.setPredictionNo(netDb.getPredictionNo());
                preTrackScale.setValueFlag("2");
                preTrackScale.setUploadFlag("1");
                preTrackScale.setLineDesc("0");
                preTrackScale.setMeasureStation(netDb.getNetSpot3No());
                preTrackScale.setMeasureStationName(netDb.getNetSpot3Name());
                preTrackScaleMapper.updateByPrimaryKeySelective(preTrackScale);
                PreTrackScale pres = preTrackScaleMapper.selectBypredictionNo(netDb.getPredictionNo());
                if(pres != null && pres.getReceiverRemark() != null && (pres.getReceiverRemark().equals("H01") || pres.getReceiverRemark().equals("H02"))){
                    netDb.setPredictionType("7");
                }
            }

            String no1 = PublicMethod.IdCreate(3);
            netDb.setActualNo(no1);
            if (netDb != null && netDb.getNetWeight() != null) {
                //2021年3月7日 净重保留两位小数；
                BigDecimal net;
                net = new BigDecimal(String.valueOf(netDb.getNetWeight())).setScale(2, BigDecimal.ROUND_HALF_UP);
                netDb.setNetWeight(net);
            }
            netDb.setUploadFlag("1");
            netDb.setCreateTime(new Date());
            if(netDb.getGrossTime().compareTo(netDb.getTareTime()) >= 0) {
                netDb.setNetSpot3No(netDb.getBaseSpot1No());
                netDb.setNetSpot3Name(netDb.getBaseSpot1Name());
                netDb.setNetManNo(netDb.getGrossManNo());
                netDb.setNetManName(netDb.getGrossManName());
                netDb.setNetTime(netDb.getGrossTime());
                netDb.setCreateTime(netDb.getGrossTime());
                netDb.setCreateManName(netDb.getGrossManName());
            }else {
                netDb.setNetSpot3No(netDb.getBaseSpot2No());
                netDb.setNetSpot3Name(netDb.getBaseSpot2Name());
                netDb.setNetManNo(netDb.getTareManNo());
                netDb.setNetManName(netDb.getTareManName());
                netDb.setNetTime(netDb.getTareTime());
                netDb.setCreateTime(netDb.getTareTime());
                netDb.setCreateManName(netDb.getTareManName());
            }
            meterWorkCarActualMapper.insert(netDb);

            //4、如果为期限皮重，则将期限皮重转化为一条皮重计量数据保存
            //**************实际上下面的这坨代码没啥用所以删除了**************
            //*******************************end*****************************************

            //4、存储历史皮重及历史皮重明细信息
            if ("1".equals(saveTare)) {
                MeterWorkCarActualFirst oci = new MeterWorkCarActualFirst();
                oci.setCarNo(netDb.getCarNo());
                oci.setCreateTime(netDb.getTareTime());
                oci.setBaseSpotNo(netDb.getBaseSpot2No());
                oci.setBaseSpotName(netDb.getBaseSpot2Name());
                oci.setMeterWeight(netDb.getTareWeight());
                oci.setActualFirstNo(netDb.getActualFirst2No());
                doSaveHisTare(oci);
            }



            //保存日志
            saveNote(note);
            //当存储一次数据或者结净时，将本车辆的预处理重量改为已使用
            updatePreWeight(secondDb.getCarNo());

            //6、修改计量监控
            //updateMonitor(secondDb.getBaseSpotNo());
            //updateMonitorOver(secondDb.getActualFirstNo(), secondDb.getBaseSpotNo());

            //重量类型为毛重则调用接口为
            String flag = "";
            //补充附加重量的数据
            if (StringUtils.isNotEmpty(secondDb.getAddWgtPk())) {
                insertAddWgtNo(secondDb.getActualFirstNo(), secondDb.getAddWgtPk(), secondDb.getCreateManNo(), secondDb.getCreateManName());
            }
            rm.setSucceed();
            rm.setCode("200");
            rm.setData(secondDb.getActualFirstNo());
            rm.setMessage(flag);
            return rm;
        }catch (Exception e){
            e.printStackTrace();
            rm.setFailed();
            rm.setMessage(e.getMessage());
            return rm;
        }
    }
}

