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

import com.steerinfo.baseinfo.meterbaserailwayweight.mapper.MeterBaseRailwayWeightMapper;
import com.steerinfo.baseinfo.meterbaserailwayweight.model.MeterBaseRailwayWeight;
import com.steerinfo.framework.controller.RESTfulResult;
import com.steerinfo.framework.mapper.IBaseMapper;
import com.steerinfo.framework.service.impl.BaseServiceImpl;
import com.steerinfo.framework.service.pagehelper.PageHelper;
import com.steerinfo.framework.service.pagehelper.PageList;
import com.steerinfo.framework.user.UserPayload;
import com.steerinfo.meterwork.constants.DbConstants;
import com.steerinfo.meterwork.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.pretrack.prerailwayscale.mapper.PreRailwayScaleMapper;
import com.steerinfo.pretrack.prerailwayscale.model.PreRailwayScale;
import com.steerinfo.pretrack.prerailwayscale.service.IPreRailwayScaleService;
import com.steerinfo.pretrack.pretrackscale.model.PreTrackScale;
import com.steerinfo.util.CommonPage;
import com.steerinfo.util.FieldsCollector;
import com.steerinfo.util.StringUtils;
import io.micrometer.core.instrument.Meter;
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 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 MeterBaseRailwayWeightMapper meterBaseRailwayWeightMapper;

    @Resource
    private PreRailwayScaleMapper preRailwayScaleMapper;

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

    @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, "只有已匹配委托且已发布的数据才能进行撤销发布操作");
        }

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

    @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 = new UserPayload();
        String userName = userPayload.getUserName();
        String userId = userPayload.getId();
        model.setValueFlag("2");
        model.setUploadFlag("1");
        model.setUpdateTime(new Date());
        model.setUpdateManName(userName);
        model.setUpdateManNo(userId);
        try {
            meterWorkRailwayActualMapper.updateByPrimaryKeySelective(model);
        } catch (Exception e) {
            throw e;
        }
        return ++i;
    }

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

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

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

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

            String preNo = "";
            Map<String, Object> repair = new HashMap<>();
            if (predictionNo == null){
                if (mwcaf1.getPredictionNo() == "" && mwcaf2.getPredictionNo() != ""){
                    preNo = mwcaf2.getPredictionNo();
                    repair.put("predictionNo",preNo);
                    repair.put("actualFirstNo",mwcaf1.getActualFirstNo());
                    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("system");
                scale.setUploadFlag("1");
                scale.setUpdateManName("二次计量洁净更新");
                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);
            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, "选中两条一次计量数据中列车车次不一致！！！");
            }
            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("system");
                prs.setUpdateManName("火车二次计量洁净操作");
                preRailwayScaleMapper.updateByPrimaryKeySelective(prs);
            }
            return actualRow;
        } catch (MarkerMetException e) {
            throw e;
        }
    }

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

        MeterWorkRailwayActFirst actFirst01 = meterWorkRailwayActFirstMapper.selectByPrimaryKey(actFirstNo01);
        MeterWorkRailwayActFirst actFirst02 = meterWorkRailwayActFirstMapper.selectByPrimaryKey(actFirstNo02);

        if(actFirst01 == null || actFirst02 == null){
            rm.setFailed();
            rm.setMessage("一次计量数据编号不存在于轨道衡一次计量表");
            return rm;
        }else{
            if(!actFirst01.getRailwayNo().equals(actFirst02.getRailwayNo())){
                rm.setFailed();
                rm.setMessage("请选择同一车号的一次计量数据进行结净");
                return rm;
            }else if(!actFirst01.getValueFlag().equals("1") || !actFirst02.getValueFlag().equals("1")){
                rm.setFailed();
                rm.setMessage("请选择有效的一次计量数据进行结净");
                return rm;
            }else{
                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);
                }
                //洁净操作
                MeterWorkRailwayActual actualRow = new MeterWorkRailwayActual();
                MeterWorkRailwayActual mwca2 = meterWorkRailwayActualMapper.manualAdd(actFirstNo01, actFirstNo02);
                BeanUtils.copyProperties(mwca2, actualRow);
                //标志位为洁净
                actFirst01.setValueFlag(DbConstants.NET);
                actFirst01.setNote(Notes);
                meterWorkRailwayActFirstMapper.updateByPrimaryKey(actFirst01);
                actFirst02.setNote(Notes);
                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.setNetMode(DbConstants.TYPE);
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
                String no = meterWorkRailwayActualMapper.getNewID(sdf.format(new Date()));
                actualRow.setActualNo(sdf.format(new Date()) + no);
                actualRow.setNetWeight(actFirst01.getMeterWeight().subtract(actFirst02.getMeterWeight()));
                actualRow.setUploadFlag("1");
                actualRow.setNote(Notes);
                actualRow.setLcNo(actFirst01.getLcNo());

                meterWorkRailwayActualMapper.insertSelective(actualRow);
                rm.setSucceed();
                rm.setData(actualRow);
                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, "只有未匹配的净重数据才能进行委托匹配操作");
        }
        PreRailwayScale prerow = preRailwayScaleMapper.selectByPrimaryKey(predictionNo);
        if (prerow == null) {
            throw new MarkerMetException(500, "不存在对应的委托数据");
        } else if (!prerow.getValueFlag().equals("1")) {
            throw new MarkerMetException(500, "只有未使用的委托才能进行匹配委托操作");
        }
        if (!queryrow.getRailwayNo().equals(prerow.getRailwayNo())) {
            throw new MarkerMetException(500, "洁净数据中车号和预报中车号不一致，不允许进行匹配委托操作");
        }
        UserPayload payload = UserPayload.getCurrUser();
        String userId = payload.getId();
        String userName = payload.getUserName();

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

        // 皮重
        MeterWorkRailwayActFirst tarerow = meterWorkRailwayActFirstMapper.selectAndMatch(queryrow.getActualFirst2No(), predictionNo);
        tarerow.setUpdateTime(new Date());
        tarerow.setUpdateManName(userName + ": 洁净数据匹配委托操作");
        tarerow.setUpdateManNo(userId);
        meterWorkRailwayActFirstMapper.updateByPrimaryKey(tarerow);

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

        MeterWorkRailwayActual mwca = meterWorkRailwayActualMapper.mathPredcition(actualNo, predictionNo);
        mwca.setValueFlag("1");
        mwca.setIsPreSacale("1");
        mwca.setPredictionType("1");
        mwca.setUploadFlag("1");
