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

import com.steerinfo.baseinfo.meterbasevideoinfo.mapper.MeterBaseVideoinfoMapper;
import com.steerinfo.baseinfo.meterbasevideoinfo.model.MeterBaseVideoinfo;
import com.steerinfo.framework.controller.RESTfulResult;
import com.steerinfo.framework.mapper.IBaseMapper;
import com.steerinfo.framework.service.impl.BaseServiceImpl;
import com.steerinfo.framework.service.pagehelper.PageHelper;
import com.steerinfo.framework.service.pagehelper.PageList;
import com.steerinfo.framework.user.UserPayload;
import com.steerinfo.framework.utils.collection.ListUtils;
import com.steerinfo.meterwork.constants.DbConstants;
import com.steerinfo.meterwork.except.MarkerMetException;
import com.steerinfo.meterwork.meterworkhookactfirst.mapper.MeterWorkHookActFirstMapper;
import com.steerinfo.meterwork.meterworkhookactfirst.model.MeterWorkHookActFirst;
import com.steerinfo.meterwork.meterworkhookactfirst.service.IMeterWorkHookActFirstService;
import com.steerinfo.meterwork.meterworkhookactual.mapper.MeterWorkHookActualMapper;
import com.steerinfo.meterwork.meterworkhookactual.model.MeterWorkHookActual;
import com.steerinfo.meterwork.meterworkimage.mapper.MeterWorkImageMapper;
import com.steerinfo.meterwork.meterworkimage.model.MeterWorkImage;
import com.steerinfo.meterwork.meterworkrailwayactfirst.model.MeterWorkRailwayActFirst;
import com.steerinfo.meterwork.meterworkrailwayactual.model.MeterWorkRailwayActual;
import com.steerinfo.meterwork.meterworkrailwayscheduledhelp.model.MeterWorkRailwayScheduledHelp;
import com.steerinfo.meterwork.meterworkrailwayscheduledhelp.service.impl.MeterWorkRailwayScheduledHelpServiceImpl;
import com.steerinfo.meterwork.meterworkscheduledhelp.model.MeterWorkScheduledHelp;
import com.steerinfo.meterwork.meterworkscheduledhelp.service.impl.MeterWorkScheduledHelpServiceImpl;
import com.steerinfo.pretrack.prehookscale.mapper.PreHookScaleMapper;
import com.steerinfo.pretrack.prehookscale.model.PreHookScale;
import com.steerinfo.pretrack.prerailwayscale.model.PreRailwayScale;
import com.steerinfo.util.FieldsCollector;
import com.steerinfo.util.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * MeterWorkHookActFirst服务实现：
 * @author generator
 * @version 1.0-SNAPSHORT 2022-01-20 03:30
 * 类描述
 * 修订历史：
 * 日期：2022-01-20
 * 作者：generator
 * 参考：
 * 描述：MeterWorkHookActFirst服务实现
 * @see null
 * @Copyright 湖南视拓信息技术股份有限公司. All rights reserved.
 */
@Service(value = "meterWorkHookActFirstService")
public class MeterWorkHookActFirstServiceImpl extends BaseServiceImpl<MeterWorkHookActFirst, String> implements IMeterWorkHookActFirstService {

    @Resource
    private MeterWorkHookActFirstMapper meterWorkHookActFirstMapper;

    @Resource
    private PreHookScaleMapper preHookScaleMapper;

    @Resource
    private MeterWorkImageMapper meterWorkImageMapper;

    @Resource
    private MeterWorkRailwayScheduledHelpServiceImpl meterWorkRailwayScheduledHelpService;

    @Resource
    private MeterBaseVideoinfoMapper meterBaseVideoinfoMapper;

    @Resource
    private MeterWorkHookActualMapper meterWorkHookActualMapper;

