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

import cn.hutool.db.handler.HandleHelper;
import com.steerinfo.baseinfo.combaseinfo.mapper.ComBaseInfoMapper;
import com.steerinfo.baseinfo.combaseinfo.model.ComBaseInfo;
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.baseinfo.meterbaseuserprintconfig.mapper.MeterBaseUserPrintConfigMapper;
import com.steerinfo.baseinfo.meterbaseuserprintconfig.model.MeterBaseUserPrintConfig;
import com.steerinfo.baseinfo.meterbasevehiclerangeconfig.mapper.MeterBaseVehicleRangeConfigMapper;
import com.steerinfo.baseinfo.meterbasevehiclerangeconfig.model.MeterBaseVehicleRangeConfig;
import com.steerinfo.baseinfo.meterbasevehiclerangeconfig.service.IMeterBaseVehicleRangeConfigService;
import com.steerinfo.baseinfo.meterbasevehiclerangeprintconfig.mapper.MeterBaseVehicleRangePrintConfigMapper;
import com.steerinfo.baseinfo.meterbasevehiclerangeprintconfig.model.MeterBaseVehicleRangePrintConfig;
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.except.MarkerMetException;
import com.steerinfo.meterwork.meterworkcaractual.model.MeterWorkCarActual;
import com.steerinfo.meterwork.meterworkcaractualfirst.model.MeterWorkCarActualFirst;
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.meterworkrailwayactual.mapper.MeterWorkRailwayActualMapper;
import com.steerinfo.meterwork.meterworkrailwayactual.model.MeterWorkRailwayActual;
import com.steerinfo.meterwork.meterworkrailwayactual.service.IMeterWorkRailwayActualService;
import com.steerinfo.meterwork.meterworkrailwayreceived.mapper.MeterWorkRailwayReceivedMapper;
import com.steerinfo.meterwork.meterworkrailwayreceived.model.MeterWorkRailwayReceived;
import com.steerinfo.meterwork.meterworkrailwayrecmain.mapper.MeterWorkRailwayRecMainMapper;
import com.steerinfo.meterwork.meterworkrailwayrecmain.model.MeterWorkRailwayRecMain;
import com.steerinfo.pretrack.prerailwayscale.mapper.PreRailwayScaleMapper;
import com.steerinfo.pretrack.prerailwayscale.model.PreRailwayScale;
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.apache.catalina.User;
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 = "meterWorkRailwayActualService")
public class MeterWorkRailwayActualServiceImpl extends BaseServiceImpl<MeterWorkRailwayActual, String> implements IMeterWorkRailwayActualService {

    @Resource
    private MeterWorkRailwayActualMapper meterWorkRailwayActualMapper;

    @Resource
    private MeterWorkRailwayActFirstMapper meterWorkRailwayActFirstMapper;

    @Resource
    private MeterWorkRailwayReceivedMapper meterWorkRailwayReceivedMapper;

    @Resource
    private MeterBaseUserPrintConfigMapper meterBaseUserPrintConfigMapper;

    @Resource
    private MeterWorkRailwayRecMainMapper meterWorkRailwayRecMainMapper;

    @Resource
    private MeterBaseRailwayAiweightMapper meterBaseRailwayAiweightMapper;

    @Resource
    private MeterBaseRailwayWeightMapper meterBaseRailwayWeightMapper;

    @Resource
    private MeterBaseOperationLogMapper meterBaseOperationLogMapper;

    @Resource
    private MeterBaseVehicleRangePrintConfigMapper meterBaseVehicleRangePrintConfigMapper;

    @Resource
    private MeterBaseVehicleRangeConfigMapper meterBaseVehicleRangeConfigMapper;

    @Resource
    private PreRailwayScaleMapper preRailwayScaleMapper;

    @Resource
    private ComBaseInfoMapper comBaseInfoMapper;

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

    @Autowired
    IMeterBaseVehicleRangeConfigService meterBaseVehicleRangeConfigService;

    @Override
    protected IBaseMapper<MeterWorkRailwayActual, String> getMapper() {
        return meterWorkRailwayActualMapper;
    }

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

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

    @Override
    public int cancel(MeterWorkRailwayActual 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, "只有已匹配委托且已发布的数据才能进行撤销发布操作");
        }
        PreRailwayScale scale = preRailwayScaleMapper.selectByPrimaryKey(model.getPredictionNo());
        if(scale != null && scale.getValueFlag().equals("9")) {
            throw new MarkerMetException(500, "只有未结算的结净数据才能进行撤销发布操作");
        }

        UserPayload userPayload = new UserPayload();
        String userName = userPayload.getUserName();
        String userId = userPayload.getUserCode();
        model.setValueFlag("1");
        model.setUploadFlag("1");
        model.setUpdateTime(new Date());
        model.setUpdateManName(userName);
        model.setUpdateManNo(userId);
        try {
            meterWorkRailwayActualMapper.updateByPrimaryKeySelective(model);

            MeterBaseOperationLog logModel = new MeterBaseOperationLog();
            logModel.setId(PublicMethod.IdCreate(2));
            logModel.setCreateManNo(userId);
            logModel.setCreateManName(userName);
            logModel.setCreateTime(new Date());
            logModel.setOperationPage("web端-轨道衡净重数据维护");
            logModel.setOperationFunction("取消发布");
            logModel.setOperationId(model.getActualNo());
            logModel.setOperationPredictionNo(model.getPredictionNo());
            logModel.setOperationCarnNo(model.getRailwayNo());
            meterBaseOperationLogMapper.insertSelective(logModel);
        } catch (Exception e) {
            throw e;
        }
        return ++i;
    }

    @Override
    public RESTfulResult batchCancel(List<MeterWorkRailwayActual> models) {
        RESTfulResult rm = new RESTfulResult();
        rm.setFailed();
        try{
            Assert.isTrue(models.size() >= 1, "请勾选数据进行撤销发布");
            for (MeterWorkRailwayActual model: models){
                MeterWorkRailwayActual modelTemp = meterWorkRailwayActualMapper.selectByPrimaryKey(model.getActualNo());
                if (modelTemp.getActualNo() == null || "".equals(modelTemp.getActualNo())) {
                    throw new MarkerMetException(500, "数据主键为空");
                }
                if (modelTemp.getPredictionNo() == null || "".equals(modelTemp.getPredictionNo()) || "1".equals(modelTemp.getValueFlag())) {
                    throw new MarkerMetException(500, "只有已匹配委托且已发布的数据才能进行撤销发布操作");
                }
                PreRailwayScale scale = preRailwayScaleMapper.selectByPrimaryKey(model.getPredictionNo());
                if(scale != null && scale.getValueFlag().equals("9")) {
                    throw new MarkerMetException(500, "只有未结算的结净数据才能进行撤销发布操作");
                }
            }
//            UserPayload userPayload = UserPayload.getCurrUser();
            String userName = null;
            String userId = null;
            try{
                UserPayload userPayload = UserPayload.getCurrUser();
                userName = userPayload.getUserName();
                userId = userPayload.getUserCode();
            }catch (Exception e) {
                userName = models.get(0).getUpdateManName();
                userId = models.get(0).getUpdateManNo();
            }
            int count = 0;
            for (MeterWorkRailwayActual model: models){
                MeterWorkRailwayActual modelTemp = meterWorkRailwayActualMapper.selectByPrimaryKey(model.getActualNo());
                modelTemp.setValueFlag("1");
                modelTemp.setUploadFlag("1");
                modelTemp.setUpdateTime(new Date());
                modelTemp.setUpdateManName(userName);
                modelTemp.setUpdateManNo(userId);
                meterWorkRailwayActualMapper.updateByPrimaryKeySelective(modelTemp);

                MeterBaseOperationLog logModel = new MeterBaseOperationLog();
                logModel.setId(PublicMethod.IdCreate(2));
                logModel.setCreateManNo(userId);
                logModel.setCreateManName(userName);
                logModel.setCreateTime(new Date());
                logModel.setOperationPage("web端-轨道衡净重数据维护");
                logModel.setOperationFunction("批量取消发布");
                logModel.setOperationId(modelTemp.getActualNo());
                logModel.setOperationPredictionNo(modelTemp.getPredictionNo());
                logModel.setOperationCarnNo(modelTemp.getRailwayNo());
                meterBaseOperationLogMapper.insertSelective(logModel);
                count ++;
            }
            rm.setSucceed();
            rm.setMessage("共有"+ count +"条数据撤销发布成功");
            rm.setData(count);
        }catch (Exception e) {
            e.printStackTrace();
            rm.setMessage(e.getMessage());
        }
        return rm;
    }

    //动态衡作废结净数据、并恢复从表数据
    @Override
    public RESTfulResult deleteList(List<MeterWorkRailwayActual> models) {
        RESTfulResult rm = new RESTfulResult();
        rm.setFailed();
        try{
            int count = 0;
            Assert.isTrue(models.size() >= 1, "请勾选数据进行作废数据");
            for (MeterWorkRailwayActual model: models){
                MeterWorkRailwayActual modelTemp = meterWorkRailwayActualMapper.selectByPrimaryKey(model.getActualNo());
                if (modelTemp.getActualNo() == null || "".equals(modelTemp.getActualNo())) {
                    rm.setMessage("未找到结净计量数据，请确认！！！");
                    return rm;
                }
                if ("2".equals(modelTemp.getValueFlag()) || "0".equals(modelTemp.getValueFlag())) {
                    rm.setMessage("只有有效未发布的数据才能进行作废操作");
                    return rm;
                }
            }

            String userId= models.get(0).getUpdateManNo();
            String userName = models.get(0).getUpdateManName();

            for(MeterWorkRailwayActual 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 (MeterWorkRailwayActual modelTemp: models) {
                //循环每一个结净记录
                MeterWorkRailwayActual model = meterWorkRailwayActualMapper.selectByPrimaryKey(modelTemp.getActualNo());
                //委托不能为空
                if(model.getPredictionNo() != null && 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);
                    }
                }

                // 清空一次毛重、皮重委托信息
                MeterWorkRailwayActFirst firstGross = meterWorkRailwayActFirstMapper.selectByPrimaryKey(model.getActualFirst1No());
                if(firstGross != null){
                    firstGross = meterWorkRailwayActFirstMapper.selectAndRemove(model.getActualFirst1No());
                    firstGross.setValueFlag(DbConstants.VALID);
                    firstGross.setUpdateManNo(userId);
                    firstGross.setUpdateManName(userName);
                    firstGross.setNote(model.getNote());
                    firstGross.setUpdateTime(new Date());
                    firstGross.setIsPreSacale("0");
                    firstGross.setValueFlag("0");
//                    meterWorkRailwayActFirstMapper.updateByPrimaryKeySelective(firstGross);
                    meterWorkRailwayActFirstMapper.deleteByPrimaryKey(firstGross.getActualFirstNo());
                    MeterWorkRailwayReceived received = meterWorkRailwayReceivedMapper.selectAndRemove(firstGross.getActualFirstNo());
                    received.setValueFlag("0");
                    received.setIsAutoOperation("1");
                    meterWorkRailwayReceivedMapper.updateByPrimaryKeySelective(received);
                    //恢复从表数据
//                    preRailwayScaleMapper.updateMeterWorkRailwayReceiveds(firstGross.getActualFirstNo());
                }

                MeterWorkRailwayActFirst firstTare = meterWorkRailwayActFirstMapper.selectByPrimaryKey(model.getActualFirst2No());
                if(firstTare != null){
                    firstTare =  meterWorkRailwayActFirstMapper.selectAndRemove(model.getActualFirst2No());
                    firstTare.setValueFlag(DbConstants.VALID);
                    firstTare.setUpdateManNo(userId);
                    firstTare.setUpdateManName(userName);
                    firstTare.setNote(model.getNote());
                    firstTare.setUpdateTime(new Date());
                    firstTare.setIsPreSacale("0");
                    firstTare.setValueFlag("0");
                    meterWorkRailwayActFirstMapper.deleteByPrimaryKey(firstTare.getActualFirstNo());
                    MeterWorkRailwayReceived received = meterWorkRailwayReceivedMapper.selectAndRemove(firstTare.getActualFirstNo());
                    received.setValueFlag("0");
                    received.setIsAutoOperation("1");
                    meterWorkRailwayReceivedMapper.updateByPrimaryKeySelective(received);
                    //恢复从表数据
//                    preRailwayScaleMapper.updateMeterWorkRailwayReceiveds(firstTare.getActualFirstNo());
                }
                // 作废结净数据并解除委托
                MeterWorkRailwayActual actualRow = meterWorkRailwayActualMapper.cleanPredcition(model.getActualNo());
                actualRow.setUploadFlag("1");
                actualRow.setValueFlag("0");
                actualRow.setIsPreSacale("0");
                meterWorkRailwayActualMapper.updateByPrimaryKey(actualRow);

                MeterBaseOperationLog logModel = new MeterBaseOperationLog();
                logModel.setId(PublicMethod.IdCreate(2));
                logModel.setCreateManNo(userId);
                logModel.setCreateManName(userName);
                logModel.setCreateTime(new Date());
                logModel.setOperationPage("C#端-动轨净重数据维护");
                logModel.setOperationFunction("结净废除");
                logModel.setOperationId(model.getActualNo());
                logModel.setOperationPredictionNo(model.getPredictionNo());
                logModel.setOperationCarnNo(model.getRailwayNo());
                meterBaseOperationLogMapper.insertSelective(logModel);
                //删结净
                //meterWorkCarActualMapper.deleteByPrimaryKey(model.getActualNo());
            }
            rm.setSucceed();
            rm.setMessage("共有"+ count +"条数据作废净重数据成功");
            rm.setData(count);
        }catch (Exception e) {
            e.printStackTrace();
            rm.setMessage(e.getMessage());
        }
        return rm;
    }

    @Override
    public int publish(MeterWorkRailwayActual 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 = UserPayload.getCurrUser();
        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 {
            meterWorkRailwayActualMapper.updateByPrimaryKeySelective(model);

            MeterBaseOperationLog logModel = new MeterBaseOperationLog();
            logModel.setId(PublicMethod.IdCreate(2));
            logModel.setCreateManNo(userId);
            logModel.setCreateManName(userName);
            logModel.setCreateTime(new Date());
            logModel.setOperationPage("web端-轨道衡净重数据维护");
            logModel.setOperationFunction("发布");
            logModel.setOperationId(model.getActualNo());
            logModel.setOperationPredictionNo(model.getPredictionNo());
            logModel.setOperationCarnNo(model.getRailwayNo());
            meterBaseOperationLogMapper.insertSelective(logModel);
        } catch (Exception e) {
            throw e;
        }
        return ++i;
    }

    @Override
    public RESTfulResult batchPublish(List<MeterWorkRailwayActual> models) {
        RESTfulResult rm = new RESTfulResult();
        rm.setFailed();
        try{
            Assert.isTrue(models.size() >= 1, "请勾选数据进行发布");
            for (MeterWorkRailwayActual model: models){
                MeterWorkRailwayActual modelTemp = meterWorkRailwayActualMapper.selectByPrimaryKey(model.getActualNo());
                if (modelTemp.getPredictionNo() == null || "".equals(modelTemp.getPredictionNo()) || "2".equals(modelTemp.getValueFlag())) {
                    throw new MarkerMetException(500, "只有已匹配委托且未发布的数据才能进行数据发布操作");
                }
            }
//            UserPayload userPayload = UserPayload.getCurrUser();
//            String userName = userPayload.getUserName();
//            String userId = userPayload.getUserCode();
            String userName = null;
            String userId = null;
            try{
                UserPayload userPayload = UserPayload.getCurrUser();
                userName = userPayload.getUserName();
                userId = userPayload.getUserCode();
            }catch (Exception e) {
                userName = models.get(0).getUpdateManName();
                userId = models.get(0).getUpdateManNo();
            }
            int count = 0;
            for (MeterWorkRailwayActual model: models){
                MeterWorkRailwayActual modelTemp = meterWorkRailwayActualMapper.selectByPrimaryKey(model.getActualNo());
                modelTemp.setValueFlag("2");
                modelTemp.setUploadFlag("1");
                modelTemp.setIsAutoPublish("1");
                modelTemp.setUpdateTime(new Date());
                modelTemp.setUpdateManName(userName);
                modelTemp.setUpdateManNo(userId);
                meterWorkRailwayActualMapper.updateByPrimaryKeySelective(modelTemp);

                MeterBaseOperationLog logModel = new MeterBaseOperationLog();
                logModel.setId(PublicMethod.IdCreate(2));
                logModel.setCreateManNo(userId);
                logModel.setCreateManName(userName);
                logModel.setCreateTime(new Date());
                logModel.setOperationPage("web端-轨道衡净重数据维护");
                logModel.setOperationFunction("批量发布");
                logModel.setOperationId(modelTemp.getActualNo());
                logModel.setOperationPredictionNo(modelTemp.getPredictionNo());
                logModel.setOperationCarnNo(modelTemp.getRailwayNo());
                logModel.setOperationBeforeFix(model.toString());
                logModel.setOperationAfterFix(modelTemp.toString());
                meterBaseOperationLogMapper.insertSelective(logModel);
                count ++;
            }
            rm.setSucceed();
            rm.setMessage("共有"+ count +"条数据发布成功");
            rm.setData(count);
        }catch (Exception e) {
            e.printStackTrace();
            rm.setMessage(e.getMessage());
        }
        return rm;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public MeterWorkRailwayActual clean(String actualFirstNo, String dataNo, String predictionNo) throws MarkerMetException {
        try {
            String userId = "";
            String userName = "";
            try{
                UserPayload userPayload = UserPayload.getCurrUser();
                userId = userPayload.getUserCode();
                userName = userPayload.getUserName();
            }catch (Exception e) {
                userId = "system";
                userName = "system";
            }
            if (actualFirstNo == null && actualFirstNo.equals("")) {
                throw new MarkerMetException(500, "毛重数据编号为空");
            }
            if (dataNo == null && dataNo.equals("")) {
                throw new MarkerMetException(500, "皮重数据编号为空");
            }
            MeterWorkRailwayActFirst mwcaf1 = meterWorkRailwayActFirstMapper.selectByPrimaryKey(actualFirstNo);
            if (mwcaf1 == null) {
                throw new MarkerMetException(500, "未查询到相应的毛重数据！！");
            }
            if (mwcaf1.getValueFlag().equals("2")) {
                throw new MarkerMetException(500, "毛重数据已结净，请重试！！");
            }

            MeterWorkRailwayActFirst mwcaf2 = meterWorkRailwayActFirstMapper.selectByPrimaryKey(dataNo);
            if (mwcaf2 == null) {
                throw new MarkerMetException(500, "未查询到相应的皮重数据！！");
            }
            if (mwcaf2.getValueFlag().equals("2")) {
                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());
                    meterWorkRailwayActFirstMapper.repairPre(repair);
                }
                if (mwcaf2.getPredictionNo() == "" && mwcaf2.getPredictionNo() != ""){
                    preNo = mwcaf1.getPredictionNo();
                    repair.put("predictionNo",preNo);
                    repair.put("actualFirstNo",mwcaf2.getActualFirstNo());
                    meterWorkRailwayActFirstMapper.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(userId);
                scale.setUpdateManName(userName);
                scale.setUploadFlag("1");
                scale.setMeasureStation(mwcaf2.getBaseSpotNo());
                scale.setMeasureStationName(mwcaf2.getBaseSpotName());
                preRailwayScaleMapper.updateByPrimaryKeySelective(scale);
            }

            MeterWorkRailwayActual actualRow = new MeterWorkRailwayActual();

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

            mwcaf1.setValueFlag(DbConstants.NET);
            meterWorkRailwayActFirstMapper.updateByPrimaryKey(mwcaf1);
            mwcaf2.setValueFlag(DbConstants.NET);
            meterWorkRailwayActFirstMapper.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 = meterWorkRailwayActualMapper.getNewID(sdf.format(new Date()));
//            actualRow.setActualNo(sdf.format(new Date()) + no);
            String no = PublicMethod.IdCreate(3);
            actualRow.setActualNo(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());
                actualRow.setLcNo(meterWorkRailwayActFirstMapper.getFirstLcNo(actualRow.getActualFirst1No()));
            }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());
                actualRow.setLcNo(meterWorkRailwayActFirstMapper.getFirstLcNo(actualRow.getActualFirst2No()));
            }
            meterWorkRailwayActualMapper.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(userId);
                prs.setUpdateManName(userName);
                prs.setMeasureStation(actualRow.getNetManName());
                prs.setMeasureStationName(actualRow.getNetSpot3Name());
                preRailwayScaleMapper.updateByPrimaryKeySelective(prs);
            }

            MeterBaseOperationLog logModel = new MeterBaseOperationLog();
            logModel.setId(PublicMethod.IdCreate(2));
            logModel.setCreateManNo(userId);
            logModel.setCreateManName(userName);
            logModel.setCreateTime(new Date());
            logModel.setOperationPage("web端-轨道衡一次数据维护");
            logModel.setOperationFunction("毛皮结净");
            logModel.setOperationId(actualRow.getActualNo());
            logModel.setOperationPredictionNo(actualRow.getPredictionNo());
            logModel.setOperationCarnNo(actualRow.getRailwayNo());
            logModel.setOperationBeforeFix(actualRow.getActualFirst1No() + "," + actualRow.getActualFirst2No());
            meterBaseOperationLogMapper.insertSelective(logModel);
            return actualRow;
        } catch (MarkerMetException e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw e;
        }
    }

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

            String userId = "";
            String userName = "";
            try{
                UserPayload userPayload = UserPayload.getCurrUser();
                userId = userPayload.getUserCode();
                userName = userPayload.getUserName();
            }catch (Exception e) {
                userId = "system";
                userName = "system";
            }
            //勾选的两个一次数据为空，报错
            if((actFirstNo01 == null || StringUtils.isEmpty(actFirstNo01)) || (actFirstNo02 == null || StringUtils.isEmpty(actFirstNo02))) {
                rm.setMessage("未选择两个一次记录");
                return rm;
            }
            MeterWorkRailwayActFirst actFirst01 = meterWorkRailwayActFirstMapper.selectByPrimaryKey(actFirstNo01);
            MeterWorkRailwayActFirst actFirst02 = meterWorkRailwayActFirstMapper.selectByPrimaryKey(actFirstNo02);
            String scaleNo = null;
            //列次号不能为空
            if( (actFirst01.getLcNo() == null || actFirst02.getLcNo() == null)
                    || (StringUtils.isEmpty(actFirst01.getLcNo()) || actFirst01.getLcNo().equals("无列次"))
                    || (StringUtils.isEmpty(actFirst02.getLcNo()) || actFirst02.getLcNo().equals("无列次"))) {
                rm.setMessage("一次数据列次号不允许为空");
                return rm;
            }
            //从勾选的委托、两个一次数据中赋值委托号
            if(predictionNo != null && StringUtils.isNotEmpty(predictionNo)){
                if((actFirst01.getPredictionNo() != null && StringUtils.isNotEmpty(actFirst01.getPredictionNo())
                        || actFirst02.getPredictionNo() != null && StringUtils.isNotEmpty(actFirst02.getPredictionNo()))){
                    rm.setMessage("两个一次记录已带有委托，不能在勾选委托");
                    return rm;
                }
                scaleNo = predictionNo;
            }else if((actFirst01.getPredictionNo() != null && StringUtils.isNotEmpty(actFirst01.getPredictionNo()))){
                scaleNo = actFirst01.getPredictionNo();
            }else if(actFirst02.getPredictionNo() != null && StringUtils.isNotEmpty(actFirst02.getPredictionNo())){
                scaleNo = actFirst02.getPredictionNo();
            }

            PreRailwayScale scale = preRailwayScaleMapper.selectByPrimaryKey(scaleNo);
            //存储结净记录
            MeterWorkRailwayActual actualRow = new MeterWorkRailwayActual();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");

            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
                MeterWorkRailwayActFirst tempModel = new MeterWorkRailwayActFirst();
                BeanUtils.copyProperties(actFirst01, tempModel);
                BeanUtils.copyProperties(actFirst02, actFirst01);
                BeanUtils.copyProperties(tempModel, actFirst02);
            }

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

                //更新一次数据
                //更新第一次毛重数据库
                actFirst01.setWeightType("0");
                actFirst01.setValueFlag(DbConstants.NET);
                actFirst01.setUpdateManNo(userId);
                actFirst01.setUpdateManName(userName);
                actFirst01.setUpdateTime(new Date());
                actFirst01.setIsPreSacale("1");
                actFirst01.setPredictionNo(scale.getPredictionNo());
                actFirst01.setPredictionType("1");
                actFirst01.setNote(Notes);
                meterWorkRailwayActFirstMapper.updateByPrimaryKeySelective(actFirst01);
                //更新第一次皮重数据库
                actFirst02.setWeightType("1");
                actFirst02.setValueFlag(DbConstants.NET);
                actFirst02.setUpdateManNo(userId);
                actFirst02.setUpdateManName(userName);
                actFirst02.setUpdateTime(new Date());
                actFirst02.setIsPreSacale("1");
                actFirst02.setPredictionNo(scale.getPredictionNo());
                actFirst02.setPredictionType("1");
                actFirst02.setNote(Notes);
                meterWorkRailwayActFirstMapper.updateByPrimaryKeySelective(actFirst02);
                //新增历史皮
                meterWorkRailwayActFirstService.doSaveTare(actFirst02);

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

