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

import com.jisco.dynamicweight.util.UserUtil;
import com.steerinfo.baseinfo.combaseinfo.mapper.ComBaseInfoMapper;
import com.steerinfo.baseinfo.meterbaseoperationlog.mapper.MeterBaseOperationLogMapper;
import com.steerinfo.baseinfo.meterbaseoperationlog.model.MeterBaseOperationLog;
import com.steerinfo.baseinfo.meterbaserailwayaiweight.mapper.MeterBaseRailwayAiweightMapper;
import com.steerinfo.baseinfo.meterbaserailwayaiweight.model.MeterBaseRailwayAiweight;
import com.steerinfo.baseinfo.meterbaserailwayweight.mapper.MeterBaseRailwayWeightMapper;
import com.steerinfo.baseinfo.meterbaserailwayweight.model.MeterBaseRailwayWeight;
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.meterwork.constants.DbConstants;
import com.steerinfo.meterwork.constants.DjPbModel;
import com.steerinfo.meterwork.except.MarkerMetException;
import com.steerinfo.meterwork.meterworkcaractual.model.MeterWorkCarActual;
import com.steerinfo.meterwork.meterworkcaractualbak.model.MeterWorkCarActualBak;
import com.steerinfo.meterwork.meterworkcaractualfirst.model.MeterWorkCarActualFirst;
import com.steerinfo.meterwork.meterworkcaractualfirstbak.controller.MeterWorkCarActualFirstBakController;
import com.steerinfo.meterwork.meterworkcaractualfirstbak.model.MeterWorkCarActualFirstBak;
import com.steerinfo.meterwork.meterworkrailwayactfirst.mapper.MeterWorkRailwayActFirstMapper;
import com.steerinfo.meterwork.meterworkrailwayactfirst.model.MeterWorkRailwayActFirst;
import com.steerinfo.meterwork.meterworkrailwayactfirst.service.IMeterWorkRailwayActFirstService;
import com.steerinfo.meterwork.meterworkrailwayactfirstbak.mapper.MeterWorkRailwayActFirstBakMapper;
import com.steerinfo.meterwork.meterworkrailwayactfirstbak.model.MeterWorkRailwayActFirstBak;
import com.steerinfo.meterwork.meterworkrailwayactfirstbak.service.IMeterWorkRailwayActFirstBakService;
import com.steerinfo.meterwork.meterworkrailwayactual.mapper.MeterWorkRailwayActualMapper;
import com.steerinfo.meterwork.meterworkrailwayactual.model.MeterWorkRailwayActual;
import com.steerinfo.meterwork.meterworkrailwayactual.service.IMeterWorkRailwayActualService;
import com.steerinfo.meterwork.meterworkrailwayactualbak.mapper.MeterWorkRailwayActualBakMapper;
import com.steerinfo.meterwork.meterworkrailwayactualbak.model.MeterWorkRailwayActualBak;
import com.steerinfo.meterwork.meterworkrailwayactualbak.service.IMeterWorkRailwayActualBakService;
import com.steerinfo.meterwork.meterworkrailwaymotorialreceived.mapper.MeterWorkRailwayMotorialReceivedMapper;
import com.steerinfo.meterwork.meterworkrailwaymotorialreceived.model.MeterWorkRailwayMotorialReceived;
import com.steerinfo.meterwork.meterworkrailwayreceived.mapper.MeterWorkRailwayReceivedMapper;
import com.steerinfo.meterwork.meterworkrailwayreceived.model.MeterWorkRailwayReceived;
import com.steerinfo.pretrack.prerailwayscale.mapper.PreRailwayScaleMapper;
import com.steerinfo.pretrack.prerailwayscale.model.PreRailwayScale;
import com.steerinfo.pretrack.prerailwayscale.service.IPreRailwayScaleService;
import com.steerinfo.pretrack.pretrackscale.model.PreTrackScale;
import com.steerinfo.util.CommonPage;
import com.steerinfo.util.FieldsCollector;
import com.steerinfo.util.PublicMethod;
import com.steerinfo.util.StringUtils;
import io.micrometer.core.instrument.Meter;
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 javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

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

    @Resource
    private MeterWorkRailwayActualBakMapper meterWorkRailwayActualBakMapper;

    @Resource
    private MeterWorkRailwayActFirstBakMapper meterWorkRailwayActFirstBakMapper;

    @Resource
    private MeterWorkRailwayReceivedMapper meterWorkRailwayReceivedMapper;

    @Resource
    private MeterBaseRailwayAiweightMapper meterBaseRailwayAiweightMapper;

    @Resource
    private MeterBaseOperationLogMapper meterBaseOperationLogMapper;

    @Resource
    private MeterBaseRailwayWeightMapper meterBaseRailwayWeightMapper;

    @Resource
    private PreRailwayScaleMapper preRailwayScaleMapper;

    @Resource
    private MeterWorkRailwayActualMapper meterWorkRailwayActualMapper;

    @Resource
    private MeterWorkRailwayActFirstMapper meterWorkRailwayActFirstMapper;

    @Resource
    private ComBaseInfoMapper comBaseInfoMapper;

    //二次计量方法，用于检化验接口表
    @Autowired
    IMeterWorkRailwayActFirstBakService meterWorkRailwayActFirstBakService;

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


    @Override
    protected IBaseMapper<MeterWorkRailwayActualBak, String> getMapper() {
        return meterWorkRailwayActualBakMapper;
    }

    @Override
    public int audit(List<MeterWorkRailwayActualBak> model) {
        int i = 0;
        if (model == null || model.size() < 1) {
            throw new MarkerMetException(500, "参数为空！！");
        }
        boolean flErr = false;
        for (MeterWorkRailwayActualBak mw : model) {
            check(mw);
            try {
                mw.setUploadFlag(DbConstants.VALID);
                meterWorkRailwayActualBakMapper.updateByPrimaryKeySelective(mw);
            } catch (Exception ex) {
                flErr = true;
            }
            i++;
        }
        return flErr ? 0 : i;
    }

    @Override
    public int unaudit(List<MeterWorkRailwayActualBak> model) {
        int i = 0;
        if (model == null || model.size() < 1) {
            throw new MarkerMetException(500, "参数为空！！");
        }
        boolean flErr = false;
        for (MeterWorkRailwayActualBak mw : model) {
            check(mw);
            try {
                mw.setUploadFlag(DbConstants.INVALID);
                meterWorkRailwayActualBakMapper.updateByPrimaryKeySelective(mw);
            } catch (Exception ex) {
                flErr = true;
            }
            i++;
        }
        return flErr ? 0 : i;
    }

    @Override
    public int cancel(MeterWorkRailwayActualBak model) {
        int i = 0;
        if (model == null) {
            throw new MarkerMetException(500, "参数为空！！");
        }
        if (model.getActualNo() == null || "".equals(model.getActualNo())) {
            throw new MarkerMetException(500, "数据主键为空");
        }
        if (model.getPredictionNo() == null || "".equals(model.getPredictionNo()) || "1".equals(model.getValueFlag())) {
            throw new MarkerMetException(500, "只有已匹配委托且已发布的数据才能进行撤销发布操作");
        }

        UserPayload userPayload = new UserPayload();
        String userName = userPayload.getUserName();
        String userId = userPayload.getUserCode();
        model.setValueFlag("1");
        model.setUpdateTime(new Date());
        model.setUpdateManName(userName);
        model.setUpdateManNo(userId);
        try {
            meterWorkRailwayActualBakMapper.updateByPrimaryKeySelective(model);
        } catch (Exception e) {
            throw e;
        }
        return ++i;
    }

    @Override
    public int publish(MeterWorkRailwayActualBak model) {
        int i = 0;
        if (model == null) {
            throw new MarkerMetException(500, "参数为空！！");
        }
        if (model.getActualNo() == null || "".equals(model.getActualNo())) {
            throw new MarkerMetException(500, "数据主键为空");
        }
        if (model.getPredictionNo() == null || "".equals(model.getPredictionNo()) || "2".equals(model.getValueFlag())) {
            throw new MarkerMetException(500, "只有已匹配委托且未发布的数据才能进行数据发布操作");
        }

        UserPayload userPayload = new UserPayload();
        String userName = userPayload.getUserName();
        String userId = userPayload.getUserCode();
        model.setValueFlag("2");
        model.setUploadFlag("1");
        model.setUpdateTime(new Date());
        model.setUpdateManName(userName);
        model.setUpdateManNo(userId);
        try {
            meterWorkRailwayActualBakMapper.updateByPrimaryKeySelective(model);
        } catch (Exception e) {
            throw e;
        }
        return ++i;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public MeterWorkRailwayActualBak clean(String actualFirstNo, String dataNo, String predictionNo) throws MarkerMetException {
        try {
            if (actualFirstNo == null && actualFirstNo.equals("")) {
                throw new MarkerMetException(500, "毛重数据编号为空");
            }
            if (dataNo == null && dataNo.equals("")) {
                throw new MarkerMetException(500, "皮重数据编号为空");
            }
            MeterWorkRailwayActFirstBak mwcaf1 = meterWorkRailwayActFirstBakMapper.selectByPrimaryKey(actualFirstNo);
            if (mwcaf1 == null) {
                throw new MarkerMetException(500, "未查询到相应的毛重数据！！");
            }

            MeterWorkRailwayActFirstBak mwcaf2 = meterWorkRailwayActFirstBakMapper.selectByPrimaryKey(dataNo);
            if (mwcaf2 == null) {
                throw new MarkerMetException(500, "未查询到相应的皮重数据！！");
            }
            if (mwcaf2.getMeterWeight().compareTo(mwcaf1.getMeterWeight()) == 1) {
                throw new MarkerMetException(500, "皮重重量大于毛重重量！！");
            }

            // 选中的是否为同一车的数据
            if (!mwcaf1.getRailwayNo().equals(mwcaf2.getRailwayNo())) {
                throw new MarkerMetException(500, "请选择同一车号的一次计量数据进行结净");
            }

            // 一次计量数据是否已经完成委托匹配
            if ((mwcaf1.getPredictionNo() != null && "".equals(mwcaf1.getPredictionNo())) || (mwcaf2.getPredictionNo() != null && "".equals(mwcaf2.getPredictionNo()))) {
                if (!mwcaf1.getPredictionNo().equals(mwcaf2.getPredictionNo())) {
                    throw new MarkerMetException(500, "选中的两条一次计量数据匹配的委托不一致，不允许进行结净操作！！！");
                } else if (predictionNo != null && !"".equals(predictionNo)) {
                    throw new MarkerMetException(500, "选中的两条一次计量数据已经匹配委托，请正确选择数据！！！");
                }
            }

            String preNo = "";
            Map<String, Object> repair = new HashMap<>();
            if (predictionNo == null){
                if (mwcaf1.getPredictionNo() == "" && mwcaf2.getPredictionNo() != ""){
                    preNo = mwcaf2.getPredictionNo();
                    repair.put("predictionNo",preNo);
                    repair.put("actualFirstNo",mwcaf1.getActualFirstNo());
                    meterWorkRailwayActFirstBakMapper.repairPre(repair);
                }
                if (mwcaf2.getPredictionNo() == "" && mwcaf2.getPredictionNo() != ""){
                    preNo = mwcaf1.getPredictionNo();
                    repair.put("predictionNo",preNo);
                    repair.put("actualFirstNo",mwcaf2.getActualFirstNo());
                    meterWorkRailwayActFirstBakMapper.repairPre(repair);
                }
                if(mwcaf2.getPredictionNo() != "" && mwcaf2.getPredictionNo() != ""){
                    preNo = mwcaf1.getPredictionNo();
                }
            }
            else {
                preNo = predictionNo;
            }

            //修改预报
            if (preNo != null && !"".equals(preNo)) {
                // 选中预报和选中一次计量数据中车号是否一致
                PreRailwayScale queryRow = preRailwayScaleMapper.selectByPrimaryKey(preNo);
                if (!mwcaf1.getRailwayNo().equals(queryRow.getRailwayNo())) {
                    throw new MarkerMetException(500, "选中预报中火车号与一次计量数据中火车号不一致！！！");
                }
                PreRailwayScale scale = new PreRailwayScale();
                scale.setPredictionNo(preNo);
                scale.setValueFlag(DbConstants.NET);
                scale.setUpdateTime(new Date());
                scale.setUpdateManNo("system");
                scale.setUploadFlag("1");
                scale.setUpdateManName("二次计量结净更新");
                scale.setMeasureStation(mwcaf2.getBaseSpotNo());
                scale.setMeasureStationName(mwcaf2.getBaseSpotName());
                preRailwayScaleMapper.updateByPrimaryKeySelective(scale);
            }

            MeterWorkRailwayActualBak actualRow = new MeterWorkRailwayActualBak();

            // 判断前端是否传入了预报编号
            if (predictionNo != null && !"".equals(predictionNo)) {
                // 根据一次计量数据和预报数据生成净重相关信息
                MeterWorkRailwayActFirstBak first1 = meterWorkRailwayActFirstBakMapper.selectAndMatch(actualFirstNo, predictionNo);
                BeanUtils.copyProperties(first1,mwcaf1);
                MeterWorkRailwayActFirstBak first2 = meterWorkRailwayActFirstBakMapper.selectAndMatch(dataNo, predictionNo);
                BeanUtils.copyProperties(first2, mwcaf2);
                MeterWorkRailwayActualBak mwca1 = meterWorkRailwayActualBakMapper.manualAddPre(actualFirstNo, dataNo, predictionNo);
                BeanUtils.copyProperties(mwca1, actualRow);
            } else {
                MeterWorkRailwayActualBak mwca2 = meterWorkRailwayActualBakMapper.manualAdd(actualFirstNo, dataNo);
                BeanUtils.copyProperties(mwca2, actualRow);
            }

            mwcaf1.setValueFlag(DbConstants.NET);
            meterWorkRailwayActFirstBakMapper.updateByPrimaryKey(mwcaf1);
            mwcaf2.setValueFlag(DbConstants.NET);
            meterWorkRailwayActFirstBakMapper.updateByPrimaryKey(mwcaf2);

            cleanCheck(actualRow);

            if (actualRow.getGrossTime().compareTo(actualRow.getTareTime()) == 1) {
                actualRow.setNetSpot3No(actualRow.getBaseSpot1No());
                actualRow.setNetSpot3Name(actualRow.getBaseSpot1Name());
            } else {
                actualRow.setNetSpot3No(actualRow.getBaseSpot2No());
                actualRow.setNetSpot3Name(actualRow.getBaseSpot2Name());
            }
            actualRow.setNetMode(DbConstants.TYPE);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            String no = meterWorkRailwayActualBakMapper.getNewID(sdf.format(new Date()));
            actualRow.setActualNo(sdf.format(new Date()) + no);
            actualRow.setNetWeight(mwcaf1.getMeterWeight().subtract(mwcaf2.getMeterWeight()));
            actualRow.setUploadFlag("1");
            if(mwcaf1.getLcNo().equals(mwcaf2.getLcNo())){
                actualRow.setLcNo(mwcaf1.getLcNo());
                actualRow.setCreateTime(new Date());
            }else{
                throw new MarkerMetException(500, "选中两条一次计量数据中列车车次不一致！！！");
            }
            actualRow.setCreateTime(new Date());
            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());
            }
            meterWorkRailwayActualBakMapper.insertSelective(actualRow);

            //预报的处理
            if (StringUtils.isNotEmpty(actualRow.getPredictionNo())) {
                PreRailwayScale prs = new PreRailwayScale();
                prs.setPredictionNo(actualRow.getPredictionNo());
                prs.setValueFlag(DbConstants.NET); //已结净
                prs.setUploadFlag("1");
                prs.setUpdateTime(new Date());
                prs.setUpdateManNo("system");
                prs.setUpdateManName("火车二次计量结净操作");
                prs.setMeasureStation(actualRow.getNetManName());
                prs.setMeasureStationName(actualRow.getNetSpot3Name());
                preRailwayScaleMapper.updateByPrimaryKeySelective(prs);
            }
            return actualRow;
        } catch (MarkerMetException e) {
            throw e;
        }
    }

    @Override
    public RESTfulResult cleanByfirstNoAndNotes(String actFirstNo01, String actFirstNo02, String predictionNo, String Notes) {
        RESTfulResult rm = new RESTfulResult();
        rm.setFailed();

        MeterWorkRailwayActFirstBak actFirst01 = meterWorkRailwayActFirstBakMapper.selectByPrimaryKey(actFirstNo01);
        MeterWorkRailwayActFirstBak actFirst02 = meterWorkRailwayActFirstBakMapper.selectByPrimaryKey(actFirstNo02);
        PreRailwayScale scale = preRailwayScaleMapper.selectByPrimaryKey(predictionNo);
        //存储结净记录
        MeterWorkRailwayActualBak actualRow = new MeterWorkRailwayActualBak();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        UserPayload payload = new UserPayload();
        String userId = payload.getUserCode();
        String userName = payload.getUserName();

        Assert.isTrue(actFirst01 != null || actFirst02 != null, "一次计量数据编号不存在于轨道衡一次计量表");
        Assert.isTrue(actFirst01.getRailwayNo().equals(actFirst02.getRailwayNo()), "请选择同一车号的一次计量数据进行结净");
        Assert.isTrue(actFirst01.getValueFlag().equals("1") || actFirst02.getValueFlag().equals("1"), "请选择有效的一次计量数据进行结净");
        if (actFirst01.getMeterWeight().compareTo(actFirst02.getMeterWeight()) == -1) {    //A小于B, 置换，始终保证A>B
            MeterWorkRailwayActFirstBak tempModel = new MeterWorkRailwayActFirstBak();
            BeanUtils.copyProperties(actFirst01, tempModel);
            BeanUtils.copyProperties(actFirst02, actFirst01);
            BeanUtils.copyProperties(tempModel, actFirst02);
        }

        if(scale != null) {
            //将委托中的编号和收发货的等数据拷贝进一次数据中
            MeterWorkRailwayActFirstBak first1 = meterWorkRailwayActFirstBakMapper.selectAndMatch(actFirst01.getActualFirstNo(), scale.getPredictionNo());
            BeanUtils.copyProperties(first1, actFirst01);
            MeterWorkRailwayActFirstBak first2 = meterWorkRailwayActFirstBakMapper.selectAndMatch(actFirst02.getActualFirstNo(), scale.getPredictionNo());
            BeanUtils.copyProperties(first2, actFirst02);

            //更新一次数据
            //更新第一次毛重数据库
            actFirst01.setWeightType("0");
            actFirst01.setValueFlag(DbConstants.NET);
            actFirst01.setUpdateManNo("system");
            actFirst01.setUpdateManName("匹配结净更新");
            actFirst01.setUpdateTime(new Date());
            actFirst01.setIsPreSacale("1");
            actFirst01.setPredictionNo(scale.getPredictionNo());
            actFirst01.setPredictionType("1");
            actFirst01.setNote(Notes);
            meterWorkRailwayActFirstBakMapper.updateByPrimaryKeySelective(actFirst01);
            //更新第一次皮重数据库
            actFirst02.setWeightType("1");
            actFirst02.setValueFlag(DbConstants.NET);
            actFirst02.setUpdateManNo("system");
            actFirst02.setUpdateManName("匹配结净更新");
            actFirst02.setUpdateTime(new Date());
            actFirst02.setIsPreSacale("1");
            actFirst02.setPredictionNo(scale.getPredictionNo());
            actFirst02.setPredictionType("1");
            actFirst02.setNote(Notes);
            meterWorkRailwayActFirstBakMapper.updateByPrimaryKeySelective(actFirst02);

            MeterWorkRailwayActualBak mwca = meterWorkRailwayActualBakMapper.manualAddPre(actFirst01.getActualFirstNo(), actFirst02.getActualFirstNo(), scale.getPredictionNo());
            BeanUtils.copyProperties(mwca, actualRow);

            actualRow.setActualNo(sdf.format(new Date()) + meterWorkRailwayActualBakMapper.getNewID(sdf.format(new Date())));
            actualRow.setUploadFlag("1");
            actualRow.setValueFlag("1");
            actualRow.setIsPreSacale("1");
            actualRow.setCreateTime(new Date());
            actualRow.setCreateManName(userName);
            actualRow.setNetTime(new Date());
            actualRow.setNote(Notes);
            actualRow.setLcNo(actFirst01.getLcNo());
            actualRow.setNetMode(DbConstants.TYPE);
            actualRow.setNetWeight(actFirst01.getMeterWeight().subtract(actFirst02.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());
            }
            meterWorkRailwayActualBakMapper.insertSelective(actualRow);

            scale.setValueFlag(DbConstants.NET);
            scale.setUpdateTime(new Date());
            scale.setUpdateManNo("system");
            scale.setUpdateManName("匹配结净更新");
            scale.setUploadFlag("1");
            scale.setPredictionType("1");
            scale.setMeasureStation(actualRow.getNetSpot3No());
            scale.setMeasureStationName(actualRow.getNetSpot3Name());
            preRailwayScaleMapper.updateByPrimaryKeySelective(scale);
        }else {
            MeterWorkRailwayActualBak mwca2 = meterWorkRailwayActualBakMapper.manualAdd(actFirst01.getActualFirstNo(), actFirst02.getActualFirstNo());
            BeanUtils.copyProperties(mwca2, actualRow);

            //标志位为结净
            actFirst01.setWeightType("0");
            actFirst01.setNote(Notes);
            actFirst01.setIsPreSacale("0");
            actFirst01.setValueFlag(DbConstants.NET);
            meterWorkRailwayActFirstBakMapper.updateByPrimaryKey(actFirst01);
            actFirst02.setWeightType("1");
            actFirst02.setNote(Notes);
            actFirst02.setIsPreSacale("0");
            actFirst02.setValueFlag(DbConstants.NET);
            meterWorkRailwayActFirstBakMapper.updateByPrimaryKey(actFirst02);

            cleanCheck(actualRow);

            if (actualRow.getGrossTime().compareTo(actualRow.getTareTime()) == 1) {
                actualRow.setNetSpot3No(actualRow.getBaseSpot1No());
                actualRow.setNetSpot3Name(actualRow.getBaseSpot1Name());
            } else {
                actualRow.setNetSpot3No(actualRow.getBaseSpot2No());
                actualRow.setNetSpot3Name(actualRow.getBaseSpot2Name());
            }
            actualRow.setActualNo(sdf.format(new Date()) + meterWorkRailwayActualBakMapper.getNewID(sdf.format(new Date())));
            actualRow.setUploadFlag("1");
            actualRow.setValueFlag("1");
            actualRow.setIsPreSacale("0");
            actualRow.setNote(Notes);
            actualRow.setLcNo(actFirst01.getLcNo());
            actualRow.setCreateManName(userName);
            actualRow.setCreateTime(new Date());
            actualRow.setNetTime(new Date());
            actualRow.setNetMode(DbConstants.TYPE);
            actualRow.setNetWeight(actFirst01.getMeterWeight().subtract(actFirst02.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());
            }
            meterWorkRailwayActualBakMapper.insertSelective(actualRow);
        }
        rm.setSucceed();
        rm.setData(actualRow);
        return rm;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public MeterWorkRailwayActualBak matchPrediction (String actualNo, String predictionNo, String note) throws MarkerMetException {
        if (actualNo == null || "".equals(actualNo)) {
            throw new MarkerMetException(500, "结净数据主键不能为空");
        }
        if (predictionNo == null || "".equals(predictionNo)) {
            throw new MarkerMetException(500, "委托编号不能为空");
        }
        MeterWorkRailwayActualBak queryrow = meterWorkRailwayActualBakMapper.selectByPrimaryKey(actualNo);
        if (queryrow != null) {
            if(StringUtils.isEmpty(queryrow.getIsPreSacale())){
                queryrow.setIsPreSacale("0");
            }
        }

        if (queryrow == null) {
            throw new MarkerMetException(500, "不存在对应的结净数据");
        } else if (!queryrow.getIsPreSacale().equals("0") && queryrow.getPredictionNo() != null) {
            throw new MarkerMetException(500, "只有未匹配的净重数据才能进行委托匹配操作");
        }
        PreRailwayScale prerow = preRailwayScaleMapper.selectByPrimaryKey(predictionNo);
        if (prerow == null) {
            throw new MarkerMetException(500, "不存在对应的委托数据");
        } else if (!prerow.getValueFlag().equals("1")) {
            throw new MarkerMetException(500, "只有未使用的委托才能进行匹配委托操作");
        }
        if (!queryrow.getRailwayNo().equals(prerow.getRailwayNo())) {
            throw new MarkerMetException(500, "结净数据中车号和预报中车号不一致，不允许进行匹配委托操作");
        }
        String userId;
        String userName;
        try{
            UserPayload payload = UserPayload.getCurrUser();
            userId = payload.getUserCode();
            userName = payload.getUserName();
        }catch (Exception e){
            userId = "admin";
            userName = "admins";
        }

        // 处理一次计量数据
        // 毛重
        MeterWorkRailwayActFirstBak grossrow = meterWorkRailwayActFirstBakMapper.selectAndMatch(queryrow.getActualFirst1No(), predictionNo);
        grossrow.setUpdateTime(new Date());
        grossrow.setUpdateManNo(userId);
        grossrow.setUpdateManName(userName);
        grossrow.setNote("结净数据匹配委托操作");
        grossrow.setIsPreSacale("1");
        meterWorkRailwayActFirstBakMapper.updateByPrimaryKey(grossrow);

        // 皮重       特殊情况：标识皮重过磅，会导致没有皮重信息，就直接跳过
        try{
            MeterWorkRailwayActFirstBak tarerow = meterWorkRailwayActFirstBakMapper.selectAndMatch(queryrow.getActualFirst2No(), predictionNo);
            tarerow.setUpdateTime(new Date());
            tarerow.setUpdateManNo(userId);
            tarerow.setUpdateManName(userName);
            tarerow.setNote("结净数据匹配委托操作");
            tarerow.setIsPreSacale("1");
            meterWorkRailwayActFirstBakMapper.updateByPrimaryKey(tarerow);
        }catch(Exception e) {

        }

        MeterWorkRailwayActualBak mwca = meterWorkRailwayActualBakMapper.mathPredcition(actualNo, predictionNo);
        mwca.setValueFlag("1");
        mwca.setIsPreSacale("1");
        mwca.setPredictionType("1");
        mwca.setUploadFlag("1");
//        mwca.setNote(note); 添加修改原因记录
        meterWorkRailwayActualBakMapper.updateByPrimaryKey(mwca);

        // 处理预报
        if (StringUtils.isNotEmpty(predictionNo)) {
            PreRailwayScale scale = new PreRailwayScale();
            scale.setPredictionNo(predictionNo);
            scale.setValueFlag("2");
            scale.setUploadFlag("1");
            scale.setUpdateTime(new Date());
            scale.setUpdateManNo("system");
            scale.setUpdateManName("计量结净数据匹配委托操作");
            scale.setMeasureStation(mwca.getNetSpot3No());
            scale.setMeasureStationName(mwca.getNetSpot3Name());
            preRailwayScaleMapper.updateByPrimaryKeySelective(scale);
        }

        MeterBaseOperationLog logModel = new MeterBaseOperationLog();
        logModel.setId(PublicMethod.IdCreate(2));
        logModel.setCreateManNo(userId);
        logModel.setCreateManName(userName);
        logModel.setCreateTime(new Date());
        logModel.setOperationPage("轨道衡数据补录-新净重补录数据");
        logModel.setOperationFunction("匹配委托");
        logModel.setOperationId(mwca.getActualNo());
        logModel.setOperationPredictionNo(predictionNo);
        logModel.setOperationCarnNo(mwca.getRailwayNo());
        logModel.setOperationBeforeFix(queryrow.toString());
        logModel.setOperationAfterFix(mwca.toString());
        meterBaseOperationLogMapper.insertSelective(logModel);
        return mwca;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int addData (MeterWorkRailwayActualBak model) throws MarkerMetException {
        if (model.getActualFirst1No() == null || "".equals(model.getActualFirst1No())) {
            throw new MarkerMetException(500, "毛重数据主键不能为空");
        }
        if (model.getRailwayNo() == null || "".equals(model.getRailwayNo())) {
            throw new MarkerMetException(500, "火车号不能为空");
        }
        if (model.getPredictionNo() == null || "".equals(model.getPredictionNo())) {
            throw new MarkerMetException(500, "选中的毛重数据需要先匹配委托");
        }
        MeterWorkRailwayActFirstBak queryrow = meterWorkRailwayActFirstBakMapper.selectByPrimaryKey(model.getActualFirst1No());
        if (queryrow == null) {
            throw new MarkerMetException(500, "不存在对应的毛重数据");
        }
        UserPayload payload = UserPayload.getCurrUser();
        String userId = payload.getUserCode();
        String userName = payload.getUserName();

        // 处理一次计量数据
        // 毛重
        queryrow.setUpdateTime(new Date());
        queryrow.setUpdateManName(userName + ": 一次数据输入历史皮重结净操作");
        queryrow.setUpdateManNo(userId);
        queryrow.setValueFlag("2");
        meterWorkRailwayActFirstBakMapper.updateByPrimaryKey(queryrow);

        // 新增一条皮重
        MeterWorkRailwayActFirstBak tarerow = new MeterWorkRailwayActFirstBak();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        Date time = new Date();
        String idNo = sdf.format(new Date()) + meterWorkRailwayActFirstBakMapper.getNewID(sdf.format(time));
        tarerow.setActualFirstNo(idNo);
        tarerow.setRailwayNo(model.getRailwayNo());
        tarerow.setMeterWeight(model.getTareWeight());
        tarerow.setCreateManName(userName);
        tarerow.setCreateManNo(userId);
        tarerow.setCreateTime(new Date());
        tarerow.setMeterMode("3");
        tarerow.setDataSource(queryrow.getDataSource());
        tarerow.setMemo("静轨一次计量数据输入历史皮重结净操作新增皮重数据");
        tarerow.setValueFlag("2");
        tarerow.setWeightType("3");
        int num1 = meterWorkRailwayActFirstBakMapper.insertSelective(tarerow);

        // 新增净重数据
        String idNo2 = sdf.format(new Date()) + meterWorkRailwayActFirstBakMapper.getNewID(sdf.format(time));
        model.setActualNo(idNo2);
        model.setTareManName(userName);
        model.setTareManNo(userId);
        model.setTareTime(time);
        model.setNetMode("2");
        model.setTareMode("3");
        model.setNetTime(time);
        model.setNetManName(userName);
        model.setNetManNo(userId);
        model.setDataSource(queryrow.getDataSource());
        model.setValueFlag("1");
        model.setUploadFlag("1");
//        model.setNote(); // 添加修改原因记录
        model.setCreateTime(new Date());
        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());
        }
        int num = meterWorkRailwayActualBakMapper.insertSelective(model);

        // 处理预报信息
        PreRailwayScale pres = new PreRailwayScale();
        pres.setPredictionNo(model.getPredictionNo());
        pres.setValueFlag("2");
        pres.setUploadFlag("1");
        pres.setUpdateManName(userName+ ": 使用历史皮重结净操作");
        pres.setUpdateTime(new Date());
        pres.setUpdateManNo(userId);
        pres.setMeasureStation(model.getNetSpot3No());
        pres.setMeasureStationName(model.getNetSpot3Name());
        preRailwayScaleMapper.updateByPrimaryKeySelective(pres);
        return num;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public MeterWorkRailwayActualBak cleanPrediction (MeterWorkRailwayActualBak model) throws MarkerMetException {
        if (model.getActualNo() == null || "".equals(model.getActualNo())) {
            throw new MarkerMetException(500, "结净数据主键不能为空");
        }
        if (!model.getValueFlag().equals("1") && model.getPredictionNo() != null && !"".equals(model.getPredictionNo())) {
            throw new MarkerMetException(500, "只有有效已匹配的结净数据才能进行解除操作");
        }
        MeterWorkRailwayActualBak mwcaquery = meterWorkRailwayActualBakMapper.selectByPrimaryKey(model.getActualNo());
        if (mwcaquery == null) {
            throw new MarkerMetException(500, "不存在对应的结净数据");
        }
        if(model.getPredictionNo() != null && StringUtils.isNotEmpty(model.getPredictionNo())){
            PreRailwayScale scaleTemp = preRailwayScaleMapper.selectByPrimaryKey(model.getPredictionNo());
            if(scaleTemp.getValueFlag().equals("9")) {
                throw new MarkerMetException(500, "结净数据中包含已结算的委托");
            }
            if(scaleTemp.getPredictionType().equals("5") || scaleTemp.getPredictionType().equals("6") || scaleTemp.getPredictionType().equals("7")){
                throw new MarkerMetException(500, "结净数据中包含特殊委托匹配结净的数据!!!");
            }
        }

        UserPayload payload = UserPayload.getCurrUser();
        String userId = payload.getUserCode();
        String userName = payload.getUserName();

        // 处理一次计量数据
        // 毛重
        MeterWorkRailwayActFirstBak grossrow = meterWorkRailwayActFirstBakMapper.selectAndRemove(model.getActualFirst1No());
//        grossrow.setValueFlag("3");
        grossrow.setUpdateTime(new Date());
        grossrow.setUpdateManName(userName + ": 结净数据解除委托操作");
        grossrow.setUpdateManNo(userId);
        grossrow.setNote("结净数据解除委托操作");
        grossrow.setIsPreSacale("0");
        meterWorkRailwayActFirstBakMapper.updateByPrimaryKey(grossrow);

        // 皮重
        try{
            MeterWorkRailwayActFirstBak tarerow = meterWorkRailwayActFirstBakMapper.selectAndRemove(model.getActualFirst2No());
//        tarerow.setValueFlag("3");
            tarerow.setUpdateTime(new Date());
            tarerow.setUpdateManName(userName + ": 结净数据解除委托操作");
            tarerow.setUpdateManNo(userId);
            tarerow.setNote("结净数据解除委托操作");
            tarerow.setIsPreSacale("0");
            meterWorkRailwayActFirstBakMapper.updateByPrimaryKey(tarerow);
        }catch(Exception e) {

        }

        // 处理预报
        if (StringUtils.isNotEmpty(model.getPredictionNo())) {
            PreRailwayScale scale = new PreRailwayScale();
            scale.setPredictionNo(model.getPredictionNo());
            scale.setValueFlag("1");
            scale.setUploadFlag("1");
            scale.setUpdateTime(new Date());
            scale.setUpdateManNo(userId);
            scale.setUpdateManName(userName + ": 结净数据解除委托操作");
            preRailwayScaleMapper.updateByPrimaryKeySelective(scale);
        }
        MeterWorkRailwayActualBak mwca = meterWorkRailwayActualBakMapper.cleanPredcition(model.getActualNo());

        mwca.setUpdateManNo(userId);
        mwca.setUpdateManName(userName);
        mwca.setUpdateTime(new Date());
        mwca.setValueFlag("3");
        mwca.setIsPreSacale("0");
        mwca.setUploadFlag("1");
        meterWorkRailwayActualBakMapper.updateByPrimaryKey(mwca);

        MeterBaseOperationLog logModel = new MeterBaseOperationLog();
        logModel.setId(PublicMethod.IdCreate(2));
        logModel.setCreateManNo(userId);
        logModel.setCreateManName(userName);
        logModel.setCreateTime(new Date());
        logModel.setOperationPage("静态轨道衡-静轨净重数据维护");
        logModel.setOperationFunction("撤销委托");
        logModel.setOperationId(mwca.getActualNo());
        logModel.setOperationPredictionNo(model.getPredictionNo());
        logModel.setOperationCarnNo(mwca.getRailwayNo());
        logModel.setOperationBeforeFix(mwcaquery.toString());
        logModel.setOperationAfterFix(mwca.toString());
        meterBaseOperationLogMapper.insertSelective(logModel);
        return mwca;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int remove(List<MeterWorkRailwayActualBak> models) throws MarkerMetException {
        try {
            int num = 0;
            if (models.size() <= 0 || models == null) {
                throw new MarkerMetException(500, "参数为空！！！");
            }
            for(MeterWorkRailwayActualBak model: models) {
                if(model.getPredictionNo() != null && StringUtils.isNotEmpty(model.getPredictionNo())) {
                    throw new MarkerMetException(500, "结净数据已匹配委托，请撤销委托之后才能进行毛皮分解");
                }
//                if (StringUtils.isNotEmpty(model.getPredictionNo())) {
//                    PreRailwayScale scaleTemp = preRailwayScaleMapper.selectByPrimaryKey(model.getPredictionNo());
//                    if(scaleTemp.getValueFlag().equals("9")) {
//                        throw new MarkerMetException(500,"结净数据中包含已结算的委托！！！");
//                    }
//                    if(scaleTemp.getPredictionType().equals("5") || scaleTemp.getPredictionType().equals("6") || scaleTemp.getPredictionType().equals("7")){
//                        throw new MarkerMetException(500, "结净数据中包含特殊委托匹配结净的数据!!!");
//                    }
//                }
            }

            UserPayload userPayload = UserPayload.getCurrUser();
            String userId = userPayload.getUserCode();
            String userName = userPayload.getUserName();

            for (MeterWorkRailwayActualBak model : models) {
                //毛重
                MeterWorkRailwayActFirstBak grossrow = meterWorkRailwayActFirstBakMapper.selectByPrimaryKey(model.getActualFirst1No());
                if (grossrow == null) {
                    throw new MarkerMetException(500, "未查询到相应的毛重数据！！");
                }
                // 清空委托信息
//                MeterWorkRailwayActFirst grossrow = meterWorkRailwayActFirstBakMapper.selectAndRemove(model.getActualFirst1No());
                //grossrow.setValueFlag("3");
                //grossrow.setIsPreSacale("0");
                grossrow.setUpdateManNo(userId);
                grossrow.setUpdateManName(userName);
                grossrow.setUpdateTime(new Date());
                grossrow.setNote("结净数据毛皮分解");
//                grossrow.setUpdateManNo("system");
//                grossrow.setUpdateManName("静态衡解除操作");
//                grossrow.setUpdateTime(new Date());
                grossrow.setValueFlag("1");
                meterWorkRailwayActFirstBakMapper.updateByPrimaryKey(grossrow);
                //皮重
                MeterWorkRailwayActFirstBak mwcaf2 = meterWorkRailwayActFirstBakMapper.selectByPrimaryKey(model.getActualFirst2No());

//                MeterBaseRailwayWeight mbrw = meterBaseRailwayWeightMapper.selectByPrimaryKey(model.getActualFirst2No());
//                if (mwcaf2 == null) {
//                    throw new MarkerMetException(500, "未查询到相应的皮重数据！！");
//                }
//                // 清空委托信息
//                MeterWorkRailwayActFirst tarerow = meterWorkRailwayActFirstBakMapper.selectAndRemove(model.getActualFirst2No());
//                if (tarerow != null) {
//                    //tarerow.setValueFlag("3");
//                    tarerow.setIsPreSacale("0");
//                    tarerow.setUpdateManNo("system");
//                    tarerow.setUpdateManName("静态衡解除操作");
//                    tarerow.setUpdateTime(new Date());
//                    tarerow.setLcNo(model.getLcNo());
//                    tarerow.setValueFlag("1");
//                    meterWorkRailwayActFirstBakMapper.updateByPrimaryKey(tarerow);
//                }
                //未查询到相应的标识皮直接跳过
                if(mwcaf2 != null && mwcaf2.getMeterWeight().compareTo(model.getTareWeight().multiply(new BigDecimal(1000))) == 0) {
                    // 清空委托信息
//                MeterWorkRailwayActFirst tarerow = meterWorkRailwayActFirstBakMapper.selectAndRemove(model.getActualFirst2No());
                    MeterWorkRailwayActFirstBak tarerow = meterWorkRailwayActFirstBakMapper.selectByPrimaryKey(model.getActualFirst2No());
                if (tarerow != null) {
                    //tarerow.setValueFlag("3");
                    //tarerow.setIsPreSacale("0");
//                    tarerow.setUpdateManNo("system");
//                    tarerow.setUpdateManName("静态衡解除操作");
                    tarerow.setUpdateManNo(userId);
                    tarerow.setUpdateManName(userName);
                    tarerow.setUpdateTime(new Date());
                    tarerow.setNote("结净数据毛皮分解");
//                    tarerow.setLcNo(model.getLcNo());
                    tarerow.setValueFlag("1");
                    meterWorkRailwayActFirstBakMapper.updateByPrimaryKey(tarerow);
                }
                    //恢复标志标识皮数据
                    HashMap<String, Object> obj = new HashMap<>();
                    obj.put("railwayNo", model.getRailwayNo());
                    obj.put("valueFlag", "1");
                    List<MeterBaseRailwayAiweight> AIModel = meterBaseRailwayAiweightMapper.selectByParameters(obj);
                    if(AIModel.size() >= 1) {
                        AIModel.get(0).setValueFlag("0");
                        meterBaseRailwayAiweightMapper.updateByPrimaryKeySelective(AIModel.get(0));
                    }
                }

                if (StringUtils.isNotEmpty(model.getPredictionNo())) {
                    PreRailwayScale scale = new PreRailwayScale();
                    scale.setPredictionNo(model.getPredictionNo());
                    scale.setValueFlag("1"); //使用中
                    scale.setUploadFlag("1");
//                    scale.setUpdateManNo("system");
//                    scale.setUpdateManName("静态衡解除操作");
                    scale.setUpdateManNo(userId);
                    scale.setUpdateManName(userName);
                    scale.setUpdateTime(new Date());
                    preRailwayScaleMapper.updateByPrimaryKeySelective(scale);
                }
//                meterWorkRailwayActualBakMapper.deleteByPrimaryKey(model.getActualNo());
                model.setValueFlag("0");
                meterWorkRailwayActualBakMapper.updateByPrimaryKeySelective(model);
                num++;
            }
            return num;
        } catch (MarkerMetException e) {
            throw e;
        }
    }

    @Override
    public RESTfulResult removeDynamicModel(MeterWorkRailwayActualBak model) {
        RESTfulResult rm = new RESTfulResult();
        try {
            String userId, userName;
            try{
                UserPayload payload = UserPayload.getCurrUser();
                userId = payload.getUserCode();
                userName = payload.getUserName();
            }catch (Exception e){
                userId = "admin";
                userName = "admins";
            }

            if(model.getPredictionNo() != null && StringUtils.isNotEmpty(model.getPredictionNo())){
                PreRailwayScale scaleTemp = preRailwayScaleMapper.selectByPrimaryKey(model.getPredictionNo());
                if(scaleTemp.getValueFlag().equals("9")) {
                    throw new MarkerMetException(500, "结净数据中包含已结算的委托!!!");
                }
                if(scaleTemp.getPredictionType().equals("5") || scaleTemp.getPredictionType().equals("6") || scaleTemp.getPredictionType().equals("7")){
                    throw new MarkerMetException(500, "结净数据中包含特殊委托匹配结净的数据!!!");
                }
            }

            Assert.isTrue(Objects.nonNull(model.getActualNo()), "结净数据为空");
            if (StringUtils.isNotEmpty(model.getPredictionNo())) {
                PreRailwayScale scaleTemp = preRailwayScaleMapper.selectByPrimaryKey(model.getPredictionNo());
                Assert.isTrue(!scaleTemp.getValueFlag().equals("9"), "结净数据匹配的委托已结算");
            }

            //毛重
            MeterWorkRailwayActFirstBak mwcaf1 = meterWorkRailwayActFirstBakMapper.selectByPrimaryKey(model.getActualFirst1No());
            if (mwcaf1 != null && mwcaf1.getActualFirstNo()!= null && StringUtils.isNotEmpty(mwcaf1.getActualFirstNo())) {
                // 清空委托信息
                MeterWorkRailwayActFirstBak grossrow = meterWorkRailwayActFirstBakMapper.selectAndRemove(model.getActualFirst1No());
                grossrow.setValueFlag("1");
                grossrow.setIsPreSacale("0");
                grossrow.setUpdateManNo(userId);
                grossrow.setUpdateManName(userName);
                grossrow.setNote("动态衡解除操作");
                grossrow.setUpdateTime(new Date());
                grossrow.setLcNo(model.getLcNo());
                meterWorkRailwayActFirstBakMapper.updateByPrimaryKey(grossrow);
                //判断是从表数据，进行删除一次数据且恢复从表数据，不是则跳过
                doReceivedRemove(userId, userName, grossrow);
            }

            //皮重
            MeterWorkRailwayActFirstBak mwcaf2 = meterWorkRailwayActFirstBakMapper.selectByPrimaryKey(model.getActualFirst2No());
            if (mwcaf2 != null && mwcaf2.getActualFirstNo()!= null && StringUtils.isNotEmpty(mwcaf2.getActualFirstNo())) {
                // 清空委托信息
                MeterWorkRailwayActFirstBak tarerow = meterWorkRailwayActFirstBakMapper.selectAndRemove(model.getActualFirst2No());
                if (tarerow != null) {
                    tarerow.setValueFlag("1");
                    tarerow.setIsPreSacale("0");
                    tarerow.setUpdateManNo(userId);
                    tarerow.setUpdateManName(userName);
                    tarerow.setNote("动态衡解除操作");
                    tarerow.setLcNo(model.getLcNo());
                    meterWorkRailwayActFirstBakMapper.updateByPrimaryKey(tarerow);
                    doReceivedRemove(userId, userName, tarerow);
                }
            }

            //恢复标志标识皮数据
            HashMap<String, Object> obj = new HashMap<>();
            obj.put("railwayNo", model.getRailwayNo());
            obj.put("valueFlag", "1");
            List<MeterBaseRailwayAiweight> AIModel = meterBaseRailwayAiweightMapper.selectByParameters(obj);
            if(AIModel.size() >= 1) {
                AIModel.get(0).setValueFlag("0");
                meterBaseRailwayAiweightMapper.updateByPrimaryKeySelective(AIModel.get(0));
            }

            //委托
            if (model.getPredictionNo() != null && StringUtils.isNotEmpty(model.getPredictionNo())) {
                PreRailwayScale scale = new PreRailwayScale();
                scale.setPredictionNo(model.getPredictionNo());
                scale.setValueFlag("1"); //使用中
                scale.setUploadFlag("1");
                scale.setUpdateManNo(userId);
                scale.setUpdateManName(userName);
                scale.setUpdateTime(new Date());
                preRailwayScaleMapper.updateByPrimaryKeySelective(scale);
            }
            meterWorkRailwayActualBakMapper.deleteByPrimaryKey(model.getActualNo());
            rm.setSucceed();
            rm.setMessage("操作成功");
            rm.setData("操作成功");
            rm.setData("200");
        } catch (MarkerMetException e) {
            e.printStackTrace();
            rm.setMessage("操作异常:" + e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            rm.setMessage("操作异常:" + e.getMessage());
        }
        return rm;
    }

    //判断是从表数据，进行删除一次数据且恢复从表数据，不是则跳过
    public void doReceivedRemove(String userId, String userName, MeterWorkRailwayActFirstBak grossrow) {
        //恢复从表数据
        MeterWorkRailwayReceived receivedModel = meterWorkRailwayReceivedMapper.selectByPrimaryKey(grossrow.getActualFirstNo());
        if(receivedModel.getActualFirstNo() != null && StringUtils.isNotEmpty(receivedModel.getActualFirstNo())) {
            meterWorkRailwayActFirstBakMapper.deleteByPrimaryKey(grossrow.getActualFirstNo());
            receivedModel.setValueFlag("1");
            receivedModel.setUpdateManNo(userId);
            receivedModel.setUpdateManName(userName);
            receivedModel.setUpdateTime(new Date());
            meterWorkRailwayReceivedMapper.updateByPrimaryKeySelective(receivedModel);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<String> distinctRailwayNo(HashMap<String, Object> param) {
//        String railwayTypeNo = param.get("railwayTypeNo") == null ? "":param.get("railwayTypeNo").toString();
//        String lcNo = param.get("lcNo") == null ? "" : param.get("lcNo").toString();
//        String railwayNo = param.get("railwayNo") == null ? "":param.get("railwayNo").toString();
//        String startTime = param.get("startTime") == null ? "":param.get("startTime").toString();
//        String endTime = param.get("endTime") == null ? "":param.get("endTime").toString();;
//        String baseSpotName = param.get("baseSpotName") == null ? "": param.get("baseSpotName").toString();
//        String matterName = param.get("matterName") == null ? "": param.get("matterName").toString();
//        String predictionNo = param.get("predictionNo") == null ? "": param.get("predictionNo").toString();
//        String valueFlag = param.get("valueFlag") == null ? "":param.get("valueFlag").toString();
//
//        HashMap<String, Object> obj = new HashMap<>();
//        obj.put("railwayTypeNo", railwayTypeNo);
//        obj.put("railwayNo", railwayNo);
//        obj.put("lcNo", lcNo);
//        obj.put("startTime", startTime);
//        obj.put("endTime", endTime);
//        obj.put("baseSpotName", baseSpotName);
//        obj.put("matterName", matterName);
//        obj.put("predictionNo", predictionNo);
//        obj.put("valueFlag", valueFlag);
//        List<String> list = meterWorkRailwayActualBakMapper.distinctRailwayNo(param).stream().map(MeterWorkRailwayActual::getRailwayNo).collect(Collectors.toList());
//        return list;

        if(param.get("lcNo") != null) {
            String[] lcNoTemp = param.get("lcNo").toString().split(",");
//        param.remove("lcNo");
            param.put("lcNoTemp", lcNoTemp);
            for (String str:
                    lcNoTemp) {
                if(str.equals("")) {
                    param.put("lcNoNull", "1");
                    break;
                }else {
                    param.put("lcNoNull", "");
                }
            }
        }

        List<String> list = new ArrayList<>();
        try{
            list = meterWorkRailwayActualBakMapper.distinctRailwayNoTemp(param)
                    .stream()
                    .map(MeterWorkRailwayActualBak::getRailwayNo)
                    .distinct()
                    .collect(Collectors.toList());
            if(list==null && list.isEmpty()) {
                list.add("");
            }
        }catch (Exception e) {
            list.add("");
        }
        return list;
    }

    @Override
    public List<String> distinctLcNo(HashMap<String, Object> param) {
//        String railwayTypeNo = param.get("railwayTypeNo") == null ? "":param.get("railwayTypeNo").toString();
//        String startTime = param.get("startTime") == null ? "":param.get("startTime").toString();
//        String endTime = param.get("endTime") == null ? "":param.get("endTime").toString();
//        String railwayNo = param.get("railwayNo") == null ? "": param.get("railwayNo").toString();
//        String baseSpotNo = param.get("baseSpotNo") == null ? "":param.get("baseSpotNo").toString();
//        String matterName = param.get("matterName") == null ? "":param.get("matterName").toString();
//        String predictionNo = param.get("predictionNo") == null ? "":param.get("predictionNo").toString();
//        String forwardingUnitName = param.get("forwardingUnitName") == null ? "": param.get("forwardingUnitName").toString();
//        String receivingUintName = param.get("receivingUintName") == null ? "":param.get("receivingUintName").toString();
//        String valueFlag = param.get("valueFlag") == null ? "": param.get("valueFlag").toString();
//        String lcNo = param.get("lcNo") == null ? "": param.get("lcNo").toString();
//
//        HashMap<String, Object> obj = new HashMap<>();
//        obj.put("railwayTypeNo", railwayTypeNo);
//        obj.put("startTime", startTime);
//        obj.put("endTime", endTime);
//        obj.put("railwayNo", railwayNo);
//        obj.put("baseSpotNo", baseSpotNo);
//        obj.put("matterName", matterName);
//        obj.put("predictionNo", predictionNo);
//        obj.put("forwardingUnitName", forwardingUnitName);
//        obj.put("receivingUintName", receivingUintName);
//        obj.put("valueFlag", valueFlag);
//        obj.put("lcNo", lcNo);
        List<MeterWorkRailwayActualBak> templist = meterWorkRailwayActualBakMapper.distinctLcNo(param);
        List<String> list = new ArrayList<>();
        if (templist != null && !templist.isEmpty() ) {
            try{
                list = templist.stream().map(MeterWorkRailwayActualBak::getLcNo).distinct().collect(Collectors.toList());
                if(list==null && list.isEmpty()) {
                    list.add("");
                }
            }catch (Exception e) {
                list.add("");
            }
        }
        return list;
//        List<String> list = null;
//        if(templist.size() != 0)
//        {
//            list = templist.stream().map(MeterWorkRailwayActualBak::getLcNo).collect(Collectors.toList());
//        }
//        return list;
    }

    @Override
    public RESTfulResult distinctLcNoAndRailwayNo(HashMap<String, Object> param) {
        RESTfulResult rm = new RESTfulResult();
        rm.setFailed();
        try{
//            String railwayTypeNo = param.get("railwayTypeNo") == null ? "":param.get("railwayTypeNo").toString();
//            String startTime = param.get("startTime") == null ? "":param.get("startTime").toString();
//            String endTime = param.get("endTime") == null ? "":param.get("endTime").toString();
//            String railwayNo = param.get("railwayNo") == null ? "":param.get("railwayNo").toString();
//            String baseSpotName = param.get("baseSpotName") == null ? "": param.get("baseSpotName").toString();
//            String matterName = param.get("matterName") == null ? "": param.get("matterName").toString();
//            String predictionNo = param.get("predictionNo") == null ? "": param.get("predictionNo").toString();
//            String valueFlag = param.get("valueFlag") == null ? "":param.get("valueFlag").toString();
//
//            HashMap<String, Object> param = new HashMap<>();
            HashMap<String, Object> obj = new HashMap<>();
//            obj.put("railwayTypeNo", railwayTypeNo);
//            obj.put("startTime", startTime);
//            obj.put("endTime", endTime);
//            obj.put("railwayNo", railwayNo);
//            obj.put("baseSpotName", baseSpotName);
//            obj.put("matterName", matterName);
//            obj.put("predictionNo", predictionNo);
//            obj.put("valueFlag", valueFlag);

            List<MeterWorkRailwayActualBak> tempList = meterWorkRailwayActualBakMapper.distinctLcNo(param);
            List<String> list = null;
            List<String> railwayNum = null;
            if(tempList.size() != 0)
            {
                list = tempList.stream().map(MeterWorkRailwayActualBak::getLcNo).distinct().collect(Collectors.toList());
                railwayNum = tempList.stream().map(MeterWorkRailwayActualBak::getRailwayNo).distinct().collect(Collectors.toList());
            }
            obj.put("LcList", list);
            obj.put("railwayNoList", railwayNum);
            rm.setSucceed();
            rm.setCode("200");
            rm.setMessage("操作成功！！");
            rm.setData(obj);
        }catch(Exception e) {
            e.printStackTrace();
            rm.setMessage("操作异常！！>>" + e.getMessage());
        }
        return rm;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int removeDt(List<MeterWorkRailwayActualBak> models) throws MarkerMetException {
        try {
            int num = 0;
            if (models.size() <= 0 || models == null) {
                throw new MarkerMetException(500, "参数为空！！！");
            }
            models.sort(Comparator.comparing(MeterWorkRailwayActualBak::getPredictionNo).thenComparing(MeterWorkRailwayActualBak::getNetTime));

            List<PreRailwayScale> lm = new ArrayList<>();

            for (MeterWorkRailwayActualBak model : models) {
                //毛重删除
                meterWorkRailwayActFirstBakMapper.deleteByPrimaryKey(model.getActualFirst1No());
                //皮重删除
                meterWorkRailwayActFirstBakMapper.deleteByPrimaryKey(model.getActualFirst2No());
                //净重删除
                meterWorkRailwayActualBakMapper.deleteByPrimaryKey(model.getActualNo());

                //修改数据
                if(model.getActualFirst1No().substring(0,2).equals("20")) {
                    preRailwayScaleMapper.updateMeterWorkRailwayReceiveds(model.getActualFirst1No());
                }else {
                    preRailwayScaleMapper.updateMeterWorkRailwayReceiveds("20"+model.getActualFirst1No());
                }

                //预报次数还原，如果是选矿的需要还原次数，砂石的预报是永久的，所以不要做这个操作
                if ("00025".equals(model.getBaseSpot1No())) {
                    boolean bflag = false;
                    for (PreRailwayScale p : lm) {
                        if (p.getPredictionNo().equals(model.getPredictionNo())) {
                            p.setRailwayCarriageNo((Integer.parseInt(p.getRailwayCarriageNo()) + 1) + "");
                            p.setValueFlag(DbConstants.IN); //正使用
                            lm.add(p);
                            break;
                        }
                    }
                    if (!bflag) {
                        PreRailwayScale pp = preRailwayScaleMapper.selectByPrimaryKey(model.getPredictionNo());
                        if (pp != null && pp.getRailwayCarriageNo() != null) {
                            PreRailwayScale p = new PreRailwayScale();
                            p.setPredictionNo(model.getPredictionNo());
                            p.setRailwayCarriageNo((Integer.parseInt(pp.getRailwayCarriageNo()) + 1) + "");
                            p.setValueFlag(DbConstants.IN); //正使用
                            lm.add(p);
                        }
                    }
                }

                num++;
            }

            for (PreRailwayScale p : lm) {
                preRailwayScaleMapper.updateByPrimaryKeySelective(p);
            }

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


    @Override
    @Transactional(rollbackFor = Exception.class)
    public PageList<MeterWorkRailwayActualBak> selectView(HashMap parmas, Integer pageNum, Integer pageSize) throws MarkerMetException {
        String flag = parmas.get("flag").toString();
        if (StringUtils.isEmpty(flag)) {
            throw new MarkerMetException(500, "标识符为空!!");
        }
        if (!flag.equals("1") && !flag.equals("0")) {
            throw new MarkerMetException(500, "标识符不正确!!");
        }
        if (flag.equals("1")) {
            parmas.put("railwayTypeName", "动态轨道衡");
            parmas.put("railwayTypeNo", DbConstants.ACT);
        }
        if (flag.equals("0")) {
            parmas.put("railwayTypeName", "静态轨道衡");
            parmas.put("railwayTypeNo", DbConstants.STATIC);
        }
        if (parmas.containsKey("createTime1") && StringUtils.isNotEmpty(parmas.get("createTime1").toString())
                && parmas.get("createTime1").toString().length() < 12) {
            parmas.put("createTime1", parmas.get("createTime1") + " 00:00:00");
        }
        if (parmas.containsKey("createTime2") && StringUtils.isNotEmpty(parmas.get("createTime2").toString())
                && parmas.get("createTime2").toString().length() < 12) {
            parmas.put("createTime2", parmas.get("createTime2") + " 23:59:59");
        }
        if (parmas.containsKey("netTime1") && StringUtils.isNotEmpty(parmas.get("netTime1").toString())
                && parmas.get("netTime1").toString().length() < 12) {
            parmas.put("netTime1", parmas.get("netTime1") + " 00:00:00");
        }
        if (parmas.containsKey("netTime1") && StringUtils.isNotEmpty(parmas.get("netTime2").toString())
                && parmas.get("netTime1").toString().length() < 12) {
            parmas.put("netTime2", parmas.get("netTime2") + " 23:59:59");
        }
        PageHelper.startPage(pageNum, pageSize);
        List<MeterWorkRailwayActualBak> rows = meterWorkRailwayActualBakMapper.selectView(parmas);
        PageList pageInfo = new PageList(rows);
        return pageInfo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public PageList<MeterWorkRailwayActualBak> selectDiff(HashMap parmas, Integer pageNum, Integer pageSize) {
        String flag = parmas.get("flag").toString();
        if (flag == null || "".equals(flag)) {
            throw new MarkerMetException(500, "标识符为空!!");
        }
        if (!flag.equals("1") && !flag.equals("0")) {
            throw new MarkerMetException(500, "标识符不正确!!");
        }
        if (flag.equals("1")) {
            parmas.put("railwayTypeName", "动态轨道衡");
            parmas.put("railwayTypeNo", DbConstants.ACT);
        }
        if (flag.equals("0")) {
            parmas.put("railwayTypeName", "静态轨道衡");
            parmas.put("railwayTypeNo", DbConstants.STATIC);
        }
        PageHelper.startPage(pageNum, pageSize);
        List<MeterWorkRailwayActualBak> rows = meterWorkRailwayActualBakMapper.selectDiff(parmas);
        PageList pageInfo = new PageList(rows);
        return pageInfo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public MeterWorkRailwayActualBak termclean(String actualFirstNo, String dataNo) {
        try {
            if (actualFirstNo == null && actualFirstNo.equals("")) {
                throw new MarkerMetException(500, "毛重数据编号为空");
            }
            if (dataNo == null && dataNo.equals("")) {
                throw new MarkerMetException(500, "皮重数据编号为空");
            }
            MeterWorkRailwayActFirstBak mwraf1 = meterWorkRailwayActFirstBakMapper.selectByPrimaryKey(actualFirstNo);
            if (mwraf1 == null) {
                throw new MarkerMetException(500, "未查询到相应的毛重数据！！");
            }

            MeterBaseRailwayWeight mbrw = meterBaseRailwayWeightMapper.selectByPrimaryKey(dataNo);
            if (mbrw == null) {
                throw new MarkerMetException(500, "未查询到相应的皮重数据！！");
            }
            if (mbrw.getRailwayWeight().compareTo(mwraf1.getMeterWeight()) == 1) {
                throw new MarkerMetException(500, "皮重重量大于毛重重量！！");
            }

            mwraf1.setValueFlag(DbConstants.NET);
            meterWorkRailwayActFirstBakMapper.updateByPrimaryKey(mwraf1);
            MeterWorkRailwayActualBak mwca = meterWorkRailwayActualBakMapper.tareAdd(actualFirstNo, dataNo);
            check(mwca);
            if (mwca.getGrossTime().compareTo(mwca.getTareTime()) == 1) {
                mwca.setNetSpot3No(mwca.getBaseSpot1No());
                mwca.setNetSpot3Name(mwca.getBaseSpot1Name());
            } else {
                mwca.setNetSpot3No(mwca.getBaseSpot2No());
                mwca.setNetSpot3Name(mwca.getBaseSpot2Name());
            }
            mwca.setNetMode(DbConstants.TYPE);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            String no = meterWorkRailwayActualBakMapper.getNewID(sdf.format(new Date()));
            mwca.setActualNo(sdf.format(new Date()) + no);
            mwca.setNetWeight(mwraf1.getMeterWeight().subtract(mbrw.getRailwayWeight()));
            mwca.setUploadFlag("1");
            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());
            }
            meterWorkRailwayActualBakMapper.insertSelective(mwca);
            return mwca;
        } catch (MarkerMetException e) {
            throw e;
        }
    }


    private void check(MeterWorkRailwayActualBak model) throws MarkerMetException {
        if ("001019001".equals(model.getRailwayTypeNo())) {
            if (model.getRailwayNo() == null || model.getRailwayNo().equals("")) {
                throw new MarkerMetException(500, "火车车号不能为空");
            }
        }
        if (model.getMatterNo() == null || model.getMatterNo().equals("")) {
            throw new MarkerMetException(500, "物料编号不能为空");
        }
        if (model.getMatterName() == null || model.getMatterName().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.getActualFirst1No() == null || model.getActualFirst1No().equals("")) {
            throw new MarkerMetException(500, "毛重计量作业编号不能为空");
        }
        if (model.getGrossTime() == null || model.getGrossTime().equals("")) {
            throw new MarkerMetException(500, "毛重计量时间不能为空");
        }
        if (model.getBaseSpot1No() == null || model.getBaseSpot1No().equals("")) {
            throw new MarkerMetException(500, "毛重计量点编号不能为空");
        }
        if (model.getBaseSpot1Name() == null || model.getBaseSpot1Name().equals("")) {
            throw new MarkerMetException(500, "毛重计量点名称不能为空");
        }
        if (model.getActualFirst2No() == null || model.getActualFirst2No().equals("")) {
            throw new MarkerMetException(500, "皮重计量作业编号不能为空");
        }
        if (model.getTareTime() == null || model.getTareTime().equals("")) {
            throw new MarkerMetException(500, "皮重计量时间不能为空");
        }
        if (model.getActualNo() == null && model.getValueFlag() == null)
            model.setValueFlag(DbConstants.VALID);
        if (model.getActualNo() == null && model.getUploadFlag() == null)
            model.setUploadFlag(DbConstants.VALID);
        UserPayload payload = UserPayload.getCurrUser();
        String userId = payload.getUserCode();
        String userName = payload.getUserName();
        if (model.getActualNo() == null) {
            model.setNetTime(new Date());
            model.setNetManNo(userId);
            model.setNetManName(userName);
        }
    }

    private void cleanCheck(MeterWorkRailwayActualBak model) throws MarkerMetException {
            if (model.getRailwayNo() == null || model.getRailwayNo().equals("")) {
                throw new MarkerMetException(500, "火车车号不能为空");
            }
//        if (model.getMatterNo() == null || model.getMatterNo().equals("")) {
//            throw new MarkerMetException(500, "物料编号不能为空");
//        }
//        if (model.getMatterName() == null || model.getMatterName().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.getActualFirst1No() == null || model.getActualFirst1No().equals("")) {
            throw new MarkerMetException(500, "毛重计量作业编号不能为空");
        }
        if (model.getGrossTime() == null || model.getGrossTime().equals("")) {
            throw new MarkerMetException(500, "毛重计量时间不能为空");
        }
        if (model.getBaseSpot1No() == null || model.getBaseSpot1No().equals("")) {
            throw new MarkerMetException(500, "毛重计量点编号不能为空");
        }
        if (model.getBaseSpot1Name() == null || model.getBaseSpot1Name().equals("")) {
            throw new MarkerMetException(500, "毛重计量点名称不能为空");
        }
        if (model.getActualFirst2No() == null || model.getActualFirst2No().equals("")) {
            throw new MarkerMetException(500, "皮重计量作业编号不能为空");
        }
        if (model.getTareTime() == null || model.getTareTime().equals("")) {
            throw new MarkerMetException(500, "皮重计量时间不能为空");
        }
        if (model.getActualNo() == null && model.getValueFlag() == null && (model.getPredictionNo() == null || "".equals(model.getPredictionNo()))) {
            model.setValueFlag("3"); // 未匹配
        } else if (model.getActualNo() == null && model.getValueFlag() == null && (model.getPredictionNo() != null && !"".equals(model.getPredictionNo()))) {
            model.setValueFlag("1"); // 已匹配
        }

        if (model.getActualNo() == null && model.getUploadFlag() == null)
            model.setUploadFlag(DbConstants.VALID);
        UserPayload payload = UserPayload.getCurrUser();
        String userId = payload.getUserCode();
        String userName = payload.getUserName();
        if (model.getActualNo() == null) {
            model.setNetTime(new Date());
            model.setCreateTime(new Date());
            model.setNetManNo(userId);
            model.setNetManName(userName);
//            model.setNote();
        }
    }

    @Override
    public RESTfulResult doQueryWf(CommonPage<MeterWorkRailwayActualBak> oci) {
        RESTfulResult rm = new RESTfulResult();
        try {
            rm.setCode("200");
            if (oci.getParam() != null) {
                int iStart = oci.getPageSize() > 0 ? oci.getPageSize() : 9999;
                Map<String, Object> map = FieldsCollector.beanToMap(oci.getParam());
                PageHelper.startPage(oci.getPageNum(), iStart);
                List<MeterWorkRailwayActualBak> rows = meterWorkRailwayActualBakMapper.selectByParameters(map);
                PageList pageInfo = new PageList(rows);
                rm.setData(pageInfo);
            }
        } catch (Exception ex) {
            rm.setCode("500");
            rm.setMessage("查询失败：" + ex.getMessage());
        }
        return rm;
    }

    //动轨获取数据（需要将kg转化为T）
    public PageList<MeterWorkRailwayActualBak> doQueryActWf(HashMap parmas, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<MeterWorkRailwayActualBak> rows = meterWorkRailwayActualBakMapper.selectByParameter(parmas);
        for (MeterWorkRailwayActualBak row : rows) {
            if (row.getNetWeight() != null) {
                row.setNetWeight(row.getNetWeight().divide(new BigDecimal(1000)));
            }
            if (row.getGrossWeight() != null) {
                row.setGrossWeight(row.getGrossWeight().divide(new BigDecimal(1000)));
            }
            if (row.getTareWeight() != null) {
                row.setTareWeight(row.getTareWeight().divide(new BigDecimal(1000)));
            }
        }
        PageList pageInfo = new PageList(rows);
        return pageInfo;
    }


    /**
     * 批量修改二次计量的数据，同步修改一次计量数据
     *
     * @param actuals,actualFirsts,scales
     * @return
     */
    @Override
    public int batchEditActual(List<MeterWorkRailwayActualBak> actuals, List<MeterWorkRailwayActFirstBak> actualFirsts, List<PreRailwayScale> scales) {
        int num = 0;
        try {
            //=======================二次计量数据的修改：开始=====================
            if (actuals != null && actuals.size() >= 0) {
                for (MeterWorkRailwayActualBak actual : actuals) {
                    updateActual(actual);//二次计量数据更新

                    //一次计量，毛重的处理
                    MeterWorkRailwayActFirstBak first = actualToFirstGross(actual);
                    if (first != null && first.getActualFirstNo() != null)
                        updateActualFirst(first);

                    //一次计量，皮重的处理
                    MeterWorkRailwayActFirstBak firstTare = actualToFirstTare(actual);
                    if (firstTare != null && firstTare.getActualFirstNo() != null)
                        updateActualFirst(firstTare);

                    //预报处理
                    PreRailwayScale scale = actualToScale(actual);
                    if (scale != null && scale.getPredictionNo() != null)
                        updateRailwayScale(scale);
                    num++;
                }
            }
            //=======================二次计量数据的修改：结束=====================


            //=======================一次计量数据的修改：开始=====================
            if (actualFirsts != null && actualFirsts.size() >= 0) {
                for (MeterWorkRailwayActFirstBak actualFirst : actualFirsts) {
                    updateActualFirst(actualFirst);//一次计量数据更新
                    //预报处理
                    PreRailwayScale scale = firstToScale(actualFirst);
                    if (scale != null && scale.getPredictionNo() != null)
                        updateRailwayScale(scale);
                    num++;
                }
            }
            //=======================一次计量数据的修改：结束=====================


            //=======================预报数据的修改：开始=====================
            if (scales != null && scales.size() >= 0) {
                for (PreRailwayScale scale : scales) {
                    if (StringUtils.isNotEmpty(scale.getPredictionNo())) {
                        scale.setUpdateTime(new Date());
                        preRailwayScaleMapper.updateByPrimaryKeySelective(scale);
                        num++;
                    }
                }
            }
            //=======================预报数据的修改：结束=====================
            return num;
        } catch (Exception ex) {
            ex.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return 0;
        }
    }

    /**
     * 二次计量批量修改
     *
     * @param actuals
     * @return
     */
    @Override
    public int batchEditActuals(List<MeterWorkRailwayActualBak> actuals) {
        int num = 0;
        try {
            if (actuals == null || actuals.size() == 0) {
                throw new MarkerMetException(500, "参数不允许为空！");
            }
            if (actuals != null && actuals.size() >= 0) {
                for (MeterWorkRailwayActualBak actual : actuals) {
                    updateActual(actual);//二次计量数据更新
                    //一次计量，毛重的处理
                    MeterWorkRailwayActFirstBak first = actualToFirstGross(actual);
                    if (first != null && first.getActualFirstNo() != null)
                        updateActualFirst(first);

                    //一次计量，皮重的处理
                    MeterWorkRailwayActFirstBak firstTare = actualToFirstTare(actual);
                    if (firstTare != null && firstTare.getActualFirstNo() != null)
                        updateActualFirst(firstTare);

                    //预报处理
                    PreRailwayScale scale = actualToScale(actual);
                    if (scale != null && scale.getPredictionNo() != null)
                        updateRailwayScale(scale);
                    num++;
                }
            }
            return num;
        } catch (Exception ex) {
            ex.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return 0;
        }
    }

    /**
     * 一次计量批量修改
     *
     * @param actualFirsts
     * @return
     */
    @Override
    public int batchEditActFirsts(List<MeterWorkRailwayActFirstBak> actualFirsts) {
        int num = 0;
        try {
            if (actualFirsts == null || actualFirsts.size() == 0) {
                throw new MarkerMetException(500, "参数不允许为空！");
            }
            if (actualFirsts != null && actualFirsts.size() >= 0) {
                for (MeterWorkRailwayActFirstBak actualFirst : actualFirsts) {
                    updateActualFirst(actualFirst);//一次计量数据更新
                    //预报处理
                    PreRailwayScale scale = firstToScale(actualFirst);
                    if (scale != null && scale.getPredictionNo() != null)
                        updateRailwayScale(scale);
                    num++;
                }
            }
            return num;
        } catch (Exception ex) {
            ex.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return 0;
        }
    }

    @Override
    public double getGrossAvg(HashMap actual) {
        return meterWorkRailwayActualBakMapper.getGrossAvg(actual);
    }

    /**
     * 预报批量修改
     *
     * @param scales
     * @return
     */
    public int batchEditScales(List<PreRailwayScale> scales) {
        int num = 0;
        try {
            if (scales == null || scales.size() == 0) {
                throw new MarkerMetException(500, "参数不允许为空！");
            }
            if (scales != null && scales.size() >= 0) {
                for (PreRailwayScale scale : scales) {
                    if (StringUtils.isNotEmpty(scale.getPredictionNo())) {
                        scale.setUpdateTime(new Date());
                        preRailwayScaleMapper.updateByPrimaryKeySelective(scale);
                        num++;
                    }
                }
            }
            return num;
        } catch (Exception ex) {
            ex.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return 0;
        }
    }

    /**
     * 更新二次计量数据
     *
     * @param actual
     * @return
     */
    public int updateActual(MeterWorkRailwayActualBak actual) {
        if (StringUtils.isNotEmpty(actual.getActualNo())) {
            actual.setUpdateTime(new Date());
            meterWorkRailwayActualBakMapper.updateByPrimaryKeySelective(actual);
        }
        return 0;
    }

    /**
     * 更新一次计量数据
     *
     * @param actFirst
     * @return
     */
    public int updateActualFirst(MeterWorkRailwayActFirstBak actFirst) {
        if (StringUtils.isNotEmpty(actFirst.getActualFirstNo())) {
            actFirst.setUpdateTime(new Date());
            meterWorkRailwayActFirstBakMapper.updateByPrimaryKeySelective(actFirst);
        }
        return 0;
    }

    /**
     * 更新预报数据
     *
     * @param scale
     * @return
     */
    public int updateRailwayScale(PreRailwayScale scale) {
        if (StringUtils.isNotEmpty(scale.getPredictionNo())) {
            scale.setUpdateTime(new Date());
            preRailwayScaleMapper.updateByPrimaryKeySelective(scale);
        }
        return 0;
    }

    /**
     * 二次计量实体转换为一次计量实体;毛重数据
     *
     * @param actual
     * @return
     */
    public MeterWorkRailwayActFirstBak actualToFirstGross(MeterWorkRailwayActualBak actual) {
        MeterWorkRailwayActFirstBak actFirst = new MeterWorkRailwayActFirstBak();
        actFirst.setActualFirstNo(actual.getActualFirst1No()); //毛重计量编号
        actFirst.setPredictionNo(actual.getPredictionNo());
        actFirst.setNoticeNo(actual.getNoticeNo());
        actFirst.setMatterNo(actual.getMatterNo());
        actFirst.setMatterName(actual.getMatterName());
        actFirst.setContractNo(actual.getContractNo());
        actFirst.setBatchNo(actual.getBatchNo());
        actFirst.setCustomerSupplierNo(actual.getCustomerSupplierNo());
        actFirst.setCustomerSupplierName(actual.getCustomerSupplierName());
        actFirst.setForwardingUnitNo(actual.getForwardingUnitNo());
        actFirst.setForwardingUnitName(actual.getForwardingUnitName());
        actFirst.setReceivingUintNo(actual.getReceivingUintNo());
        actFirst.setReceivingUintName(actual.getReceivingUintName());
        actFirst.setMaterialNo(actual.getMaterialNo());
        actFirst.setMaterialName(actual.getMaterialName());
        actFirst.setSpecNo(actual.getSpecNo());
        actFirst.setSpecName(actual.getSpecName());
        actFirst.setLoadPointNo(actual.getLoadPointNo());
        actFirst.setLoadPointName(actual.getLoadPointName());
        actFirst.setSampleNo(actual.getSampleNo());
        actFirst.setSampleVoucher(actual.getSampleVoucher());
        actFirst.setCarrierUnitNo(actual.getCarrierUnitNo());
        actFirst.setCarrierUnitName(actual.getCarrierUnitName());
        actFirst.setMeterTypeNo(actual.getMeterTypeNo());
        actFirst.setMeterTypeName(actual.getMeterTypeName());
        actFirst.setArrival(actual.getArrival());
        actFirst.setStation(actual.getStation());
        actFirst.setSourceArea(actual.getSourceArea());
        actFirst.setMemo(actual.getMemo());
        actFirst.setUpdateManNo(actual.getUpdateManNo());
        actFirst.setUpdateManName(actual.getUpdateManName());
        return actFirst;
    }


    /**
     * 二次计量实体转换为一次计量实体;毛重数据
     *
     * @param actual
     * @return
     */
    public MeterWorkRailwayActFirstBak actualToFirstTare(MeterWorkRailwayActualBak actual) {
        MeterWorkRailwayActFirstBak actFirst = new MeterWorkRailwayActFirstBak();
        actFirst.setActualFirstNo(actual.getActualFirst2No()); //皮重计量编号
        actFirst.setPredictionNo(actual.getPredictionNo());
        actFirst.setNoticeNo(actual.getNoticeNo());
        actFirst.setMatterNo(actual.getMatterNo());
        actFirst.setMatterName(actual.getMatterName());
        actFirst.setContractNo(actual.getContractNo());
        actFirst.setBatchNo(actual.getBatchNo());
        actFirst.setCustomerSupplierNo(actual.getCustomerSupplierNo());
        actFirst.setCustomerSupplierName(actual.getCustomerSupplierName());
        actFirst.setForwardingUnitNo(actual.getForwardingUnitNo());
        actFirst.setForwardingUnitName(actual.getForwardingUnitName());
        actFirst.setReceivingUintNo(actual.getReceivingUintNo());
        actFirst.setReceivingUintName(actual.getReceivingUintName());
        actFirst.setMaterialNo(actual.getMaterialNo());
        actFirst.setMaterialName(actual.getMaterialName());
        actFirst.setSpecNo(actual.getSpecNo());
        actFirst.setSpecName(actual.getSpecName());
        actFirst.setLoadPointNo(actual.getLoadPointNo());
        actFirst.setLoadPointName(actual.getLoadPointName());
        actFirst.setSampleNo(actual.getSampleNo());
        actFirst.setSampleVoucher(actual.getSampleVoucher());
        actFirst.setCarrierUnitNo(actual.getCarrierUnitNo());
        actFirst.setCarrierUnitName(actual.getCarrierUnitName());
        actFirst.setMeterTypeNo(actual.getMeterTypeNo());
        actFirst.setMeterTypeName(actual.getMeterTypeName());
        actFirst.setArrival(actual.getArrival());
        actFirst.setStation(actual.getStation());
        actFirst.setSourceArea(actual.getSourceArea());
        actFirst.setMemo(actual.getMemo());
        actFirst.setUpdateManNo(actual.getUpdateManNo());
        actFirst.setUpdateManName(actual.getUpdateManName());
        return actFirst;
    }

    /**
     * 二次计量实体转换为预报实体
     *
     * @param actual
     * @return
     */
    public PreRailwayScale actualToScale(MeterWorkRailwayActualBak actual) {
        PreRailwayScale scale = new PreRailwayScale();
        scale.setPredictionNo(actual.getPredictionNo());
        scale.setNoticeNo(actual.getNoticeNo());
        scale.setMatterNo(actual.getMatterNo());
        scale.setMatterName(actual.getMatterName());
        scale.setContractNo(actual.getContractNo());
        scale.setBatchNo(actual.getBatchNo());
        scale.setCustomerSupplierNo(actual.getCustomerSupplierNo());
        scale.setCustomerSupplierName(actual.getCustomerSupplierName());
        scale.setForwardingUnitNo(actual.getForwardingUnitNo());
        scale.setForwardingUnitName(actual.getForwardingUnitName());
        scale.setReceivingUintNo(actual.getReceivingUintNo());
        scale.setReceivingUintName(actual.getReceivingUintName());
        scale.setMaterialNo(actual.getMaterialNo());
        scale.setMaterialName(actual.getMaterialName());
        scale.setSpecNo(actual.getSpecNo());
        scale.setSpecName(actual.getSpecName());
        scale.setLoadPointNo(actual.getLoadPointNo());
        scale.setLoadPointName(actual.getLoadPointName());
        scale.setSampleNo(actual.getSampleNo());
        scale.setSampleVoucher(actual.getSampleVoucher());
        scale.setCarrierUnitNo(actual.getCarrierUnitNo());
        scale.setCarrierUnitName(actual.getCarrierUnitName());
        scale.setMeterTypeNo(actual.getMeterTypeNo());
        scale.setMeterTypeName(actual.getMeterTypeName());
        scale.setArrival(actual.getArrival());
        scale.setStation(actual.getStation());
        scale.setSourceArea(actual.getSourceArea());
        scale.setMemo(actual.getMemo());
        return scale;
    }


    /**
     * 一次计量实体转换为预报实体
     *
     * @param first
     * @return
     */
    public PreRailwayScale firstToScale(MeterWorkRailwayActFirstBak first) {
        PreRailwayScale scale = new PreRailwayScale();
        scale.setPredictionNo(first.getPredictionNo());
        scale.setNoticeNo(first.getNoticeNo());
        scale.setMatterNo(first.getMatterNo());
        scale.setMatterName(first.getMatterName());
        scale.setContractNo(first.getContractNo());
        scale.setBatchNo(first.getBatchNo());
        scale.setCustomerSupplierNo(first.getCustomerSupplierNo());
        scale.setCustomerSupplierName(first.getCustomerSupplierName());
        scale.setForwardingUnitNo(first.getForwardingUnitNo());
        scale.setForwardingUnitName(first.getForwardingUnitName());
        scale.setReceivingUintNo(first.getReceivingUintNo());
        scale.setReceivingUintName(first.getReceivingUintName());
        scale.setMaterialNo(first.getMaterialNo());
        scale.setMaterialName(first.getMaterialName());
        scale.setSpecNo(first.getSpecNo());
        scale.setSpecName(first.getSpecName());
        scale.setLoadPointNo(first.getLoadPointNo());
        scale.setLoadPointName(first.getLoadPointName());
        scale.setSampleNo(first.getSampleNo());
        scale.setSampleVoucher(first.getSampleVoucher());
        scale.setCarrierUnitNo(first.getCarrierUnitNo());
        scale.setCarrierUnitName(first.getCarrierUnitName());
        scale.setMeterTypeNo(first.getMeterTypeNo());
        scale.setMeterTypeName(first.getMeterTypeName());
        scale.setMemo(first.getMemo());
        scale.setArrival(first.getArrival());
        scale.setStation(first.getStation());
        scale.setSourceArea(first.getSourceArea());
        if (first.getShipmentNum() != null)
            scale.setShipmentNum(first.getShipmentNum());
        if (first.getShipmentNetWeight() != null)
            scale.setShipmentNetWeight(first.getShipmentNetWeight());
        if (first.getShipmentGrossWeight() != null)
            scale.setShipmentGrossWeight(first.getShipmentGrossWeight());
        return scale;
    }

    @Override
    @Transactional
    public int checkandadditional(MeterWorkRailwayActualBak model) {
        try{
            int num = 0;
            UserPayload payload = UserPayload.getCurrUser();
            String userId = payload.getUserCode();
            String userName = payload.getUserName();
//            String userId = "admin";
//            String userName = "admins";
            if(model.getGrossWeight() == null || model.getGrossWeight().equals(""))
            {
                throw new MarkerMetException(500, "毛重数据不能为空");
            }
            if(model.getTareWeight() == null || model.getTareWeight().equals(""))
            {
                throw new MarkerMetException(500,"皮重数据不能为空");
            }
            if(model.getRailwayNo() == null || model.getRailwayNo().equals(""))
            {
                throw new MarkerMetException(500, "车号不能为空");
            }
            if(new BigDecimal(model.getGrossWeight().toString()).compareTo(new BigDecimal(model.getTareWeight().toString())) == -1)
            {
                throw new MarkerMetException(500, "毛重重量小于皮重");
            }
            if(model.getNetWeight() == null || model.getNetWeight().equals(""))
            {
                throw new MarkerMetException(500, "净重数据不能为空");
            }
            String predictionNo = model.getPredictionNo()==null?"":model.getPredictionNo();
            MeterWorkRailwayActFirstBak mwraf1 = new MeterWorkRailwayActFirstBak();
            MeterWorkRailwayActFirstBak mwraf2 = new MeterWorkRailwayActFirstBak();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            String afl = sdf.format(new Date());
            if(predictionNo == "" || "".equals(predictionNo)){
                //添加毛重一次计量数据
                String actualFirstNo = sdf.format(new Date()) + meterWorkRailwayActFirstBakMapper.getNewID(afl);
                mwraf1.setActualFirstNo(actualFirstNo);
                mwraf1.setValueFlag("2");
                mwraf1.setCreateTime(new Date());
                mwraf1.setCreateManNo(userId);
                mwraf1.setCreateManName(userName);
                mwraf1.setRailwayNo(model.getRailwayNo());
                mwraf1.setMeterWeight(model.getGrossWeight());
                mwraf1.setDataSource("4");
                mwraf1.setMeterMode("3");
                mwraf1.setIsPreSacale("0");
                meterWorkRailwayActFirstBakMapper.insertSelective(mwraf1);
                //添加皮重一次计量数据
                String dataNo = sdf.format(new Date()) + meterWorkRailwayActFirstBakMapper.getNewID(afl);
                mwraf2.setActualFirstNo(dataNo);
                mwraf2.setValueFlag("2");
                mwraf2.setCreateTime(new Date());
                mwraf2.setCreateManNo(userId);
                mwraf2.setCreateManName(userName);
                mwraf2.setRailwayNo(model.getRailwayNo());
                mwraf2.setMeterWeight(model.getTareWeight());
                mwraf2.setDataSource("4");
                mwraf2.setMeterMode("3");
                mwraf2.setIsPreSacale("0");
                meterWorkRailwayActFirstBakMapper.insertSelective(mwraf2);
                //添加净重重一次计量数据
                String ActualNo = sdf.format(new Date()) + meterWorkRailwayActualBakMapper.getNewID(afl);
                model.setActualNo(ActualNo);
                model.setValueFlag("2");
                model.setActualFirst1No(actualFirstNo);
                model.setGrossManNo(userId);
                model.setGrossManName(userName);
                model.setGrossTime(mwraf1.getCreateTime());
                model.setGrossMode("3");
                model.setActualFirst2No(dataNo);
                model.setTareManNo(userId);
                model.setTareManName(userName);
                model.setTareTime(mwraf2.getCreateTime());
                model.setTareMode("3");
                model.setNetManNo(userId);
                model.setNetManName(userName);
                model.setNetTime(new Date());
                model.setNetMode("3");
                model.setDataSource("4");
                model.setIsPreSacale("0");
                model.setUploadFlag("1");
                model.setCreateTime(new Date());
                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());
                }
                meterWorkRailwayActualBakMapper.insertSelective(model);
                num++;
            }
            else {
                PreRailwayScale preRailwayScale = preRailwayScaleMapper.selectBypredictionNo(predictionNo);
                preRailwayScale.setValueFlag("2");
                preRailwayScale.setUploadFlag("1");
                preRailwayScale.setUpdateTime(new Date());
                preRailwayScale.setUpdateManNo("system");
                preRailwayScale.setUpdateManName("计量结净数据手动录入");

                //添加毛重一次计量数据
                String actualFirstNo = sdf.format(new Date()) + meterWorkRailwayActFirstBakMapper.getNewID(afl);
                BeanUtils.copyProperties(preRailwayScale, mwraf1);
                mwraf1.setActualFirstNo(actualFirstNo);
                mwraf1.setIsPreSacale("1");
                mwraf1.setValueFlag("2");
                mwraf1.setCreateTime(new Date());
                mwraf1.setCreateManNo(userId);
                mwraf1.setCreateManName(userName);
                mwraf1.setRailwayNo(model.getRailwayNo());
                mwraf1.setMeterWeight(model.getGrossWeight());
                mwraf1.setDataSource("4");
                mwraf1.setMeterMode("3");
                meterWorkRailwayActFirstBakMapper.insertSelective(mwraf1);
                //添加皮重一次计量数据
                String dataNo = sdf.format(new Date()) + meterWorkRailwayActFirstBakMapper.getNewID(afl);
                BeanUtils.copyProperties(preRailwayScale, mwraf2, predictionNo);
                mwraf2.setActualFirstNo(dataNo);
                mwraf2.setIsPreSacale("1");
                mwraf2.setValueFlag("2");
                mwraf2.setCreateTime(new Date());
                mwraf2.setCreateManNo(userId);
                mwraf2.setCreateManName(userName);
                mwraf2.setRailwayNo(model.getRailwayNo());
                mwraf2.setMeterWeight(model.getTareWeight());
                mwraf2.setDataSource("4");
                mwraf2.setMeterMode("3");
                meterWorkRailwayActFirstBakMapper.insertSelective(mwraf2);
                //添加净重重一次计量数据
                String ActualNo = sdf.format(new Date()) + meterWorkRailwayActualBakMapper.getNewID(afl);
                BeanUtils.copyProperties(preRailwayScale, model);
                model.setActualNo(ActualNo);
                model.setIsPreSacale("1");
                model.setValueFlag("2");
                model.setActualFirst1No(actualFirstNo);
                model.setGrossManNo(userId);
                model.setGrossManName(userName);
                model.setGrossTime(mwraf1.getCreateTime());
                model.setGrossMode("3");
                model.setActualFirst2No(dataNo);
                model.setTareManNo(userId);
                model.setTareManName(userName);
                model.setTareTime(mwraf2.getCreateTime());
                model.setTareMode("3");
                model.setNetManNo(userId);
                model.setNetManName(userName);
                model.setNetTime(new Date());
                model.setNetMode("3");
                model.setDataSource("4");
                model.setUploadFlag("1");
                model.setCreateTime(new Date());
                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());
                }
                meterWorkRailwayActualBakMapper.insertSelective(model);

                preRailwayScale.setMeasureStation(model.getNetSpot3No());
                preRailwayScale.setMeasureStationName(model.getNetSpot3Name());
                preRailwayScaleMapper.updateByPrimaryKey(preRailwayScale);
                num++;
            }
            return num;
        }
        catch (Exception e){
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return -1;
        }
    }

    @Override
    public RESTfulResult supplementaryData(MeterWorkRailwayActualBak model) {
        RESTfulResult rm = new RESTfulResult();
        rm.setFailed();

        try{
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            String afl = sdf.format(new Date());
            MeterWorkRailwayActFirstBak mwcaf1 = new MeterWorkRailwayActFirstBak();
            MeterWorkRailwayActFirstBak mwcaf2 = new MeterWorkRailwayActFirstBak();
            MeterWorkRailwayActualBak actualRow = new MeterWorkRailwayActualBak();
            String predictionNo = model.getPredictionNo();

            PreRailwayScale scale = new PreRailwayScale();
            if(predictionNo != null && StringUtils.isNotEmpty(predictionNo)) {
                scale = preRailwayScaleMapper.selectByPrimaryKey(predictionNo);
                if(scale.getValueFlag().equals("2")) {
                    rm.setMessage("委托已匹配，请确认！！");
                    return rm;
                }
            }
            /*UserPayload payload = UserPayload.getCurrUser();
            String userId = payload.getUserCode();
            String userName = payload.getUserName();*/

            //毛重
            String actualFirstNo = sdf.format(new Date()) + meterWorkRailwayActFirstBakMapper.getNewID(afl);
            mwcaf1.setActualFirstNo(actualFirstNo);
            mwcaf1.setRailwayNo(model.getRailwayNo());
            mwcaf1.setMeterWeight(model.getGrossWeight());
            mwcaf1.setRailwayTypeNo(model.getRailwayTypeNo());
            mwcaf1.setRailwayTypeName(model.getRailwayTypeName());
            mwcaf1.setWeightType("0");
            mwcaf1.setCreateManNo(model.getGrossManNo());
            mwcaf1.setCreateManName(model.getGrossManName());
            mwcaf1.setCreateTime(model.getGrossTime());
            mwcaf1.setBaseSpotNo(model.getBaseSpot1No());
            mwcaf1.setBaseSpotName(model.getBaseSpot1Name());
            mwcaf1.setValueFlag("2");
            mwcaf1.setCheckFlag("0");
            mwcaf1.setDataSource("4");
            mwcaf1.setMeterMode("3");
            mwcaf1.setIsPreSacale("0");
            meterWorkRailwayActFirstBakMapper.insertSelective(mwcaf1);
            //皮重
            String actualSecondNo = sdf.format(new Date()) + meterWorkRailwayActFirstBakMapper.getNewID(afl);
            mwcaf2.setActualFirstNo(actualSecondNo);
            mwcaf2.setRailwayNo(model.getRailwayNo());
            mwcaf2.setMeterWeight(model.getTareWeight());
            mwcaf2.setWeightType("1");
            mwcaf2.setRailwayTypeNo(model.getRailwayTypeNo());
            mwcaf2.setRailwayTypeName(model.getRailwayTypeName());
            mwcaf2.setCreateManNo(model.getGrossManNo());
            mwcaf2.setCreateManName(model.getGrossManName());
            mwcaf2.setCreateTime(model.getTareTime());
            mwcaf2.setBaseSpotNo(model.getBaseSpot2No());
            mwcaf2.setBaseSpotName(model.getBaseSpot2Name());
            mwcaf2.setValueFlag("2");
            mwcaf2.setCheckFlag("0");
            mwcaf2.setDataSource("4");
            mwcaf2.setMeterMode("3");
            mwcaf2.setIsPreSacale("0");
            meterWorkRailwayActFirstBakMapper.insertSelective(mwcaf2);
            //净重
            if(StringUtils.isNotEmpty(predictionNo)){
                //将委托中的编号和收发货的等数据拷贝进一次数据中
                MeterWorkRailwayActFirstBak first1 = meterWorkRailwayActFirstBakMapper.selectAndMatch(actualFirstNo, predictionNo);
                BeanUtils.copyProperties(first1,mwcaf1);
                mwcaf1.setIsPreSacale("1");
                meterWorkRailwayActFirstBakMapper.updateByPrimaryKey(mwcaf1);
                MeterWorkRailwayActFirstBak first2 = meterWorkRailwayActFirstBakMapper.selectAndMatch(actualSecondNo, predictionNo);
                BeanUtils.copyProperties(first2, mwcaf2);
                mwcaf2.setIsPreSacale("1");
                meterWorkRailwayActFirstBakMapper.updateByPrimaryKey(mwcaf2);
                //更新预报数据

                scale.setValueFlag(DbConstants.NET);
                scale.setUpdateTime(new Date());
                scale.setUpdateManNo("system");
                scale.setUpdateManName("手动录入");
                scale.setUploadFlag("1");
                scale.setValueFlag("2");
                scale.setMeasureStation(mwcaf2.getBaseSpotNo());
                scale.setMeasureStationName(mwcaf2.getBaseSpotName());
                preRailwayScaleMapper.updateByPrimaryKeySelective(scale);
                //将委托中的编号和收发货单位和一次数据等数据拷贝进结净数据中
                MeterWorkRailwayActualBak mwca1 = meterWorkRailwayActualBakMapper.manualAddPre(actualFirstNo, actualSecondNo, predictionNo);
                BeanUtils.copyProperties(mwca1, actualRow);

            }else {
                //将委托中的编号和收发货单位和一次数据等数据拷贝进结净数据中
                MeterWorkRailwayActualBak mwca1 = meterWorkRailwayActualBakMapper.manualAdd(actualFirstNo, actualSecondNo);
                BeanUtils.copyProperties(mwca1, actualRow);
            }
            String no = meterWorkRailwayActualBakMapper.getNewID(sdf.format(new Date()));
            actualRow.setActualNo(sdf.format(new Date()) + no);
            actualRow.setRailwayTypeNo(model.getRailwayTypeNo());
            actualRow.setRailwayTypeName(model.getRailwayTypeName());
            actualRow.setNetTime(model.getNetTime());
            actualRow.setNetMode(DbConstants.TYPE);
            actualRow.setNote("手动录入");
            actualRow.setUploadFlag("1");
            actualRow.setIsPreSacale("1");
            actualRow.setValueFlag("1");
            actualRow.setGrossMode("3");
            actualRow.setTareMode("3");
            actualRow.setCreateManName(model.getGrossManName());
            actualRow.setCreateTime(new Date());
            actualRow.setNetTime(model.getNetTime());
            actualRow.setDataSource("4");
            actualRow.setPredictionType("1");
            actualRow.setUpdateManNo("system");
            actualRow.setUpdateManName("手动录入");
            actualRow.setUpdateTime(new Date());
            actualRow.setPredictionNo(predictionNo);
            actualRow.setNetWeight(mwcaf1.getMeterWeight().subtract(mwcaf2.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());
            }
            meterWorkRailwayActualBakMapper.insertSelective(actualRow);
            rm.setSucceed();
            rm.setMessage("操作成功！！！");
            rm.setCode("200");
            return rm;
        }catch(Exception e){
            e.printStackTrace();
            rm.setMessage("操作异常，请确认！！");
            return rm;
        }
    }

    @Override
    public RESTfulResult firstAndEntrustById(String actualNo) {
        RESTfulResult rm = new RESTfulResult();
        rm.setMessage("查询失败！");
        rm.setFailed();

        List<String> actualNoList = new ArrayList<>();
        MeterWorkRailwayActualBak carActual = meterWorkRailwayActualBakMapper.selectByPrimaryKey(actualNo);
        if(carActual != null) {
            actualNoList.add(0, carActual.getActualFirst1No());
            actualNoList.add(1, carActual.getActualFirst2No());
            String entrust = carActual.getPredictionNo() == null ? "" : carActual.getPredictionNo();
            List<MeterWorkRailwayActFirstBak> firstList = meterWorkRailwayActFirstBakMapper.selectById(actualNoList);
            PreRailwayScale scale = preRailwayScaleMapper.selectByPrimaryKey(entrust);
            HashMap<String, Object> map = new HashMap<>();
            map.put("firstList", firstList);
            map.put("scale", scale);
            rm.setData(map);
            rm.setSucceed();
            rm.setCode("200");
            rm.setMessage("操作成功！！");
            return rm;
        }
        return null;
    }

    @Override
    public RESTfulResult specialRemove(HashMap params) {
        RESTfulResult rm = new RESTfulResult();
        rm.setFailed();
        rm.setData(null);
        rm.setCode("500");
        String type = params.get("type") == null ? "" : params.get("type").toString();
        MeterWorkRailwayActualBak actualModel01 = meterWorkRailwayActualBakMapper.selectByPrimaryKey(params.get("actualNo01").toString());
        MeterWorkRailwayActualBak actualModel02 = meterWorkRailwayActualBakMapper.selectByPrimaryKey(params.get("actualNo02").toString());
        if(actualModel01 == null || actualModel02 == null){
            rm.setMessage("未找到一次计量数据，请确认！！！");
            return rm;
        }
        List<MeterWorkRailwayActualBak> models = new ArrayList<MeterWorkRailwayActualBak>();
        models.add(actualModel01);
        models.add(actualModel02);

        if(models == null || models.size() == 0) {
            rm.setMessage("参数为空，请确认！！！");
            return rm;
        }
        //models必须是2个，而且他们的预报组合号一致
//        if(!models.get(0).getPredictionCombination().equals(models.get(1).getPredictionCombination())){
//            rm.setMessage("必须选择两个预报组合号一致的结净数据!!!");
//            return rm;
//        }

        for(MeterWorkRailwayActualBak modelTemp: models) {
            PreRailwayScale scaleTemp = preRailwayScaleMapper.selectByPrimaryKey(modelTemp.getPredictionNo());
            if(scaleTemp.getValueFlag().equals("9")) {
                rm.setMessage("两个结净数据中包含已结算的委托!!!");
                return rm;
            }
        }

        switch(type){
            case "5":
            case "6":
            case "7": {
                if(type.equals("5")){
                    //类型为双委托类型
                    for (MeterWorkRailwayActualBak model: models) {
                        if(!model.getPredictionType().equals("5")) {
                            rm.setMessage("选中的计量数据当中有一条或多条不是双委托结净数据，请确认！！");
                            return rm;
                        }
                    }
                } else if(type.equals("6")){
                    //类型为混卸类型
                    for (MeterWorkRailwayActualBak model: models) {
                        if(!model.getPredictionType().equals("6")) {
                            rm.setMessage("选中的计量数据当中有一条或多条不是混卸委托结净数据，请确认！！");
                        }
                    }
                }else if(type.equals("7")){
                    //类型为混装类型
                    for (MeterWorkRailwayActualBak model: models) {
                        if(!model.getPredictionType().equals("7")) {
                            rm.setMessage("选中的计量数据当中有一条或多条不是混装委托结净数据，请确认！！");
                        }
                    }
                }
                for (MeterWorkRailwayActualBak model: models) {
                    // 改委托
                    if (StringUtils.isNotEmpty(model.getPredictionNo())) {
                        removeScaleEl(model.getPredictionNo());
                    }
                    // 清空一次毛皮重委托信息
                    MeterWorkRailwayActFirstBak firstGross = meterWorkRailwayActFirstBakMapper.selectAndRemove(model.getActualFirst1No());
                    MeterWorkRailwayActFirstBak firstTare = meterWorkRailwayActFirstBakMapper.selectAndRemove(model.getActualFirst2No());
                    if(firstGross != null){
                        removeFirstEl(firstGross);
                        meterWorkRailwayActFirstBakMapper.updateByPrimaryKey(firstGross);
                    }
                    if(firstTare != null){
                        removeFirstEl(firstTare);
                        meterWorkRailwayActFirstBakMapper.updateByPrimaryKey(firstTare);
                    }
                    removeEl(model);
                    meterWorkRailwayActualBakMapper.updateByPrimaryKeySelective(model);
                }
                rm.setSucceed();
                rm.setMessage("操作成功！！");
                rm.setCode("200");
            }
        }
        return rm;
    }

    @Override
    public RESTfulResult commonRemove(HashMap params) {
        RESTfulResult rm = new RESTfulResult();
        rm.setFailed();
        rm.setData(null);
        rm.setCode("500");
        try{

            MeterWorkRailwayActualBak actualModel = meterWorkRailwayActualBakMapper.selectByPrimaryKey(params.get("actualNo").toString());
            if(actualModel == null){
                rm.setMessage("未找到结净计量数据，请确认！！！");
                return rm;
            }
//            if(actualModel.getPredictionNo() == null || StringUtils.isEmpty(actualModel.getPredictionNo())) {
//                rm.setMessage("结净作废只能作废已匹配委托的结净数据，请进行毛皮分解操作");
//                return rm;
//            }

            UserPayload userPayload = UserPayload.getCurrUser();
            String userId= userPayload.getUserCode();
            String userName = userPayload.getUserName();

            List<MeterWorkRailwayActualBak> models = new ArrayList<>();
            models.add(actualModel);

            for(MeterWorkRailwayActualBak modelTemp: models) {
                if(modelTemp.getPredictionNo() != null && StringUtils.isNotEmpty(modelTemp.getPredictionNo())){
                    PreRailwayScale scaleTemp = preRailwayScaleMapper.selectByPrimaryKey(modelTemp.getPredictionNo());
                    if(scaleTemp.getValueFlag().equals("9")) {
                        rm.setMessage("结净数据中包含已结算的委托!!!");
                        return rm;
                    }
//                    if(scaleTemp.getPredictionType().equals("5") || scaleTemp.getPredictionType().equals("6") || scaleTemp.getPredictionType().equals("7")){
//                        rm.setMessage("结净数据中包含特殊委托匹配结净的数据!!!");
//                        return rm;
//                    }
                }
            }
            for (MeterWorkRailwayActualBak model: models) {
                //循环每一个结净记录
                //委托不能为空
                if(StringUtils.isNotEmpty(model.getPredictionNo())){
                    // 改委托
                    if (StringUtils.isNotEmpty(model.getPredictionNo())) {
                        PreRailwayScale scale = preRailwayScaleMapper.selectByPrimaryKey(model.getPredictionNo());
                        scale.setValueFlag("1");
                        scale.setUploadFlag("1");
                        scale.setUpdateTime(new Date());
                        scale.setUpdateManNo(userId);
                        scale.setUpdateManName(userName + ":结净废除操作");
                        preRailwayScaleMapper.updateByPrimaryKeySelective(scale);
                    }
                }
                // 清空一次毛重、皮重委托信息
                MeterWorkRailwayActFirstBak firstGross;
                MeterWorkRailwayActFirstBak firstTare;
                if(StringUtils.isNotEmpty(model.getActualFirst1No())&&StringUtils.isNotEmpty(model.getActualFirst2No())){
                    firstGross = meterWorkRailwayActFirstBakMapper.selectAndRemove(model.getActualFirst1No());
                    firstTare =  meterWorkRailwayActFirstBakMapper.selectAndRemove(model.getActualFirst2No());
                }else{
                    firstGross = meterWorkRailwayActFirstBakMapper.selectByPrimaryKey(model.getActualFirst1No());
                    firstTare = meterWorkRailwayActFirstBakMapper.selectByPrimaryKey(model.getActualFirst2No());
                }
                if(firstGross != null){
                    firstGross.setValueFlag(DbConstants.VALID);
//                    firstGross.setUpdateManNo("system");
//                    firstGross.setUpdateManName("结净废除更新");
                    firstGross.setUpdateManNo(userId);
                    firstGross.setUpdateManName(userName);
                    firstGross.setNote(model.getNote());
                    firstGross.setUpdateTime(new Date());
                    firstGross.setIsPreSacale("0");
                    firstGross.setValueFlag("0");
                    meterWorkRailwayActFirstBakMapper.updateByPrimaryKey(firstGross);
                }
                if(firstTare != null){
                    firstTare.setValueFlag(DbConstants.VALID);
//                    firstTare.setUpdateManNo("system");
//                    firstTare.setUpdateManName("结净废除更新");
                    firstTare.setUpdateManNo(userId);
                    firstTare.setUpdateManName(userName);
                    firstTare.setNote(model.getNote());
                    firstTare.setUpdateTime(new Date());
                    firstTare.setIsPreSacale("0");
                    firstTare.setValueFlag("0");
                    meterWorkRailwayActFirstBakMapper.updateByPrimaryKey(firstTare);
                }
                // 作废结净数据并解除委托
                MeterWorkRailwayActualBak cleanModel = meterWorkRailwayActualBakMapper.cleanPredcition(model.getActualNo());
                cleanModel.setUploadFlag("1");
                cleanModel.setValueFlag("0");
                meterWorkRailwayActualBakMapper.updateByPrimaryKeySelective(cleanModel);
                //删结净
                //meterWorkCarActualMapper.deleteByPrimaryKey(model.getActualNo());
            }
            rm.setSucceed();
            rm.setMessage("操作成功！！");
            rm.setCode("200");
        }catch(Exception e){
            e.printStackTrace();
            rm.setMessage("操作异常，请确认！>>>" + e.getMessage());
        }
        return rm;
    }

    //还原委托
    public void removeScaleEl(String predictionNo){
        String userId;
        String userName;
        try{
            UserPayload payload = UserPayload.getCurrUser();
            userId = payload.getUserCode();
            userName = payload.getUserName();
        }catch(Exception e) {
            userId = "admin";
            userName = "admins";
        }
        PreRailwayScale scale = preRailwayScaleMapper.selectByPrimaryKey(predictionNo);
        scale.setValueFlag("1");
        scale.setUploadFlag("1");
        scale.setUpdateTime(new Date());
        scale.setUpdateManNo(userId);
        scale.setUpdateManName(userName);
        preRailwayScaleMapper.updateByPrimaryKeySelective(scale);
    }

    //还原一次
    public void removeFirstEl(MeterWorkRailwayActFirstBak model) {
        String userId;
        String userName;
        try{
            UserPayload payload = UserPayload.getCurrUser();
            userId = payload.getUserCode();
            userName = payload.getUserName();
        }catch(Exception e) {
            userId = "admin";
            userName = "admins";
        }
        model.setValueFlag("0");
        model.setUpdateManNo(userId);
        model.setUpdateManName(userName);
        model.setUpdateTime(new Date());
        model.setIsPreSacale("0");
    }

    //还原结净
    public void removeEl(MeterWorkRailwayActualBak model) {
        String userId;
        String userName;
        try{
            UserPayload payload = UserPayload.getCurrUser();
            userId = payload.getUserCode();
            userName = payload.getUserName();
        }catch(Exception e) {
            userId = "admin";
            userName = "admins";
        }
        model.setUpdateManNo(userId);
        model.setUpdateManName(userName);
        model.setUpdateTime(new Date());
        model.setUploadFlag("1");
        model.setIsPreSacale("0");
        model.setValueFlag("0");
        model.setIsBoundList("0");
        model.setBoundListUrl("");
        model.setContractNo("");
        model.setIsBoundListDownloaded("0");
        model.setDocumentId("");
    }

    @Override
    public PageList<MeterWorkRailwayActualBak> likeByDesc(Map<String, Object> parameters, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<MeterWorkRailwayActualBak> rows = meterWorkRailwayActualBakMapper.likeByDesc(parameters);
        PageList pageInfo = new PageList(rows);
        return pageInfo;
    }

    @Override
    public List<MeterWorkRailwayActualBak> webByLikeDesc(HashMap<String, Object> parameters) {
        if(parameters.get("lcNoTemp") != null) {
            String[] lcNoTemp = parameters.get("lcNoTemp")==null? "".split(","): parameters.get("lcNoTemp").toString().split(",");
            parameters.remove("lcNoTemp");
            parameters.put("lcNoTemp", lcNoTemp);
            for (String str:
                    lcNoTemp) {
                if(str.equals("")) {
                    parameters.put("lcNoNull", "1");
                    break;
                }else {
                    parameters.put("lcNoNull", "");
                }
            }
        }
        if(parameters.get("railwayNoArr") != null) {
            String[] railwayNoList = parameters.get("railwayNoArr").toString().split(",");
            parameters.put("railwayNoList", railwayNoList);
        }
        List<MeterWorkRailwayActualBak> rows = meterWorkRailwayActualBakMapper.likeByDescTemp(parameters);
        return rows;
    }

    @Override
    public List<MeterWorkRailwayActualBak> noPage(Map<String, Object> params) {
        List<MeterWorkRailwayActualBak> rows = meterWorkRailwayActualBakMapper.likeByDesc(params);
        return rows;
    }

    @Override
    public RESTfulResult batchUpdateLcNo(List<MeterWorkRailwayActualBak> models) {
        RESTfulResult rm = new RESTfulResult();
        rm.setFailed();
        try {
            if(!CollectionUtils.isEmpty(models)){
//                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
//                String afl = sdf.format(new Date());
//                String lcNo = meterWorkRailwayActualBakMapper.getLcNo(afl, models.get(0).getNetSpot3No());
                int count = 0;
                for(MeterWorkRailwayActualBak model: models) {
//                    model.setLcNo(model.getNetSpot3Name().replaceAll("#", "")
//                            .replaceAll("轨道衡", "")
//                            .replaceAll("静轨", "")
//                            .replaceAll("静态", "") + "-" + afl + lcNo + "(" + models.size() + ")");
                    MeterWorkRailwayActFirstBak grossModel = meterWorkRailwayActFirstBakMapper.selectByPrimaryKey(model.getActualFirst1No());
                    MeterWorkRailwayActFirstBak tareModel = meterWorkRailwayActFirstBakMapper.selectByPrimaryKey(model.getActualFirst2No());
                    if(model.getGrossTime().compareTo(model.getTareTime()) >= 0) {
                        model.setLcNo(grossModel.getLcNo());
                    }else {
                        model.setLcNo(tareModel.getLcNo());
                    }
                    meterWorkRailwayActualBakMapper.updateByPrimaryKeySelective(model);
                    count++;
                }
                rm.setSucceed();
                rm.setCode("200");
                rm.setData(count);
                rm.setMessage("操作成功,总共"+ count +"条数据修改列次编号成功!!");
            }
        }catch(Exception e) {
            e.printStackTrace();
            rm.setMessage("操作异常！！>>>" + e.getMessage());
        }
        return rm;
    }

    @Override
    public RESTfulResult batchActualUpdateLcNo(List<MeterWorkRailwayActualBak> models) {
        RESTfulResult rm = new RESTfulResult();
        rm.setFailed();
        try {
            int count = 0;
            int lcCount = 0;
            if(models.size() >= 1) {
                List<MeterWorkRailwayActFirstBak> grossList = new ArrayList<>();
                List<MeterWorkRailwayActFirstBak> tareList = new ArrayList<>();
                for(MeterWorkRailwayActualBak model: models) {
                    if(StringUtils.isNotEmpty(model.getLcNo())) {
                        rm.setMessage("净重数据已经含有列次号，不允许生成列次号！");
                        return rm;
                    }
                    MeterWorkRailwayActFirstBak grossModel = meterWorkRailwayActFirstBakMapper.selectByPrimaryKey(model.getActualFirst1No());
                    MeterWorkRailwayActFirstBak tareModel = meterWorkRailwayActFirstBakMapper.selectByPrimaryKey(model.getActualFirst2No());
                    if(grossModel != null && tareModel != null) {
                        if(StringUtils.isNotEmpty(grossModel.getLcNo()) && StringUtils.isNotEmpty(tareModel.getLcNo())) {
                            rm.setMessage("净重数据所的一次数据已经含有列次号，不允许生成列次号！");
                            return rm;
                        }
                        grossList.add(grossModel);
                        tareList.add(tareModel);
                        lcCount += 2;
                    }
                }

                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
                if(grossList.size() >= 1) {
                    String afl = sdf.format(new Date());
                    String lcNo = meterWorkRailwayActFirstBakMapper.getLcNo(afl, grossList.get(0).getBaseSpotNo());
                    for (MeterWorkRailwayActFirstBak model : grossList) {
                        model.setLcNo(model.getBaseSpotName().replaceAll("#", "")
                                .replaceAll("轨道衡", "")
                                .replaceAll("静轨", "")
                                .replaceAll("静态", "") + "-" + afl + lcNo + "(" + lcCount + ")");
                        model.setLcNo(model.getLcNo());
                        meterWorkRailwayActFirstBakMapper.updateByPrimaryKeySelective(model);
                    }
                }

                if(tareList.size() >= 1) {
                    String afl = sdf.format(new Date());
                    String lcNo = meterWorkRailwayActFirstBakMapper.getLcNo(afl, tareList.get(0).getBaseSpotNo());
                    for (MeterWorkRailwayActFirstBak model : tareList) {
                        model.setLcNo(model.getBaseSpotName().replaceAll("#", "")
                                .replaceAll("轨道衡", "")
                                .replaceAll("静轨", "")
                                .replaceAll("静态", "") + "-" + afl + lcNo + "(" + lcCount + ")");
                        model.setLcNo(model.getLcNo());
                        meterWorkRailwayActFirstBakMapper.updateByPrimaryKeySelective(model);
                    }
                }
                for(MeterWorkRailwayActualBak model: models) {
                    MeterWorkRailwayActFirstBak grossModel = meterWorkRailwayActFirstBakMapper.selectByPrimaryKey(model.getActualFirst1No());
                    MeterWorkRailwayActFirstBak tareModel = meterWorkRailwayActFirstBakMapper.selectByPrimaryKey(model.getActualFirst2No());
                    if(model.getGrossTime().compareTo(model.getTareTime()) >= 0) {
                        model.setLcNo(grossModel.getLcNo());
                    }else {
                        model.setLcNo(tareModel.getLcNo());
                    }
                    meterWorkRailwayActualBakMapper.updateByPrimaryKeySelective(model);
                    count++;
                }
            }else {
                rm.setMessage("未勾选净重数据，请重新勾选！");
            }
            rm.setSucceed();
            rm.setCode("200");
            rm.setData(count);
            rm.setMessage("操作成功,总共"+ count +"条数据修改列次编号成功!!");
        }catch(Exception e) {
            e.printStackTrace();
            rm.setMessage("操作异常！！>>>" + e.getMessage());
        }
            return rm;
    }

    @Override
    public RESTfulResult autoPrintRailway(HashMap<String, Object> params) {
        RESTfulResult rm = new RESTfulResult();
        rm.setFailed();
        try {
            //查询配置表所有发货单位编号
            HashMap<String, Object> obj = new HashMap<>();
            obj.put("pBaseCode", "001038");
            List<String> matterModels = comBaseInfoMapper.matterNoByBaseCode(obj);
            params.put("list", matterModels);
            List<MeterWorkRailwayActualBak> actualModels = meterWorkRailwayActualBakMapper.autoPrintRailway(params);

            rm.setSucceed();
            rm.setCode("200");
            rm.setData(actualModels);
            rm.setMessage("操作成功,总共"+ actualModels.size() +"条数据!!");
        }catch(Exception e) {
            e.printStackTrace();
            rm.setMessage("操作异常！！>>>" + e.getMessage());
        }
        return rm;
    }

    @Override
    public String subStr(String str, String flag) {
        String[] ss = str.split(",");
        if(flag.equals("0")){
            return ss[0];
        }else {
            return ss[1];
        }

    }

    @Override
    public RESTfulResult CopyToActual(List<String> ids, String railwayNo) throws Exception{
        RESTfulResult rm = new RESTfulResult();
        rm.setFailed();
        try{
            for (String id : ids) {
                //根据id获取对应的一次数据
                MeterWorkRailwayActualBak actualBak = meterWorkRailwayActualBakMapper.selectByPrimaryKey(id);

                //一次数据为空
                if (actualBak == null) {
                    //抛出异常
                    //事务回滚
                    throw new Exception("结净数据为空");
                }

//                if (!railwayNo.equals(actualBak.getRailwayNo())) {
//                    throw new Exception(id + "的车号不一致");
//                }

                //判断是否符合要求
                String note = isSuit(actualBak);
                if (note.equals("1")) {
                    //复制到First正式表里面
                    MeterWorkRailwayActual actual = new MeterWorkRailwayActual();
                    //复制一份
                    BeanUtils.copyProperties(actualBak, actual);
                    //修改主键
                    actual.setActualFirst1No(actual.getActualFirst1No() + "bak");
                    actual.setActualFirst2No(actual.getActualFirst2No() + "bak");
                    actual.setActualNo(actual.getActualNo() + "bak");

                    MeterWorkRailwayActual tempActual = meterWorkRailwayActualMapper.selectByPrimaryKey(actual.getActualNo());
                    if(tempActual != null) {
                        throw new Exception("结净数据已转成正式数据，不能重复转正式数据");
                    }
                    MeterWorkRailwayActFirst tempGrossFirst = meterWorkRailwayActFirstMapper.selectByPrimaryKey(actual.getActualFirst1No());
                    if(tempActual != null) {
                        throw new Exception("一次毛重数据已转成正式数据，不能重复转正式数据");
                    }
                    MeterWorkRailwayActFirst tempTareFirst = meterWorkRailwayActFirstMapper.selectByPrimaryKey(actual.getActualFirst2No());
                    if(tempActual != null) {
                        throw new Exception("一次皮重数据已转成正式数据，不能重复转正式数据");
                    }

                    meterWorkRailwayActualMapper.insert(actual);

                    try {
                        //新增日志
                        MeterBaseOperationLog logModel = new MeterBaseOperationLog();
                        logModel.setId(PublicMethod.IdCreate(2));
                        logModel.setCreateManNo(UserUtil.getCurrentUserId());
                        logModel.setCreateManName(UserUtil.getCurrentUserName());
                        logModel.setCreateTime(new Date());
                        if("001019001".equals(actual.getRailwayTypeNo())){
                            logModel.setOperationPage("web端-静态轨道衡净重数据维护");
                        }else{
                            logModel.setOperationPage("web端-吊钩秤净重数据维护");
                        }

                        logModel.setOperationFunction("新增");
                        logModel.setOperationId(actual.getActualNo());
                        logModel.setOperationPredictionNo(actual.getPredictionNo());
                        logModel.setOperationCarnNo(actual.getRailwayNo());
                        meterBaseOperationLogMapper.insertSelective(logModel);
                    }catch (Exception e){
                        logger.error("web端-汽车衡一次数据维护日志新增失败");
                        e.printStackTrace();
                    }

                    //同时将两个一次也复制一下
                    MeterWorkRailwayActFirstBak firstBak1 = meterWorkRailwayActFirstBakMapper.selectByPrimaryKey(actualBak.getActualFirst1No());
                    MeterWorkRailwayActFirstBak firstBak2 = meterWorkRailwayActFirstBakMapper.selectByPrimaryKey(actualBak.getActualFirst2No());

                    MeterWorkRailwayActFirst first1 = new MeterWorkRailwayActFirst();
                    MeterWorkRailwayActFirst first2 = new MeterWorkRailwayActFirst();
                    BeanUtils.copyProperties(firstBak1, first1);
                    BeanUtils.copyProperties(firstBak2, first2);
                    first1.setActualFirstNo(first1.getActualFirstNo() + "bak");
                    first2.setActualFirstNo(first2.getActualFirstNo() + "bak");
                    meterWorkRailwayActFirstMapper.insert(first1);
                    meterWorkRailwayActFirstMapper.insert(first2);

                    firstBak1.setValueFlag("0");
                    firstBak2.setValueFlag("0");
                    actualBak.setValueFlag("0");
                    meterWorkRailwayActFirstBakMapper.updateByPrimaryKeySelective(firstBak1);
                    meterWorkRailwayActFirstBakMapper.updateByPrimaryKeySelective(firstBak2);
                    meterWorkRailwayActualBakMapper.updateByPrimaryKeySelective(actualBak);
                } else {
                    throw new Exception(note);
                }
            }
            rm.setSucceed();
            rm.setCode("200");
            rm.setMessage("复制成功");
        }catch(Exception e) {
            e.printStackTrace();
            rm.setMessage(e.getMessage());
        }
        return rm;
    }

    private String isSuit(MeterWorkRailwayActualBak model){

        //毛重信息
        if (model.getBaseSpot1No() == null || StringUtils.isEmpty(model.getBaseSpot1No())) {
            return "毛重计量编号为空";
        }
        if (model.getBaseSpot1Name() == null || StringUtils.isEmpty(model.getBaseSpot1Name())) {
            return "毛重计量名称为空";
        }
        if(model.getGrossManNo() == null || StringUtils.isEmpty(model.getGrossManNo())) {
            return  "毛重计量员编号为空";
        }
        if(model.getGrossManName() == null || StringUtils.isEmpty(model.getGrossManName())) {
            return  "毛重计量员为空";
        }
        if (model.getGrossTime() == null || StringUtils.isEmpty(model.getGrossTime().toString())) {
            return "毛重时间为空";
        }
        if (model.getGrossWeight() == null || StringUtils.isEmpty(model.getGrossWeight().toString())) {
            return "毛重为空";
        }
        //皮重信息
        if (model.getBaseSpot2No() == null || StringUtils.isEmpty(model.getBaseSpot2No())) {
            return "皮重计量点编号为空";
        }
        if (model.getBaseSpot2Name() == null || StringUtils.isEmpty(model.getBaseSpot2Name())) {
            return "皮重计量点为空";
        }
        if(model.getTareManNo() == null || StringUtils.isEmpty(model.getTareManNo())) {
            return  "皮重计量员编号为空";
        }
        if(model.getTareManName() == null || StringUtils.isEmpty(model.getTareManName())) {
            return "皮重计量员名称为空";
        }
        if (model.getTareTime() == null || StringUtils.isEmpty(model.getTareTime().toString())) {
            return "皮重时间为空";
        }
        if (model.getTareWeight() == null || StringUtils.isEmpty(model.getTareWeight().toString())) {
            return "皮重为空";
        }

        //结净信息
        if (model.getNetSpot3No() == null || StringUtils.isEmpty(model.getNetSpot3No())) {
            return "净重计量点编号为空";
        }
        if (model.getNetSpot3Name() == null || StringUtils.isEmpty(model.getNetSpot3Name())) {
            return "净重计量点名称为空";
        }
        if(model.getNetManNo() == null || StringUtils.isEmpty(model.getNetManNo())) {
            return "净重计量员编号为空";
        }
        if(model.getNetManName() == null || StringUtils.isEmpty(model.getNetManName())) {
            return  "净重计量员为空";
        }
        if (model.getNetTime() == null || StringUtils.isEmpty(model.getNetTime().toString())) {
            return "净重时间为空";
        }
        if (model.getNetWeight() == null || StringUtils.isEmpty(model.getNetWeight().toString())) {
            return "净重为空";
        }
        //创建人、创建时间
        if(model.getCreateManName() == null || StringUtils.isEmpty(model.getCreateManName())) {
            return  "创建人为空";
        }
        if (model.getCreateTime() == null || StringUtils.isEmpty(model.getCreateTime().toString())) {
            return "创建时间为空";
        }
        if (model.getDataSource() == null || StringUtils.isEmpty(model.getDataSource())) {
            return "计量数据来源为空";
        }
        if (model.getUploadFlag() == null || StringUtils.isEmpty(model.getUploadFlag())){
            return "同步标志为空";
        }
        if (model.getValueFlag() == null || StringUtils.isEmpty(model.getValueFlag())){
            return "数据状态为空";
        }
        if(model.getPredictionNo() == null){
            return "委托编号为空";
        }
        return "1";
    }

    //=========================eason add 2023-04-14=====================================
    @Override
    public RESTfulResult addNetEmergencyList(List<MeterWorkRailwayActualBak> lt) throws Exception {
        List<DjPbModel> lst=new ArrayList<>();
        RESTfulResult rm = new RESTfulResult();
        rm.setCode("200");

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

        for(MeterWorkRailwayActualBak model:lt){
            String str=model.getActualNo();

            MeterWorkRailwayActFirstBak mwcaf1 = new MeterWorkRailwayActFirstBak();
            MeterWorkRailwayActFirstBak mwcaf2 = new MeterWorkRailwayActFirstBak();
            MeterWorkRailwayActualBak actualRow = new MeterWorkRailwayActualBak();
            String predictionNo = model.getPredictionNo();

            //毛重
            String actualFirstNo = sdf.format(new Date()) + meterWorkRailwayActFirstBakMapper.getNewID(afl);
            mwcaf1.setActualFirstNo(actualFirstNo);
            mwcaf1.setRailwayNo(model.getRailwayNo());
            mwcaf1.setMeterWeight(model.getGrossWeight());
            mwcaf1.setRailwayTypeNo(model.getRailwayTypeNo());
            mwcaf1.setRailwayTypeName(model.getRailwayTypeName());
            mwcaf1.setWeightType("0");
            mwcaf1.setCreateManNo(model.getGrossManNo());
            mwcaf1.setCreateManName(model.getGrossManName());
            mwcaf1.setCreateTime(model.getGrossTime());
            mwcaf1.setBaseSpotNo(model.getBaseSpot1No());
            mwcaf1.setBaseSpotName(model.getBaseSpot1Name());
            mwcaf1.setValueFlag("2");
            mwcaf1.setCheckFlag("0");
            mwcaf1.setDataSource("4");
            mwcaf1.setMeterMode("3");
            mwcaf1.setIsPreSacale("0");
            meterWorkRailwayActFirstBakMapper.insertSelective(mwcaf1);
            //皮重
            String actualSecondNo = sdf.format(new Date()) + meterWorkRailwayActFirstBakMapper.getNewID(afl);
            mwcaf2.setActualFirstNo(actualSecondNo);
            mwcaf2.setRailwayNo(model.getRailwayNo());
            mwcaf2.setMeterWeight(model.getTareWeight());
            mwcaf2.setWeightType("1");
            mwcaf2.setRailwayTypeNo(model.getRailwayTypeNo());
            mwcaf2.setRailwayTypeName(model.getRailwayTypeName());
            mwcaf2.setCreateManNo(model.getGrossManNo());
            mwcaf2.setCreateManName(model.getGrossManName());
            mwcaf2.setCreateTime(model.getTareTime());
            mwcaf2.setBaseSpotNo(model.getBaseSpot2No());
            mwcaf2.setBaseSpotName(model.getBaseSpot2Name());
            mwcaf2.setValueFlag("2");
            mwcaf2.setCheckFlag("0");
            mwcaf2.setDataSource("4");
            mwcaf2.setMeterMode("3");
            mwcaf2.setIsPreSacale("0");
            meterWorkRailwayActFirstBakMapper.insertSelective(mwcaf2);

            //将委托中的编号和收发货单位和一次数据等数据拷贝进结净数据中
            MeterWorkRailwayActualBak mwca1 = meterWorkRailwayActualBakMapper.manualAdd(actualFirstNo, actualSecondNo);
            BeanUtils.copyProperties(mwca1, actualRow);

            String no = meterWorkRailwayActualBakMapper.getNewID(sdf.format(new Date()));
            actualRow.setActualNo(sdf.format(new Date()) + no);
            actualRow.setRailwayTypeNo(model.getRailwayTypeNo());
            actualRow.setRailwayTypeName(model.getRailwayTypeName());
            actualRow.setNetTime(model.getNetTime());
            actualRow.setNetMode(DbConstants.TYPE);
            actualRow.setNote("手动录入");
            actualRow.setUploadFlag("1");
            actualRow.setIsPreSacale("1");
            actualRow.setValueFlag("1");
            actualRow.setGrossMode("3");
            actualRow.setTareMode("3");
            actualRow.setCreateManName(model.getGrossManName());
            actualRow.setCreateTime(new Date());
            actualRow.setNetTime(model.getNetTime());
            actualRow.setDataSource("4");
            actualRow.setPredictionType("1");
            actualRow.setUpdateManNo("system");
            actualRow.setUpdateManName("手动录入");
            actualRow.setUpdateTime(new Date());
            actualRow.setPredictionNo(predictionNo);
            actualRow.setNetWeight(mwcaf1.getMeterWeight().subtract(mwcaf2.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());
            }
            meterWorkRailwayActualBakMapper.insertSelective(actualRow);

            try {
                add(model);
                DjPbModel dm = new DjPbModel();
                dm.setKey(str);
                dm.setValue(actualFirstNo);
                lst.add(dm);
            }catch (Exception ex){ }
        }

        rm.setData(lst);
        rm.setMessage("成功");
        return rm;
    }

}