//        mwca.setNote(note); 添加修改原因记录
        meterWorkRailwayActualMapper.updateByPrimaryKey(mwca);
        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.getId();
        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);
        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);

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

        // 新增净重数据
        String idNo2 = sdf.format(new Date()) + meterWorkRailwayActFirstMapper.getNewID(sdf.format(time));
        model.setActualNo(idNo2);
        model.setTareManName(userName);
        model.setTareManNo(userId);
        model.setTareTime(time);
        model.setNetMode("2");
        model.setTareMode("3");
        model.setNetTime(time);
        model.setNetManName(userName);
        model.setNetManNo(userId);
        model.setDataSource(queryrow.getDataSource());
        model.setValueFlag("1");
        model.setUploadFlag("1");
//        model.setNote(); // 添加修改原因记录
        int num = meterWorkRailwayActualMapper.insertSelective(model);
        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, "不存在对应的洁净数据");
        }
        UserPayload payload = UserPayload.getCurrUser();
        String userId = payload.getId();
        String userName = payload.getUserName();

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

        // 皮重
        MeterWorkRailwayActFirst tarerow = meterWorkRailwayActFirstMapper.selectAndRemove(model.getActualFirst2No());
//        tarerow.setValueFlag("3");
        tarerow.setUpdateTime(new Date());
        tarerow.setUpdateManName(userName + ": 洁净数据解除委托操作");
        tarerow.setUpdateManNo(userId);
        meterWorkRailwayActFirstMapper.updateByPrimaryKey(tarerow);

        // 处理预报
        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("system");
            scale.setUpdateManName("计量洁净数据解除委托操作");
            preRailwayScaleMapper.updateByPrimaryKeySelective(scale);
        }
        MeterWorkRailwayActual mwca = meterWorkRailwayActualMapper.cleanPredcition(model.getActualNo());

        mwca.setUpdateManNo(userId);
        mwca.setUpdateManName(userName);
        mwca.setUpdateTime(new Date());
        mwca.setValueFlag("3");
        mwca.setUploadFlag("1");
        meterWorkRailwayActualMapper.updateByPrimaryKey(mwca);
        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) {
                //毛重
                MeterWorkRailwayActFirst mwcaf1 = meterWorkRailwayActFirstMapper.selectByPrimaryKey(model.getActualFirst1No());
                if (mwcaf1 == null) {
                    throw new MarkerMetException(500, "未查询到相应的毛重数据！！");
                }
                // 清空委托信息
                MeterWorkRailwayActFirst grossrow = meterWorkRailwayActFirstMapper.selectAndRemove(model.getActualFirst1No());
                //grossrow.setValueFlag("3");
                grossrow.setIsPreSacale("0");
                grossrow.setUpdateManNo("system");
                grossrow.setUpdateManName("静态衡解除操作");
                grossrow.setUpdateTime(new Date());
                grossrow.setLcNo(model.getLcNo());
                grossrow.setValueFlag("1");
                meterWorkRailwayActFirstMapper.updateByPrimaryKey(grossrow);
                //皮重
                MeterWorkRailwayActFirst mwcaf2 = meterWorkRailwayActFirstMapper.selectByPrimaryKey(model.getActualFirst2No());
                MeterBaseRailwayWeight mbrw = meterBaseRailwayWeightMapper.selectByPrimaryKey(model.getActualFirst2No());
                if (mwcaf2 == null && mbrw == 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 (StringUtils.isNotEmpty(model.getPredictionNo())) {
                    PreRailwayScale scale = new PreRailwayScale();
                    scale.setPredictionNo(model.getPredictionNo());
                    scale.setValueFlag("1"); //使用中
                    scale.setUploadFlag("1");
                    scale.setUpdateManNo("system");
                    scale.setUpdateManName("静态衡解除操作");
                    scale.setUpdateTime(new Date());
                    preRailwayScaleMapper.updateByPrimaryKeySelective(scale);
                }
                meterWorkRailwayActualMapper.deleteByPrimaryKey(model.getActualNo());
                //meterWorkRailwayActualMapper.updateByPrimaryKeySelective(model);
                num++;
            }

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

    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<String> distinctRailwayNo(String railwayTypeNo, String lcNo, String railwayNo, String startTime, String endTime,String baseSpotName,String matterName,String predictionNo, String valueFlag) {
        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(obj).stream().map(MeterWorkRailwayActual::getRailwayNo).collect(Collectors.toList());
        return list;
    }

    @Override
    public List<String> distinctLcNo(String railwayTypeNo, String startTime, String endTime) {
        HashMap<String, Object> obj = new HashMap<>();
        obj.put("railwayTypeNo", railwayTypeNo);
        obj.put("startTime", startTime);
        obj.put("endTime", endTime);
        List<MeterWorkRailwayActual> templist = meterWorkRailwayActualMapper.distinctLcNo(obj);
        List<String> list = null;
        if(templist.size() != 0)
        {
            list = templist.stream().map(MeterWorkRailwayActual::getLcNo).collect(Collectors.toList());
        }
        return list;
    }

    @Override
    public RESTfulResult distinctLcNoAndRailwayNo(String railwayTypeNo, String startTime, String endTime, String railwayNo, String baseSpotName, String matterName, String predictionNo, String valueFlag) {
        RESTfulResult rm = new RESTfulResult();
        rm.setFailed();
        try{
            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(obj);
            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());
            }
            param.put("LcList", list);
            param.put("railwayNoList", railwayNum);
            rm.setSucceed();
            rm.setCode("200");
            rm.setMessage("操作成功！！");
            rm.setData(param);
        }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);
            mwca.setNetWeight(mwraf1.getMeterWeight().subtract(mbrw.getRailwayWeight()));
            mwca.setUploadFlag("1");
            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.getId();
        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.getId();
        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.getId();
            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);
                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);
                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);
                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");
                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("计量洁净数据手动录入");
                preRailwayScaleMapper.updateByPrimaryKey(preRailwayScale);
                //添加毛重一次计量数据
                String actualFirstNo = sdf.format(new Date()) + meterWorkRailwayActFirstMapper.getNewID(afl);
                BeanUtils.copyProperties(preRailwayScale, mwraf1);
                mwraf1.setActualFirstNo(actualFirstNo);
                mwraf1.setIsPreSacale("1");
                mwraf1.setValueFlag("2");
                mwraf1.setCreateTime(new Date());
                mwraf1.setCreateManNo(userId);
                mwraf1.setCreateManName(userName);
                mwraf1.setRailwayNo(model.getRailwayNo());
                mwraf1.setMeterWeight(model.getGrossWeight());
                mwraf1.setDataSource("4");
                mwraf1.setMeterMode("3");
                meterWorkRailwayActFirstMapper.insertSelective(mwraf1);
                //添加皮重一次计量数据
                String dataNo = sdf.format(new Date()) + meterWorkRailwayActFirstMapper.getNewID(afl);
                BeanUtils.copyProperties(preRailwayScale, mwraf2, predictionNo);
                mwraf2.setActualFirstNo(dataNo);
                mwraf2.setIsPreSacale("1");
                mwraf2.setValueFlag("2");
                mwraf2.setCreateTime(new Date());
                mwraf2.setCreateManNo(userId);
                mwraf2.setCreateManName(userName);
                mwraf2.setRailwayNo(model.getRailwayNo());
                mwraf2.setMeterWeight(model.getTareWeight());
                mwraf2.setDataSource("4");
                mwraf2.setMeterMode("3");
                meterWorkRailwayActFirstMapper.insertSelective(mwraf2);
                //添加净重重一次计量数据
                String ActualNo = sdf.format(new Date()) + meterWorkRailwayActualMapper.getNewID(afl);
                BeanUtils.copyProperties(preRailwayScale, model);
                model.setActualNo(ActualNo);
                model.setIsPreSacale("1");
                model.setValueFlag("2");
                model.setActualFirst1No(actualFirstNo);
                model.setGrossManNo(userId);
                model.setGrossManName(userName);
                model.setGrossTime(mwraf1.getCreateTime());
                model.setGrossMode("3");
                model.setActualFirst2No(dataNo);
                model.setTareManNo(userId);
                model.setTareManName(userName);
                model.setTareTime(mwraf2.getCreateTime());
                model.setTareMode("3");
                model.setNetManNo(userId);
                model.setNetManName(userName);
                model.setNetTime(new Date());
                model.setNetMode("3");
                model.setDataSource("4");
                model.setUploadFlag("1");
                meterWorkRailwayActualMapper.insertSelective(model);
                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 = preRailwayScaleMapper.selectByPrimaryKey(predictionNo);
            if(scale.getValueFlag().equals("2")) {
                rm.setMessage("委托已匹配，请确认！！");
                return rm;
            }

            /*UserPayload payload = UserPayload.getCurrUser();
            String userId = payload.getId();
            String userName = payload.getUserName();*/

            //毛重
            String actualFirstNo = sdf.format(new Date()) + meterWorkRailwayActFirstMapper.getNewID(afl);
            mwcaf1.setActualFirstNo(actualFirstNo);
            mwcaf1.setRailwayNo(model.getRailwayNo());
            mwcaf1.setMeterWeight(model.getGrossWeight());
            mwcaf1.setRailwayTypeNo(model.getRailwayTypeNo());
            mwcaf1.setRailwayTypeName(model.getRailwayTypeName());
            mwcaf1.setWeightType("0");
            mwcaf1.setCreateManNo(model.getGrossManNo());
            mwcaf1.setCreateManName(model.getGrossManName());
            mwcaf1.setCreateTime(model.getGrossTime());
            mwcaf1.setBaseSpotNo(model.getBaseSpot1No());
            mwcaf1.setBaseSpotName(model.getBaseSpot1Name());
            mwcaf1.setValueFlag("2");
            mwcaf1.setCheckFlag("0");
            mwcaf1.setDataSource("4");
            mwcaf1.setMeterMode("3");
            mwcaf1.setIsPreSacale("0");
            meterWorkRailwayActFirstMapper.insertSelective(mwcaf1);
            //皮重
            String actualSecondNo = sdf.format(new Date()) + meterWorkRailwayActFirstMapper.getNewID(afl);
            mwcaf2.setActualFirstNo(actualSecondNo);
            mwcaf2.setRailwayNo(model.getRailwayNo());
            mwcaf2.setMeterWeight(model.getTareWeight());
            mwcaf2.setWeightType("1");
            mwcaf2.setRailwayTypeNo(model.getRailwayTypeNo());
            mwcaf2.setRailwayTypeName(model.getRailwayTypeName());
            mwcaf2.setCreateManNo(model.getGrossManNo());
            mwcaf2.setCreateManName(model.getGrossManName());
            mwcaf2.setCreateTime(model.getTareTime());
            mwcaf2.setBaseSpotNo(model.getBaseSpot2No());
            mwcaf2.setBaseSpotName(model.getBaseSpot2Name());
            mwcaf2.setValueFlag("2");
            mwcaf2.setCheckFlag("0");
            mwcaf2.setDataSource("4");
            mwcaf2.setMeterMode("3");
            mwcaf2.setIsPreSacale("0");
            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");
                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);
            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()));
            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();
            List<MeterWorkRailwayActFirst> firstList = meterWorkRailwayActFirstMapper.selectById(actualNoList);
            PreRailwayScale scale = preRailwayScaleMapper.selectByPrimaryKey(entrust);
            HashMap<String, Object> map = new HashMap<>();
            map.put("firstList", firstList);
            map.put("scale", scale);
            rm.setData(map);
            rm.setSucceed();
            rm.setCode("200");
            rm.setMessage("操作成功！！");
            return rm;
        }
        return null;
    }

    @Override
    public RESTfulResult specialRemove(HashMap params) {
        RESTfulResult rm = new RESTfulResult();
        rm.setFailed();
        rm.setData(null);
        rm.setCode("500");
        String type = params.get("type") == null ? "" : params.get("type").toString();
        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.size() != 2 && models.get(0).getPredictionCombination().equals(models.get(1).getPredictionCombination())){
            rm.setMessage("必须选择两个预报组合号一致的洁净数据!!!");
            return rm;
        }

        switch(type){
            case "5": {
                //类型为双委托类型
                for (MeterWorkRailwayActual model: models) {
                    if(!model.getPredictionType().equals("5")) {
                        rm.setMessage("选中的计量数据当中有一条或多条不是双委托洁净数据，请确认！！");
                        return rm;
                    }
                }
                for (MeterWorkRailwayActual model: models) {
                    //循环每一个洁净记录
                    //判断委托是否为双委托组合的第二个委托，是：删除一次数据和洁净记录、否：修改一次记录、
                    String combination = model.getPredictionCombination();
                    String[] param = combination.split(",");

                    if(model.getPredictionNo().equals(param[1])){
                        // 改委托
                        if (StringUtils.isNotEmpty(model.getPredictionNo())) {
                            PreRailwayScale scale = preRailwayScaleMapper.selectByPrimaryKey(model.getPredictionNo());
                            scale.setValueFlag("1");
                            scale.setUploadFlag("1");
                            scale.setUpdateTime(new Date());
                            scale.setUpdateManNo("system");
                            scale.setUpdateManName("双委托解除操作");
                            preRailwayScaleMapper.updateByPrimaryKeySelective(scale);
                        }
                        // 删一次
                        MeterWorkRailwayActFirst firstGross = meterWorkRailwayActFirstMapper.selectByPrimaryKey(model.getActualFirst1No());
                        MeterWorkRailwayActFirst firstTare = meterWorkRailwayActFirstMapper.selectByPrimaryKey(model.getActualFirst2No());
                        if(firstGross.getPredictionNo().equals(model.getPredictionNo())){
                            meterWorkRailwayActFirstMapper.deleteByPrimaryKey(model.getActualFirst1No());
                        }
                        if(firstTare.getPredictionNo().equals(model.getPredictionNo())){
                            meterWorkRailwayActFirstMapper.deleteByPrimaryKey(model.getActualFirst2No());
                        }

                        // 删洁净
                        meterWorkRailwayActualMapper.deleteByPrimaryKey(model.getActualNo());
                    }
                    else {
                        // 清空毛重数据中的委托信息
                        MeterWorkRailwayActFirst mwcafg = meterWorkRailwayActFirstMapper.selectAndRemove(model.getActualFirst1No());
                        if (mwcafg == null) {
                            rm.setMessage("未查询到相应的毛重数据！！");
                            return rm;
                        }
                        mwcafg.setValueFlag(DbConstants.VALID);
                        mwcafg.setNote(model.getNote());
                        mwcafg.setUpdateManName("system");
                        mwcafg.setUpdateManName("双委托解除更新");
                        mwcafg.setUpdateTime(new Date());
                        mwcafg.setIsPreSacale("0");
                        meterWorkRailwayActFirstMapper.updateByPrimaryKey(mwcafg);
                        //皮重
                        MeterWorkRailwayActFirst mwcaft = meterWorkRailwayActFirstMapper.selectAndRemove(model.getActualFirst2No());
                        if (mwcaft == null) {
                            rm.setMessage("未查询到相应的皮重数据！！");
                            return rm;
                        }
                        mwcaft.setValueFlag(DbConstants.VALID);
                        mwcaft.setUpdateManName("system");
                        mwcaft.setUpdateManName("双委托解除更新");
                        mwcaft.setNote(model.getNote());
                        mwcaft.setUpdateTime(new Date());
                        mwcaft.setIsPreSacale("0");
                        meterWorkRailwayActFirstMapper.updateByPrimaryKey(mwcaft);
                        //修改预报
                        if (StringUtils.isNotEmpty(model.getPredictionNo())) {
                            PreRailwayScale scale = preRailwayScaleMapper.selectByPrimaryKey(model.getPredictionNo());
                            scale.setValueFlag("1");
                            scale.setUploadFlag("1");
                            scale.setUpdateTime(new Date());
                            scale.setUpdateManNo("system");
                            scale.setUpdateManName("双委托解除操作");
                            preRailwayScaleMapper.updateByPrimaryKeySelective(scale);
                        }
                        meterWorkRailwayActualMapper.deleteByPrimaryKey(model.getActualNo());
                    }
                }
                rm.setSucceed();
                rm.setMessage("操作成功！！");
                rm.setCode("200");
            }
            break;
            case "6": {         //类型为混卸类型
                for (MeterWorkRailwayActual model: models) {
                    if(!model.getPredictionType().equals("6")) {
                        rm.setMessage("选中的计量数据当中有一条或多条不是混卸委托洁净数据，请确认！！");
                    }
                }
                for (MeterWorkRailwayActual model: models) {
                    //循环每一个洁净记录
                    //判断委托是否为双委托组合的第二个委托，是：删除一次数据和洁净记录、否：修改一次记录、
                    String combination = model.getPredictionCombination();
                    String[] param = combination.split(",");

                    if(model.getPredictionNo().equals(param[0])){

                        // 改委托
                        if (StringUtils.isNotEmpty(model.getPredictionNo())) {
                            PreRailwayScale scale = preRailwayScaleMapper.selectByPrimaryKey(model.getPredictionNo());
                            scale.setValueFlag("1");
                            scale.setUploadFlag("1");
                            scale.setUpdateTime(new Date());
                            scale.setUpdateManNo("system");
                            scale.setUpdateManName("混卸解除操作");
                            preRailwayScaleMapper.updateByPrimaryKeySelective(scale);
                        }
                        // 删一次毛重、清空一次皮重委托信息
                        MeterWorkRailwayActFirst firstTare = meterWorkRailwayActFirstMapper.selectByPrimaryKey(model.getActualFirst2No());
                        MeterWorkRailwayActFirst firstGross = meterWorkRailwayActFirstMapper.selectAndRemove(model.getActualFirst1No());
                        if(firstTare.getPredictionNo().equals(model.getPredictionNo())){
                            meterWorkRailwayActFirstMapper.deleteByPrimaryKey(model.getActualFirst2No());
                        }
                        if(firstGross != null){
                            firstGross.setValueFlag(DbConstants.VALID);
                            firstGross.setUpdateManName("system");
                            firstGross.setUpdateManName("混卸解除更新");
                            firstGross.setNote(model.getNote());
                            firstGross.setUpdateTime(new Date());
                            firstGross.setIsPreSacale("0");
                            meterWorkRailwayActFirstMapper.updateByPrimaryKey(firstGross);
                        }
                        // 删洁净
                        meterWorkRailwayActualMapper.deleteByPrimaryKey(model.getActualNo());
                    }
                    else {
                        // 清空毛重数据中的委托信息
                        MeterWorkRailwayActFirst mwcafg = meterWorkRailwayActFirstMapper.selectAndRemove(model.getActualFirst1No());
                        if (mwcafg == null) {
                            rm.setMessage("未查询到相应的毛重数据！！");
                            return rm;
                        }
                        mwcafg.setValueFlag(DbConstants.VALID);
                        mwcafg.setNote(model.getNote());
                        mwcafg.setUpdateManName("system");
                        mwcafg.setUpdateManName("混卸解除更新");
                        mwcafg.setUpdateTime(new Date());
                        mwcafg.setIsPreSacale("0");
                        meterWorkRailwayActFirstMapper.updateByPrimaryKey(mwcafg);
                        //皮重
                        MeterWorkRailwayActFirst mwcaft = meterWorkRailwayActFirstMapper.selectAndRemove(model.getActualFirst2No());
                        if (mwcaft == null) {
                            rm.setMessage("未查询到相应的皮重数据！！");
                            return rm;
                        }
                        mwcaft.setValueFlag(DbConstants.VALID);
                        mwcaft.setUpdateManName("system");
                        mwcaft.setUpdateManName("混卸解除更新");
                        mwcaft.setNote(model.getNote());
                        mwcaft.setUpdateTime(new Date());
                        mwcaft.setIsPreSacale("0");
                        meterWorkRailwayActFirstMapper.updateByPrimaryKey(mwcaft);
                        //修改预报
                        if (StringUtils.isNotEmpty(model.getPredictionNo())) {
                            PreRailwayScale scale = preRailwayScaleMapper.selectByPrimaryKey(model.getPredictionNo());
                            scale.setValueFlag("1");
                            scale.setUploadFlag("1");
                            scale.setUpdateTime(new Date());
                            scale.setUpdateManNo("system");
                            scale.setUpdateManName("混卸解除操作");
                            preRailwayScaleMapper.updateByPrimaryKeySelective(scale);
                        }
                        meterWorkRailwayActualMapper.deleteByPrimaryKey(model.getActualNo());
                    }
                }
                rm.setSucceed();
                rm.setMessage("操作成功！！");
                rm.setCode("200");
            }
            break;
            case "7": {         //类型为混装类型
                for (MeterWorkRailwayActual model: models) {
                    if(!model.getPredictionType().equals("7")) {
                        rm.setMessage("选中的计量数据当中有一条或多条不是混装委托洁净数据，请确认！！");
                    }
                }
                for (MeterWorkRailwayActual model: models) {
                    //循环每一个洁净记录
                    //判断委托是否为双委托组合的第二个委托，是：删除一次数据和洁净记录、否：修改一次记录、
                    String combination = model.getPredictionCombination();
                    String[] param = combination.split(",");

                    if(model.getPredictionNo().equals(param[0])){

                        // 改委托
                        if (StringUtils.isNotEmpty(model.getPredictionNo())) {
                            PreRailwayScale scale = preRailwayScaleMapper.selectByPrimaryKey(model.getPredictionNo());
                            scale.setValueFlag("1");
                            scale.setUploadFlag("1");
                            scale.setUpdateTime(new Date());
                            scale.setUpdateManNo("system");
                            scale.setUpdateManName("混装解除操作");
                            preRailwayScaleMapper.updateByPrimaryKeySelective(scale);
                        }
                        // 删一次毛重、清空一次皮重委托信息
                        MeterWorkRailwayActFirst firstGross = meterWorkRailwayActFirstMapper.selectByPrimaryKey(model.getActualFirst1No());
                        MeterWorkRailwayActFirst firstTare = meterWorkRailwayActFirstMapper.selectAndRemove(model.getActualFirst2No());
                        if(firstGross.getPredictionNo().equals(model.getPredictionNo())){
                            meterWorkRailwayActFirstMapper.deleteByPrimaryKey(model.getActualFirst1No());
                        }
                        if(firstTare != null){
                            firstTare.setValueFlag(DbConstants.VALID);
                            firstTare.setUpdateManName("system");
                            firstTare.setUpdateManName("混装解除更新");
                            firstTare.setNote(model.getNote());
                            firstTare.setUpdateTime(new Date());
                            firstTare.setIsPreSacale("0");
                            meterWorkRailwayActFirstMapper.updateByPrimaryKey(firstTare);
                        }
                        // 删洁净
                        meterWorkRailwayActualMapper.deleteByPrimaryKey(model.getActualNo());
                    }
                    else {
                        // 清空毛重数据中的委托信息
                        MeterWorkRailwayActFirst mwcafg = meterWorkRailwayActFirstMapper.selectAndRemove(model.getActualFirst1No());
                        if (mwcafg == null) {
                            rm.setMessage("未查询到相应的毛重数据！！");
                            return rm;
                        }
                        mwcafg.setValueFlag(DbConstants.VALID);
                        mwcafg.setNote(model.getNote());
                        mwcafg.setUpdateManName("system");
                        mwcafg.setUpdateManName("混装解除更新");
                        mwcafg.setUpdateTime(new Date());
                        mwcafg.setIsPreSacale("0");
                        meterWorkRailwayActFirstMapper.updateByPrimaryKey(mwcafg);
                        //皮重
                        MeterWorkRailwayActFirst mwcaft = meterWorkRailwayActFirstMapper.selectAndRemove(model.getActualFirst2No());
                        if (mwcaft == null) {
                            rm.setMessage("未查询到相应的皮重数据！！");
                            return rm;
                        }
                        mwcaft.setValueFlag(DbConstants.VALID);
                        mwcaft.setUpdateManName("system");
                        mwcaft.setUpdateManName("混装解除更新");
                        mwcaft.setNote(model.getNote());
                        mwcaft.setUpdateTime(new Date());
                        mwcaft.setIsPreSacale("0");
                        meterWorkRailwayActFirstMapper.updateByPrimaryKey(mwcaft);
                        //修改预报
                        if (StringUtils.isNotEmpty(model.getPredictionNo())) {
                            PreRailwayScale scale = preRailwayScaleMapper.selectByPrimaryKey(model.getPredictionNo());
                            scale.setValueFlag("1");
                            scale.setUploadFlag("1");
                            scale.setUpdateTime(new Date());
                            scale.setUpdateManNo("system");
                            scale.setUpdateManName("混装解除操作");
                            preRailwayScaleMapper.updateByPrimaryKeySelective(scale);
                        }
                        meterWorkRailwayActualMapper.deleteByPrimaryKey(model.getActualNo());
                    }
                }
                rm.setSucceed();
                rm.setMessage("操作成功！！");
                rm.setCode("200");
            }
            break;
        }
        return rm;
    }

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

    @Override
    public RESTfulResult batchUpdateLcNo(List<MeterWorkRailwayActual> models) {
        RESTfulResult rm = new RESTfulResult();
        rm.setFailed();
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
            String lcNo = sdf.format(new Date());
            int count = 0;
            for(MeterWorkRailwayActual model: models) {
                model.setLcNo(lcNo);
                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;
    }
}