    @Override
    protected IBaseMapper<MeterWorkHookActFirst, String> getMapper() {
        return meterWorkHookActFirstMapper;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int checkandadd(MeterWorkHookActFirst model) {
        try {
            check(model);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            String no = meterWorkHookActFirstMapper.getNewID(sdf.format(new Date()));
            model.setActualFirstNo(sdf.format(new Date()) + no);
            model.setCreateTime(new Date());
            int num = meterWorkHookActFirstMapper.insertSelective(model);
            return num;
        } catch (MarkerMetException e) {
            throw e;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int checkandupdate(MeterWorkHookActFirst model) {
        try {
            check(model);
            if (model.getValueFlag().equals(DbConstants.NET)) {
                throw new MarkerMetException(500, "已经结净的数据无法修改！！");
            }
            int num = meterWorkHookActFirstMapper.updateByPrimaryKeySelective(model);

            PreHookScale scale = firstToScale(model);
            if (scale != null && scale.getPredictionNo() != null) {
                scale.setUpdateTime(new Date());
                scale.setUpdateManName(model.getUpdateManName());
                scale.setUpdateManNo(model.getUpdateManNo());
                preHookScaleMapper.updateByPrimaryKeySelective(scale);
            }

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

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

    private void check(MeterWorkHookActFirst model) throws MarkerMetException {
        if ("001019005".equals(model.getRailwayTypeNo())) {
            if (model.getRailwayNo() == null || model.getRailwayNo().equals("")) {
                throw new MarkerMetException(500, "火车车号不能为空");
            }
        }
        if (model.getBaseSpotNo() == null || model.getBaseSpotNo().equals("")) {
            throw new MarkerMetException(500, "计量点编号不能为空");
        }
        if (model.getBaseSpotName() == null || model.getBaseSpotName().equals("")) {
            throw new MarkerMetException(500, "计量点名称不能为空");
        }
        UserPayload payload = UserPayload.getCurrUser();
        String userId = payload.getUserCode();
        String userName = payload.getUserName();
        if (StringUtils.isEmpty(model.getActualFirstNo())) {
            model.setCreateManNo(userId);
            model.setCreateManName(userName);
            model.setCreateTime(new Date());
            model.setValueFlag(DbConstants.VALID);
            model.setCheckFlag(DbConstants.INVALID);
        } else {
            model.setUpdateTime(new Date());
            model.setUpdateManNo(userId);
            model.setUpdateManName(userName);
        }
    }

    /**
     * 一次计量实体，转换为预报实体
     *
     * @param first
     * @return
     */
    public PreHookScale firstToScale(MeterWorkHookActFirst first) {
        PreHookScale scale = new PreHookScale();
        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());
        return scale;
    }

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

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

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateRailwayNo(MeterWorkHookActFirst model) {
        try {
            ckeckcar(model);
            int num = meterWorkHookActFirstMapper.updateByPrimaryKeySelective(model);
            return num;
        } catch (MarkerMetException e) {
            throw e;
        }
    }

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

    /**
     * 除了结净状态外，其他状态数据：未使用，有效已匹配均可废除
     * @param model
     * @return
     */
    //@Override
    //@Transactional(rollbackFor = Exception.class)
    //public int abolish(MeterWorkHookActFirst model) {
    //    try {
    //        if (model == null) {
    //            throw new MarkerMetException(500, "参数为空!!");
    //        }
    //        check(model);
    //        if (model.getValueFlag().equals(ActFirstValueFlag.NET)) {
    //            throw new MarkerMetException(500, "已结净的数据不可再废除!!");
    //        }
    //        if (model.getValueFlag().equals(ActFirstValueFlag.ABOLISH)) {
    //            throw new MarkerMetException(500, "该数据已经是废除状态，不可重复废除!!");
    //        }
    //
    //        model.setValueFlag(ActFirstValueFlag.ABOLISH);
    //        int num = meterWorkHookActFirstMapper.updateByPrimaryKeySelective(model);
    //        if (StringUtils.isNotEmpty(model.getPredictionNo())) {
    //            PreHookScale scale = preHookScaleMapper.selectByPrimaryKey(model.getPredictionNo());
    //            if (scale != null && StringUtils.isNotEmpty(scale.getPredictionNo())) {
    //                scale.setPredictionNo(model.getPredictionNo());
    //                scale.setUpdateTime(new Date());
    //                scale.setUpdateManName(model.getUpdateManName());
    //                scale.setUpdateManNo(model.getUpdateManNo());
    //                scale.setpValueFlag(scale.getValueFlag());
    //                scale.setValueFlag("3");
    //                preHookScaleMapper.updateByPrimaryKeySelective(scale);
    //            }
    //        }
    //        return num;
    //    } catch (MarkerMetException e) {
    //        throw e;
    //    }
    //}

    /**
     *只有未使用状态的数据才允许废除
     * @param model
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int abolish(MeterWorkHookActFirst model) {
        try {
            if (model == null) {
                throw new MarkerMetException(500, "参数为空!!");
            }
            check(model);
            if (model.getValueFlag().equals("2")) {
                throw new MarkerMetException(500, "已结净的数据不可再废除!!");
            }
            if (model.getValueFlag().equals("0")) {
                throw new MarkerMetException(500, "该数据已经是废除状态，不可重复废除!!");
            }
            if (model.getValueFlag().equals("1")) {
                throw new MarkerMetException(500, "已匹配委托的数据不可再废除!!");
            }

            model.setValueFlag("0");
            int num = meterWorkHookActFirstMapper.updateByPrimaryKeySelective(model);

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

    /**
     * 除了结净状态外，其他状态数据均可启用
     * @param model
     * @return
     */
    //@Override
    //@Transactional(rollbackFor = Exception.class)
    //public int recover(MeterWorkHookActFirst model) {
    //    try {
    //        if (model == null) {
    //            throw new MarkerMetException(500, "参数为空!!");
    //        }
    //        check(model);
    //        if (model.getValueFlag().equals(ActFirstValueFlag.NET)) {
    //            throw new MarkerMetException(500, "已结净状态数据无法启用");
    //        }
    //        if (model.getPredictionNo() != null && !"".equals(model.getPredictionNo())) {
    //            model.setValueFlag("1");
    //        } else {
    //            model.setValueFlag("3");
    //        }
    //
    //        int num = meterWorkHookActFirstMapper.updateByPrimaryKeySelective(model);
    //
    //        if (StringUtils.isNotEmpty(model.getPredictionNo())) {
    //            PreHookScale scale = preHookScaleMapper.selectByPrimaryKey(model.getPredictionNo());
    //            if (scale != null && StringUtils.isNotEmpty(scale.getPredictionNo())) {
    //                scale.setPredictionNo(model.getPredictionNo());
    //                scale.setUpdateTime(new Date());
    //                scale.setUpdateManName(model.getUpdateManName());
    //                scale.setUpdateManNo(model.getUpdateManNo());
    //                scale.setpValueFlag(scale.getValueFlag());
    //                scale.setValueFlag("4");
    //                preHookScaleMapper.updateByPrimaryKeySelective(scale);
    //            }
    //        }
    //        return num;
    //    } catch (MarkerMetException e) {
    //        throw e;
    //    }
    //}

    /**
     * 只有已废除状态，且预报编号为空的数据才允许启用
     * @param model
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int recover(MeterWorkHookActFirst model) {
        try {
            if (model == null) {
                throw new MarkerMetException(500, "参数为空!!");
            }
            check(model);
            if (model.getValueFlag().equals("0") && StringUtils.isEmpty(model.getPredictionNo())) {
                model.setValueFlag("3");
                int num = meterWorkHookActFirstMapper.updateByPrimaryKeySelective(model);
                return num;
            }else {
                throw new MarkerMetException(500, "数据状态不对无法启用，只有已废除状态数据才可启用！！");
            }
        } catch (MarkerMetException e) {
            throw e;
        }
    }

    /**
     * 一次计量信息与预报信息进行匹配
     *
     * @param actualFirstNo
     * @param predictionNo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public MeterWorkHookActFirst match(String actualFirstNo, String predictionNo){
        try {
            if (actualFirstNo == null || "".equals(actualFirstNo)) {
                throw new MarkerMetException(500, "计量作业编号为空!!");
            }
            if (predictionNo == null || "".equals(predictionNo)) {
                throw new MarkerMetException(500, "预报编号为空!!");
            }
            MeterWorkHookActFirst meterWorkHookActFirst = meterWorkHookActFirstMapper.selectByPrimaryKey(actualFirstNo);
            if (meterWorkHookActFirst == null) {
                throw new MarkerMetException(500, "该计量作业信息不存在");
            }
            if (meterWorkHookActFirst.getPredictionNo() != null && !"".equals(meterWorkHookActFirst.getPredictionNo())) {
                throw new MarkerMetException(500, "该计量作业已匹配！！");
            }
            MeterWorkHookActFirst model = meterWorkHookActFirstMapper.selectAndMatch(actualFirstNo, predictionNo);
            model.setValueFlag("1");
            model.setUpdateTime(new Date());
            model.setUpdateManNo("system");
            model.setUpdateManName("吊钩秤一次计量匹配操作");

            PreHookScale prs = preHookScaleMapper.selectByPrimaryKey(predictionNo);
            if (prs == null) {
                throw new MarkerMetException(500, "该预报信息不存在");
            }
            prs.setValueFlag("4"); //使用中
            prs.setUpdateTime(new Date());
            prs.setUpdateManNo("system");
            prs.setUpdateManName("吊钩秤一次计量匹配操作");
//            prs.setNote(); 需要添加修改原因写入
            preHookScaleMapper.updateByPrimaryKeySelective(prs);
            meterWorkHookActFirstMapper.updateByPrimaryKeySelective(model);
            return model;
        } catch (MarkerMetException e) {
            throw e;
        }
    }

    /**
     * 一次计量数据撤销匹配的委托
     * @param model
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int remove(MeterWorkHookActFirst model) {
        try {
            if (model == null) {
                throw new MarkerMetException(500, "参数为空!!");
            }
            if (model.getPredictionNo() == null || "".equals(model.getPredictionNo())) {
                throw new MarkerMetException(500, "该条数据还未匹配委托!!");
            }

            PreHookScale pls = preHookScaleMapper.selectByPrimaryKey(model.getPredictionNo());
            pls.setPredictionNo(model.getPredictionNo());

            UserPayload payload = UserPayload.getCurrUser();
            String userId = payload.getUserCode();
            String userName = payload.getUserName();
            model.setUpdateManNo(userId);
            pls.setUpdateManName(userName);
            pls.setUpdateTime(new Date());
            pls.setpValueFlag(pls.getValueFlag());
            pls.setValueFlag("1");

            preHookScaleMapper.updateByPrimaryKeySelective(pls);
            MeterWorkHookActFirst mwcaf = meterWorkHookActFirstMapper.selectAndRemove(model.getActualFirstNo());
            mwcaf.setValueFlag("3");
            int num = meterWorkHookActFirstMapper.updateByPrimaryKey(mwcaf);
            return num;
        } catch (MarkerMetException e) {
            throw e;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<String> distinctCarNo(String railwayNo, String startTime, String endTime) {
        HashMap<String, Object> obj = new HashMap<>();
        obj.put("railwayNo", railwayNo);
        obj.put("startTime", startTime);
        obj.put("endTime", endTime);
        List<String> list = meterWorkHookActFirstMapper.distinctCarNo(obj).stream().map(MeterWorkHookActFirst::getRailwayNo).collect(Collectors.toList());
        return list;
    }

    /**
     * 吊钩秤计量保存逻辑
     *
     * @param model
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String doAddWfStatic(MeterWorkHookActFirst model) throws Exception {
        BigDecimal zero = new BigDecimal(0);
        String id = "";//需要返回的作业编号
        if (model == null || StringUtils.isEmpty(model.getPredictionNo())) {
            throw new MarkerMetException(500, "预报编号为空不允许进行保存操作!");
        }
        if (model.getMeterWeight() == null || model.getMeterWeight().compareTo(zero) <= 0) {
            throw new MarkerMetException(500, "采集重量为空或小于0不允许进行保存操作!");
        }
        //验证预报编号与预报的车号是否一致
        PreHookScale preHookScale = preHookScaleMapper.selectByPrimaryKey(model.getPredictionNo());
        if (preHookScale == null || StringUtils.isEmpty(preHookScale.getPredictionNo())) {
            throw new MarkerMetException(500, "未查询到预报编号为【" + model.getPredictionNo() + "】的数据，请刷新后重试!");
        } else {
            if (StringUtils.isEmpty(preHookScale.getRailwayNo())) {
                throw new MarkerMetException(500, "预报【" + model.getPredictionNo() + "】中的车号为空，不允许进行保存操作，请刷新后重试!");
            } else {
                if (!preHookScale.getRailwayNo().equals(model.getRailwayNo())) {
                    throw new MarkerMetException(500, "预报【" + model.getPredictionNo() + "】中的车号【" + preHookScale.getRailwayNo() + "】" +
                            "与界面车号【" + model.getRailwayNo() + "】不一致，不允许进行保存操作，请刷新后重试!");
                }
                if ("3".equals(preHookScale.getValueFlag())) {
                    throw new MarkerMetException(500, "预报【" + model.getPredictionNo() + "】已被作废，不允许进行保存操作，请重新选择预报!");
                }
                if ("2".equals(preHookScale.getValueFlag())) {
                    throw new MarkerMetException(500, "预报【" + model.getPredictionNo() + "】已经使用（已出净重），不允许再次使用，请重新选择预报或者进行复磅!");
                }
            }

        }
        //验证当前使用的预报号与一次计量的预报号是否一致
        MeterWorkHookActFirst searchFirst = new MeterWorkHookActFirst();
        searchFirst.setRailwayNo(model.getRailwayNo());
        searchFirst.setValueFlag("1");
        Map<String, Object> mapSearchFirst = FieldsCollector.beanToMap(searchFirst);
        List<MeterWorkHookActFirst> searchFirstList = meterWorkHookActFirstMapper.selectByParameters(mapSearchFirst);
        if (searchFirstList != null && searchFirstList.size() > 1) {
            throw new MarkerMetException(500, "车号【" + model.getRailwayNo() + "】存在【" + searchFirstList.size() + "】条有效数据，不允许计量操作，请先在网页上进行作废!");
        }
        if (searchFirstList != null && searchFirstList.size() == 1) {
            if (!model.getPredictionNo().equals(searchFirstList.get(0).getPredictionNo())) {
                throw new MarkerMetException(500, "车号【" + model.getRailwayNo() + "】一次计量的预报【"
                        + searchFirstList.get(0).getPredictionNo() + "】与当前使用的预报【" + model.getPredictionNo() + "】不一致，不允许计量操作，请先在网页上进行修改!");
            }
        }


        //1、判断是否是二次数据（二次数据需要结净）
        HashMap<String, Object> obj = new HashMap<>();
        obj.put("railwayNo", model.getRailwayNo());
        obj.put("railwayCarriageNo", model.getRailwayCarriageNo());
        obj.put("valueFlag", "1");//有效，未结净
        List<MeterWorkHookActFirst> mwrafs = meterWorkHookActFirstMapper.selectBy(obj);

        //2、判断是否为混装,若为混装将计量预报分割出
        ArrayList<String> ids = new ArrayList<>(); //ids用于更新预报操作
        if (StringUtils.isNotEmpty(model.getPredictionCombination())) {
            String[] preSclas = model.getPredictionCombination().split(",");
            Collections.addAll(ids, preSclas);
        }

        if (mwrafs.size() == 0) {
            //===========一次计量处理开始==============
            if (model.getRailwayFactoryWeight() == null || model.getRailwayFactoryWeight().compareTo(zero) <= 0) {
                //============一毛一皮的计量数据处理开始==============
                model.setWeightType("0");
                model.setMeterSortWeight(zero); //分检重量
                model.setMeterBalanceWeight(model.getMeterWeight()); //结算重量
                id = doAddWfStaticFrist(model);
                //3、修改预报状态为【使用中】
                if (StringUtils.isNotEmpty(model.getPredictionNo())
                        && model.getPredictionNo().length() > 10) {
                    ids.add(model.getPredictionNo());
                    preHookScaleMapper.batchUpdateByIdsForIn(ids);
                }
                //============一毛一皮的计量数据处理结束==============
            } else {
                //============毛重+自重的计量数据处理开始==============
                //毛重数据保存
                model.setWeightType("0");
                model.setMeterSortWeight(zero); //分检重量
                model.setMeterBalanceWeight(model.getMeterWeight());//结算重量
                model.setCreateTime(new Date()); //服务端重新赋值，避免出现皮重比毛重时间晚的情况；2021年6月10日
                id = doAddWfStaticFrist(model);

                //皮重计量实体的组装；皮重数据保存
                MeterWorkHookActFirst hookActFirst = new MeterWorkHookActFirst();
                BeanUtils.copyProperties(model, hookActFirst);
                hookActFirst.setMeterWeight(model.getRailwayFactoryWeight()); //皮重等于自重
                hookActFirst.setMeterSortWeight(zero);//分检重量
                hookActFirst.setMeterBalanceWeight(model.getRailwayFactoryWeight());//结算重量
                hookActFirst.setWeightType("1");
                Calendar tareDate = Calendar.getInstance();
                tareDate.add(Calendar.SECOND, -10);//自重的皮重减10s,用于查询最近的一条毛重数据，保证复磅数据准确
                hookActFirst.setCreateTime(tareDate.getTime());
                id = doAddWfStaticFrist(hookActFirst);

                //净重数据保存
                PreHookScale preHookScales = preHookScaleMapper.selectByPrimaryKey(model.getPredictionNo());
                doAddWfStaticNet(preHookScales, model, hookActFirst); //预报，毛重，皮重

                //3、修改预报状态为【已使用】
                if (StringUtils.isNotEmpty(model.getPredictionNo())
                        && model.getPredictionNo().length() > 10) {
                    ids.add(model.getPredictionNo());
                    preHookScaleMapper.batchUpdateByIdsForUsed(ids);
                }
                //============毛重+自重的计量数据处理结束==============
            }
            //===========一次计量处理结束==============
        } else {
            //===========二次计量处理开始==============
            for (MeterWorkHookActFirst mwraf : mwrafs) {
                //查询预报信息
                PreHookScale prs = preHookScaleMapper.selectByPrimaryKey(mwraf.getPredictionNo());

                //保存第二次的一次计量数据；特别说明：先皮后毛不会做分检，所以不需要考虑
                MeterWorkHookActFirst meterWorkHookActFirst = new MeterWorkHookActFirst();
                BeanUtils.copyProperties(mwraf, meterWorkHookActFirst);
                meterWorkHookActFirst.setCreateTime(new Date());
                meterWorkHookActFirst.setCreateManName(model.getCreateManName());
                meterWorkHookActFirst.setCreateManNo(model.getCreateManNo());
                meterWorkHookActFirst.setMeterGroup(model.getMeterGroup());
                meterWorkHookActFirst.setMeterClass(model.getMeterClass());
                meterWorkHookActFirst.setBaseSpotNo(model.getBaseSpotNo());
                meterWorkHookActFirst.setBaseSpotName(model.getBaseSpotName());
                meterWorkHookActFirst.setWeightType("1"); //假定为皮重，在出净重时会重新调整状态位
                meterWorkHookActFirst.setMeterWeight(model.getMeterWeight());
                meterWorkHookActFirst.setMeterSortWeight(zero);
                meterWorkHookActFirst.setMeterBalanceWeight(meterWorkHookActFirst.getMeterWeight());
                meterWorkHookActFirst.setPredictionNo(prs.getPredictionNo());
                meterWorkHookActFirst.setNoticeNo(prs.getNoticeNo());
                meterWorkHookActFirst.setMatterNo(prs.getMatterNo());
                meterWorkHookActFirst.setMatterName(prs.getMatterName());
                meterWorkHookActFirst.setContractNo(prs.getContractNo());
                meterWorkHookActFirst.setBatchNo(prs.getBatchNo());
                meterWorkHookActFirst.setCustomerSupplierNo(prs.getCustomerSupplierNo());
                meterWorkHookActFirst.setCustomerSupplierName(prs.getCustomerSupplierName());
                meterWorkHookActFirst.setForwardingUnitNo(prs.getForwardingUnitNo());
                meterWorkHookActFirst.setForwardingUnitName(prs.getForwardingUnitName());
                meterWorkHookActFirst.setReceivingUintNo(prs.getReceivingUintNo());
                meterWorkHookActFirst.setReceivingUintName(prs.getReceivingUintName());
                meterWorkHookActFirst.setMaterialNo(prs.getMaterialNo());
                meterWorkHookActFirst.setMaterialName(prs.getMaterialName());
                meterWorkHookActFirst.setSpecNo(prs.getSpecNo());
                meterWorkHookActFirst.setSpecName(prs.getSpecName());
                meterWorkHookActFirst.setLoadPointNo(prs.getLoadPointNo());
                meterWorkHookActFirst.setLoadPointName(prs.getLoadPointName());
                meterWorkHookActFirst.setSampleNo(prs.getSampleNo());
                meterWorkHookActFirst.setSampleVoucher(prs.getSampleVoucher());
                meterWorkHookActFirst.setCarrierUnitNo(prs.getCarrierUnitNo());
                meterWorkHookActFirst.setCarrierUnitName(prs.getCarrierUnitName());
                meterWorkHookActFirst.setMeterTypeNo(prs.getMeterTypeNo());
                meterWorkHookActFirst.setMeterTypeName(prs.getMeterTypeName());
                meterWorkHookActFirst.setArrival(prs.getArrival());
                meterWorkHookActFirst.setStation(prs.getStation());
                meterWorkHookActFirst.setSourceArea(prs.getSourceArea());

                id = doAddWfStaticFrist(meterWorkHookActFirst);
                //保存结净数据
                if (mwraf.getMeterWeight().compareTo(meterWorkHookActFirst.getMeterWeight()) >= 0) {
                    doAddWfStaticNet(prs, mwraf, meterWorkHookActFirst); //预报，毛重，皮重
                } else {
                    doAddWfStaticNet(prs, meterWorkHookActFirst, mwraf);//预报，皮重，毛重
                }
            }
            //3、修改预报状态为【已使用】
            if (StringUtils.isNotEmpty(model.getPredictionNo())
                    && model.getPredictionNo().length() > 10) {
                ids.add(model.getPredictionNo());
                preHookScaleMapper.batchUpdateByIdsForUsed(ids);
            }
        }
        //===========二次计量处理结束==============
        //4、保存图片（一、二次计量共用）
        SaveImg(meterWorkHookActFirstMapper.selectByPrimaryKey(id));
        return id;
    }

    @Override
    @Transactional
    public RESTfulResult doAddWfStaticTwo(PreHookScale scale, MeterWorkHookActFirst grossModel, MeterWorkHookActFirst tareModel) {
        RESTfulResult rm = new RESTfulResult();
        rm.setFailed();

        try {
            HashMap<String, Object> map = new HashMap<>();
            List<MeterWorkHookActFirst> firsts = new ArrayList<>();
            List<MeterWorkHookActual> actuals = new ArrayList<>();

            BigDecimal num = grossModel.getMeterWeight().subtract(tareModel.getMeterWeight()).abs();
            /*if(num.compareTo(BigDecimal.valueOf(400)) == -1){
                rm.setMessage("选择的两条一次计量数据不能小于400kg，请确认！！");
                return rm;
            }*/
            if (!grossModel.getRailwayNo().equals(tareModel.getRailwayNo())) {
                rm.setMessage("两条一次计量数据车号不一致,请确认！！");
                return rm;
            }

            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            String afl = sdf.format(new Date());
            String firstNo = sdf.format(new Date()) + meterWorkHookActFirstMapper.getNewID(afl);
            String flag = null;
            //存储当前计量的数据
            if (grossModel.getActualFirstNo() == null) {
                grossModel.setActualFirstNo(firstNo);
                grossModel.setCreateTime(new Date());
                meterWorkHookActFirstMapper.insertSelective(grossModel);
                flag = "0";
            }
            if (tareModel.getActualFirstNo() == null) {
                tareModel.setActualFirstNo(firstNo);
                tareModel.setCreateTime(new Date());
                meterWorkHookActFirstMapper.insertSelective(tareModel);
                flag = "1";
            }

            MeterWorkHookActual actualRow = new MeterWorkHookActual();
            //毛重一次
            MeterWorkHookActFirst model01 = meterWorkHookActFirstMapper.selectByPrimaryKey(grossModel.getActualFirstNo());
            //皮重一次
            MeterWorkHookActFirst model02 = meterWorkHookActFirstMapper.selectByPrimaryKey(tareModel.getActualFirstNo());

            //修改委托状态
            if (scale != null) {
                //委托信息是否为有效数据
                if (scale.getValueFlag().equals("2") || scale.getValueFlag().equals("3")) {
                    rm.setMessage("委托信息已使用或者已作废！！");
                    return rm;
                }

                //将委托中的编号和收发货的等数据拷贝进一次数据中
                MeterWorkHookActFirst first1 = meterWorkHookActFirstMapper.selectAndMatch(model01.getActualFirstNo(), scale.getPredictionNo());
                BeanUtils.copyProperties(first1, model01);
                MeterWorkHookActFirst first2 = meterWorkHookActFirstMapper.selectAndMatch(model02.getActualFirstNo(), scale.getPredictionNo());
                BeanUtils.copyProperties(first2, model02);

                //修改委托编号
                scale.setValueFlag(DbConstants.NET);
                scale.setUpdateTime(new Date());
                scale.setUpdateManNo("system");
                scale.setUpdateManName("自动匹配更新");
                scale.setUploadFlag("1");
                scale.setPredictionType("1");
                preHookScaleMapper.updateByPrimaryKeySelective(scale);

                //修改毛重一次数据状态
                model01.setValueFlag(DbConstants.NET);
                model01.setUpdateManName("system");
                model01.setUpdateManName("自动匹配更新");
                model01.setUpdateTime(new Date());
                model01.setWeightType("0");
                model01.setIsPreScale("1");
                model01.setPredictionNo(scale.getPredictionNo());
                model01.setPredictionType("1");
                meterWorkHookActFirstMapper.updateByPrimaryKeySelective(model01);
                //修改皮重一次数据状态
                model02.setValueFlag(DbConstants.NET);
                model02.setUpdateManName("system");
                model02.setUpdateManName("自动匹配更新");
                model02.setUpdateTime(new Date());
                model02.setWeightType("1");
                model02.setIsPreScale("1");
                model02.setPredictionNo(scale.getPredictionNo());
                model02.setPredictionType("1");
                meterWorkHookActFirstMapper.updateByPrimaryKeySelective(model02);

                MeterWorkHookActual mwca1 = meterWorkHookActualMapper.manualAddPre(model01.getActualFirstNo(), model02.getActualFirstNo(), scale.getPredictionNo());
                BeanUtils.copyProperties(mwca1, actualRow);
                //保存结净
                String no = meterWorkHookActualMapper.getNewID(sdf.format(new Date()));
                actualRow.setActualNo(sdf.format(new Date()) + no);
                actualRow.setNetTime(new Date());
                actualRow.setNetMode(DbConstants.TYPE);
                actualRow.setNote("自动匹配结净");
                actualRow.setNetMode("1");
                actualRow.setUploadFlag("1");
                actualRow.setValueFlag("1");
                actualRow.setIsPreScale("1");
                actualRow.setPredictionNo(scale.getPredictionNo());
                actualRow.setPredictionType("1");
                actualRow.setNetWeight(model01.getMeterWeight().subtract(model02.getMeterWeight()));
                meterWorkHookActualMapper.insertSelective(actualRow);
            } else {
                //修改毛重一次数据状态
                model01.setValueFlag(DbConstants.NET);
                model01.setUpdateManName("system");
                model01.setUpdateManName("自动匹配更新");
                model01.setUpdateTime(new Date());
                model01.setWeightType("0");
                model01.setIsPreScale("0");
                meterWorkHookActFirstMapper.updateByPrimaryKeySelective(model01);
                //修改皮重一次数据状态
                model02.setValueFlag(DbConstants.NET);
                model02.setUpdateManName("system");
                model02.setUpdateManName("自动匹配更新");
                model02.setUpdateTime(new Date());
                model02.setWeightType("1");
                model02.setIsPreScale("0");
                meterWorkHookActFirstMapper.updateByPrimaryKeySelective(model02);

                MeterWorkHookActual mwca1 = meterWorkHookActualMapper.manualAdd(model01.getActualFirstNo(), model02.getActualFirstNo());
                BeanUtils.copyProperties(mwca1, actualRow);
                //保存结净
                String no = meterWorkHookActualMapper.getNewID(sdf.format(new Date()));
                actualRow.setActualNo(sdf.format(new Date()) + no);
                actualRow.setNetTime(new Date());
                actualRow.setNetMode(DbConstants.TYPE);
                actualRow.setNote("自动匹配结净");
                actualRow.setNetMode("1");
                actualRow.setUploadFlag("1");
                actualRow.setValueFlag("1");
                actualRow.setIsPreScale("0");
                actualRow.setNetWeight(model01.getMeterWeight().subtract(model02.getMeterWeight()));
                meterWorkHookActualMapper.insertSelective(actualRow);
            }

            if (flag.equals("0")) {
                firsts.add(model01);
            } else if (flag.equals("1")) {
                firsts.add(model02);
            }
            actuals.add(actualRow);
            map.put("firsts", firsts);
            map.put("actuals", actuals);

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

    //保存计量数据
    private String doAddWfStaticFrist(MeterWorkHookActFirst model) {
        //此为第一次计量的数据
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String afl = sdf.format(model.getCreateTime());
        //一次数据
        String firstNo = meterWorkHookActFirstMapper.getNewID(afl);
        model.setActualFirstNo(afl + firstNo);
        model.setValueFlag("1");
        model.setCheckFlag("0");
        model.setMeterMode("1");
        model.setCreateTime(new Date());
        meterWorkHookActFirstMapper.insertSelective(model);
        return model.getActualFirstNo();
    }

    /**
     * 需要两次计量时完善结净数据
     *
     * @param prs 预报
     * @param one 毛重实体
     * @param two 皮重实体
     * @return
     */
    private MeterWorkHookActual doAddWfStaticNet(PreHookScale prs, MeterWorkHookActFirst one, MeterWorkHookActFirst two) {
        MeterWorkHookActual netHook = new MeterWorkHookActual();
        //补充编号
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String afl = sdf.format(new Date());
        String netNo = meterWorkHookActualMapper.getNewID(afl);
        netHook.setActualNo(afl + netNo);

        //补充数据
        netHook.setPredictionNo(prs.getPredictionNo());
        netHook.setNoticeNo(prs.getNoticeNo());
        netHook.setMatterNo(prs.getMatterNo());
        netHook.setMatterName(prs.getMatterName());
        netHook.setContractNo(prs.getContractNo());
        netHook.setBatchNo(prs.getBatchNo());
        netHook.setCustomerSupplierNo(prs.getCustomerSupplierNo());
        netHook.setCustomerSupplierName(prs.getCustomerSupplierName());
        netHook.setForwardingUnitNo(prs.getForwardingUnitNo());
        netHook.setForwardingUnitName(prs.getForwardingUnitName());
        netHook.setReceivingUintNo(prs.getReceivingUintNo());
        netHook.setReceivingUintName(prs.getReceivingUintName());
        netHook.setMaterialNo(prs.getMaterialNo());
        netHook.setMaterialName(prs.getMaterialName());
        netHook.setSpecNo(prs.getSpecNo());
        netHook.setSpecName(prs.getSpecName());
        netHook.setLoadPointNo(prs.getLoadPointNo());
        netHook.setLoadPointName(prs.getLoadPointName());
        netHook.setSampleNo(prs.getSampleNo());
        netHook.setSampleVoucher(prs.getSampleVoucher());
        netHook.setCarrierUnitNo(prs.getCarrierUnitNo());
        netHook.setCarrierUnitName(prs.getCarrierUnitName());
        netHook.setMeterTypeNo(prs.getMeterTypeNo());
        netHook.setMeterTypeName(prs.getMeterTypeName());
        netHook.setStation(prs.getStation());
        netHook.setArrival(prs.getArrival());
        netHook.setSourceArea(prs.getSourceArea());

        //将毛重数据补充进来
        netHook.setRailwayNo(one.getRailwayNo());
        netHook.setRailwayCarriageNo(one.getRailwayCarriageNo());
        netHook.setActualFirst1No(one.getActualFirstNo());
        netHook.setGrossWeight(one.getMeterBalanceWeight());
        netHook.setGrossManNo(one.getCreateManNo());
        netHook.setGrossManName(one.getCreateManName());
        netHook.setGrossTime(one.getCreateTime());
        netHook.setBaseSpot1No(one.getBaseSpotNo());
        netHook.setBaseSpot1Name(one.getBaseSpotName());
        netHook.setGrossClass(one.getMeterClass());
        netHook.setGrossGroup(one.getMeterGroup());
        netHook.setGrossMode(one.getMeterMode());
        netHook.setRailwayTypeNo(one.getRailwayTypeNo());
        netHook.setRailwayTypeName(one.getRailwayTypeName());
        netHook.setWaterNum(one.getWaterNum());
        //将皮重数据补充
        netHook.setActualFirst2No(two.getActualFirstNo());
        netHook.setTareWeight(two.getMeterWeight());
        netHook.setTareManNo(two.getCreateManNo());
        netHook.setTareManName(two.getCreateManName());
        netHook.setTareTime(two.getCreateTime());
        netHook.setBaseSpot2No(two.getBaseSpotNo());
        netHook.setBaseSpot2Name(two.getBaseSpotName());
        netHook.setTareClass(two.getMeterClass());
        netHook.setTareGroup(two.getMeterGroup());
        netHook.setTareMode(two.getMeterMode());
        //补充净重数据

        if (one.getCreateTime().after(two.getCreateTime())) {
            netHook.setNetManNo(one.getCreateManNo());
            netHook.setNetManName(one.getCreateManName());
            netHook.setNetTime(one.getCreateTime());
            netHook.setNetSpot3No(one.getBaseSpotNo());
            netHook.setNetSpot3Name(one.getBaseSpotName());
            netHook.setNetClass(one.getMeterClass());
            netHook.setNetGroup(one.getMeterGroup());
        } else {
            netHook.setNetManNo(two.getCreateManNo());
            netHook.setNetManName(two.getCreateManName());
            netHook.setNetTime(two.getCreateTime());
            netHook.setNetSpot3No(two.getBaseSpotNo());
            netHook.setNetSpot3Name(two.getBaseSpotName());
            netHook.setNetClass(two.getMeterClass());
            netHook.setNetGroup(two.getMeterGroup());
        }
        netHook.setNetWeight(one.getMeterBalanceWeight().subtract(two.getMeterBalanceWeight()));
        netHook.setNetMode("1");
        netHook.setValueFlag("1");
        netHook.setUploadFlag("1");
        if ("001019002".equals(one.getRailwayTypeNo())) {
            netHook.setNetTime(new Date()); //动轨的特殊处理
            //假如一次数据为补录，则结净数据中的grossModel为3，标识毛重为手工录入的
            if ("补录".equals(one.getRailwayModelName())) {
                netHook.setGrossMode("3");
                //METER_WORK_RAILWAY_ACTUAL_BAR
                meterWorkHookActualMapper.insertSelectiveBar(netHook);
            }
        }
        meterWorkHookActualMapper.insertSelective(netHook);


        //修改一次的状态
        one.setValueFlag("2");//结净
        one.setWeightType("0");//毛重
        two.setValueFlag("2");//结净
        two.setWeightType("1");//皮重
        meterWorkHookActFirstMapper.updateByPrimaryKeySelective(one);
        meterWorkHookActFirstMapper.updateByPrimaryKeySelective(two);
        return netHook;
    }

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

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

    @Override
    public RESTfulResult selfServiceMeasurement(MeterWorkHookActFirst first) {
        RESTfulResult rm = new RESTfulResult();
        rm.setFailed();

        HashMap<String, Object> resultMap = new HashMap<>();
        List<MeterWorkHookActFirst> firsts = new ArrayList<>();
        List<MeterWorkHookActual> actuals = new ArrayList<>();

        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            String afl = sdf.format(new Date());
            //报警信息
            MeterWorkRailwayScheduledHelp railwayHelp = new MeterWorkRailwayScheduledHelp();
            String railwayNo = first.getRailwayNo() == null ? "" : first.getRailwayNo();
            railwayHelp.setWarmType("1");
            railwayHelp.setWarmTypeName("");
            railwayHelp.setRailwayNo(railwayNo);
            railwayHelp.setBaseSpotNo(first.getBaseSpotNo());
            railwayHelp.setBaseSpotName(first.getBaseSpotName());

            //查询车号是否为空，为空写入报警信息表
            if (StringUtils.isEmpty(first.getRailwayNo())) {
                first.setActualFirstNo(afl + meterWorkHookActFirstMapper.getNewID(afl));
                first.setRailwayNo("无车号");
                first.setCreateTime(new Date());
                int i = meterWorkHookActFirstMapper.insertSelective(first);
                if (i >= 1) {
                    firsts.add(first);
                    railwayHelp.setHelpContent("车号为空,请联系处理");
                    meterWorkRailwayScheduledHelpService.checkAdd(railwayHelp);
                    rm.setSucceed();
                    rm.setMessage("车号为空,请联系处理");
                    resultMap.put("firsts", firsts);
                    resultMap.put("acutals", null);
                    rm.setData(resultMap);
                    return rm;
                }
            } else {
                //查询根据车号查询有效的一次数据
                HashMap<String, Object> map = new HashMap<>();
                map.put("railwayNo", railwayNo);
                map.put("valueFlag", "1");
                List<MeterWorkHookActFirst> firstList = meterWorkHookActFirstMapper.selectByParameters(map);
                if (firstList.size() >= 1) {
                    if (firstList.size() == 1) {
                        first.setActualFirstNo(afl + meterWorkHookActFirstMapper.getNewID(afl));
                        first.setCreateTime(new Date());
                        meterWorkHookActFirstMapper.insertSelective(first);
                        BigDecimal num = firstList.get(0).getMeterWeight().subtract(first.getMeterWeight()).abs();
                        //结净数据不能小于10t
                        if (num.compareTo(DbConstants.RAILWAY_WEIGHT) == -1) {
                            first.setActualFirstNo(afl + meterWorkHookActFirstMapper.getNewID(afl));
                            first.setCreateTime(new Date());
                            int i = meterWorkHookActFirstMapper.insertSelective(first);
                            if (i >= 1) {
                                railwayHelp.setHelpContent("计量完成，车号" + first.getRailwayNo() + "存在重量相近的一次记录，无法自动结净匹配");
                                meterWorkRailwayScheduledHelpService.checkAdd(railwayHelp);
                                rm.setSucceed();
                                rm.setMessage("计量完成，车号" + first.getRailwayNo() + "存在重量相近的一次记录，无法自动结净匹配");
                                resultMap.put("firsts", firsts);
                                resultMap.put("actuals", null);
                                rm.setData(resultMap);
                                return rm;
                            }
                        }
                        String Content;
                        HashMap<String, Object> obj = new HashMap<>();
                        if (first.getMeterWeight().compareTo(firstList.get(0).getMeterWeight()) == -1) {
                            Content = matchPreClean(firstList.get(0), first);
                            obj.put("actualFirst2No", first.getActualFirstNo());
                        } else {
                            Content = matchPreClean(first, firstList.get(0));
                            obj.put("acutalFirst1No", first.getActualFirstNo());
                        }
                        railwayHelp.setHelpContent(Content);
                        meterWorkRailwayScheduledHelpService.checkAdd(railwayHelp);
                        rm.setSucceed();
                        rm.setMessage(Content);

                        List<MeterWorkHookActual> models = meterWorkHookActualMapper.selectByParameter(obj);
                        if (models.size() >= 1) {
                            actuals.add(models.get(0));
                        } else {
                            actuals.add(null);
                        }
                        resultMap.put("firsts", firsts);
                        resultMap.put("actuals", actuals);
                        rm.setData(resultMap);
                        return rm;
                    } else if (firstList.size() >= 2) {
                        first.setActualFirstNo(afl + meterWorkHookActFirstMapper.getNewID(afl));
                        first.setCreateTime(new Date());
                        int i = meterWorkHookActFirstMapper.insertSelective(first);
                        if (i >= 1) {
                            firsts.add(first);
                            railwayHelp.setHelpContent("计量完成，车号" + first.getRailwayNo() + "存在多条一次记录未结净，保存一次记录成功！！");
                            meterWorkRailwayScheduledHelpService.checkAdd(railwayHelp);
                            rm.setSucceed();
                            rm.setMessage("计量完成，车号" + first.getRailwayNo() + "存在多条一次记录未结净，保存一次记录成功！！");
                            resultMap.put("firsts", firsts);
                            resultMap.put("actuals", null);
                            rm.setData(resultMap);
                            return rm;
                        }
                    }
                } else {
                    first.setActualFirstNo(afl + meterWorkHookActFirstMapper.getNewID(afl));
                    first.setCreateTime(new Date());
                    int i = meterWorkHookActFirstMapper.insertSelective(first);
                    if (i >= 1) {
                        firsts.add(first);
                        railwayHelp.setHelpContent("计量完成，车号" + first.getRailwayNo() + "保存一次记录成功！！");
                        meterWorkRailwayScheduledHelpService.checkAdd(railwayHelp);
                        rm.setSucceed();
                        rm.setMessage("计量完成，车号" + first.getRailwayNo() + "保存一次记录成功！！");
                        resultMap.put("firsts", firsts);
                        resultMap.put("actuals", null);
                        rm.setData(resultMap);
                        return rm;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            rm.setMessage("操作异常！！>>>" + e.getMessage());
        }
        return rm;
    }

    public String matchPreClean(MeterWorkHookActFirst grossModel, MeterWorkHookActFirst tareModel) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String sfl = sdf.format(new Date());
        MeterWorkHookActual actualRow = new MeterWorkHookActual();

        List<PreHookScale> railwayScales = preHookScaleMapper.selectByRailwayNo(grossModel.getRailwayNo());
        if (railwayScales.size() >= 1) {
            if (railwayScales.size() == 1) {
                ///////////无委托自动计量

                PreHookScale scale = railwayScales.get(0);
                MeterWorkHookActFirst actFirst01 = meterWorkHookActFirstMapper.selectAndMatch(grossModel.getActualFirstNo(), scale.getPredictionNo());
                BeanUtils.copyProperties(actFirst01, grossModel);
                MeterWorkHookActFirst actFirst02 = meterWorkHookActFirstMapper.selectAndMatch(tareModel.getActualFirstNo(), scale.getPredictionNo());
                BeanUtils.copyProperties(actFirst02, tareModel);

                //更新预报数据
                scale.setValueFlag(DbConstants.NET);
                scale.setUpdateTime(new Date());
                scale.setUpdateManNo("system");
                scale.setUpdateManName("自助计量结净更新");
                scale.setUploadFlag("1");
                scale.setPredictionType("1");
                preHookScaleMapper.updateByPrimaryKeySelective(scale);

                //更新一次数据
                //更新第一次毛重数据库
                grossModel.setValueFlag(DbConstants.NET);
                grossModel.setUpdateManName("system");
                grossModel.setUpdateManName("智能计量双委托结净更新");
                grossModel.setUpdateTime(new Date());
                grossModel.setWeightType("0");
                grossModel.setIsPreScale("1");
                grossModel.setPredictionNo(scale.getPredictionNo());
                grossModel.setPredictionType("1");
                meterWorkHookActFirstMapper.updateByPrimaryKey(grossModel);
                //更新第一次皮重数据库
                tareModel.setValueFlag(DbConstants.NET);
                tareModel.setUpdateManName("system");
                tareModel.setUpdateManName("自助计量结净更新");
                tareModel.setUpdateTime(new Date());
                tareModel.setWeightType("1");
                tareModel.setIsPreScale("1");
                tareModel.setPredictionNo(scale.getPredictionNo());
                tareModel.setPredictionType("1");
                meterWorkHookActFirstMapper.updateByPrimaryKey(tareModel);

                //将委托中的编号和收发货单位和一次数据等数据拷贝进结净数据中
                MeterWorkHookActual mwca1 = meterWorkHookActualMapper.manualAddPre(grossModel.getActualFirstNo(), tareModel.getActualFirstNo(), scale.getPredictionNo());
                BeanUtils.copyProperties(mwca1, actualRow);

                //添加结净数据
                String no = meterWorkHookActualMapper.getNewID(sdf.format(new Date()));
                actualRow.setActualNo(sdf.format(new Date()) + no);
                actualRow.setNetTime(new Date());
                actualRow.setNetMode(DbConstants.TYPE);
//                actualRow.setNote("自助计量匹配结净");
                actualRow.setNetMode("1");
                actualRow.setUploadFlag("1");
                actualRow.setValueFlag("1");
                actualRow.setIsPreScale("1");
                actualRow.setPredictionNo(scale.getPredictionNo());
                actualRow.setPredictionType("1");
                actualRow.setNetWeight(grossModel.getMeterWeight().subtract(tareModel.getMeterWeight()));
                meterWorkHookActualMapper.insertSelective(actualRow);
                return "计量完成，" + grossModel.getRailwayNo() + "与委托编号" + scale.getPredictionNo() + "计量结净";
            } else {
                //更新第一次毛重数据库
                grossModel.setValueFlag(DbConstants.NET);
                grossModel.setUpdateManName("system");
                grossModel.setUpdateManName("自助计量结净更新");
                grossModel.setUpdateTime(new Date());
                grossModel.setWeightType("0");
                grossModel.setIsPreScale("0");
                meterWorkHookActFirstMapper.updateByPrimaryKey(grossModel);
                //更新第一次皮重数据库
                tareModel.setValueFlag(DbConstants.NET);
                tareModel.setUpdateManName("system");
                tareModel.setUpdateManName("自助计量结净更新");
                tareModel.setUpdateTime(new Date());
                tareModel.setWeightType("1");
                tareModel.setIsPreScale("0");
                meterWorkHookActFirstMapper.updateByPrimaryKey(tareModel);

                //将委托中的编号和收发货单位和一次数据等数据拷贝进结净数据中
                MeterWorkHookActual mwca1 = meterWorkHookActualMapper.manualAdd(grossModel.getActualFirstNo(), tareModel.getActualFirstNo());
                BeanUtils.copyProperties(mwca1, actualRow);

                //添加结净数据
                String no = meterWorkHookActualMapper.getNewID(sdf.format(new Date()));
                actualRow.setActualNo(sdf.format(new Date()) + no);
                actualRow.setNetTime(new Date());
                actualRow.setNetMode(DbConstants.TYPE);
                actualRow.setNote("自助计量匹配结净");
                actualRow.setNetMode("1");
                actualRow.setUploadFlag("1");
                actualRow.setValueFlag("1");
                actualRow.setIsPreScale("0");
                actualRow.setNetWeight(grossModel.getMeterWeight().subtract(tareModel.getMeterWeight()));
                meterWorkHookActualMapper.insertSelective(actualRow);
                return "计量完成，车号" + grossModel.getRailwayNo() + "在委托信息表含有多条有效委托信息,无委托结净";
            }
        } else {
            ///////////无委托自动计量

            //更新第一次毛重数据库
            grossModel.setValueFlag(DbConstants.NET);
            grossModel.setUpdateManName("system");
            grossModel.setUpdateManName("自助计量结净更新");
            grossModel.setUpdateTime(new Date());
            grossModel.setWeightType("0");
            grossModel.setIsPreScale("0");
            meterWorkHookActFirstMapper.updateByPrimaryKey(grossModel);
            //更新第一次皮重数据库
            tareModel.setValueFlag(DbConstants.NET);
            tareModel.setUpdateManName("system");
            tareModel.setUpdateManName("自助计量结净更新");
            tareModel.setUpdateTime(new Date());
            tareModel.setWeightType("1");
            tareModel.setIsPreScale("0");
            meterWorkHookActFirstMapper.updateByPrimaryKey(tareModel);

            //将委托中的编号和收发货单位和一次数据等数据拷贝进结净数据中
            MeterWorkHookActual mwca1 = meterWorkHookActualMapper.manualAdd(grossModel.getActualFirstNo(), tareModel.getActualFirstNo());
            BeanUtils.copyProperties(mwca1, actualRow);

            //添加结净数据
            String no = meterWorkHookActualMapper.getNewID(sdf.format(new Date()));
            actualRow.setActualNo(sdf.format(new Date()) + no);
            actualRow.setNetTime(new Date());
            actualRow.setNetMode(DbConstants.TYPE);
            actualRow.setNote("自助计量匹配结净");
            actualRow.setNetMode("1");
            actualRow.setUploadFlag("1");
            actualRow.setValueFlag("1");
            actualRow.setIsPreScale("0");
            actualRow.setNetWeight(grossModel.getMeterWeight().subtract(tareModel.getMeterWeight()));
            meterWorkHookActualMapper.insertSelective(actualRow);
            return "计量完成，车号" + grossModel.getRailwayNo() + "无委托结净";
        }
    }
}