//                actualRow.setActualNo(sdf.format(new Date()) + meterWorkRailwayActualMapper.getNewID(sdf.format(new Date())));
                String no = PublicMethod.IdCreate(3);
                actualRow.setActualNo(no);
                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.setPredictionType("1");
                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());
                    actualRow.setLcNo(meterWorkRailwayActFirstMapper.getFirstLcNo(actualRow.getActualFirst1No()));
                }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());
                    actualRow.setLcNo(meterWorkRailwayActFirstMapper.getFirstLcNo(actualRow.getActualFirst2No()));
                }
                meterWorkRailwayActualMapper.insertSelective(actualRow);

                scale.setValueFlag(DbConstants.NET);
                scale.setUpdateTime(new Date());
                scale.setUpdateManNo(userId);
                scale.setUpdateManName(userName);
                scale.setUploadFlag("1");
                scale.setPredictionType("1");
                scale.setMeasureStation(actualRow.getNetSpot3No());
                scale.setMeasureStationName(actualRow.getNetSpot3Name());
                preRailwayScaleMapper.updateByPrimaryKeySelective(scale);
            }else {
                MeterWorkRailwayActual mwca2 = meterWorkRailwayActualMapper.manualAdd(actFirst01.getActualFirstNo(), actFirst02.getActualFirstNo());
                BeanUtils.copyProperties(mwca2, actualRow);

                //标志位为结净
                actFirst01.setWeightType("0");
                actFirst01.setNote(Notes);
                actFirst01.setIsPreSacale("0");
                actFirst01.setValueFlag(DbConstants.NET);
                meterWorkRailwayActFirstMapper.updateByPrimaryKey(actFirst01);
                actFirst02.setWeightType("1");
                actFirst02.setNote(Notes);
                actFirst02.setIsPreSacale("0");
                actFirst02.setValueFlag(DbConstants.NET);
                meterWorkRailwayActFirstMapper.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()) + meterWorkRailwayActualMapper.getNewID(sdf.format(new Date())));
                String no = PublicMethod.IdCreate(3);
                actualRow.setActualNo(no);
                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());
                    actualRow.setLcNo(meterWorkRailwayActFirstMapper.getFirstLcNo(actualRow.getActualFirst1No()));
                }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());
                    actualRow.setLcNo(meterWorkRailwayActFirstMapper.getFirstLcNo(actualRow.getActualFirst2No()));
                }
                meterWorkRailwayActualMapper.insertSelective(actualRow);
            }
            MeterBaseOperationLog logModel = new MeterBaseOperationLog();
            logModel.setId(PublicMethod.IdCreate(2));
            logModel.setCreateManNo(userId);
            logModel.setCreateManName(userName);
            logModel.setCreateTime(new Date());
            logModel.setOperationPage("web端-轨道衡一次数据维护");
            logModel.setOperationFunction("毛皮结净");
            logModel.setOperationId(actualRow.getActualNo());
            logModel.setOperationPredictionNo(actualRow.getPredictionNo());
            logModel.setOperationCarnNo(actualRow.getRailwayNo());
            logModel.setOperationBeforeFix(actualRow.getActualFirst1No() + "," + actualRow.getActualFirst2No());
            meterBaseOperationLogMapper.insertSelective(logModel);
            rm.setSucceed();
            rm.setData(actualRow);
        }catch(Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            rm.setMessage(e.getMessage());
        }
        return rm;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public MeterWorkRailwayActual 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, "委托编号不能为空");
        }
        MeterWorkRailwayActual queryrow = meterWorkRailwayActualMapper.selectByPrimaryKey(actualNo);
        if (queryrow != null) {
            if(com.steerinfo.util.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, "只有未匹配的净重数据才能进行委托匹配操作");
        }
        try{
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            if(queryrow.getUpdateTime() != null && StringUtils.isNotEmpty(queryrow.getUpdateTime().toString())) {
                String sDate = df.format(queryrow.getUpdateTime());
                String eDate = df.format(new Date());
                long sTime = df.parse(sDate).getTime();
                long eTime = df.parse(eDate).getTime();
                long diff = (eTime - sTime) / 1000;
                if(diff <= 15) {
                    throw new MarkerMetException(500, "匹配委托需在解除委托15秒后进行，请稍等");
                }
            }
        }catch(Exception e) {
            e.printStackTrace();
            throw new MarkerMetException(500, "操作失败");
        }

        PreRailwayScale prerow = preRailwayScaleMapper.selectByPrimaryKey(predictionNo);
        if (prerow == null) {
            throw new MarkerMetException(500, "不存在对应的委托数据");
        } else if (prerow.getValueFlag().equals("9")) {
            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";
        }

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

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

        }

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

        // 处理预报
        if (StringUtils.isNotEmpty(predictionNo)) {
            PreRailwayScale scale = new PreRailwayScale();
            scale.setPredictionNo(predictionNo);
            scale.setPredictionType("1");
            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("web端-轨道衡净重数据维护");
        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 (MeterWorkRailwayActual 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, "选中的毛重数据需要先匹配委托");
        }
        MeterWorkRailwayActFirst queryrow = meterWorkRailwayActFirstMapper.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");
        meterWorkRailwayActFirstMapper.updateByPrimaryKey(queryrow);

        // 新增一条皮重
        MeterWorkRailwayActFirst tarerow = new MeterWorkRailwayActFirst();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        Date time = new Date();
//        String idNo = sdf.format(new Date()) + meterWorkRailwayActFirstMapper.getNewID(sdf.format(time));
//        tarerow.setActualFirstNo(idNo);
        String idNo = PublicMethod.IdCreate(3);
        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 = meterWorkRailwayActFirstMapper.insertSelective(tarerow);

        // 新增净重数据
