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

import com.alibaba.druid.sql.visitor.functions.Substring;
import com.steerinfo.TimedTask.lgwgt.mapper.LgWgtMapper;
import com.steerinfo.TimedTask.lgwgt.model.LgWgt;
import com.steerinfo.TimedTask.rsbcread.mapper.RsBcreadMapper;
import com.steerinfo.TimedTask.rsbcread.model.RsBcread;
import com.steerinfo.baseinfo.combaseinfo.mapper.ComBaseInfoMapper;
import com.steerinfo.baseinfo.combaseinfo.model.ComBaseInfo;
import com.steerinfo.baseinfo.meterbaseoperationlog.model.MeterBaseOperationLog;
import com.steerinfo.baseinfo.meterbaseoperationlog.service.IMeterBaseOperationLogService;
import com.steerinfo.baseinfo.meterbasevideoinfo.mapper.MeterBaseVideoinfoMapper;
import com.steerinfo.baseinfo.meterbasevideoinfo.model.MeterBaseVideoinfo;
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.dto.ShuGenVo;
import com.steerinfo.meterwork.dto.StaffPerformanceAnalysis;
import com.steerinfo.meterwork.except.MarkerMetException;
import com.steerinfo.meterwork.meterworkimage.mapper.MeterWorkImageMapper;
import com.steerinfo.meterwork.meterworkimage.model.MeterWorkImage;
import com.steerinfo.meterwork.meterworkstockonline.mapper.MeterWorkStockOnlineMapper;
import com.steerinfo.meterwork.meterworkstockonline.model.MeterWorkStockOnline;
import com.steerinfo.meterwork.meterworkstorageactual.mapper.MeterWorkStorageActualMapper;
import com.steerinfo.meterwork.meterworkstorageactual.model.MeterWorkStorageActual;
import com.steerinfo.meterwork.meterworkstorageactual.service.IMeterWorkStorageActualService;
import com.steerinfo.meterwork.meterworkstoragesinglewgt.mapper.MeterWorkStorageSingleWgtMapper;
import com.steerinfo.meterwork.meterworkstoragesinglewgt.model.MeterWorkStorageSingleWgt;
import com.steerinfo.meterwork.meterworkstoragesinglewgt.service.IMeterWorkStorageSingleWgtService;
import com.steerinfo.pretrack.prestoragescale.mapper.PreStorageScaleMapper;
import com.steerinfo.pretrack.prestoragescale.model.PreStorageScale;
import com.steerinfo.pretrack.pretrackscale.model.PreTrackScale;
import com.steerinfo.util.*;
import com.sun.org.apache.bcel.internal.generic.IF_ACMPEQ;
import org.apache.cxf.endpoint.Client;
import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;
import org.apache.http.util.EntityUtils;
import org.apache.ibatis.jdbc.Null;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

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

    @Resource
    private MeterWorkStorageActualMapper meterWorkStorageActualMapper;

    @Resource
    private MeterBaseVideoinfoMapper meterBaseVideoinfoMapper;

    @Resource
    private MeterWorkImageMapper meterWorkImageMapper;

    @Resource
    private MeterWorkStockOnlineMapper onlineMapper;

    @Resource
    private ComBaseInfoMapper comBaseInfoMapper;

    @Resource
    private PreStorageScaleMapper preStorageScaleMapper;

    @Resource
    private MeterWorkStorageSingleWgtMapper meterWorkStorageSingleWgtMapper;

    @Resource
    private LgWgtMapper lgWgtMapper;

    @Resource
    private RsBcreadMapper rsBcreadMapper;

    @Override
    protected IBaseMapper<MeterWorkStorageActual, String> getMapper() {
        return meterWorkStorageActualMapper;
    }

    @Autowired
    IMeterBaseOperationLogService meterBaseOperationLogService;

    @Override
    public int audit(MeterWorkStorageActual model) {
        try {
            check(model);
            if (model.getCheckFlag().equals(DbConstants.VALID)) {
                throw new MarkerMetException(500, "该数据已经审核！！");
            } else {
                model.setCheckFlag(DbConstants.VALID);
            }
            int num = meterWorkStorageActualMapper.updateByPrimaryKeySelective(model);
            return num;
        } catch (MarkerMetException e) {
            throw e;
        }

    }

    @Override
    public int unaudit(MeterWorkStorageActual model) {
        try {
            check(model);
            if (model.getCheckFlag().equals(DbConstants.INVALID)) {
                throw new MarkerMetException(500, "该数据还未审核！！");
            } else {
                model.setCheckFlag(DbConstants.VALID);
            }
            int num = meterWorkStorageActualMapper.updateByPrimaryKeySelective(model);
            return num;
        } catch (MarkerMetException e) {
            throw e;
        }

    }

    @Override
    public PageList<MeterWorkStorageActual> selectView(Map<String, Object> parmas, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<MeterWorkStorageActual> rows = meterWorkStorageActualMapper.selectView(parmas);
        PageList pageInfo = new PageList(rows);
        return pageInfo;
    }

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

    @Override
    public List<MeterWorkStorageActual> doQueryWf(MeterWorkStorageActual model) {
        return meterWorkStorageActualMapper.doQueryWf(model);
    }

    @Override
    public List<MeterWorkStorageActual> doQueryTimeWf(CommonPage<MeterWorkStorageActual> model) {
        HashMap<String, Object> obj = new HashMap<>();
        obj.put("startTime", model.getStartTime());
        obj.put("endTime", model.getEndTime());
        if (model.getParam() != null) {
            obj.put("baseSpotNo", model.getParam().getBaseSpotNo());
            obj.put("productNo", model.getParam().getProductNo());
            obj.put("batchNo", model.getParam().getBatchNo());
        }
        return meterWorkStorageActualMapper.doQueryTimeWf(obj);
    }

    private void check(MeterWorkStorageActual model) {
        UserPayload payload = UserPayload.getCurrUser();
        String userId = payload.getUserCode();
        String userName = payload.getUserName();
        if (StringUtils.isEmpty(model.getActualNo())) {
            model.setCreateManNo(userId);
            model.setCreateManName(userName);
            model.setValueFlag(DbConstants.VALID);
            model.setCheckFlag(DbConstants.INVALID);
        } else {
            model.setUpdateTime(new Date());
            model.setUpdateManNo(userId);
            model.setUpdateManName(userName);
        }
    }

    @Override
    @Transactional
    public String doAddWf(MeterWorkStorageActual model) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String no = meterWorkStorageActualMapper.getNewID(sdf.format(new Date()));
        model.setActualNo(sdf.format(new Date()) + no);
        model.setPredictionNo(model.getActualNo());
        model.setCreateTime(new Date());
        meterWorkStorageActualMapper.insertSelective(model);
        //保存图片
        SaveImg(model);

        //返回编号
        return model.getActualNo();
    }

    /**
     * 图片保存信息
     *
     * @param oci
     * @throws Exception
     */
    @Transactional(rollbackFor = Exception.class)
    public void SaveImg(MeterWorkStorageActual oci) {
        try {
            //查下当前配置的摄像头有多少个
            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("S" + oci.getActualNo());
                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.getActualNo() + "_" + i);
                }
                meterWorkImageMapper.insertSelective(mwi);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int doUpdateWf(List<MeterWorkStorageActual> model) {
        UserPayload payload = UserPayload.getCurrUser();
        String userId = payload.getUserCode();
        String userName = payload.getUserName();

        for (MeterWorkStorageActual mw : model) {
            mw.setUpdateManNo(userId);
            mw.setUpdateManName(userName);
            mw.setUpdateTime(new Date());

            meterWorkStorageActualMapper.updateByPrimaryKeySelective(mw);
        }
        return 0;
    }

    /**
     * 热送磅实绩保存接口
     *
     * @param model
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String doAddHotDeliveryBelt(MeterWorkStorageActual model) {
        try {
            String str = "";
            if (model.getNetWeight() == null || model.getNetWeight().compareTo(BigDecimal.valueOf(0)) < 0) {
                return "重量必须要大于0！";
            }
            if (model == null) {
                return "参数不允许为空！";
            }
            if (StringUtils.isNotEmpty(model.getPredictionNo())) {
                //============预报验证：开始============
                PreStorageScale storageScale = preStorageScaleMapper.selectByPrimaryKey(model.getPredictionNo());
                if (storageScale == null || storageScale.getPredictionNo() == null) {
                    return "预报编号[" + model.getPredictionNo() + "]查不到对应的预报数据，请重新做预报或选择预报！";
                }
                if (DbConstants.STORAGE_SCALE_VALUE_INVALID.equals(storageScale.getValueFlag())) {
                    return "预报编号[" + model.getPredictionNo() + "]对应的预报已经[作废]，请重新做预报或选择预报！";
                }
                if (StringUtils.isEmpty(storageScale.getPackageNo())) {
                    return "预报的顺序号不允许为空，请重新选择预报！";
                }
                if (StringUtils.isEmpty(storageScale.getBlockNum())) {
                    return "预报的总支数不允许为空，请重新选择预报！";
                }
                if (DbConstants.STORAGE_SCALE_VALUE_USED.equals(storageScale.getValueFlag())) {
                    //2021年10月26日 添加预报的使用次数的限制，在预报完成后，还可以手动补量
                    MeterWorkStorageActual actualCondition = new MeterWorkStorageActual();
                    actualCondition.setPredictionNo(storageScale.getPredictionNo());
                    actualCondition.setValueFlag(DbConstants.STORAGE_ACTUAL_VALUE_VALID);
                    List<MeterWorkStorageActual> actualList = meterWorkStorageActualMapper.selectByParameters(FieldsCollector.beanToMap(actualCondition));
                    if (ListUtils.isNotEmpty(actualList) && actualList.size() >= Integer.parseInt(storageScale.getBlockNum())) {
                        return "预报编号[" + model.getPredictionNo() + "]对应的预报已经[使用完成]，且已生产支数[ " + actualList.size() + " ]" +
                                "大于或等于预报总支数[" + storageScale.getBlockNum() + "]，请重新做预报或选择预报！";
                    }
                }

                MeterWorkStorageActual InsertStorage = new MeterWorkStorageActual();
                //============预报验证：结束============
                BeanUtils.copyProperties(model, InsertStorage);
                BeanUtils.copyProperties(storageScale, InsertStorage);
                //清空预报的相关数据影响
                InsertStorage.setUpdateManName(null);
                InsertStorage.setUpdateManNo(null);
                InsertStorage.setUpdateTime(null);
                //生产时间；班次；班组
                InsertStorage.setProductDate(model.getProductDate());
                InsertStorage.setMeterClass(model.getMeterClass());
                InsertStorage.setMeterGroup(model.getMeterGroup());
                InsertStorage.setMemo(model.getMemo());

                //计量点；计量员
                InsertStorage.setBaseSpotNo(model.getBaseSpotNo());
                InsertStorage.setBaseSpotName(model.getBaseSpotName());
                InsertStorage.setCreateTime(new Date());
                InsertStorage.setCreateManNo(model.getCreateManNo());
                InsertStorage.setCreateManName(model.getCreateManName());
                //炉号、MES炉号、顺序炉号处理
                InsertStorage = calculateHeatNo(InsertStorage);

                //============顺序号验证及预报更新：开始============
//                热送磅预报支数卡控：
//                第一次 顺序号是1 ，总支数是20，那么做到20只的时候结束预报；
//                第二次 顺序号是21，总支数是30，那么做到第51只的时候结束预报；
                String strPackageNo = "";
                //注意：若是实绩维护页面新增的数据，则顺序号以界面的为准，即model.getPackageNo()不为null；计量界面只传了预报编号及必要的计量信息上来
                if (StringUtils.isEmpty(model.getPackageNo())) {
                    strPackageNo = meterWorkStorageActualMapper.selectMaxPackgeNo(storageScale.getPredictionNo());

                    if (StringUtils.isEmpty(strPackageNo) || (new BigDecimal(strPackageNo)).compareTo(new BigDecimal(storageScale.getPackageNo())) < 0) {
                        strPackageNo = storageScale.getPackageNo();
                        InsertStorage.setPackageNo(storageScale.getPackageNo());
                    } else {
                        InsertStorage.setPackageNo(strPackageNo);
                    }
                } else {
                    strPackageNo = model.getPackageNo();
                    InsertStorage.setPackageNo(model.getPackageNo());
                }
                if (DbConstants.STORAGE_SCALE_VALUE_NOTUSE.equals(storageScale.getValueFlag())) {
                    storageScale.setValueFlag(DbConstants.STORAGE_SCALE_VALUE_INUSE);
                    preStorageScaleMapper.updateByPrimaryKeySelective(storageScale);
                }
                //2021年11月17日 从strPackageNo调整为strPackageNoEnd
                String strPackageNoEnd = meterWorkStorageActualMapper.selectCountPackgeNo(storageScale.getPredictionNo());
                if (StringUtils.isNotEmpty(strPackageNoEnd)
                        && (strPackageNoEnd.equals(storageScale.getBlockNum()) || Integer.parseInt(strPackageNoEnd) > Integer.parseInt(storageScale.getBlockNum()))) {
                    //当次顺序号大于/等于总支数，则预报完成；
                    storageScale.setValueFlag(DbConstants.STORAGE_SCALE_VALUE_USED);
                    preStorageScaleMapper.updateByPrimaryKeySelective(storageScale);
                }
                //============顺序号验证及预报更新：结束============

                String maxID = comBaseInfoMapper.getConfigID("meter_work_storage_actual", "actual_no");
                InsertStorage.setActualNo(maxID);
                InsertStorage.setValueFlag(DbConstants.STORAGE_ACTUAL_VALUE_VALID);
                InsertStorage.setCreateTime(new Date());
                meterWorkStorageActualMapper.insertSelective(InsertStorage);
                //保存图片
                SaveImg(InsertStorage);
                //返回编号
                str = InsertStorage.getActualNo() + "#！炉号:" + InsertStorage.getHeatNo()
                        + ";顺序号:" + InsertStorage.getPackageNo() + ";净重:" + InsertStorage.getNetWeight() + "kg;";
                if (StringUtils.isNotEmpty(InsertStorage.getBlockNum()) && StringUtils.isNotEmpty(InsertStorage.getPackageNo())) {
                    int iWarning = Integer.parseInt(InsertStorage.getBlockNum()) - Integer.parseInt(InsertStorage.getPackageNo());
                    if (iWarning == 5 || iWarning == 10) {
                        str = str + ";" + iWarning + "支报警";
                    }
                }
                SyncDataToMes00031(InsertStorage);
                SyncDataToMes00033(InsertStorage);
                return str;
            } else {
                //=============================无预报保存计量实绩==========================
                MeterWorkStorageActual InsertStorage = new MeterWorkStorageActual();
                //将前端界面的实体copy一份，取重量，班次班组等信息
                BeanUtils.copyProperties(model, InsertStorage);
                InsertStorage.setCreateTime(new Date());
                InsertStorage.setValueFlag(DbConstants.STORAGE_ACTUAL_VALUE_VALID);
                String maxID = comBaseInfoMapper.getConfigID("meter_work_storage_actual", "actual_no");
                InsertStorage.setActualNo(maxID);
                InsertStorage.setCreateTime(new Date());
                meterWorkStorageActualMapper.insertSelective(InsertStorage);
                SyncDataToMes00031(InsertStorage);
                SyncDataToMes00033(InsertStorage);
                //保存图片
                SaveImg(InsertStorage);
                return InsertStorage.getActualNo() + "#！无预报保存数据，净重：" + InsertStorage.getNetWeight() + "kg，请及时匹配预报数据";
            }
        } catch (Exception ex) {
            throw ex;
        }
    }

    /**
     * 热送向接口表中新增数据
     *
     * @return
     */
    public String SyncDataToMes00031(MeterWorkStorageActual storageActual) {
        String str = "";
        try {
            if (!"00031".equals(storageActual.getBaseSpotNo())) {
                return str;
            }
            if (storageActual.getNetWeight() != null
                    && storageActual.getNetWeight().compareTo(new BigDecimal(1000)) > 0) {
                LgWgt lgWgt = new LgWgt();
                lgWgt = assignmentLgWgt(storageActual, lgWgt);
                String maxId = lgWgtMapper.queryMaxId();
                lgWgt.setSeq(Long.valueOf(maxId));
                lgWgt.setInTime(PublicMethod.dateToStringYYYMMDDSS(new Date()));
                lgWgtMapper.insertSelective(lgWgt);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            throw ex;
        }
        return str;
    }


    /**
     * 使用实绩表字段给接口表字段赋值
     *
     * @param storageActual 实绩表字段;数据源source
     * @param lgWgt         接口表字段；目标实体target
     * @return
     */
    private LgWgt assignmentLgWgt(MeterWorkStorageActual storageActual, LgWgt lgWgt) {
        lgWgt.setWgt(storageActual.getNetWeight().intValue());
        if (StringUtils.isNotEmpty(storageActual.getPackageNo())) {
            lgWgt.setGxNo(Short.valueOf(storageActual.getPackageNo()));
        }
        if (StringUtils.isNotEmpty(storageActual.getPackageNo())) {
            lgWgt.setGxNo(Short.valueOf(storageActual.getPackageNo()));
        }
        lgWgt.setStatus(Short.valueOf("0"));
        if (StringUtils.isNotEmpty(storageActual.getMeterClass())) {
            lgWgt.setBc(storageActual.getMeterClass());
        }
        if (StringUtils.isNotEmpty(storageActual.getMeterGroup())) {
            lgWgt.setBz(storageActual.getMeterGroup());
        }
        if (StringUtils.isNotEmpty(storageActual.getSpecName())) {
            lgWgt.setGg(storageActual.getSpecName());
        }
        if (StringUtils.isNotEmpty(storageActual.getGradeName())) {
            lgWgt.setGz(storageActual.getGradeName());
        }
        if (storageActual.getTheoreticalWeight() != null) {
            lgWgt.setLlzl(storageActual.getTheoreticalWeight().shortValue());
        }
        if (StringUtils.isNotEmpty(storageActual.getHeatNo())) {
            lgWgt.setSmpLot(storageActual.getHeatNo());
        }
        return lgWgt;
    }

    /**
     * 热送向接口表中新增数据
     *
     * @return
     */
    public String SyncDataToMes00033(MeterWorkStorageActual storageActual) {
        String str = "";
        try {
            if (!"00033".equals(storageActual.getBaseSpotNo())) {
                return str;
            }
            if (storageActual.getNetWeight() != null
                    && storageActual.getNetWeight().compareTo(new BigDecimal(1000)) > 0) {
                RsBcread rsBcread = new RsBcread();
                rsBcread.setXh(BigDecimal.valueOf(Integer.parseInt(storageActual.getActualNo().substring(3))));
                rsBcread.setZhonglian(storageActual.getNetWeight().intValue());
                rsBcreadMapper.insertSelective(rsBcread);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            throw ex;
        }
        return str;
    }

    /**
     * 批量修改数据
     *
     * @param models
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String doUpdateClient(List<MeterWorkStorageActual> models) {
        String str = "";
        String strOprateType = "";
        try {
            if (ListUtils.isEmpty(models)) {
                return "必须选择一条数据，再进行审核或修改！";
            }
            if (models.size() > 999) {
                return "每次最多审核1000！";
            }
            if (models.size() > 1) {
                for (MeterWorkStorageActual storageActual : models) {
                    storageActual.setPackageNo(null);
//                    storageActual.setGrossWeight(null);
//                    storageActual.setReferWeight(null);
//                    storageActual.setTareWeight(null);
//                    storageActual.setNetWeight(null);
//                    storageActual.setActualWeight(null);
                }
            }
            for (MeterWorkStorageActual storageActual : models) {
                if (StringUtils.isEmpty(storageActual.getActualNo())) {
                    return "主键编号不允许为空！";
                }
                if (StringUtils.isEmpty(storageActual.getUpdateManName()) || StringUtils.isEmpty(storageActual.getUpdateManNo())) {
                    return "修改人名称及修改人编码不允许为空！";
                }
                //用钢号字段判断是否为作废或者还原
                if (!StringUtils.isEmpty(storageActual.getGradeName())) {
                    str = checkAddAndUpdate(storageActual);
                    if (StringUtils.isNotEmpty(str)) {
                        return str;
                    }
                }
                //数据审核;将前端传进进来的“审核”标志位转换为“1”
                if ("审核".equals(storageActual.getCheckFlag())) {
                    strOprateType = "审核";
                    if (StringUtils.isEmpty(storageActual.getCheckManName()) || StringUtils.isEmpty(storageActual.getCheckManNo())) {
                        return "审核人编码及审核人姓名不允许为空！";
                    }
                    storageActual.setCheckTime(new Date());
                    storageActual.setCheckFlag("1");
                }
            }
            for (MeterWorkStorageActual storageActual : models) {
                //修改前的数据
                MeterWorkStorageActual upBefore = meterWorkStorageActualMapper.selectByPrimaryKey(storageActual.getActualNo());

                //炉号、MES炉号、顺序炉号处理
                storageActual = calculateHeatNo(storageActual);
                storageActual.setUpdateTime(new Date());
                meterWorkStorageActualMapper.updateByPrimaryKeySelective(storageActual);

                if (!"审核".equals(strOprateType)) {
                    //添加日志记录
                    MeterBaseOperationLog operationLog = new MeterBaseOperationLog();
                    operationLog.setOperationPage("热送磅实绩维护");
                    operationLog.setOperationFunction("数据修改");
                    insertOperateLog(upBefore, operationLog);
                }
            }
            //更新单只计量重量表
            if ("审核".equals(models.get(0).getCheckFlag()) || "1".equals(models.get(0).getCheckFlag())) {
                editSingleWgt(models);
            }
        } catch (MarkerMetException e) {
            throw e;
        } catch (Exception ex) {
            ex.printStackTrace();
            throw ex;
        }
        return str;
    }

    /**
     * 批量修改数据
     *
     * @param models
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String doUpdateClientXH(List<MeterWorkStorageActual> models) {
        String str = "";
        try {
            if (ListUtils.isEmpty(models)) {
                return "必须选择一条数据，再进行修改！";
            }
            for (MeterWorkStorageActual storageActual : models) {
                if (StringUtils.isEmpty(storageActual.getActualNo())) {
                    return "主键编号不允许为空！";
                }
                if (StringUtils.isEmpty(storageActual.getUpdateManName()) || StringUtils.isEmpty(storageActual.getUpdateManNo())) {
                    return "修改人名称及修改人编码不允许为空！";
                }
            }
            for (MeterWorkStorageActual storageActual : models) {
                //修改前的数据
                MeterWorkStorageActual upBefore = meterWorkStorageActualMapper.selectByPrimaryKey(storageActual.getActualNo());

                storageActual.setUpdateTime(new Date());
                meterWorkStorageActualMapper.updateByPrimaryKeySelective(storageActual);

                //添加日志记录
                MeterBaseOperationLog operationLog = new MeterBaseOperationLog();
                operationLog.setOperationPage("热送磅实绩维护");
                operationLog.setOperationFunction("修改序号");
                insertOperateLog(upBefore, operationLog);
            }
        } catch (MarkerMetException e) {
            throw e;
        } catch (Exception ex) {
            ex.printStackTrace();
            throw ex;
        }
        return str;
    }


    /**
     * 重新计算一次炉号
     * 1、将炉号从后截取8位作为MES炉号；
     * 2、MES炉号+三位顺序号 作为坯料号，顺序号不够3位前面用0补位
     *
     * @param storageActual
     */
    private MeterWorkStorageActual calculateHeatNo(MeterWorkStorageActual storageActual) {
        if (StringUtils.isNotEmpty(storageActual.getHeatNo()) && storageActual.getHeatNo().length() > 8) {
            storageActual.setHeatNoMes(storageActual.getHeatNo().substring(storageActual.getHeatNo().length() - 8));
            int iMaxHeatNoSeq = meterWorkStorageActualMapper.selectMaxHeatNoSeq(storageActual.getHeatNo());
            storageActual.setHeatNoSeq(storageActual.getHeatNoMes() + String.format("%03d", iMaxHeatNoSeq));
        }
        return storageActual;
    }

    /**
     * 向单只计量表中插入数据;
     * 计算同计量点、同规格、同钢种、同班次单支平均重量
     *
     * @param models
     * @return
     */
    private String editSingleWgt(List<MeterWorkStorageActual> models) {
        String str = "";
        try {
            List<MeterWorkStorageActual> storageActualList = meterWorkStorageActualMapper.selectCheckGroup(models);
            for (MeterWorkStorageActual actual : storageActualList) {
                MeterWorkStorageSingleWgt storageSingleWgt = new MeterWorkStorageSingleWgt();
                storageSingleWgt.setBaseSpotNo(actual.getBaseSpotNo());
                storageSingleWgt.setBaseSpotName(actual.getBaseSpotName());
                storageSingleWgt.setGradeNo(actual.getGradeNo());
                storageSingleWgt.setGradeName(actual.getGradeName());
                storageSingleWgt.setSpecNo(actual.getSpecNo());
                storageSingleWgt.setSpecName(actual.getSpecName());
                storageSingleWgt.setMeterClass(actual.getMeterClass());
                storageSingleWgt.setWeightType("0");
                storageSingleWgt.setValueFlag("1");
                List<MeterWorkStorageSingleWgt> storageSingleWgtList = meterWorkStorageSingleWgtMapper.selectByParameters(FieldsCollector.beanToMap(storageSingleWgt));
                if (ListUtils.isEmpty(storageSingleWgtList)) {
                    String maxID = comBaseInfoMapper.getConfigID("meter_work_storage_single_wgt", "single_wgt_no");
                    storageSingleWgt.setSingleWgtNo(maxID);
                    storageSingleWgt.setSingleWeight(actual.getTheoreticalWeight());
                    storageSingleWgt.setProductDate(models.get(0).getProductDate());
                    storageSingleWgt.setCreateManName(models.get(0).getCheckManName());
                    storageSingleWgt.setCreateManNo(models.get(0).getCheckManNo());
                    storageSingleWgt.setCreateTime(new Date());
                    meterWorkStorageSingleWgtMapper.insertSelective(storageSingleWgt);
                } else {
                    storageSingleWgt.setSingleWeight(actual.getTheoreticalWeight());
                    storageSingleWgt.setProductDate(models.get(0).getProductDate());
                    storageSingleWgt.setUpdateManName(models.get(0).getCheckManName());
                    storageSingleWgt.setUpdateManNo(models.get(0).getCheckManNo());
                    storageSingleWgt.setUpdateTime(new Date());
                    meterWorkStorageSingleWgtMapper.updateByPrimaryKeySelective(storageSingleWgt);
                }

            }
        } catch (Exception ex) {
            ex.printStackTrace();
            throw ex;
        }
        return str;
    }

    /**
     * 数据新增或者修改前的数据校验
     *
     * @param storageActual
     * @return
     */
    private String checkAddAndUpdate(MeterWorkStorageActual storageActual) {
        String str = "";
        try {
            if (StringUtils.isEmpty(storageActual.getPredictionNo())) {
                return "预报编号不允许为空！";
            }
            if (StringUtils.isEmpty(storageActual.getBlockNum())) {
                return "总支数不允许为空！";
            }
            if (StringUtils.isEmpty(storageActual.getMeterClass())) {
                return "班次不允许为空！";
            }
            if (StringUtils.isEmpty(storageActual.getGradeName())) {
                return "钢种名称不允许为空！";
            }
            if (StringUtils.isEmpty(storageActual.getHeatNo())) {
                return "炉号不允许为空！";
            }
            if (StringUtils.isEmpty(storageActual.getSpecName())) {
                return "规格名称不允许为空！";
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            throw ex;
        }
        return str;
    }


    /**
     * C#端热送磅分组数据查询
     *
     * @param params
     * @return
     */
    @Override
    public List<MeterWorkStorageActual> doQueryGroup(HashMap params) {
        return meterWorkStorageActualMapper.doQueryGroup(params);
    }

    /**
     * C#端热送磅审核数据查询
     *
     * @param params
     * @return
     */
    @Override
    public List<MeterWorkStorageActual> doQueryCheckCount(HashMap params) {
        return meterWorkStorageActualMapper.doQueryCheckCount(params);
    }

    /**
     * @param upBefore     修改前的数据
     * @param operationLog 操作日志实体：此处传界面及
     */
    public void insertOperateLog(MeterWorkStorageActual upBefore, MeterBaseOperationLog operationLog) {

        //修改后的数据
        MeterWorkStorageActual upAfter = meterWorkStorageActualMapper.selectByPrimaryKey(upBefore.getActualNo());
        //记录日志数据
        operationLog.setCreateManNo(upAfter.getUpdateManNo());
        operationLog.setCreateManName(upAfter.getUpdateManName());
        operationLog.setOperationId(upBefore.getActualNo());
        operationLog.setOperationPredictionNo(upBefore.getPredictionNo());
        operationLog.setOperationCarnNo(upBefore.getHeatNo() + " | " + upBefore.getPackageNo());
        operationLog.setLogType("热送磅");
        operationLog.setLogTypeCode("001002004");
        meterBaseOperationLogService.addComparePropertiesLog(upBefore, upAfter, operationLog);
    }
}