//        String idNo2 = sdf.format(new Date()) + meterWorkRailwayActFirstMapper.getNewID(sdf.format(time));
//        model.setActualNo(idNo2);
        String idNo2 = PublicMethod.IdCreate(3);
        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());
            model.setLcNo(meterWorkRailwayActFirstMapper.getFirstLcNo(model.getActualFirst1No()));
        }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());
            model.setLcNo(meterWorkRailwayActFirstMapper.getFirstLcNo(model.getActualFirst2No()));
        }
        int num = meterWorkRailwayActualMapper.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 MeterWorkRailwayActual cleanPrediction (MeterWorkRailwayActual 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, "只有有效已匹配的结净数据才能进行解除操作");
        }
        MeterWorkRailwayActual mwcaquery = meterWorkRailwayActualMapper.selectByPrimaryKey(model.getActualNo());
        if (mwcaquery == null) {
            throw new MarkerMetException(500, "不存在对应的结净数据");
        }else {
            try{
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                if(mwcaquery.getUpdateTime() != null && StringUtils.isNotEmpty(mwcaquery.getUpdateTime().toString())) {
                    String sDate = df.format(mwcaquery.getUpdateTime());
                    String eDate = df.format(new Date());
                    long sTime = df.parse(sDate).getTime();
                    long eTime = df.parse(eDate).getTime();
                    long diff = (eTime - sTime) / 1000;
                    if(diff <= 15) {
                        throw new MarkerMetException(500, "解除委托需在匹配委托15秒后进行，请稍等");
                    }
                }
            }catch(Exception e) {
                e.printStackTrace();
                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();

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

        // 皮重
        try{
            MeterWorkRailwayActFirst tarerow = meterWorkRailwayActFirstMapper.selectAndRemove(model.getActualFirst2No());
//        tarerow.setValueFlag("3");
            tarerow.setUpdateTime(new Date());
            tarerow.setUpdateManName(userName);
            tarerow.setUpdateManNo(userId);
            tarerow.setNote("结净数据解除委托操作");
            tarerow.setIsPreSacale("0");
            meterWorkRailwayActFirstMapper.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);
        }
        MeterWorkRailwayActual mwca = meterWorkRailwayActualMapper.cleanPredcition(model.getActualNo());

        mwca.setUpdateManNo(userId);
        mwca.setUpdateManName(userName);
        mwca.setUpdateTime(new Date());
        mwca.setValueFlag("1");
        mwca.setIsPreSacale("0");
        mwca.setUploadFlag("1");
        mwca.setNote(model.getNote());
        meterWorkRailwayActualMapper.updateByPrimaryKey(mwca);

        MeterBaseOperationLog logModel = new MeterBaseOperationLog();
        logModel.setId(PublicMethod.IdCreate(2));
        logModel.setCreateManNo(userId);
        logModel.setCreateManName(userName);
        logModel.setCreateTime(new Date());
        logModel.setOperationPage("web端-轨道衡净重数据维护");
        logModel.setOperationFunction("撤销委托");
        logModel.setOperationId(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<MeterWorkRailwayActual> models) throws MarkerMetException {
        try {
            int num = 0;
            if (models.size() <= 0 || models == null) {
                throw new MarkerMetException(500, "参数为空！！！");
            }
            for(MeterWorkRailwayActual model: models) {
                if(model.getPredictionNo() != null && StringUtils.isNotEmpty(model.getPredictionNo())) {
                    throw new MarkerMetException(500, "结净数据已匹配委托，请撤销委托之后才能进行毛皮分解");
                }
                //毛重
                MeterWorkRailwayActFirst mwcaf1 = meterWorkRailwayActFirstMapper.selectByPrimaryKey(model.getActualFirst1No());
                if(mwcaf1 != null && StringUtils.isNotEmpty(mwcaf1.getPredictionNo())) {
                    throw new MarkerMetException(500, "请将一次数据作业编号" +mwcaf1.getActualFirstNo() +"解除委托之后在毛皮分解");
                }
                //皮重
                MeterWorkRailwayActFirst mwcaf2 = meterWorkRailwayActFirstMapper.selectByPrimaryKey(model.getActualFirst2No());
                if(mwcaf2 != null && StringUtils.isNotEmpty(mwcaf2.getPredictionNo())) {
                    throw new MarkerMetException(500, "请将一次数据作业编号"+ mwcaf2.getActualFirstNo() +"解除委托之后在毛皮分解");
                }
//                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 (MeterWorkRailwayActual model : models) {
                //毛重
                MeterWorkRailwayActFirst grossrow = meterWorkRailwayActFirstMapper.selectByPrimaryKey(model.getActualFirst1No());
                if (grossrow == null) {
                    throw new MarkerMetException(500, "未查询到相应的毛重数据！！");
                }
                // 清空委托信息
//                MeterWorkRailwayActFirst grossrow = meterWorkRailwayActFirstMapper.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");
                meterWorkRailwayActFirstMapper.updateByPrimaryKey(grossrow);
                //皮重
                MeterWorkRailwayActFirst mwcaf2 = meterWorkRailwayActFirstMapper.selectByPrimaryKey(model.getActualFirst2No());

//                MeterBaseRailwayWeight mbrw = meterBaseRailwayWeightMapper.selectByPrimaryKey(model.getActualFirst2No());
//                if (mwcaf2 == null) {
//                    throw new MarkerMetException(500, "未查询到相应的皮重数据！！");
//                }
//                // 清空委托信息
//                MeterWorkRailwayActFirst tarerow = meterWorkRailwayActFirstMapper.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");
//                    meterWorkRailwayActFirstMapper.updateByPrimaryKey(tarerow);
//                }
                //未查询到相应的标识皮直接跳过
//                if(mwcaf2 != null && mwcaf2.getMeterWeight().compareTo(model.getTareWeight().multiply(new BigDecimal(1000))) == 0) {
                    // 清空委托信息
//                MeterWorkRailwayActFirst tarerow = meterWorkRailwayActFirstMapper.selectAndRemove(model.getActualFirst2No());
                MeterWorkRailwayActFirst tarerow = meterWorkRailwayActFirstMapper.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");
                    meterWorkRailwayActFirstMapper.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);
//                }
//                meterWorkRailwayActualMapper.deleteByPrimaryKey(model.getActualNo());
                MeterBaseOperationLog logModel = new MeterBaseOperationLog();
                logModel.setId(PublicMethod.IdCreate(2));
                logModel.setCreateManNo(userId);
                logModel.setCreateManName(userName);
                logModel.setCreateTime(new Date());
                logModel.setOperationPage("web端-轨道衡净重数据维护");
                logModel.setOperationFunction("毛皮分解");
                logModel.setOperationId(model.getActualNo());
                logModel.setOperationPredictionNo(model.getPredictionNo());
                logModel.setOperationCarnNo(model.getRailwayNo());
                logModel.setOperationBeforeFix(model.toString());

                model.setIsPreSacale("0");
                model.setUploadFlag("1");
                model.setValueFlag("0");
                meterWorkRailwayActualMapper.updateByPrimaryKeySelective(model);

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

    @Override
    public RESTfulResult removeDynamicModel(MeterWorkRailwayActual 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"), "结净数据匹配的委托已结算");
            }

            //毛重
            MeterWorkRailwayActFirst mwcaf1 = meterWorkRailwayActFirstMapper.selectByPrimaryKey(model.getActualFirst1No());
            if (mwcaf1 != null && mwcaf1.getActualFirstNo()!= null && StringUtils.isNotEmpty(mwcaf1.getActualFirstNo())) {
                // 清空委托信息
                MeterWorkRailwayActFirst grossrow = meterWorkRailwayActFirstMapper.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());
                meterWorkRailwayActFirstMapper.updateByPrimaryKey(grossrow);
                //判断是从表数据，进行删除一次数据且恢复从表数据，不是则跳过
                doReceivedRemove(userId, userName, grossrow);
            }

            //皮重
            MeterWorkRailwayActFirst mwcaf2 = meterWorkRailwayActFirstMapper.selectByPrimaryKey(model.getActualFirst2No());
            if (mwcaf2 != null && mwcaf2.getActualFirstNo()!= null && StringUtils.isNotEmpty(mwcaf2.getActualFirstNo())) {
                // 清空委托信息
                MeterWorkRailwayActFirst tarerow = meterWorkRailwayActFirstMapper.selectAndRemove(model.getActualFirst2No());
                if (tarerow != null) {
                    tarerow.setValueFlag("1");
                    tarerow.setIsPreSacale("0");
                    tarerow.setUpdateManNo(userId);
                    tarerow.setUpdateManName(userName);
                    tarerow.setNote("动态衡解除操作");
                    tarerow.setLcNo(model.getLcNo());
                    meterWorkRailwayActFirstMapper.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);
            }
            meterWorkRailwayActualMapper.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, MeterWorkRailwayActFirst grossrow) {
        //恢复从表数据
        MeterWorkRailwayReceived receivedModel = meterWorkRailwayReceivedMapper.selectByPrimaryKey(grossrow.getActualFirstNo());
        if(receivedModel.getActualFirstNo() != null && StringUtils.isNotEmpty(receivedModel.getActualFirstNo())) {
            meterWorkRailwayActFirstMapper.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) {
        if(param==null) {
            param = new HashMap<>();
        }
//        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 = meterWorkRailwayActualMapper.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 = meterWorkRailwayActualMapper.distinctRailwayNoTemp(param)
                    .stream()
                    .map(MeterWorkRailwayActual::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<MeterWorkRailwayActual> templist = meterWorkRailwayActualMapper.distinctLcNo(param);
        List<String> list = new ArrayList<>();
        if (templist != null && !templist.isEmpty() ) {
            try{
                list = templist.stream().map(MeterWorkRailwayActual::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(MeterWorkRailwayActual::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<MeterWorkRailwayActual> tempList = meterWorkRailwayActualMapper.distinctLcNo(param);
            List<String> list = null;
            List<String> railwayNum = null;
            if(tempList.size() != 0)
            {
                list = tempList.stream().map(MeterWorkRailwayActual::getLcNo).distinct().collect(Collectors.toList());
                railwayNum = tempList.stream().map(MeterWorkRailwayActual::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<MeterWorkRailwayActual> models) throws MarkerMetException {
        try {
            int num = 0;
            if (models.size() <= 0 || models == null) {
                throw new MarkerMetException(500, "参数为空！！！");
            }
            models.sort(Comparator.comparing(MeterWorkRailwayActual::getPredictionNo).thenComparing(MeterWorkRailwayActual::getNetTime));

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

            for (MeterWorkRailwayActual model : models) {
                //毛重删除
                meterWorkRailwayActFirstMapper.deleteByPrimaryKey(model.getActualFirst1No());
                //皮重删除
                meterWorkRailwayActFirstMapper.deleteByPrimaryKey(model.getActualFirst2No());
                //净重删除
                meterWorkRailwayActualMapper.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<MeterWorkRailwayActual> 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<MeterWorkRailwayActual> rows = meterWorkRailwayActualMapper.selectView(parmas);
        PageList pageInfo = new PageList(rows);
        return pageInfo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public PageList<MeterWorkRailwayActual> 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<MeterWorkRailwayActual> rows = meterWorkRailwayActualMapper.selectDiff(parmas);
        PageList pageInfo = new PageList(rows);
        return pageInfo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public MeterWorkRailwayActual termclean(String actualFirstNo, String dataNo) {
        try {
            if (actualFirstNo == null && actualFirstNo.equals("")) {
                throw new MarkerMetException(500, "毛重数据编号为空");
            }
            if (dataNo == null && dataNo.equals("")) {
                throw new MarkerMetException(500, "皮重数据编号为空");
            }
            MeterWorkRailwayActFirst mwraf1 = meterWorkRailwayActFirstMapper.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);
            meterWorkRailwayActFirstMapper.updateByPrimaryKey(mwraf1);
            MeterWorkRailwayActual mwca = meterWorkRailwayActualMapper.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 = meterWorkRailwayActualMapper.getNewID(sdf.format(new Date()));
//            mwca.setActualNo(sdf.format(new Date()) + no);
            String no = PublicMethod.IdCreate(3);
            mwca.setActualNo(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());
                mwca.setLcNo(meterWorkRailwayActFirstMapper.getFirstLcNo(mwca.getActualFirst1No()));
            }else {
                mwca.setNetSpot3No(mwca.getBaseSpot2No());
                mwca.setNetSpot3Name(mwca.getBaseSpot2Name());
                mwca.setNetManNo(mwca.getTareManNo());
                mwca.setNetManName(mwca.getTareManName());
                mwca.setNetTime(mwca.getTareTime());
                mwca.setCreateTime(mwca.getTareTime());
                mwca.setCreateManName(mwca.getTareManName());
                mwca.setLcNo(meterWorkRailwayActFirstMapper.getFirstLcNo(mwca.getActualFirst2No()));
            }
            meterWorkRailwayActualMapper.insertSelective(mwca);
            return mwca;
        } catch (MarkerMetException e) {
            throw e;
        }
    }


    private void check(MeterWorkRailwayActual 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(MeterWorkRailwayActual 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<MeterWorkRailwayActual> 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<MeterWorkRailwayActual> rows = meterWorkRailwayActualMapper.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<MeterWorkRailwayActual> doQueryActWf(HashMap parmas, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<MeterWorkRailwayActual> rows = meterWorkRailwayActualMapper.selectByParameter(parmas);
        for (MeterWorkRailwayActual 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<MeterWorkRailwayActual> actuals, List<MeterWorkRailwayActFirst> actualFirsts, List<PreRailwayScale> scales) {
        int num = 0;
        try {
            //=======================二次计量数据的修改：开始=====================
            if (actuals != null && actuals.size() >= 0) {
                for (MeterWorkRailwayActual actual : actuals) {
                    updateActual(actual);//二次计量数据更新

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

                    //一次计量，皮重的处理
                    MeterWorkRailwayActFirst 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 (MeterWorkRailwayActFirst 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<MeterWorkRailwayActual> actuals) {
        int num = 0;
        try {
            if (actuals == null || actuals.size() == 0) {
                throw new MarkerMetException(500, "参数不允许为空！");
            }
            if (actuals != null && actuals.size() >= 0) {
                for (MeterWorkRailwayActual actual : actuals) {
                    updateActual(actual);//二次计量数据更新
                    //一次计量，毛重的处理
                    MeterWorkRailwayActFirst first = actualToFirstGross(actual);
                    if (first != null && first.getActualFirstNo() != null)
                        updateActualFirst(first);

                    //一次计量，皮重的处理
                    MeterWorkRailwayActFirst 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<MeterWorkRailwayActFirst> actualFirsts) {
        int num = 0;
        try {
            if (actualFirsts == null || actualFirsts.size() == 0) {
                throw new MarkerMetException(500, "参数不允许为空！");
            }
            if (actualFirsts != null && actualFirsts.size() >= 0) {
                for (MeterWorkRailwayActFirst 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 meterWorkRailwayActualMapper.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(MeterWorkRailwayActual actual) {
        if (StringUtils.isNotEmpty(actual.getActualNo())) {
            actual.setUpdateTime(new Date());
            meterWorkRailwayActualMapper.updateByPrimaryKeySelective(actual);
        }
        return 0;
    }

    /**
     * 更新一次计量数据
     *
     * @param actFirst
     * @return
     */
    public int updateActualFirst(MeterWorkRailwayActFirst actFirst) {
        if (StringUtils.isNotEmpty(actFirst.getActualFirstNo())) {
            actFirst.setUpdateTime(new Date());
            meterWorkRailwayActFirstMapper.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 MeterWorkRailwayActFirst actualToFirstGross(MeterWorkRailwayActual actual) {
        MeterWorkRailwayActFirst actFirst = new MeterWorkRailwayActFirst();
        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 MeterWorkRailwayActFirst actualToFirstTare(MeterWorkRailwayActual actual) {
        MeterWorkRailwayActFirst actFirst = new MeterWorkRailwayActFirst();
        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(MeterWorkRailwayActual 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(MeterWorkRailwayActFirst 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(MeterWorkRailwayActual 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();
            MeterWorkRailwayActFirst mwraf1 = new MeterWorkRailwayActFirst();
            MeterWorkRailwayActFirst mwraf2 = new MeterWorkRailwayActFirst();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            String afl = sdf.format(new Date());
            if(predictionNo == "" || "".equals(predictionNo)){
                //添加毛重一次计量数据
//                String actualFirstNo = sdf.format(new Date()) + meterWorkRailwayActFirstMapper.getNewID(afl);
//                mwraf1.setActualFirstNo(actualFirstNo);
                String actualFirstNo = PublicMethod.IdCreate(3);
                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");
                meterWorkRailwayActFirstMapper.insertSelective(mwraf1);
                //添加皮重一次计量数据
//                String dataNo = sdf.format(new Date()) + meterWorkRailwayActFirstMapper.getNewID(afl);
//                mwraf2.setActualFirstNo(dataNo);
                String dataNo = PublicMethod.IdCreate(3);
                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");
                meterWorkRailwayActFirstMapper.insertSelective(mwraf2);
                //添加净重重一次计量数据
//                String ActualNo = sdf.format(new Date()) + meterWorkRailwayActualMapper.getNewID(afl);
//                model.setActualNo(ActualNo);
                String ActualNo = PublicMethod.IdCreate(3);
                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());
                    model.setLcNo(meterWorkRailwayActFirstMapper.getFirstLcNo(model.getActualFirst1No()));
                }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());
                    model.setLcNo(meterWorkRailwayActFirstMapper.getFirstLcNo(model.getActualFirst2No()));
                }
                meterWorkRailwayActualMapper.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()) + meterWorkRailwayActFirstMapper.getNewID(afl);
                String actualFirstNo = PublicMethod.IdCreate(3);
                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");
                meterWorkRailwayActFirstMapper.insertSelective(mwraf1);
                //添加皮重一次计量数据
//                String dataNo = sdf.format(new Date()) + meterWorkRailwayActFirstMapper.getNewID(afl);
                String dataNo = PublicMethod.IdCreate(3);
                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");
                meterWorkRailwayActFirstMapper.insertSelective(mwraf2);
                //添加净重重一次计量数据
//                String ActualNo = sdf.format(new Date()) + meterWorkRailwayActualMapper.getNewID(afl);
                String ActualNo = PublicMethod.IdCreate(3);
                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());
                    model.setLcNo(meterWorkRailwayActFirstMapper.getFirstLcNo(model.getActualFirst1No()));
                }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());
                    model.setLcNo(meterWorkRailwayActFirstMapper.getFirstLcNo(model.getActualFirst2No()));
                }
                meterWorkRailwayActualMapper.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(MeterWorkRailwayActual model) {
        RESTfulResult rm = new RESTfulResult();
        rm.setFailed();

        try{
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            String afl = sdf.format(new Date());
            MeterWorkRailwayActFirst mwcaf1 = new MeterWorkRailwayActFirst();
            MeterWorkRailwayActFirst mwcaf2 = new MeterWorkRailwayActFirst();
            MeterWorkRailwayActual actualRow = new MeterWorkRailwayActual();
            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()) + meterWorkRailwayActFirstMapper.getNewID(afl);
            String actualFirstNo = PublicMethod.IdCreate(3);
            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");
            meterWorkRailwayActFirstMapper.insertSelective(mwcaf1);
            //皮重
//            String actualSecondNo = sdf.format(new Date()) + meterWorkRailwayActFirstMapper.getNewID(afl);
            String actualSecondNo = PublicMethod.IdCreate(3);
            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");
            meterWorkRailwayActFirstMapper.insertSelective(mwcaf2);
            //净重
            if(com.steerinfo.util.StringUtils.isNotEmpty(predictionNo)){
                //将委托中的编号和收发货的等数据拷贝进一次数据中
                MeterWorkRailwayActFirst first1 = meterWorkRailwayActFirstMapper.selectAndMatch(actualFirstNo, predictionNo);
                BeanUtils.copyProperties(first1,mwcaf1);
                mwcaf1.setIsPreSacale("1");
                meterWorkRailwayActFirstMapper.updateByPrimaryKey(mwcaf1);
                MeterWorkRailwayActFirst first2 = meterWorkRailwayActFirstMapper.selectAndMatch(actualSecondNo, predictionNo);
                BeanUtils.copyProperties(first2, mwcaf2);
                mwcaf2.setIsPreSacale("1");
                meterWorkRailwayActFirstMapper.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);
                //将委托中的编号和收发货单位和一次数据等数据拷贝进结净数据中
                MeterWorkRailwayActual mwca1 = meterWorkRailwayActualMapper.manualAddPre(actualFirstNo, actualSecondNo, predictionNo);
                BeanUtils.copyProperties(mwca1, actualRow);

            }else {
                //将委托中的编号和收发货单位和一次数据等数据拷贝进结净数据中
                MeterWorkRailwayActual mwca1 = meterWorkRailwayActualMapper.manualAdd(actualFirstNo, actualSecondNo);
                BeanUtils.copyProperties(mwca1, actualRow);
            }
//            String no = meterWorkRailwayActualMapper.getNewID(sdf.format(new Date()));
//            actualRow.setActualNo(sdf.format(new Date()) + no);
            String no = PublicMethod.IdCreate(3);
            actualRow.setActualNo(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());
                actualRow.setLcNo(meterWorkRailwayActFirstMapper.getFirstLcNo(actualRow.getActualFirst1No()));
            }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());
                actualRow.setLcNo(meterWorkRailwayActFirstMapper.getFirstLcNo(actualRow.getActualFirst2No()));
            }
            meterWorkRailwayActualMapper.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<>();
        MeterWorkRailwayActual carActual = meterWorkRailwayActualMapper.selectByPrimaryKey(actualNo);
        if(carActual != null) {
            actualNoList.add(0, carActual.getActualFirst1No());
            actualNoList.add(1, carActual.getActualFirst2No());
//            String entrust = carActual.getPredictionNo() == null ? "" : carActual.getPredictionNo();
//            String railwayNo = carActual.getRailwayNo() == null ? "": carActual.getRailwayNo();
            HashMap<String, Object> obj = new HashMap<>();
            obj.put("railwayNo", carActual.getRailwayNo());
            obj.put("predictionNo", carActual.getPredictionNo());
            List<MeterWorkRailwayActFirst> firstList = meterWorkRailwayActFirstMapper.selectById(actualNoList);
//            PreRailwayScale scale = preRailwayScaleMapper.selectByPrimaryKey(entrust);
            List<PreRailwayScale> scale = preRailwayScaleMapper.selectByScale(obj);
            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();
        MeterWorkRailwayActual actualModel01 = meterWorkRailwayActualMapper.selectByPrimaryKey(params.get("actualNo01").toString());
        MeterWorkRailwayActual actualModel02 = meterWorkRailwayActualMapper.selectByPrimaryKey(params.get("actualNo02").toString());
        if(actualModel01 == null || actualModel02 == null){
            rm.setMessage("未找到一次计量数据，请确认！！！");
            return rm;
        }
        List<MeterWorkRailwayActual> models = new ArrayList<MeterWorkRailwayActual>();
        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(MeterWorkRailwayActual modelTemp: models) {
            PreRailwayScale scaleTemp = preRailwayScaleMapper.selectByPrimaryKey(modelTemp.getPredictionNo());
            if(scaleTemp.getValueFlag().equals("9")) {
                rm.setMessage("两个结净数据中包含已结算的委托!!!");
                return rm;
            }
        }
        String userId = "";
        String userName = "";
        try{
            UserPayload userPayload = UserPayload.getCurrUser();
            userId = userPayload.getUserCode();
            userName = userPayload.getUserName();
        }catch (Exception e) {
            userId = "system";
            userName = "system";
        }
        switch(type){
            case "5":
            case "6":
            case "7": {
                if(type.equals("5")){
                    //类型为双委托类型
                    for (MeterWorkRailwayActual model: models) {
                        if(!model.getPredictionType().equals("5")) {
                            rm.setMessage("选中的计量数据当中有一条或多条不是双委托结净数据，请确认！！");
                            return rm;
                        }
                    }
                } else if(type.equals("6")){
                    //类型为混卸类型
                    for (MeterWorkRailwayActual model: models) {
                        if(!model.getPredictionType().equals("6")) {
                            rm.setMessage("选中的计量数据当中有一条或多条不是混卸委托结净数据，请确认！！");
                        }
                    }
                }else if(type.equals("7")){
                    //类型为混装类型
                    for (MeterWorkRailwayActual model: models) {
                        if(!model.getPredictionType().equals("7")) {
                            rm.setMessage("选中的计量数据当中有一条或多条不是混装委托结净数据，请确认！！");
                        }
                    }
                }
                for (MeterWorkRailwayActual model: models) {
                    // 改委托
                    if (StringUtils.isNotEmpty(model.getPredictionNo())) {
                        removeScaleEl(model.getPredictionNo());
                    }
                    // 清空一次毛皮重委托信息
                    MeterWorkRailwayActFirst firstGross = meterWorkRailwayActFirstMapper.selectAndRemove(model.getActualFirst1No());
                    MeterWorkRailwayActFirst firstTare = meterWorkRailwayActFirstMapper.selectAndRemove(model.getActualFirst2No());
                    if(firstGross != null){
                        removeFirstEl(firstGross);
                        meterWorkRailwayActFirstMapper.updateByPrimaryKey(firstGross);
                    }
                    if(firstTare != null){
                        removeFirstEl(firstTare);
                        meterWorkRailwayActFirstMapper.updateByPrimaryKey(firstTare);
                    }
                    MeterWorkRailwayActual modelTemp = meterWorkRailwayActualMapper.cleanPredcition(model.getActualNo());
                    removeEl(modelTemp);
                    meterWorkRailwayActualMapper.updateByPrimaryKeySelective(modelTemp);

                    MeterBaseOperationLog logModel = new MeterBaseOperationLog();
                    logModel.setId(PublicMethod.IdCreate(2));
                    logModel.setCreateManNo(userId);
                    logModel.setCreateManName(userName);
                    logModel.setCreateTime(new Date());
                    logModel.setOperationPage("web端-轨道衡净重数据维护");
                    if(type.equals("5")){
                        logModel.setOperationFunction("取消双委托结净");
                    }else if(type.equals("6")) {
                        logModel.setOperationFunction("取消混卸结净");
                    }else if(type.equals("7")) {
                        logModel.setOperationFunction("取消混装结净");
                    }
                    logModel.setOperationId(model.getActualNo());
                    logModel.setOperationPredictionNo(model.getPredictionNo());
                    logModel.setOperationCarnNo(model.getRailwayNo());
                    logModel.setOperationBeforeFix(model.toString());
                    logModel.setOperationAfterFix(modelTemp.toString());
                    meterBaseOperationLogMapper.insertSelective(logModel);
                }
                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{

            MeterWorkRailwayActual actualModel = meterWorkRailwayActualMapper.selectByPrimaryKey(params.get("actualNo").toString());
            //操作原因
            String note = params.get("note") == null ? "": params.get("note").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<MeterWorkRailwayActual> models = new ArrayList<>();
            models.add(actualModel);

            for(MeterWorkRailwayActual 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 (MeterWorkRailwayActual model: models) {
                //循环每一个结净记录
                //委托不能为空

                // 改委托
                PreRailwayScale scale = new PreRailwayScale();
                if (StringUtils.isNotEmpty(model.getPredictionNo())) {
                    scale= preRailwayScaleMapper.selectByPrimaryKey(model.getPredictionNo());
                    scale.setValueFlag("1");
                    scale.setUploadFlag("1");
                    scale.setUpdateTime(new Date());
                    scale.setUpdateManNo(userId);
                    scale.setUpdateManName(userName);
                    preRailwayScaleMapper.updateByPrimaryKeySelective(scale);
                }else {
                    if(StringUtils.isNotEmpty(model.getActualFirst1No())) {
                        MeterWorkRailwayActFirst gross = meterWorkRailwayActFirstMapper.selectByPrimaryKey(model.getActualFirst1No());
                        if(StringUtils.isNotEmpty(gross.getPredictionNo())) {
                            scale = preRailwayScaleMapper.selectByPrimaryKey(gross.getPredictionNo());
                            scale.setValueFlag("1");
                            scale.setUploadFlag("1");
                            scale.setUpdateTime(new Date());
                            scale.setUpdateManNo(userId);
                            scale.setUpdateManName(userName);
                            preRailwayScaleMapper.updateByPrimaryKeySelective(scale);
                        }
                    }
                    if(StringUtils.isNotEmpty(model.getActualFirst2No())) {
                        MeterWorkRailwayActFirst tare = meterWorkRailwayActFirstMapper.selectByPrimaryKey(model.getActualFirst2No());
                        if(StringUtils.isNotEmpty(tare.getPredictionNo())) {
                            scale = preRailwayScaleMapper.selectByPrimaryKey(tare.getPredictionNo());
                            scale.setValueFlag("1");
                            scale.setUploadFlag("1");
                            scale.setUpdateTime(new Date());
                            scale.setUpdateManNo(userId);
                            scale.setUpdateManName(userName);
                            preRailwayScaleMapper.updateByPrimaryKeySelective(scale);
                        }
                    }
                }

                // 清空一次毛重、皮重委托信息
                MeterWorkRailwayActFirst firstGross;
                MeterWorkRailwayActFirst firstTare;
                if(StringUtils.isNotEmpty(model.getActualFirst1No())&&StringUtils.isNotEmpty(model.getActualFirst2No())){
                    firstGross = meterWorkRailwayActFirstMapper.selectAndRemove(model.getActualFirst1No());
                    firstTare =  meterWorkRailwayActFirstMapper.selectAndRemove(model.getActualFirst2No());
                }else{
                    firstGross = meterWorkRailwayActFirstMapper.selectByPrimaryKey(model.getActualFirst1No());
                    firstTare = meterWorkRailwayActFirstMapper.selectByPrimaryKey(model.getActualFirst2No());
                }
                if(firstGross != null){
                    firstGross.setValueFlag(DbConstants.VALID);
//                    firstGross.setUpdateManNo("system");
//                    firstGross.setUpdateManName("结净废除更新");
                    firstGross.setUpdateManNo(userId);
                    firstGross.setUpdateManName(userName);
                    firstGross.setNote(note);
                    firstGross.setUpdateTime(new Date());
                    firstGross.setIsPreSacale("0");
                    firstGross.setValueFlag("0");
                    meterWorkRailwayActFirstMapper.updateByPrimaryKey(firstGross);
                }
                if(firstTare != null){
                    firstTare.setValueFlag(DbConstants.VALID);
//                    firstTare.setUpdateManNo("system");
//                    firstTare.setUpdateManName("结净废除更新");
                    firstTare.setUpdateManNo(userId);
                    firstTare.setUpdateManName(userName);
                    firstTare.setNote(note);
                    firstTare.setUpdateTime(new Date());
                    firstTare.setIsPreSacale("0");
                    firstTare.setValueFlag("0");
                    meterWorkRailwayActFirstMapper.updateByPrimaryKey(firstTare);
                }
                // 作废结净数据并解除委托
                MeterWorkRailwayActual cleanModel = meterWorkRailwayActualMapper.cleanPredcition(model.getActualNo());
                cleanModel.setUploadFlag("1");
                cleanModel.setValueFlag("0");
                cleanModel.setIsPreSacale("0");
                cleanModel.setUpdateManNo(userId);
                cleanModel.setUpdateManName(userName);
                cleanModel.setUpdateTime(new Date());
                cleanModel.setNote(note);
                meterWorkRailwayActualMapper.updateByPrimaryKey(cleanModel);
                //删结净
                //meterWorkCarActualMapper.deleteByPrimaryKey(model.getActualNo());

                MeterBaseOperationLog logModel = new MeterBaseOperationLog();
                logModel.setId(PublicMethod.IdCreate(2));
                logModel.setCreateManNo(userId);
                logModel.setCreateManName(userName);
                logModel.setCreateTime(new Date());
                logModel.setOperationPage("web端-轨道衡净重数据维护");
                logModel.setOperationFunction("结净废除");
                logModel.setOperationId(model.getActualNo());
                logModel.setOperationPredictionNo(model.getPredictionNo());
                logModel.setOperationCarnNo(model.getRailwayNo());
                logModel.setOperationBeforeFix(model.toString());
            }
            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(MeterWorkRailwayActFirst 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(MeterWorkRailwayActual 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<MeterWorkRailwayActual> likeByDesc(Map<String, Object> params, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        if(params.get("railwayTypeNoStr") != null) {
            String[] typeNoStr = params.get("railwayTypeNoStr").toString().split(",");
            params.put("typeNoStr", typeNoStr);
        }
        if(params.get("netSpot3NoStr") != null) {
            String[] spotNoStr = params.get("netSpot3NoStr").toString().split(",");
            params.put("spotNoStr", spotNoStr);
        }
        List<MeterWorkRailwayActual> rows = meterWorkRailwayActualMapper.likeByDesc(params);
        PageList pageInfo = new PageList(rows);
        return pageInfo;
    }

    @Override
    public PageList<MeterWorkRailwayActual> railwayPrintLikeByDesc(Map<String, Object> parameters, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        String userId = "";
        String userName = "";
        try{
            UserPayload userPayload = UserPayload.getCurrUser();
            userId = userPayload.getUserCode();
            userName = userPayload.getUserName();
        }catch(Exception e) {
            e.printStackTrace();
            userId = "admin";
            userName = "admins";
        }
        HashMap<String, Object> map = new HashMap();
        map.put("userId", userId);
        map.put("userName", userName);
        List<MeterBaseUserPrintConfig> configs = meterBaseUserPrintConfigMapper.likeByDesc(map);
        List<MeterWorkRailwayActual> rowsTemp = meterWorkRailwayActualMapper.railwayPrintLikeByDesc(parameters);
        List<MeterWorkRailwayActual> rows = new ArrayList<>();
        if(rowsTemp.size() >= 1) {
            for(MeterWorkRailwayActual model: rowsTemp) {
                //超吨计量数据补录不需要验证用户配置物料收发货单位信息（注：超吨计量数据补录没有轨道衡类型）
                if(StringUtils.isNotEmpty(model.getRailwayTypeNo())) {
                    if(configs.size() >= 1) {
                        for(MeterBaseUserPrintConfig config: configs) {
                            //物料、发货、收货都不为空，物料、发货、收货都判断
                            if(StringUtils.isNotEmpty(config.getMatterNo()) && StringUtils.isNotEmpty(config.getForwardingUnitNo())
                                    && StringUtils.isNotEmpty(config.getReceivingUintNo())){
                                if(StringUtils.isNotEmpty(model.getMatterNo())
                                        && StringUtils.isNotEmpty(model.getForwardingUnitNo())
                                        && StringUtils.isNotEmpty(model.getReceivingUintNo())
                                        && model.getMatterNo().equals(config.getMatterNo())
                                        && model.getForwardingUnitNo().equals(config.getForwardingUnitNo())
                                        && model.getReceivingUintNo().equals(config.getReceivingUintNo())) {
                                    rows.add(model);
                                }
                            }
                            //物料为空、发货、收货判断
                            if(StringUtils.isEmpty(config.getMatterNo()) && StringUtils.isNotEmpty(config.getForwardingUnitNo())
                                    && StringUtils.isNotEmpty(config.getReceivingUintNo())) {
                                if(StringUtils.isNotEmpty(model.getForwardingUnitNo())
                                        && StringUtils.isNotEmpty(model.getReceivingUintNo())
                                        && model.getForwardingUnitNo().equals(config.getForwardingUnitNo())
                                        && model.getReceivingUintNo().equals(config.getReceivingUintNo())) {
                                    rows.add(model);
                                }
                            }
                            //发货为空、物料、收货判断
                            if(StringUtils.isNotEmpty(config.getMatterNo()) && StringUtils.isEmpty(config.getForwardingUnitNo())
                                    && StringUtils.isNotEmpty(config.getReceivingUintNo())) {
                                if(StringUtils.isNotEmpty(model.getMatterNo())
                                        && StringUtils.isNotEmpty(model.getReceivingUintNo())
                                        && model.getMatterNo().equals(config.getMatterNo())
                                        && model.getReceivingUintNo().equals(config.getReceivingUintNo())) {
                                    rows.add(model);
                                }
                            }
                            //收货为空、物料、发货判断
                            if(StringUtils.isNotEmpty(config.getMatterNo()) && StringUtils.isNotEmpty(config.getForwardingUnitNo())
                                    && StringUtils.isEmpty(config.getReceivingUintNo())) {
                                if(StringUtils.isNotEmpty(model.getMatterNo())
                                        && StringUtils.isNotEmpty(model.getForwardingUnitNo())
                                        && model.getMatterNo().equals(config.getMatterNo())
                                        && model.getForwardingUnitNo().equals(config.getForwardingUnitNo())) {
                                    rows.add(model);
                                }
                            }
                            //物料、发货都为空， 收货判断
                            if(StringUtils.isEmpty(config.getMatterNo()) && StringUtils.isEmpty(config.getForwardingUnitNo())
                                    && StringUtils.isNotEmpty(config.getReceivingUintNo())) {
                                if(StringUtils.isNotEmpty(model.getReceivingUintNo()) && model.getReceivingUintNo().equals(config.getReceivingUintNo())) {
                                    rows.add(model);
                                }
                            }
                            //物料、收货都为空， 发货货判断
                            if(StringUtils.isEmpty(config.getMatterNo()) && StringUtils.isNotEmpty(config.getForwardingUnitNo())
                                    && StringUtils.isEmpty(config.getReceivingUintNo())) {
                                if(StringUtils.isNotEmpty(model.getForwardingUnitNo()) && model.getForwardingUnitNo().equals(config.getForwardingUnitNo())) {
                                    rows.add(model);
                                }
                            }
                            //发货、收货都为空， 物料判断
                            if(StringUtils.isNotEmpty(config.getMatterNo()) && StringUtils.isEmpty(config.getForwardingUnitNo())
                                    && StringUtils.isEmpty(config.getReceivingUintNo())) {
                                if(StringUtils.isNotEmpty(model.getMatterNo()) && model.getMatterNo().equals(config.getMatterNo())) {
                                    rows.add(model);
                                }
                            }
                        }
                    }
                }else {
                    rows.add(model);
                }
            }
        }
        PageList pageInfo = new PageList(rows);
        return pageInfo;
    }

    @Override
    public PageList<MeterWorkRailwayActual> staticLimitByDesc(Map<String, Object> parameters, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<MeterWorkRailwayActual> rows = meterWorkRailwayActualMapper.likeByDesc(parameters);
        //查询静轨物料车型重量范围配置
        HashMap<String, Object> obj = new HashMap<>();
        obj.put("valueFlag", "1");
        obj.put("railwayTypeNo", "001019001");
        List<MeterBaseVehicleRangeConfig> configList = meterBaseVehicleRangeConfigMapper.likeByDesc(obj);
        if(rows.size() >= 1) {
            for (MeterWorkRailwayActual model: rows) {
                if(configList.size() >= 1) {
                    for (MeterBaseVehicleRangeConfig configModel: configList) {
                        //判断车号、计量点、物料、车型
                        if(model.getNetSpot3No().equals(configModel.getBaseSpotNo())
                            && model.getNetSpot3Name().equals(configModel.getBaseSpotName())
                            && model.getMatterNo().equals(configModel.getMatterNo())
                            && model.getMatterName().equals(configModel.getMatterName())
                            && model.getConveyanceType().equals(configModel.getCarrigeNo())){
                            //判断毛重大于毛重上限并且毛重小于毛重下限/
                            if(model.getGrossWeight().compareTo(new BigDecimal(configModel.getGrossWeightUpper())) == -1
                                && model.getGrossWeight().compareTo(new BigDecimal(configModel.getGrossWeightLower())) == 1) {
                                model.setIsOut("1");
                            }else {
                                model.setIsOut("0");
                            }
                        }
                    }
                }
            }
        }
        PageList pageInfo = new PageList(rows);
        return pageInfo;
    }

    @Override
    public PageList<MeterWorkRailwayActual> dynamicLimitByDesc(Map<String, Object> parameters, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<MeterWorkRailwayActual> rows = meterWorkRailwayActualMapper.likeByDesc(parameters);
        //存储符合条件的净重数据
        List<MeterWorkRailwayActual> rowsTemp = new ArrayList<>();
        //查询静轨物料车型重量范围配置
        HashMap<String, Object> obj = new HashMap<>();
        obj.put("valueFlag", "1");
        obj.put("railwayTypeNo", "001019002");
        List<MeterBaseVehicleRangeConfig> configList = meterBaseVehicleRangeConfigMapper.likeByDesc(obj);
        if(rows.size() >= 1) {
            for (MeterWorkRailwayActual model: rows) {
                if(configList.size() >= 1) {
                    for (MeterBaseVehicleRangeConfig configModel: configList) {
                        //判断车号、计量点、物料、发货单位、收货单位、车型、载重
                        if(model.getNetSpot3No().equals(configModel.getBaseSpotNo())
                                && model.getNetSpot3Name().equals(configModel.getBaseSpotName())
                                && model.getMatterNo().equals(configModel.getMatterNo())
                                && model.getMatterName().equals(configModel.getMatterName())
                                && model.getForwardingUnitNo().equals(configModel.getForwardingUnitNo())
                                && model.getForwardingUnitName().equals(configModel.getForwardingUnitName())
                                && model.getReceivingUintNo().equals(configModel.getReceivingUintNo())
                                && model.getReceivingUintName().equals(configModel.getReceivingUintName())
                                && model.getConveyanceType().equals(configModel.getCarrigeNo())){
                            //判断毛重大于毛重上限并且毛重小于毛重下限;     毛重上限、毛重下限、净重上限、净重下限
                            if((model.getGrossWeight().compareTo(new BigDecimal(configModel.getGrossWeightUpper())) == 1
                                    || model.getGrossWeight().compareTo(new BigDecimal(configModel.getGrossWeightLower())) == -1)
                                || (model.getNetWeight().compareTo(new BigDecimal(configModel.getNetWeightUpper())) == 1
                                    || model.getNetWeight().compareTo(new BigDecimal(configModel.getNetWeightLower())) == -1)) {
                                model.setIsOut("1");
                            }else {
                                model.setIsOut("0");
                            }
                        }
                    }
                }
            }
        }
        PageList pageInfo = new PageList(rows);
        return pageInfo;
    }

    @Override
    public List<MeterWorkRailwayActual> carActualDataDetail(HashMap<String, Object> params) {
        if(params.get("railwayTypeNoStr") != null) {
            String[] typeNoStr = params.get("railwayTypeNoStr").toString().split(",");
            params.put("typeNoStr", typeNoStr);
        }
        List<MeterWorkRailwayActual> rows = meterWorkRailwayActualMapper.carActualDataDetail(params);
        return rows;
    }

    @Override
    public List<MeterWorkRailwayActual> webByLikeDesc(HashMap<String, Object> parameters) {
        if(parameters.get("lcNoTemp") != null) {
            String[] lcNoTemp = 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("railwayNoTemp") != null) {
            String[] railwayNoTemp = parameters.get("railwayNoTemp").toString().split(",");
            parameters.remove("railwayNoTemp");
            parameters.put("railwayNoTemp", railwayNoTemp);
//            for (String str:
//                    railwayNoTemp) {
//                if(str.equals("")) {
//                    parameters.put("lcNoNull", "1");
//                    break;
//                }else {
//                    parameters.put("lcNoNull", "");
//                }
//            }
        }

        List<MeterWorkRailwayActual> rows = meterWorkRailwayActualMapper.likeByDescTemp(parameters);
        return rows;
    }

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

    @Override
    public RESTfulResult batchUpdateLcNo(List<MeterWorkRailwayActual> 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 = meterWorkRailwayActualMapper.getLcNo(afl, models.get(0).getNetSpot3No());
                int count = 0;
                for(MeterWorkRailwayActual model: models) {
//                    model.setLcNo(model.getNetSpot3Name().replaceAll("#", "")
//                            .replaceAll("轨道衡", "")
//                            .replaceAll("静轨", "")
//                            .replaceAll("静态", "") + "-" + afl + lcNo + "(" + models.size() + ")");
                    MeterWorkRailwayActFirst grossModel = meterWorkRailwayActFirstMapper.selectByPrimaryKey(model.getActualFirst1No());
                    MeterWorkRailwayActFirst tareModel = meterWorkRailwayActFirstMapper.selectByPrimaryKey(model.getActualFirst2No());
                    if(model.getGrossTime().compareTo(model.getTareTime()) >= 0) {
                        model.setLcNo(grossModel.getLcNo());
                    }else {
                        model.setLcNo(tareModel.getLcNo());
                    }
                    meterWorkRailwayActualMapper.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 autoPrintRailway(HashMap<String, Object> params) {
        RESTfulResult rm = new RESTfulResult();
        rm.setFailed();
        try {
            //查询配置表所有发货单位编号
            HashMap<String, Object> obj = new HashMap<>();
            obj.put("pBaseCode", "001038");
            obj.put("validFlag", "1");
            List<String> matterModels = comBaseInfoMapper.matterNoByBaseCode(obj);
            params.put("list", matterModels);

            HashMap<String, Object> mapObj = new HashMap<>();
            mapObj.put("pBaseCode", "001044");
            mapObj.put("validFlag", "1");
            List<String> matterNameModels = comBaseInfoMapper.matterNoByBaseName(mapObj);
            params.put("matterNameList", matterNameModels);
            List<MeterWorkRailwayActual> actualModels = meterWorkRailwayActualMapper.autoPrintRailway(params);

            //获取轨道衡有效打印限制配置（车号、车型、自重、净重上限、净重下限）
            HashMap<String, Object> printMap = new HashMap<>();
            printMap.put("valueFlag", "1");
            List<MeterBaseVehicleRangePrintConfig> printConfigs = meterBaseVehicleRangePrintConfigMapper.likeByDesc(printMap);
            List<MeterWorkRailwayActual> railwayModels = new ArrayList<>();
            if(actualModels.size() >= 1) {
                for (MeterWorkRailwayActual model: actualModels) {
                    if(printConfigs.size() >= 1) {
                        //循环所有净重信息
                        for (MeterBaseVehicleRangePrintConfig configModel: printConfigs){
                            //判断净重信息物料、车型相同、并且净重在净重上限、下限之间就是有效数据；否者不显示
                            if(configModel.getRailwayNo().equals(model.getRailwayNo())
                                    && configModel.getCarrigeNo().equals(model.getConveyanceType())) {
                                if((model.getNetWeight().compareTo(new BigDecimal(configModel.getNetWeightUpper())) != 1)
                                        && (model.getNetWeight().compareTo(new BigDecimal(configModel.getNetWeightLower()))) != -1) {
                                    railwayModels.add(model);
                                }
                            }else{
                                railwayModels.add(model);
                            }
                        }
                    }
                }
            }

            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 RESTfulResult autoPrintRailway2(HashMap<String, Object> params) {
        RESTfulResult rm = new RESTfulResult();
        rm.setFailed();
        try {
            List<MeterWorkRailwayActual> actualModels = meterWorkRailwayActualMapper.autoPrintRailway2(params);
            //获取轨道衡有效打印限制配置（车号、车型、自重、净重上限、净重下限）
            HashMap<String, Object> printMap = new HashMap<>();
            printMap.put("valueFlag", "1");
            List<MeterBaseVehicleRangePrintConfig> printConfigs = meterBaseVehicleRangePrintConfigMapper.likeByDesc(printMap);
            List<MeterWorkRailwayActual> railwayModels = new ArrayList<>();
            if(actualModels.size() >= 1) {
                for (MeterWorkRailwayActual model: actualModels) {
                    if(printConfigs.size() >= 1) {
                        //循环所有净重信息
                        for (MeterBaseVehicleRangePrintConfig configModel: printConfigs){
                            //判断净重信息物料、车型相同、并且净重在净重上限、下限之间就是有效数据；否者不显示
                            if(configModel.getRailwayNo().equals(model.getRailwayNo())
                                    && configModel.getCarrigeNo().equals(model.getConveyanceType())) {
                                if((model.getNetWeight().compareTo(new BigDecimal(configModel.getNetWeightUpper())) != 1)
                                        && (model.getNetWeight().compareTo(new BigDecimal(configModel.getNetWeightLower()))) != -1) {
                                    railwayModels.add(model);
                                }
                            }else{
                                railwayModels.add(model);
                            }
                        }
                    }
                }
            }

            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 PageList<HashMap> getNetFilterCheck(HashMap params) {
        PageHelper.startPage(Integer.parseInt(params.get("pageNum").toString()), Integer.parseInt(params.get("pageSize").toString()));
        List<HashMap> meterWorkCarActualFirsts = meterWorkRailwayActualMapper.getNetFilterCheck(params);
        PageList pageInfo = new PageList(meterWorkCarActualFirsts);
        return pageInfo;
    }

    @Override
    public PageList<HashMap> getNetFilterCheckWeightReversal(HashMap params) {
        PageHelper.startPage(Integer.parseInt(params.get("pageNum").toString()), Integer.parseInt(params.get("pageSize").toString()));
        List<HashMap> meterWorkCarActualFirsts = meterWorkRailwayActualMapper.getNetFilterCheckWeightReversal(params);
        PageList pageInfo = new PageList(meterWorkCarActualFirsts);
        return pageInfo;
    }

    @Override
    public RESTfulResult getConfigQuery(HashMap parmas, Integer pageNum, Integer pageSize) {
        RESTfulResult rm = new RESTfulResult();
        rm.setSucceed();
        //查询配置
        List<MeterBaseVehicleRangeConfig> query = meterBaseVehicleRangeConfigService.query(parmas);
        if(query==null||query.size()==0){
            rm.setFailed();
            rm.setMessage("未查询出配置");
            return rm;
        }
        if(query.size()>1){
            rm.setFailed();
            rm.setMessage("查询配置数大于1");
            return rm;
        }
        MeterBaseVehicleRangeConfig meterBaseVehicleRangeConfig = query.get(0);

        parmas.put("minGrossWeight",meterBaseVehicleRangeConfig.getGrossWeightLower());
        parmas.put("maxGrossWeight",meterBaseVehicleRangeConfig.getGrossWeightUpper());

        parmas.put("minNetWeight",meterBaseVehicleRangeConfig.getNetWeightLower());
        parmas.put("maxNetWeight",meterBaseVehicleRangeConfig.getNetWeightUpper());
        PageHelper.startPage(pageNum,pageSize);
        //meterworkrailway

        //根据配置查询
        return null;
    }

    @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 batchMatchActualView(HashMap<String, Object> param) {
        RESTfulResult rm = new RESTfulResult();
        rm.setFailed();
        try{
//            Assert.isTrue(param.get("lcNoTemp") != null, "未勾选列次号");
//            String[] lcNoStr = param.get("lcNoTemp").toString().split(",");
//            param.put("lcNoStr", lcNoStr);
//            for (String str: lcNoStr) {
//                if(str.equals("")) {
//                    param.put("lcNoNull", "1");
//                    break;
//                }else {
//                    param.put("lcNoNull", "");
//                }
//            }
            List<HashMap> data = meterWorkRailwayActualMapper.batchMatchActualView(param);
//            for (HashMap model: data) {
//                if(model.get("PREDICTION_NO") == null || StringUtils.isEmpty("PREDICTION_NO")){
//                    HashMap<String, Object> obj = new HashMap<>();
//                    obj.put("railwayNo", model.get("RAILWAY_NO"));
//                    List<PreRailwayScale> scaleList = preRailwayScaleMapper.noPage(obj);
//                    if(scaleList.size() == 1) {
//                        model.remove("PREDICTION_NO");
//                        model.remove("MATTER_NAME");
//                        model.remove("FORWARDING_UNIT_NAME");
//                        model.remove("RECEIVING_UINT_NAME");
//                        model.put("PREDICTION_NO", scaleList.get(0).getPredictionNo());
//                        model.put("MATTER_NAME", scaleList.get(0).getMatterName());
//                        model.put("FORWARDING_UNIT_NAME", scaleList.get(0).getForwardingUnitName());
//                        model.put("RECEIVING_UINT_NAME", scaleList.get(0).getReceivingUintName());
//                    }
//                }
//            }
//            Map<String, Integer> map = new HashMap<String, Integer>();
//            for (Map<String, String> temp : data) {
//                Integer count = map.get(temp.get("RAILWAY_NO"));
//                map.put(temp.get("RAILWAY_NO"), (count == null) ? 1 : count + 1);
//                Assert.isTrue(map.get(temp.get("RAILWAY_NO")) <= 2, "车号["+temp.get("RAILWAY_NO")+"]存在超过2条一次记录，请先处理后再进行批量处理！");
//            }

            rm.setData(data);
            rm.setSucceed();
            rm.setMessage("操作成功");
            rm.setCode("200");
        }catch(Exception e) {
            e.printStackTrace();
            rm.setMessage(e.getMessage());
        }
        return rm;
    }

    @Override
    public RESTfulResult batchRailwayActual(List<HashMap> models) {
        RESTfulResult rm = new RESTfulResult();
        rm.setFailed();
        try{
            UserPayload userPayload = UserPayload.getCurrUser();
            String userId = userPayload.getUserCode();
            String userName = userPayload.getUserName();
            int count = 0;
            List<String> preNoList = null;
            for(HashMap model: models) {
                String pre = model.get("TARE_SCALE_NO") == null ? "":model.get("TARE_SCALE_NO").toString();
                if(StringUtils.isNotEmpty(pre)){
                    preNoList.add(model.get("TARE_SCALE_NO") == null ? "": model.get("TARE_SCALE_NO").toString());
                }
            }
            if(preNoList != null && preNoList.size() >= 1){
                String carStr = org.apache.commons.lang3.StringUtils.join(preNoList.toArray(), ",");
                Assert.isTrue(StringUtils.isNotEmpty(carStr), "[" + carStr + "]回空皮车号带有委托，请解绑委托在进行批量提交");
            }
            for(HashMap model: models) {
                String actualNo = model.get("ACTUAL_NO") == null ? "": model.get("ACTUAL_NO").toString();
                String scaleNo = model.get("PREDICTION_NO") == null ? "": model.get("PREDICTION_NO").toString();
                String tareNo = model.get("TARE_NO") == null ? "": model.get("TARE_NO").toString();

                MeterWorkRailwayActual actualModel = new MeterWorkRailwayActual();
                MeterWorkRailwayActFirst tareNoModel = new MeterWorkRailwayActFirst();
                if(tareNo != null && StringUtils.isNotEmpty(tareNo)) {
                    actualModel = meterWorkRailwayActualMapper.selectByPrimaryKey(actualNo);
                    tareNoModel = meterWorkRailwayActFirstMapper.selectByPrimaryKey(tareNo);
                    if(StringUtils.isNotEmpty(scaleNo)) {
                        if(actualModel != null) {
                            MeterWorkRailwayActFirst tareNoTemp = meterWorkRailwayActFirstMapper.selectAndMatch(tareNoModel.getActualFirstNo(), scaleNo);
                            BeanUtils.copyProperties(tareNoTemp, tareNoModel);

                            tareNoModel.setValueFlag(DbConstants.NET);
                            tareNoModel.setUpdateManNo(userId);
                            tareNoModel.setUpdateManName(userName);
                            tareNoModel.setUpdateTime(new Date());
                            tareNoModel.setWeightType("1");
                            tareNoModel.setIsPreSacale("1");
                            tareNoModel.setPredictionType("1");
                            tareNoModel.setNote("净重批量匹配回空皮");
                            meterWorkRailwayActFirstMapper.updateByPrimaryKey(tareNoModel);

                            actualModel.setActualFirst2No(tareNoModel.getActualFirstNo());
                            actualModel.setTareWeight(tareNoModel.getMeterWeight());
                            actualModel.setTareMode(tareNoModel.getMeterMode());
                            actualModel.setTareClass(tareNoModel.getMeterClass());
                            actualModel.setTareGroup(tareNoModel.getMeterGroup());
                            actualModel.setTareTime(tareNoModel.getCreateTime());
                            actualModel.setTareManNo(tareNoModel.getCreateManNo());
                            actualModel.setTareManName(tareNoModel.getCreateManName());
                            actualModel.setNetWeight(actualModel.getGrossWeight().subtract(tareNoModel.getMeterWeight()));
                            if(actualModel.getGrossTime().compareTo(actualModel.getTareTime()) >= 0) {
                                actualModel.setNetSpot3No(actualModel.getBaseSpot1No());
                                actualModel.setNetSpot3Name(actualModel.getBaseSpot1Name());
                                actualModel.setNetManNo(actualModel.getGrossManNo());
                                actualModel.setNetManName(actualModel.getGrossManName());
                                actualModel.setNetTime(actualModel.getGrossTime());
                                actualModel.setCreateTime(actualModel.getGrossTime());
                                actualModel.setCreateManName(actualModel.getGrossManName());
                                actualModel.setLcNo(meterWorkRailwayActFirstMapper.getFirstLcNo(actualModel.getActualFirst1No()));
                            }else {
                                actualModel.setNetSpot3No(actualModel.getBaseSpot2No());
                                actualModel.setNetSpot3Name(actualModel.getBaseSpot2Name());
                                actualModel.setNetManNo(actualModel.getTareManNo());
                                actualModel.setNetManName(actualModel.getTareManName());
                                actualModel.setNetTime(actualModel.getTareTime());
                                actualModel.setCreateTime(actualModel.getTareTime());
                                actualModel.setCreateManName(actualModel.getTareManName());
                                actualModel.setLcNo(meterWorkRailwayActFirstMapper.getFirstLcNo(actualModel.getActualFirst2No()));
                            }
                            actualModel.setUpdateManNo(userId);
                            actualModel.setUpdateManName(userName);
                            actualModel.setUpdateTime(new Date());
                            actualModel.setNote("净重批量匹配回空皮");
                            meterWorkRailwayActualMapper.updateByPrimaryKeySelective(actualModel);

                            MeterBaseOperationLog logModel = new MeterBaseOperationLog();
                            logModel.setId(PublicMethod.IdCreate(2));
                            logModel.setCreateManNo(userId);
                            logModel.setCreateManName(userName);
                            logModel.setCreateTime(new Date());
                            logModel.setOperationPage("Web端-静轨净重数据批量维护");
                            logModel.setOperationFunction("净重批量匹配回空皮");
                            logModel.setOperationId(actualModel.getActualNo());
                            logModel.setOperationPredictionNo(actualModel.getPredictionNo());
                            logModel.setOperationCarnNo(actualModel.getRailwayNo());
                            meterBaseOperationLogMapper.insertSelective(logModel);

                            count ++;
                        }
                    }else {
                        tareNoModel.setValueFlag(DbConstants.NET);
                        tareNoModel.setUpdateManNo(userId);
                        tareNoModel.setUpdateManName(userName);
                        tareNoModel.setUpdateTime(new Date());
                        tareNoModel.setWeightType("1");
                        tareNoModel.setIsPreSacale("0");
                        tareNoModel.setNote("净重批量匹配回空皮");
                        meterWorkRailwayActFirstMapper.updateByPrimaryKey(tareNoModel);

                        actualModel.setActualFirst2No(tareNoModel.getActualFirstNo());
                        actualModel.setTareWeight(tareNoModel.getMeterWeight());
                        actualModel.setTareMode(tareNoModel.getMeterMode());
                        actualModel.setTareClass(tareNoModel.getMeterClass());
                        actualModel.setTareGroup(tareNoModel.getMeterGroup());
                        actualModel.setTareTime(tareNoModel.getCreateTime());
                        actualModel.setTareManNo(tareNoModel.getCreateManNo());
                        actualModel.setTareManName(tareNoModel.getCreateManName());
                        actualModel.setNetWeight(actualModel.getGrossWeight().subtract(tareNoModel.getMeterWeight()));
                        if(actualModel.getGrossTime().compareTo(actualModel.getTareTime()) >= 0) {
                            actualModel.setNetSpot3No(actualModel.getBaseSpot1No());
                            actualModel.setNetSpot3Name(actualModel.getBaseSpot1Name());
                            actualModel.setNetManNo(actualModel.getGrossManNo());
                            actualModel.setNetManName(actualModel.getGrossManName());
                            actualModel.setNetTime(actualModel.getGrossTime());
                            actualModel.setCreateTime(actualModel.getGrossTime());
                            actualModel.setCreateManName(actualModel.getGrossManName());
                            actualModel.setLcNo(meterWorkRailwayActFirstMapper.getFirstLcNo(actualModel.getActualFirst1No()));
                        }else {
                            actualModel.setNetSpot3No(actualModel.getBaseSpot2No());
                            actualModel.setNetSpot3Name(actualModel.getBaseSpot2Name());
                            actualModel.setNetManNo(actualModel.getTareManNo());
                            actualModel.setNetManName(actualModel.getTareManName());
                            actualModel.setNetTime(actualModel.getTareTime());
                            actualModel.setCreateTime(actualModel.getTareTime());
                            actualModel.setCreateManName(actualModel.getTareManName());
                            actualModel.setLcNo(meterWorkRailwayActFirstMapper.getFirstLcNo(actualModel.getActualFirst2No()));
                        }
                        actualModel.setUpdateManNo(userId);
                        actualModel.setUpdateManName(userName);
                        actualModel.setUpdateTime(new Date());
                        actualModel.setNote("净重批量匹配回空皮");
                        meterWorkRailwayActualMapper.updateByPrimaryKeySelective(actualModel);

                        MeterBaseOperationLog logModel = new MeterBaseOperationLog();
                        logModel.setId(PublicMethod.IdCreate(2));
                        logModel.setCreateManNo(userId);
                        logModel.setCreateManName(userName);
                        logModel.setCreateTime(new Date());
                        logModel.setOperationPage("Web端-静轨净重数据批量维护");
                        logModel.setOperationFunction("净重批量匹配回空皮");
                        logModel.setOperationId(actualModel.getActualNo());
                        logModel.setOperationPredictionNo(actualModel.getPredictionNo());
                        logModel.setOperationCarnNo(actualModel.getRailwayNo());
                        meterBaseOperationLogMapper.insertSelective(logModel);

                        count ++;
                    }
                }
            }
            rm.setSucceed();
            rm.setData("200");
            rm.setMessage("共有" + count + "条数据净重批量匹配回空皮成功");
        }catch(Exception e) {
            e.printStackTrace();
            rm.setMessage(e.getMessage());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return rm;
    }

    @Override
    public RESTfulResult copyActual(List<MeterWorkRailwayActual> models) {
        RESTfulResult rm = new RESTfulResult();
        rm.setFailed();
        try {
            String userId = models.get(0).getUpdateManNo();
            String userName = models.get(0).getUpdateManName();
            Assert.isTrue(models.size() >= 1, "数据不能为空");
            for(MeterWorkRailwayActual model: models) {
                Assert.isTrue(model.getPredictionNo() != null && StringUtils.isNotEmpty(model.getPredictionNo()), "委托号不能为空");
                PreRailwayScale scale = preRailwayScaleMapper.selectByPrimaryKey(model.getPredictionNo());
                if(scale != null) {
                    Assert.isTrue(!scale.getValueFlag().equals("2"), "委托信息已使用，不允许补录结净数据");
                    Assert.isTrue(!scale.getValueFlag().equals("9"), "委托信息已结算，不允许补录结净数据");
                }
            }

            List<MeterWorkRailwayActual> actualModels = new ArrayList<>();
            List<MeterWorkRailwayReceived> receiveds = new ArrayList<>();
            int count = 0;
            for(MeterWorkRailwayActual model: models) {
                MeterWorkRailwayReceived grossRec = new MeterWorkRailwayReceived();
                MeterWorkRailwayReceived tareRec = new MeterWorkRailwayReceived();

                MeterWorkRailwayActFirst grossModel = new MeterWorkRailwayActFirst();
                MeterWorkRailwayActFirst tareModel = new MeterWorkRailwayActFirst();
                MeterWorkRailwayActual actualRow = new MeterWorkRailwayActual();
                if(model.getPredictionNo() != null && StringUtils.isNotEmpty(model.getPredictionNo())) {
                    String predictionNo = model.getPredictionNo();

                    String actualFirstNo = PublicMethod.IdCreate(3);
                    grossModel.setActualFirstNo(actualFirstNo);
                    grossModel.setRailwayNo(model.getRailwayNo());
                    grossModel.setMeterWeight(model.getGrossWeight());
                    grossModel.setRailwayTypeNo(model.getRailwayTypeNo());
                    grossModel.setRailwayTypeName(model.getRailwayTypeName());
                    grossModel.setWeightType("0");
                    grossModel.setCreateManNo(model.getGrossManNo());
                    grossModel.setCreateManName(model.getGrossManName());
                    grossModel.setCreateTime(model.getGrossTime());
                    grossModel.setUpdateManNo(userId);
                    grossModel.setUpdateManName(userName);
                    grossModel.setUpdateTime(new Date());
                    grossModel.setBaseSpotNo(model.getBaseSpot1No());
                    grossModel.setBaseSpotName(model.getBaseSpot1Name());
                    grossModel.setValueFlag("2");
                    grossModel.setCheckFlag("0");
                    grossModel.setDataSource("4");
                    grossModel.setMeterMode("3");
                    grossModel.setIsPreSacale("0");
                    meterWorkRailwayActFirstMapper.insertSelective(grossModel);

                    grossRec.setActualFirstNo(actualFirstNo);
                    grossRec.setRailwayNo(model.getRailwayNo());
                    grossRec.setMeterWeight(model.getGrossWeight());
                    grossRec.setRailwayTypeNo(model.getRailwayTypeNo());
                    grossRec.setRailwayTypeName(model.getRailwayTypeName());
                    grossRec.setWeightType("0");
                    grossRec.setCreateManNo(model.getGrossManNo());
                    grossRec.setCreateManName(model.getGrossManName());
                    grossRec.setCreateTime(model.getGrossTime());
                    grossRec.setUpdateManNo(userId);
                    grossRec.setUpdateManName(userName);
                    grossRec.setUpdateTime(new Date());
                    grossRec.setBaseSpotNo(model.getBaseSpot1No());
                    grossRec.setBaseSpotName(model.getBaseSpot1Name());
                    grossRec.setValueFlag("2");
                    grossRec.setCheckFlag("0");
                    grossRec.setMeterMode("3");
                    meterWorkRailwayReceivedMapper.insertSelective(grossRec);

                    String actualSecondNo = PublicMethod.IdCreate(3);
                    tareModel.setActualFirstNo(actualSecondNo);
                    tareModel.setRailwayNo(model.getRailwayNo());
                    tareModel.setMeterWeight(model.getTareWeight());
                    tareModel.setWeightType("1");
                    tareModel.setRailwayTypeNo(model.getRailwayTypeNo());
                    tareModel.setRailwayTypeName(model.getRailwayTypeName());
                    tareModel.setCreateManNo(model.getGrossManNo());
                    tareModel.setCreateManName(model.getGrossManName());
                    tareModel.setCreateTime(model.getTareTime());
                    tareModel.setUpdateManNo(userId);
                    tareModel.setUpdateManName(userName);
                    tareModel.setUpdateTime(new Date());
                    tareModel.setBaseSpotNo(model.getBaseSpot2No());
                    tareModel.setBaseSpotName(model.getBaseSpot2Name());
                    tareModel.setValueFlag("2");
                    tareModel.setCheckFlag("0");
                    tareModel.setDataSource("4");
                    tareModel.setMeterMode("3");
                    tareModel.setIsPreSacale("0");
                    meterWorkRailwayActFirstMapper.insertSelective(tareModel);

                    tareRec.setActualFirstNo(actualSecondNo);
                    tareRec.setRailwayNo(model.getRailwayNo());
                    tareRec.setMeterWeight(model.getTareWeight());
                    tareRec.setWeightType("1");
                    tareRec.setRailwayTypeNo(model.getRailwayTypeNo());
                    tareRec.setRailwayTypeName(model.getRailwayTypeName());
                    tareRec.setCreateManNo(model.getGrossManNo());
                    tareRec.setCreateManName(model.getGrossManName());
                    tareRec.setCreateTime(model.getTareTime());
                    tareRec.setUpdateManNo(userId);
                    tareRec.setUpdateManName(userName);
                    tareRec.setUpdateTime(new Date());
                    tareRec.setBaseSpotNo(model.getBaseSpot2No());
                    tareRec.setBaseSpotName(model.getBaseSpot2Name());
                    tareRec.setValueFlag("2");
                    tareRec.setCheckFlag("0");
                    tareRec.setMeterMode("3");
                    meterWorkRailwayReceivedMapper.insertSelective(tareRec);

                    //净重

                    //将委托中的编号和收发货的等数据拷贝进一次数据中
                    MeterWorkRailwayActFirst first1 = meterWorkRailwayActFirstMapper.selectAndMatch(actualFirstNo, predictionNo);
                    BeanUtils.copyProperties(first1,grossModel);
                    grossModel.setIsPreSacale("1");
                    grossModel.setPredictionType("1");
                    meterWorkRailwayActFirstMapper.updateByPrimaryKey(grossModel);

                    MeterWorkRailwayActFirst first2 = meterWorkRailwayActFirstMapper.selectAndMatch(actualSecondNo, predictionNo);
                    BeanUtils.copyProperties(first2, tareModel);
                    tareModel.setIsPreSacale("1");
                    tareModel.setPredictionType("1");
                    meterWorkRailwayActFirstMapper.updateByPrimaryKey(tareModel);

                    //将委托中的编号和收发货的等数据拷贝进一次数据中
                    MeterWorkRailwayReceived firstRec1 = meterWorkRailwayReceivedMapper.selectAndMatch(actualFirstNo, predictionNo);
                    BeanUtils.copyProperties(firstRec1,grossRec);
                    grossRec.setPredictionType("1");
                    meterWorkRailwayReceivedMapper.updateByPrimaryKey(grossRec);

                    MeterWorkRailwayReceived firstRec2 = meterWorkRailwayReceivedMapper.selectAndMatch(actualSecondNo, predictionNo);
                    BeanUtils.copyProperties(firstRec2, tareRec);
                    tareRec.setPredictionType("1");
                    meterWorkRailwayReceivedMapper.updateByPrimaryKey(tareRec);

                    receiveds.add(grossRec);
                    receiveds.add(tareRec);

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

                    String no = PublicMethod.IdCreate(3);
                    actualRow.setActualNo(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(userId);
                    actualRow.setUpdateManName(userName);
                    actualRow.setUpdateTime(new Date());
                    actualRow.setPredictionNo(predictionNo);
                    actualRow.setNetWeight(grossModel.getMeterWeight().subtract(tareModel.getMeterWeight()));
                    if(actualRow.getGrossTime().compareTo(actualRow.getTareTime()) >= 0) {
                        actualRow.setNetSpot3No(actualRow.getBaseSpot1No());
                        actualRow.setNetSpot3Name(actualRow.getBaseSpot1Name());
                        actualRow.setNetManNo(actualRow.getGrossManNo());
                        actualRow.setNetManName(actualRow.getGrossManName());
                        actualRow.setNetTime(actualRow.getGrossTime());
                        actualRow.setCreateTime(actualRow.getGrossTime());
                        actualRow.setCreateManName(actualRow.getGrossManName());
                        //actualRow.setLcNo(meterWorkRailwayActFirstMapper.getFirstLcNo(actualRow.getActualFirst1No()));
                    }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());
                        //actualRow.setLcNo(meterWorkRailwayActFirstMapper.getFirstLcNo(actualRow.getActualFirst2No()));
                    }
//                    actualRow.setLcNo(model.getLcNo());
                    meterWorkRailwayActualMapper.insertSelective(actualRow);
                    actualModels.add(actualRow);

                    //更新预报数据
                    PreRailwayScale scale = preRailwayScaleMapper.selectByPrimaryKey(predictionNo);
                    scale.setValueFlag(DbConstants.NET);
                    scale.setPredictionType("1");
                    scale.setUpdateTime(new Date());
                    scale.setUpdateManNo(model.getNetManNo());
                    scale.setUpdateManName(model.getNetManNo());
                    scale.setUploadFlag("1");
                    scale.setValueFlag("2");
                    scale.setMeasureStation(tareModel.getBaseSpotNo());
                    scale.setMeasureStationName(tareModel.getBaseSpotName());
                    preRailwayScaleMapper.updateByPrimaryKeySelective(scale);
                    count ++;
                }

                MeterBaseOperationLog logModel = new MeterBaseOperationLog();
                logModel.setId(PublicMethod.IdCreate(2));
                logModel.setCreateManNo(model.getCreateManName());
                logModel.setCreateManName(model.getCreateManName());
                logModel.setCreateTime(new Date());
                logModel.setOperationPage("C#端-动轨净重数据维护");
                logModel.setOperationFunction("数据补录");
                logModel.setOperationId(model.getActualNo());
                logModel.setOperationPredictionNo("");
                logModel.setOperationCarnNo(model.getRailwayNo());
                logModel.setOperationBeforeFix(model.toString());
                logModel.setOperationAfterFix(actualRow.toString());
                meterBaseOperationLogMapper.insertSelective(logModel);
            }

            if(receiveds.size() >= 1) {
                List<String> spotList = receiveds
                        .stream()
                        .map(MeterWorkRailwayReceived::getBaseSpotNo)
                        .distinct()
                        .collect(Collectors.toList());
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
                List<HashMap> maps = new ArrayList<>();
                for(String spot: spotList) {
                    Long spotCount = receiveds.stream().filter(item -> StringUtils.isNotEmpty(item.getBaseSpotNo()) && item.getBaseSpotNo().equals(spot)).count();
                    String afl = sdf.format(new Date());
                    String lcNo = meterWorkRailwayRecMainMapper.getLcNo(afl,spot);
                    List<MeterWorkRailwayReceived> spotModel = receiveds.stream().filter(item ->  StringUtils.isNotEmpty(item.getBaseSpotNo()) && item.getBaseSpotNo().equals(spot)).collect(Collectors.toList());
                    HashMap<String, Object> obj = new HashMap<>();
                    obj.put("spotNo", spot);
                    obj.put("spotName", spotModel.get(0).getBaseSpotName());
                    obj.put("size", spotCount);
                    obj.put("lcNo", "-" + afl + lcNo + "(" + spotCount + ")");
                    maps.add(obj);
                }

                for(MeterWorkRailwayReceived received: receiveds) {
                    for(HashMap temp: maps) {
                        if(temp.get("spotNo").equals(received.getBaseSpotNo())) {
                            received.setRailwayWorkNo(received.getBaseSpotName().replaceAll("#", "")
                                    .replaceAll("轨道衡", "")
                                    .replaceAll("动轨", "")
                                    .replaceAll("动态", "") + temp.get("lcNo").toString());
                            MeterWorkRailwayActFirst first = meterWorkRailwayActFirstMapper.selectByPrimaryKey(received.getActualFirstNo());
                            first.setLcNo(received.getBaseSpotName().replaceAll("#", "")
                                    .replaceAll("轨道衡", "")
                                    .replaceAll("动轨", "")
                                    .replaceAll("动态", "") + temp.get("lcNo").toString());
                            meterWorkRailwayActFirstMapper.updateByPrimaryKeySelective(first);
                        }
                    }
                    meterWorkRailwayReceivedMapper.updateByPrimaryKeySelective(received);
                }

                for(MeterWorkRailwayActual actualRow: actualModels) {
                    if(actualRow.getGrossTime().compareTo(actualRow.getTareTime()) >= 0) {
                        actualRow.setLcNo(meterWorkRailwayActFirstMapper.getFirstLcNo(actualRow.getActualFirst1No()));
                    }else {
                        actualRow.setLcNo(meterWorkRailwayActFirstMapper.getFirstLcNo(actualRow.getActualFirst2No()));
                    }
                    meterWorkRailwayActualMapper.updateByPrimaryKeySelective(actualRow);
                }


                if (maps.size() >= 1) {
                    for(HashMap temp: maps) {
                        //插入主表数据
                        MeterWorkRailwayRecMain recMain = new MeterWorkRailwayRecMain();
//                    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
//                    String afl = sdf.format(new Date());
//                    String lcNo = meterWorkRailwayRecMainMapper.getLcNo(afl, receiveds.get(0).getBaseSpotNo());
//                    recMain.setActualNo(receiveds.get(0).getBaseSpotName().replaceAll("#", "")
//                            .replaceAll("轨道衡", "")
//                            .replaceAll("动轨", "")
//                            .replaceAll("动态", "") + "-" + afl + lcNo + "(" + receiveds.size() + ")");
                        recMain.setActualNo(temp.get("spotName").toString().replaceAll("#", "")
                                .replaceAll("轨道衡", "")
                                .replaceAll("动轨", "")
                                .replaceAll("动态", "") + temp.get("lcNo").toString());
//                            recMain.setActualNo(new SimpleDateFormat("yyyyMMddHHmm").format(new Date()) + PublicMethod.RandomCreate(2));
                        recMain.setIsDispose("1");
                        recMain.setSoundName(recMain.getActualNo());
                        recMain.setCarriageNum(Short.valueOf(temp.get("size").toString()));
                        recMain.setBaseSpotNo(temp.get("spotNo").toString());
                        recMain.setBaseSpotName(temp.get("spotName").toString());
                        recMain.setCreateTime(new Date());
                        meterWorkRailwayRecMainMapper.insertSelective(recMain);
                    }
                }
            }



            rm.setSucceed();
            rm.setData("200");
            rm.setMessage("共有" + count + "条数据一次批量新增成功");
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            rm.setMessage(e.getMessage());
        }
        return rm;
    }

    @Override
    public RESTfulResult updateList(List<MeterWorkRailwayActual> models) {
        RESTfulResult rm = new RESTfulResult();
        rm.setFailed();
        try {
            Assert.isTrue(models.size() >= 1, "数据不能为空");
            int count = 0;

            for(MeterWorkRailwayActual model: models) {
                MeterWorkRailwayActual modelTemp = meterWorkRailwayActualMapper.selectByPrimaryKey(model.getActualNo());
                Assert.isTrue(!modelTemp.getValueFlag().equals("2"), "选择的结净数据已发布,请取消发布之后在操作");
            }

            for(MeterWorkRailwayActual model: models) {
                String userId = model.getUpdateManNo();
                String userName = model.getUpdateManName();
                //修改前的净重数据
                MeterWorkRailwayActual modelTemp = meterWorkRailwayActualMapper.selectByPrimaryKey(model.getActualNo());

                MeterBaseOperationLog logModel = new MeterBaseOperationLog();
                logModel.setId(PublicMethod.IdCreate(2));
                logModel.setCreateManNo(userId);
                logModel.setCreateManName(userName);
                logModel.setCreateTime(new Date());
                logModel.setOperationPage("C#端-动轨净重数据维护");
                if(StringUtils.isEmpty(modelTemp.getRailwayNo()) || !modelTemp.getRailwayNo().equals(model.getRailwayNo())) {
                    logModel.setOperationFunction("车号修改");
                }else{
                    if(modelTemp.getTareWeight() == null || !(modelTemp.getTareWeight().compareTo(model.getTareWeight()) == 0)) {
                        logModel.setOperationFunction("Ai标识皮修改");
                    }
                }
                logModel.setOperationId(model.getActualNo());
                logModel.setOperationPredictionNo(model.getPredictionNo());
                logModel.setOperationCarnNo(model.getRailwayNo());
                logModel.setOperationBeforeFix(modelTemp.toString());
                logModel.setOperationAfterFix(model.toString());
                meterBaseOperationLogMapper.insertSelective(logModel);
                model.setNote("");

                model.setUpdateManNo(userId);
                model.setUpdateManName(userName);
                model.setUpdateTime(new Date());
                model.setNote(logModel.getOperationFunction());
                meterWorkRailwayActualMapper.updateByPrimaryKeySelective(model);
                count++;
            }
            rm.setSucceed(true);
            rm.setData("200");
            rm.setMessage("共有" + count + "条数据一次批量修改成功");
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            rm.setMessage(e.getMessage());
        }
        return rm;
    }

    @Override
    public RESTfulResult updatePre(MeterWorkRailwayActual model) {
        RESTfulResult rm = new RESTfulResult();
        rm.setFailed();
        try {
            String userId = model.getUpdateManNo();
            String userName = model.getUpdateManName();
//            try {
//                UserPayload userPayload = UserPayload.getCurrUser();
//                userId = userPayload.getUserCode();
//                userName = userPayload.getUserName();
//            }
//            catch (Exception e){
//                userId = "admin";
//                userName = "admin";
//            }

            MeterWorkRailwayActual modelTemp = meterWorkRailwayActualMapper.selectByPrimaryKey(model.getActualNo());
            Assert.isTrue(modelTemp != null, "未查询到"+ model.getActualNo() +"对应的结净数据");
            Assert.isTrue(!(modelTemp.getValueFlag().equals("2") && modelTemp.getValueFlag().equals("0")), model.getActualNo() + "对应的结净数据已发布或者已作废,无法匹配委托");
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            if(modelTemp.getUpdateTime() != null && StringUtils.isNotEmpty(modelTemp.getUpdateTime().toString())) {
                String sDate = df.format(modelTemp.getUpdateTime());
                String eDate = df.format(new Date());
                long sTime = df.parse(sDate).getTime();
                long eTime = df.parse(eDate).getTime();
                long diff = (eTime - sTime) / 1000;
                if(diff <= 15) {
                    rm.setMessage("匹配委托需在解除委托15秒后进行，请稍等");
                    return rm;
                }
            }
            if(modelTemp.getPredictionNo() == null || StringUtils.isEmpty(modelTemp.getPredictionNo())) {
                PreRailwayScale scale = preRailwayScaleMapper.selectByPrimaryKey(model.getPredictionNo());
                Assert.isTrue(scale != null, "未找到" + model.getPredictionNo() + "对应的委托信息");

                MeterWorkRailwayActual actualRow = meterWorkRailwayActualMapper.mathPredcition(modelTemp.getActualNo(),model.getPredictionNo());
                actualRow.setUpdateManNo(userId);
                actualRow.setUpdateManName(userName);
                actualRow.setUpdateTime(new Date());
                actualRow.setIsPreSacale("1");
                actualRow.setPredictionType("1");
                actualRow.setUploadFlag("1");
                actualRow.setValueFlag("2");
                meterWorkRailwayActualMapper.updateByPrimaryKeySelective(actualRow);

                MeterBaseOperationLog logModel = new MeterBaseOperationLog();
                logModel.setId(PublicMethod.IdCreate(2));
                logModel.setCreateManNo(userId);
                logModel.setCreateManName(userName);
                logModel.setCreateTime(new Date());
                logModel.setOperationPage("C#端-动轨净重数据维护");
                logModel.setOperationFunction("匹配委托");
                logModel.setOperationId(modelTemp.getActualNo());
                logModel.setOperationPredictionNo(modelTemp.getPredictionNo());
                logModel.setOperationCarnNo(modelTemp.getRailwayNo());
                logModel.setOperationBeforeFix(modelTemp.toString());
                logModel.setOperationAfterFix(actualRow.toString());
                meterBaseOperationLogMapper.insertSelective(logModel);

                MeterWorkRailwayActFirst grossModel = meterWorkRailwayActFirstMapper.selectByPrimaryKey(modelTemp.getActualFirst1No());
                MeterWorkRailwayActFirst tareModel = meterWorkRailwayActFirstMapper.selectByPrimaryKey(modelTemp.getActualFirst2No());
                if(grossModel != null) {
                    grossModel = meterWorkRailwayActFirstMapper.selectAndMatch(grossModel.getActualFirstNo(), model.getPredictionNo());
                    grossModel.setIsPreSacale("1");
                    grossModel.setUpdateManNo(userId);
                    grossModel.setUpdateManName(userName);
                    grossModel.setUpdateTime(new Date());
                    grossModel.setNote("动态衡匹配委托");
                    meterWorkRailwayActFirstMapper.updateByPrimaryKeySelective(grossModel);
                    MeterWorkRailwayReceived received = meterWorkRailwayReceivedMapper.selectByPrimaryKey(grossModel.getActualFirstNo());
                    if(received != null) {
                        if(StringUtils.isEmpty(received.getPredictionNo())) {
                            received.setRailwayNo(scale.getRailwayNo());
                            received.setMatterNo(scale.getMatterNo());
                            received.setMatterName(scale.getMatterName());
                            received.setReceivingUintNo(scale.getForwardingUnitNo());
                            received.setForwardingUnitName(scale.getForwardingUnitName());
                            received.setReceivingUintNo(scale.getReceivingUintNo());
                            received.setReceivingUintName(scale.getReceivingUintName());
                            meterWorkRailwayReceivedMapper.selectAndMatch(received.getActualFirstNo(), scale.getPredictionNo());
                            received.setUpdateManNo(userId);
                            received.setUpdateManName(userName);
                            received.setUpdateTime(new Date());
                            meterWorkRailwayReceivedMapper.updateByPrimaryKeySelective(received);
                        }
                    }
                }
                if(tareModel != null) {
                    tareModel = meterWorkRailwayActFirstMapper.selectAndMatch(tareModel.getActualFirstNo(), model.getPredictionNo());
                    tareModel.setIsPreSacale("1");
                    tareModel.setUpdateManNo(userId);
                    tareModel.setUpdateManName(userName);
                    tareModel.setUpdateTime(new Date());
                    tareModel.setNote("动态衡匹配委托");
                    meterWorkRailwayActFirstMapper.updateByPrimaryKeySelective(tareModel);
                    MeterWorkRailwayReceived received = meterWorkRailwayReceivedMapper.selectByPrimaryKey(tareModel.getActualFirstNo());
                    if(received != null) {
                        if(StringUtils.isEmpty(received.getPredictionNo())) {
                            received.setRailwayNo(scale.getRailwayNo());
                            received.setMatterNo(scale.getMatterNo());
                            received.setMatterName(scale.getMatterName());
                            received.setReceivingUintNo(scale.getForwardingUnitNo());
                            received.setForwardingUnitName(scale.getForwardingUnitName());
                            received.setReceivingUintNo(scale.getReceivingUintNo());
                            received.setReceivingUintName(scale.getReceivingUintName());
                            meterWorkRailwayReceivedMapper.selectAndMatch(received.getActualFirstNo(), scale.getPredictionNo());
                            received.setUpdateManNo(userId);
                            received.setUpdateManName(userName);
                            received.setUpdateTime(new Date());
                            meterWorkRailwayReceivedMapper.updateByPrimaryKeySelective(received);
                        }
                    }
                }

                scale.setUploadFlag("1");
                scale.setValueFlag("2");
                scale.setUpdateManNo(userId);
                scale.setUpdateManName(userName);
                scale.setUpdateTime(new Date());
                scale.setMeasureStation(model.getNetSpot3No());
                scale.setMeasureStationName(model.getNetSpot3Name());
                preRailwayScaleMapper.updateByPrimaryKeySelective(scale);

                rm.setSucceed();
                rm.setMessage("操作成功");
                rm.setCode("200");
                rm.setData(null);
            }else{
                rm.setMessage("选择的结净数据已匹配委托");
            }
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            rm.setMessage(e.getMessage());
        }
        return rm;
    }

    //动态衡净重数据撤销委托
    @Override
    public RESTfulResult updatePreCancel(List<MeterWorkRailwayActual> models) {
        RESTfulResult rm = new RESTfulResult();
        rm.setFailed();
        try {
            String userId = models.get(0).getUpdateManNo();
            String userName = models.get(0).getUpdateManName();
//            try {
//                UserPayload userPayload = UserPayload.getCurrUser();
//                userId = userPayload.getUserCode();
//                userName = userPayload.getUserName();
//            }
//            catch (Exception e){
//                userId = "admin";
//                userName = "admin";
//            }
            int count = 0;
            for(MeterWorkRailwayActual model:models){
                MeterWorkRailwayActual modelTemp = meterWorkRailwayActualMapper.selectByPrimaryKey(model.getActualNo());
                Assert.isTrue(modelTemp != null, "未查询到"+ model.getActualNo() +"对应的结净数据");
                Assert.isTrue(!(modelTemp.getValueFlag().equals("2") && modelTemp.getValueFlag().equals("0")), model.getActualNo() + "对应的结净数据已发布或者已作废,无法撤销委托");
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                if(modelTemp.getUpdateTime() != null && StringUtils.isNotEmpty(modelTemp.getUpdateTime().toString())) {
                    String sDate = df.format(modelTemp.getUpdateTime());
                    String eDate = df.format(new Date());
                    long sTime = df.parse(sDate).getTime();
                    long eTime = df.parse(eDate).getTime();
                    long diff = (eTime - sTime) / 1000;
                    if(diff <= 15) {
                        rm.setMessage("解除委托需在匹配委托15秒后进行，请稍等");
                        return rm;
                    }
                }
                if(modelTemp.getPredictionNo() != null && StringUtils.isNotEmpty(modelTemp.getPredictionNo())) {
                    PreRailwayScale scale = preRailwayScaleMapper.selectByPrimaryKey(modelTemp.getPredictionNo());
                    Assert.isTrue(scale != null, "未找到" + modelTemp.getPredictionNo() +"对应的委托信息");
                    Assert.isTrue(!scale.getValueFlag().equals("9"), modelTemp.getPredictionNo() +"对应的委托信息已结算");

                    MeterWorkRailwayActFirst grossModel = meterWorkRailwayActFirstMapper.selectByPrimaryKey(modelTemp.getActualFirst1No());
                    MeterWorkRailwayActFirst tareModel = meterWorkRailwayActFirstMapper.selectByPrimaryKey(modelTemp.getActualFirst2No());
                    if(grossModel != null) {        //作废毛重数据、恢复从表信息
                        grossModel = meterWorkRailwayActFirstMapper.selectAndRemove(grossModel.getActualFirstNo());
                        grossModel.setIsPreSacale("0");
                        grossModel.setUpdateManNo(userId);
                        grossModel.setUpdateManName(userName);
                        grossModel.setUpdateTime(new Date());
                        grossModel.setNote("动态衡撤销委托");
                        meterWorkRailwayActFirstMapper.updateByPrimaryKey(grossModel);
                        //撤销动态衡从表一次数据
                        MeterWorkRailwayReceived received = meterWorkRailwayReceivedMapper.selectByPrimaryKey(grossModel.getActualFirstNo());
                        if(received != null) {
                            received.setMatterNo(null);
                            received.setMatterName(null);
                            received.setReceivingUintNo(null);
                            received.setForwardingUnitName(null);
                            received.setReceivingUintNo(null);
                            received.setReceivingUintName(null);
                            received = meterWorkRailwayReceivedMapper.selectAndRemove(received.getActualFirstNo());
                            meterWorkRailwayReceivedMapper.updateByPrimaryKey(received);
                        }
                    }
                    if(tareModel != null) {
                        tareModel = meterWorkRailwayActFirstMapper.selectAndRemove(tareModel.getActualFirstNo());
                        tareModel.setIsPreSacale("0");
                        tareModel.setUpdateManNo(userId);
                        tareModel.setUpdateManName(userName);
                        tareModel.setUpdateTime(new Date());
                        tareModel.setNote("动态衡撤销委托");
                        meterWorkRailwayActFirstMapper.updateByPrimaryKey(tareModel);

                        //撤销动态衡从表一次数据
                        MeterWorkRailwayReceived received = meterWorkRailwayReceivedMapper.selectByPrimaryKey(tareModel.getActualFirstNo());
                        if(received != null) {
                            received.setMatterNo(null);
                            received.setMatterName(null);
                            received.setReceivingUintNo(null);
                            received.setForwardingUnitName(null);
                            received.setReceivingUintNo(null);
                            received.setReceivingUintName(null);
                            received = meterWorkRailwayReceivedMapper.selectAndRemove(received.getActualFirstNo());
                            meterWorkRailwayReceivedMapper.updateByPrimaryKey(received);
                        }
                    }

                    MeterWorkRailwayActual actualRow = meterWorkRailwayActualMapper.cleanPredcition(modelTemp.getActualNo());
                    actualRow.setUploadFlag("1");
                    actualRow.setValueFlag("1");
                    actualRow.setIsPreSacale("0");
                    actualRow.setUpdateManNo(userId);
                    actualRow.setUpdateManName(userName);
                    actualRow.setUpdateTime(new Date());
                    actualRow.setNote("动态衡撤销委托");
                    meterWorkRailwayActualMapper.updateByPrimaryKey(actualRow);

                    scale.setValueFlag("1");
                    scale.setUploadFlag("1");
                    scale.setUpdateManNo(userId);
                    scale.setUpdateManName(userName);
                    scale.setUpdateTime(new Date());
                    preRailwayScaleMapper.updateByPrimaryKeySelective(scale);

                    MeterBaseOperationLog logModel = new MeterBaseOperationLog();
                    logModel.setId(PublicMethod.IdCreate(2));
                    logModel.setCreateManNo(userId);
                    logModel.setCreateManName(userName);
                    logModel.setCreateTime(new Date());
                    logModel.setOperationPage("C#端-动轨净重数据维护");
                    logModel.setOperationFunction("撤销委托");
                    logModel.setOperationId(modelTemp.getActualNo());
                    logModel.setOperationPredictionNo(modelTemp.getPredictionNo());
                    logModel.setOperationCarnNo(modelTemp.getRailwayNo());
                    logModel.setOperationBeforeFix(modelTemp.toString());
                    logModel.setOperationAfterFix(actualRow.toString());
                    meterBaseOperationLogMapper.insertSelective(logModel);
                    count ++;
                }
            }
            rm.setSucceed();
            rm.setData(null);
            rm.setMessage("共"+count+"条数据撤销成功");
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            rm.setMessage(e.getMessage());
        }
        return rm;
    }

    @Override
    public RESTfulResult resolveList(List<MeterWorkRailwayActual> models) {
        RESTfulResult rm = new RESTfulResult();
        rm.setFailed();
        try {
            String userId = models.get(0).getUpdateManNo();
            String userName = models.get(0).getUpdateManName();
//            try {
//                UserPayload userPayload = UserPayload.getCurrUser();
//                userId = userPayload.getUserCode();
//                userName = userPayload.getUserName();
//            }
//            catch (Exception e){
//                userId = "admin";
//                userName = "admin";
//            }
            Assert.isTrue(models.size()>=1, "未选择结净数据，请重新操作");

            for (MeterWorkRailwayActual model: models) {
                MeterWorkRailwayActual modelTemp = meterWorkRailwayActualMapper.selectByPrimaryKey(model.getActualNo());
                if(modelTemp.getPredictionNo() != null && StringUtils.isNotEmpty(modelTemp.getPredictionNo())) {
                    rm.setMessage("选择的结净数据中包含有委托，请撤销完委托之后才能进行毛皮分解");
                    return rm;
                }
                if(modelTemp.getValueFlag().equals("2")) {
                    rm.setMessage("选择的结净数据中包含有已发布数据，无法进行毛皮分解");
                    return rm;
                }
                if(modelTemp.getValueFlag().equals("0")) {
                    rm.setMessage("选择的结净数据中包含有已作废数据，无法进行毛皮分解");
                    return rm;
                }
            }
            for (MeterWorkRailwayActual model: models) {
                MeterWorkRailwayActual modelTemp = meterWorkRailwayActualMapper.selectByPrimaryKey(model.getActualNo());
                Assert.isTrue(modelTemp != null, "未查询到"+ model.getActualNo() +"对应的结净数据");

                MeterWorkRailwayActFirst grossModel = meterWorkRailwayActFirstMapper.selectByPrimaryKey(modelTemp.getActualFirst1No());
                if(grossModel != null) {            //作废毛重数据、并回复从表数据
                    grossModel.setIsPreSacale("0");
                    grossModel.setValueFlag("0");
                    grossModel.setUpdateManNo(userId);
                    grossModel.setUpdateManName(userName);
                    grossModel.setUpdateTime(new Date());
                    grossModel.setNote("动态衡毛皮分解");
//                    meterWorkRailwayActFirstMapper.updateByPrimaryKeySelective(grossModel);
                    meterWorkRailwayActFirstMapper.deleteByPrimaryKey(grossModel.getActualFirstNo());
                    MeterWorkRailwayReceived grossRec = meterWorkRailwayReceivedMapper.selectByPrimaryKey(grossModel.getActualFirstNo());
                    if(grossRec != null ) {
                        //恢复从表数据
                        if(grossRec.getPredictionNo() != null) {
                            grossRec = meterWorkRailwayReceivedMapper.selectAndRemove(grossRec.getActualFirstNo());
                        }
                        preRailwayScaleMapper.updateMeterWorkRailwayReceiveds(grossRec.getActualFirstNo());
                        if(grossRec.getActualFirstNo() != null) {
                            MeterWorkRailwayReceived received = meterWorkRailwayReceivedMapper.selectByPrimaryKey(grossRec.getActualFirstNo());
                            if(received != null) {
                                HashMap<String, Object> obj = new HashMap<>();
                                obj.put("soundName", received.getRailwayWorkNo());
                                //把列次号变为未处理
                                List<MeterWorkRailwayRecMain> recMains = meterWorkRailwayRecMainMapper.selectByParameters(obj);
                                if(recMains.size() >= 1) {
                                    recMains.get(0).setIsDispose("0");
                                    meterWorkRailwayRecMainMapper.updateByPrimaryKeySelective(recMains.get(0));
                                }
                            }
                        }
                        //毛皮分解恢复状态未处理2023年4月20日--zn
                        grossRec.setValueFlag("1");
                        meterWorkRailwayReceivedMapper.updateByPrimaryKey(grossRec);
                    }
                }
                MeterWorkRailwayActFirst tareModel = meterWorkRailwayActFirstMapper.selectByPrimaryKey(modelTemp.getActualFirst2No());
                if(tareModel != null) {
                    tareModel.setIsPreSacale("0");
                    tareModel.setValueFlag("0");
                    tareModel.setUpdateManNo(userId);
                    tareModel.setUpdateManName(userName);
                    tareModel.setUpdateTime(new Date());
                    tareModel.setNote("动态衡毛皮分解");
                    meterWorkRailwayActFirstMapper.deleteByPrimaryKey(tareModel.getActualFirstNo());
                    MeterWorkRailwayReceived tareRec = meterWorkRailwayReceivedMapper.selectByPrimaryKey(grossModel.getActualFirstNo());
                    if(tareRec != null ) {
                        //恢复从表数据
                        if (tareRec.getPredictionNo() != null) {
                            tareRec = meterWorkRailwayReceivedMapper.selectAndRemove(tareRec.getActualFirstNo());
                        }
                        //恢复从表数据
                        preRailwayScaleMapper.updateMeterWorkRailwayReceiveds(tareRec.getActualFirstNo());

                        if (tareRec.getActualFirstNo() != null) {
                            MeterWorkRailwayReceived received = meterWorkRailwayReceivedMapper.selectByPrimaryKey(tareRec.getActualFirstNo());
                            if (received != null) {
                                HashMap<String, Object> obj = new HashMap<>();
                                obj.put("soundName", received.getRailwayWorkNo());
                                //把列次号变为未处理
                                List<MeterWorkRailwayRecMain> recMains = meterWorkRailwayRecMainMapper.selectByParameters(obj);
                                if (recMains.size() >= 1) {
                                    recMains.get(0).setIsDispose("0");
                                    meterWorkRailwayRecMainMapper.updateByPrimaryKeySelective(recMains.get(0));
                                }
                            }
                        }
                        //毛皮分解恢复状态未处理2023年4月20日--zn
                        tareRec.setValueFlag("1");
                        meterWorkRailwayReceivedMapper.updateByPrimaryKey(tareRec);
                    }
                }

                MeterWorkRailwayActual actualRow = meterWorkRailwayActualMapper.cleanPredcition(modelTemp.getActualNo());
                actualRow.setUploadFlag("1");
                actualRow.setValueFlag("0");
                actualRow.setIsPreSacale("0");
                actualRow.setUpdateManNo(userId);
                actualRow.setUpdateManName(userName);
                actualRow.setUpdateTime(new Date());
                actualRow.setNote("动态衡毛皮分解");
                meterWorkRailwayActualMapper.updateByPrimaryKey(actualRow);
//                meterWorkRailwayActualMapper.deleteByPrimaryKey(actualRow.getActualNo());

//                if(modelTemp.getPredictionNo() != null) {
//                    PreRailwayScale scale = preRailwayScaleMapper.selectByPrimaryKey(modelTemp.getPredictionNo());
//                    if(scale != null) {
//                        scale.setValueFlag("1");
//                        scale.setUploadFlag("0");
//                        scale.setUpdateManNo(userId);
//                        scale.setUpdateManName(userName);
//                        scale.setUpdateTime(new Date());
//                        preRailwayScaleMapper.updateByPrimaryKeySelective(scale);
//                    }
//                }

                MeterBaseOperationLog logModel = new MeterBaseOperationLog();
                logModel.setId(PublicMethod.IdCreate(2));
                logModel.setCreateManNo(userId);
                logModel.setCreateManName(userName);
                logModel.setCreateTime(new Date());
                logModel.setOperationPage("C#端-动轨净重数据维护");
                logModel.setOperationFunction("毛皮分解");
                logModel.setOperationId(modelTemp.getActualNo());
                logModel.setOperationPredictionNo(modelTemp.getPredictionNo());
                logModel.setOperationCarnNo(modelTemp.getRailwayNo());
                logModel.setOperationBeforeFix(modelTemp.toString());
                logModel.setOperationAfterFix(actualRow.toString());
                meterBaseOperationLogMapper.insertSelective(logModel);
            }
            rm.setSucceed(true);
            rm.setMessage("毛皮分解成功");
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            rm.setMessage(e.getMessage());
        }
        return rm;
    }

    @Override
    public RESTfulResult Upload(List<MeterWorkRailwayActual> models) {
        RESTfulResult rm = new RESTfulResult();
        rm.setFailed();
        try {
            Assert.isTrue(models.size() >= 1, "数据不能为空");
            List<MeterWorkRailwayActual> res = null;
            int count = 0;
            for(MeterWorkRailwayActual model: models) {
//                MeterWorkRailwayActual sel = new MeterWorkRailwayActual();
                HashMap sel = new HashMap();
                sel.put("actualNo",model.getActualNo());
                sel.put("uploadFlag","2");
                List<MeterWorkRailwayActual> meterWorkRailwayActual = meterWorkRailwayActualMapper.selectByParameter(sel);
                if(meterWorkRailwayActual.size() > 0){
                    res.add(model);
                }else {
                    MeterWorkRailwayActual up = new MeterWorkRailwayActual();
                    up.setValueFlag("2");
                    up.setUploadFlag("1");
                    up.setActualNo(model.getActualNo());
                    int re = meterWorkRailwayActualMapper.updateByPrimaryKeySelective(up);
                    count++;
                }
            }
            if(res.size() > 0){
                rm.setSucceed();
                rm.setCode("200");
                rm.setData(res);
                rm.setMessage("发布成功，部分数据已发布无法发布");
            }
            else {
                rm.setSucceed();
                rm.setData("200");
                rm.setMessage("共有" + count + "条数据发布成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            rm.setMessage(e.getMessage());
        }
        return rm;
    }

    @Override
    public RESTfulResult Unload(List<MeterWorkRailwayActual> models) {
        RESTfulResult rm = new RESTfulResult();
        rm.setFailed();
        try {
            Assert.isTrue(models.size() >= 1, "数据不能为空");
            List<MeterWorkRailwayActual> res = null;
            int count = 0;
            for(MeterWorkRailwayActual model: models) {
//                MeterWorkRailwayActual sel = new MeterWorkRailwayActual();
                HashMap sel = new HashMap();
                sel.put("actualNo",model.getActualNo());
                sel.put("uploadFlag","2");
                List<MeterWorkRailwayActual> meterWorkRailwayActual = meterWorkRailwayActualMapper.selectByParameter(sel);
                if(meterWorkRailwayActual.size() > 0){
                    res.add(model);
                }else {
                    MeterWorkRailwayActual up = new MeterWorkRailwayActual();
                    up.setUploadFlag("1");
                    up.setValueFlag("2");
                    up.setActualNo(model.getActualNo());
                    int re = meterWorkRailwayActualMapper.updateByPrimaryKeySelective(up);
                    count++;
                }
            }
            if(res.size() > 0){
                rm.setSucceed();
                rm.setCode("200");
                rm.setData(res);
                rm.setMessage("发布成功，部分数据已发布无法发布");
            }
            else {
                rm.setSucceed();
                rm.setData("200");
                rm.setMessage("共有" + count + "条数据发布成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            rm.setMessage(e.getMessage());
        }
        return rm;
    }

    @Override
    public List<String> distinctHookRailwayNo(HashMap<String, Object> param) {
        if(param==null){
            param=new HashMap<>();
        }

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

    @Override
    public List<MeterWorkRailwayActual> hookActualByDesc(HashMap<String, Object> parameters) {
        List<MeterWorkRailwayActual> rows = meterWorkRailwayActualMapper.hookActualByDesc(parameters);
        return rows;
    }

    @Override
    public PageList<MeterWorkRailwayActual> hookActualPageList(HashMap parmas, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<MeterWorkRailwayActual> rows = meterWorkRailwayActualMapper.hookActualByDesc(parmas);
        PageList pageInfo = new PageList(rows);
        return pageInfo;
    }

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

        List<String> actualNoList = new ArrayList<>();
        MeterWorkRailwayActual carActual = meterWorkRailwayActualMapper.selectByPrimaryKey(actualNo);
        if(carActual != null) {
            //查询一次数据
            actualNoList.add(0, carActual.getActualFirst1No());
            actualNoList.add(1, carActual.getActualFirst2No());
            List<MeterWorkRailwayActFirst> firstList = meterWorkRailwayActFirstMapper.selectById(actualNoList);
            //查询委托数据
            HashMap<String, Object> obj = new HashMap<>();
            obj.put("railwayNo", carActual.getRailwayNo());
            obj.put("predictionNo", carActual.getPredictionNo());
            //查询特殊委托接口
            HashMap<String, Object> matterObj = new HashMap<>();
            matterObj.put("pBaseCode", "001036");
            List<String> matterList = comBaseInfoMapper.matterNoByBaseCode(matterObj);
            obj.put("list", matterList);
            List<PreRailwayScale> scale = preRailwayScaleMapper.selectByHookScale(obj);

            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 cleanByHookFirstNo(String actFirstNo01, String actFirstNo02, String predictionNo) {
        RESTfulResult rm = new RESTfulResult();
        rm.setFailed();
        try{
            //勾选的两个一次数据为空，报错
            if((actFirstNo01 == null || StringUtils.isEmpty(actFirstNo01)) || (actFirstNo02 == null || StringUtils.isEmpty(actFirstNo02))) {
                rm.setMessage("未选择两个一次记录");
                return rm;
            }
            MeterWorkRailwayActFirst actFirst01 = meterWorkRailwayActFirstMapper.selectByPrimaryKey(actFirstNo01);
            MeterWorkRailwayActFirst actFirst02 = meterWorkRailwayActFirstMapper.selectByPrimaryKey(actFirstNo02);
            String scaleNo = null;
            //从勾选的委托、两个一次数据中赋值委托号
            if(predictionNo != null && StringUtils.isNotEmpty(predictionNo)){
                if((actFirst01.getPredictionNo() != null && StringUtils.isNotEmpty(actFirst01.getPredictionNo())
                        || actFirst02.getPredictionNo() != null && StringUtils.isNotEmpty(actFirst02.getPredictionNo()))){
                    rm.setMessage("两个一次记录已带有委托，不能在勾选委托");
                    return rm;
                }
                scaleNo = predictionNo;
            }else if((actFirst01.getPredictionNo() != null && StringUtils.isNotEmpty(actFirst01.getPredictionNo()))){
                scaleNo = actFirst01.getPredictionNo();
            }else if(actFirst02.getPredictionNo() != null && StringUtils.isNotEmpty(actFirst02.getPredictionNo())){
                scaleNo = actFirst02.getPredictionNo();
            }

            PreRailwayScale scale = preRailwayScaleMapper.selectByPrimaryKey(scaleNo);
            //存储结净记录
            MeterWorkRailwayActual actualRow = new MeterWorkRailwayActual();
            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
                MeterWorkRailwayActFirst tempModel = new MeterWorkRailwayActFirst();
                BeanUtils.copyProperties(actFirst01, tempModel);
                BeanUtils.copyProperties(actFirst02, actFirst01);
                BeanUtils.copyProperties(tempModel, actFirst02);
            }

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

                //更新一次数据
                //更新第一次毛重数据库
                actFirst01.setWeightType("0");
                actFirst01.setValueFlag(DbConstants.NET);
                actFirst01.setUpdateManNo(userId);
                actFirst01.setUpdateManName(userName);
                actFirst01.setUpdateTime(new Date());
                actFirst01.setIsPreSacale("1");
                actFirst01.setPredictionNo(scale.getPredictionNo());
                actFirst01.setPredictionType("1");
                actFirst01.setNote("手动毛皮结净");
                meterWorkRailwayActFirstMapper.updateByPrimaryKeySelective(actFirst01);
                //更新第一次皮重数据库
                actFirst02.setWeightType("1");
                actFirst02.setValueFlag(DbConstants.NET);
                actFirst02.setUpdateManNo(userId);
                actFirst02.setUpdateManName(userName);
                actFirst02.setUpdateTime(new Date());
                actFirst02.setIsPreSacale("1");
                actFirst02.setPredictionNo(scale.getPredictionNo());
                actFirst02.setPredictionType("1");
                actFirst02.setNote("手动毛皮结净");
                meterWorkRailwayActFirstMapper.updateByPrimaryKeySelective(actFirst02);

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

//                actualRow.setActualNo(sdf.format(new Date()) + meterWorkRailwayActualMapper.getNewID(sdf.format(new Date())));
                String no = PublicMethod.IdCreate(3);
                actualRow.setActualNo(no);
                actualRow.setUploadFlag("1");
                actualRow.setValueFlag("1");
                actualRow.setIsPreSacale("1");
                actualRow.setCreateTime(new Date());
                actualRow.setCreateManName(userName);
                actualRow.setNetTime(new Date());
                actualRow.setUpdateManNo(userId);
                actualRow.setUpdateManName(userName);
                actualRow.setNote("手动毛皮结净");
                actualRow.setLcNo(actFirst01.getLcNo());
                actualRow.setNetMode(DbConstants.TYPE);
                actualRow.setPredictionType("1");
                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());
                    actualRow.setLcNo(meterWorkRailwayActFirstMapper.getFirstLcNo(actualRow.getActualFirst1No()));
                }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());
                    actualRow.setLcNo(meterWorkRailwayActFirstMapper.getFirstLcNo(actualRow.getActualFirst2No()));
                }
                meterWorkRailwayActualMapper.insertSelective(actualRow);

                scale.setValueFlag(DbConstants.NET);
                scale.setUpdateTime(new Date());
                scale.setUpdateManNo(userId);
                scale.setUpdateManName(userName);
                scale.setUploadFlag("1");
                scale.setPredictionType("1");
                scale.setMeasureStation(actualRow.getNetSpot3No());
                scale.setMeasureStationName(actualRow.getNetSpot3Name());
                preRailwayScaleMapper.updateByPrimaryKeySelective(scale);
            }else {
                MeterWorkRailwayActual mwca2 = meterWorkRailwayActualMapper.manualAdd(actFirst01.getActualFirstNo(), actFirst02.getActualFirstNo());
                BeanUtils.copyProperties(mwca2, actualRow);

                //标志位为结净
                actFirst01.setWeightType("0");
                actFirst01.setUpdateManNo(userId);
                actFirst01.setUpdateManName(userName);
                actFirst01.setNote("手动毛皮结净");
                actFirst01.setIsPreSacale("0");
                actFirst01.setValueFlag(DbConstants.NET);
                meterWorkRailwayActFirstMapper.updateByPrimaryKey(actFirst01);
                actFirst02.setWeightType("1");
                actFirst02.setUpdateManNo(userId);
                actFirst02.setUpdateManName(userName);
                actFirst02.setNote("手动毛皮结净");
                actFirst02.setIsPreSacale("0");
                actFirst02.setValueFlag(DbConstants.NET);
                meterWorkRailwayActFirstMapper.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()) + meterWorkRailwayActualMapper.getNewID(sdf.format(new Date())));
                String no = PublicMethod.IdCreate(3);
                actualRow.setActualNo(no);
                actualRow.setUploadFlag("1");
                actualRow.setValueFlag("1");
                actualRow.setIsPreSacale("0");
                actualRow.setUpdateManNo(userId);
                actualRow.setUpdateManName(userName);
                actualRow.setNote("手动毛皮结净");
                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());
                    actualRow.setLcNo(meterWorkRailwayActFirstMapper.getFirstLcNo(actualRow.getActualFirst1No()));
                }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());
                    actualRow.setLcNo(meterWorkRailwayActFirstMapper.getFirstLcNo(actualRow.getActualFirst2No()));
                }
                meterWorkRailwayActualMapper.insertSelective(actualRow);
            }
            rm.setSucceed();
            rm.setData(actualRow);
        }catch(Exception e) {
            e.printStackTrace();
            rm.setMessage(e.getMessage());
        }
        return rm;
    }

    @Override
    public int updateCar(MeterWorkRailwayActual model) {
        try {
            if (model.getActualNo() == null || "".equals(model.getActualNo())) {
                throw new MarkerMetException(500, "操作数据主键不能为空！！！");
            }
            if (StringUtils.isNotEmpty(model.getPredictionNo())) {
                throw new MarkerMetException(500, "只有未匹配委托的数据才能修改车号！！！");
            }
            if (model.getNote() == null || "".equals(model.getNote())) {
                throw new MarkerMetException(500, "车号修改原因不能为空");
            }
            if (model.getRailwayNo() == null || model.getRailwayNo().equals("")) {
                throw new MarkerMetException(500, "车号不能为空");
            }
            UserPayload payload = UserPayload.getCurrUser();
            String userId = payload.getUserCode();
            String userName = payload.getUserName();
            model.setUpdateManName(userName);
            model.setUpdateManNo(userId);
            // 更新净重数据
            MeterWorkRailwayActual netData = new MeterWorkRailwayActual();
            netData.setActualNo(model.getActualNo());
            netData.setRailwayNo(model.getRailwayNo());
            netData.setNote(model.getNote());
            netData.setUpdateTime(new Date());
            netData.setUpdateManNo(model.getUpdateManNo());
            netData.setUpdateManName(model.getUpdateManName());
            netData.setUploadFlag("1");
            int num = meterWorkRailwayActualMapper.updateByPrimaryKeySelective(netData);

            // 更新一次计量数据
            MeterWorkRailwayActual queryData = meterWorkRailwayActualMapper.selectByPrimaryKey(netData.getActualNo());
            MeterWorkRailwayActFirst first1 = new MeterWorkRailwayActFirst();
            MeterWorkRailwayActFirst first2 = new MeterWorkRailwayActFirst();
            first1.setActualFirstNo(queryData.getActualFirst1No());
            first1.setRailwayNo(queryData.getRailwayNo());
            first1.setUpdateManNo(model.getUpdateManNo());
            first1.setUpdateManName(model.getUpdateManName());
            first1.setUpdateTime(new Date());
            first1.setNote("净重数据修改车号，同步修改一次计量数据车号");
            meterWorkRailwayActFirstMapper.updateByPrimaryKeySelective(first1);

            first2.setActualFirstNo(queryData.getActualFirst2No());
            first2.setRailwayNo(queryData.getRailwayNo());
            first2.setUpdateManNo(model.getUpdateManNo());
            first2.setUpdateManName(model.getUpdateManName());
            first2.setUpdateTime(new Date());
            first2.setNote("净重数据修改车号，同步修改一次计量数据车号");
            meterWorkRailwayActFirstMapper.updateByPrimaryKeySelective(first2);

            MeterBaseOperationLog logModel = new MeterBaseOperationLog();
            logModel.setId(PublicMethod.IdCreate(2));
            logModel.setCreateManNo(model.getUpdateManNo());
            logModel.setCreateManName(model.getUpdateManName());
            logModel.setCreateTime(new Date());
            logModel.setOperationPage("Web端-轨道衡净重数据维护");
            logModel.setOperationFunction("车号修改");
            logModel.setOperationId(model.getActualNo());
            logModel.setOperationPredictionNo(model.getPredictionNo());
            logModel.setOperationCarnNo(model.getRailwayNo());
            meterBaseOperationLogMapper.insertSelective(logModel);
            return num;
        } catch (MarkerMetException e) {
            throw e;
        }
    }

    @Override
    public PageList<HashMap> dynamicAndStaticCompare(HashMap<String, Object> parameters, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        ComBaseInfo timeModel = comBaseInfoMapper.selectByPrimaryKey("001051001");
        if(timeModel != null) {
            parameters.put("hour", timeModel.getMemo());
        }
        List<HashMap> rows = meterWorkRailwayActualMapper.dynamicAndStaticCompare(parameters);
        PageList pageInfo = new PageList(rows);
        return pageInfo;
    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public RESTfulResult auditRailwayActual(List<MeterWorkRailwayActual> models, String memo) {
        RESTfulResult rm = new RESTfulResult();
        rm.setFailed();
        try{
            UserPayload userPayload = UserPayload.getCurrUser();
            String userId = userPayload.getUserCode();
            String userName = userPayload.getUserName();
            int count = 0;
            if(models.size() >= 1) {
                for(MeterWorkRailwayActual modelTemp: models) {
                    MeterWorkRailwayActual model = meterWorkRailwayActualMapper.selectByPrimaryKey(modelTemp.getActualNo());
                    if(model != null) {
                        model.setCheckManNo(userId);
                        model.setCheckManName(userName);
                        model.setCheckTime(new Date());
                        model.setMemo(memo);
                        meterWorkRailwayActualMapper.updateByPrimaryKeySelective(model);
                        count ++;
                    }
                }
            }
            rm.setSucceed(true);
            rm.setMessage("操作成功,共有" + count + "条数据审核成功！");
            rm.setCode("200");
        }catch (Exception e) {
            e.printStackTrace();
            rm.setMessage("操作异常:>>>" + e.getMessage());
        }
        return rm;
    }
}
