package com.steerinfo.ems.trmworkprocmaterialvalue.service.impl;

import com.steerinfo.ems.Utils.BigDecimalUtil;
import com.steerinfo.ems.Utils.DateUtils;
import com.steerinfo.ems.formula.model.Formula;
import com.steerinfo.ems.formula.service.IFormulaService;
import com.steerinfo.ems.ifmesemsswapfile.model.IfMesEmsSwapfile;
import com.steerinfo.ems.ifmesemsswapfile.service.IIfMesEmsSwapfileService;
import com.steerinfo.ems.trmmaterial.mapper.TRmMaterialMapper;
import com.steerinfo.ems.trmmaterial.model.TRmMaterial;
import com.steerinfo.ems.trmmaterial.service.ITRmMaterialService;
import com.steerinfo.ems.trmworkproc.service.ITRmWorkprocService;
import com.steerinfo.ems.trmworkprocmaterial.model.TRmWorkprocMaterial;
import com.steerinfo.ems.trmworkprocmaterial.service.ITRmWorkprocMaterialService;
import com.steerinfo.ems.trmworkprocmaterialvalue.mapper.TRmWorkprocMaterialValueMapper;
import com.steerinfo.ems.trmworkprocmaterialvalue.model.TRmWorkprocMaterialValue;
import com.steerinfo.ems.trmworkprocmaterialvalue.service.ITRmWorkprocMaterialValueService;
import com.steerinfo.ems.trmworkprocproductvalue.service.ITRmWorkprocProductValueService;
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 org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * TRmWorkprocMaterialValue服务实现：
 * @author generator
 * @version 1.0-SNAPSHORT 2019-10-17 04:39
 * 类描述
 * 修订历史：
 * 日期：2019-10-17
 * 作者：generator
 * 参考：
 * 描述：TRmWorkprocMaterialValue服务实现
 * @see null
 * @Copyright 湖南视拓信息技术股份有限公司. All rights reserved.
 */
@Service(value = "tRmWorkprocMaterialValueService")
public class TRmWorkprocMaterialValueServiceImpl extends BaseServiceImpl<TRmWorkprocMaterialValue, HashMap<String, Object>> implements ITRmWorkprocMaterialValueService {

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

    @Autowired
    private TRmWorkprocMaterialValueMapper tRmWorkprocMaterialValueMapper;
	@Autowired
    IIfMesEmsSwapfileService ifMesEmsSwapfileService;
	@Autowired
    ITRmWorkprocMaterialService tRmWorkprocMaterialService;
	@Autowired
    IFormulaService  formulaService;
    @Autowired
    ITRmWorkprocProductValueService tRmWorkprocProductValueService;
    @Autowired
    TRmMaterialMapper tRmMaterialMapper;
    @Autowired
    ITRmMaterialService tRmMaterialService;
    @Autowired
    ITRmWorkprocService tRmWorkprocService;
    
    @Override
    protected IBaseMapper<TRmWorkprocMaterialValue, HashMap<String, Object>> getMapper() {
        return tRmWorkprocMaterialValueMapper;
    }

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

	@Override
	public TRmWorkprocMaterialValue updateForUKey(TRmWorkprocMaterialValue tRmWorkprocMaterialValue) {
		this.getMapper().updateByPrimaryKeySelective(tRmWorkprocMaterialValue);
		return tRmWorkprocMaterialValueMapper.selectByUPrimaryKey(tRmWorkprocMaterialValue);
	}

	public int updateValue(HashMap<String, Object> m) {
		return tRmWorkprocMaterialValueMapper.updateValue(m);
	}

	public int insertValue(HashMap<String, Object> m) {
		return tRmWorkprocMaterialValueMapper.insertValue(m);
	}

	public int deleteByPrimaryKey(HashMap<String, Object> m) {
		return tRmWorkprocMaterialValueMapper.deleteByPrimaryKey(m);
	}

	/**
	 * 将IF_MES_EMS_SWAPFILE中未读取的数据进行处理，将数据保存至T_RM_WORKPROC_MATERIAL_VALUE
	 */
	public void synchronousData() {
		int success = 0;
		int failure = 0;
        int delSize = 0;
        int abandon = 0;
		HashMap<String, Object> selectObj = new HashMap<String, Object>();
		selectObj.put("type", "1");
        List<IfMesEmsSwapfile> list = ifMesEmsSwapfileService.selectNewMaterial(selectObj); // 获取未读取的投入数据
		for (int i = 0; i < list.size(); i++) {
			IfMesEmsSwapfile swapfile = list.get(i);
			// 找出需要修改的项
			if (swapfile.getStatus().equals("9")) {
				// 在T_RM_WORKPROC_MATERIAL中查找匹配的itemId
				HashMap<String, Object> itemObj = new HashMap<String, Object>();
				itemObj.put("mesMaterialcode", swapfile.getMaterialcode());
				itemObj.put("mesProdline", swapfile.getProdline());
				itemObj.put("itemtype", "R");
                List<TRmWorkprocMaterial> relationItem = tRmWorkprocMaterialService.getMesItemid(itemObj);
                if (relationItem.size() == 1 && relationItem.get(0).getCode().equals("0")) {
                	String itemid = relationItem.get(0).getItemid();
                	// 更新数据项
                	HashMap<String, Object> delObj = new HashMap<String, Object>();
                    delObj.put("clock", DateUtils.dateToString(swapfile.getProdate(), "yyyy-MM-dd"));
                    delObj.put("itemid", itemid);
                    delObj.put("timegranid", "DAY");
                    TRmWorkprocMaterialValue tRmWorkprocMaterialValue = tRmWorkprocMaterialValueMapper.selectByPrimaryKey(delObj);
                    if (tRmWorkprocMaterialValue != null) {
                    	delSize++;
                        logger.info("[更改][投入数据更改]" + DateUtils.dateStr(new Date(), "yyyy-MM-dd HH:mm:ss") + " ：T_RM_WORKPROC_MATERIAL_VALUE表中数据将要更新;");
                        logger.info("将要更改的原数据项为：" + tRmWorkprocMaterialValue.toString());
                        delObj.put("materialcode", relationItem.get(0).getMesMaterialcode());
                        delObj.put("prodline", relationItem.get(0).getMesProdline());
                        Map<String, Object> vl =  tRmWorkprocMaterialValueMapper.getItemval(delObj);
                        Double val = Double.valueOf(vl.get("VAL").toString());
                        String ids = vl.get("IDS")==null?"":vl.get("IDS").toString();
                        if(val>0){
                        	tRmWorkprocMaterialValue.setActualvalue(new BigDecimal(val));
                            if(tRmWorkprocMaterialValue.getCorrectvalue()!=null){
                            	tRmWorkprocMaterialValue.setApportvalue(new BigDecimal(val).add(tRmWorkprocMaterialValue.getCorrectvalue()));
    						}else{
    							tRmWorkprocMaterialValue.setApportvalue(new BigDecimal(val));
    						}
                            tRmWorkprocMaterialValue.setBz("MES-" + new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(new Date()) + " fid:" + ids);
                            tRmWorkprocMaterialValueMapper.updateByPrimaryKeySelective(tRmWorkprocMaterialValue);
                        }else{
                        	tRmWorkprocMaterialValueMapper.deleteByPrimaryKey(delObj);
                        }
                    }
                }
			}
        }
		for (int i = 0; i < list.size(); i++) {
			IfMesEmsSwapfile swapfile = list.get(i);
			// 在T_RM_WORKPROC_MATERIAL中查找匹配的itemId
			HashMap<String, Object> itemObj = new HashMap<String, Object>();
			itemObj.put("mesMaterialcode", swapfile.getMaterialcode());
			itemObj.put("mesProdline", swapfile.getProdline());
			itemObj.put("itemtype", "R");
			List<TRmWorkprocMaterial> relationItem = tRmWorkprocMaterialService.getMesItemid(itemObj);
			if (relationItem.size() > 1) {
				failure++;
				logger.info("[错误][多条的关联项]" + DateUtils.dateStr(new Date(), "yyyy-MM-dd HH:mm:ss") + " ：IF_MES_EMS_SWAPFILE中 FID 为 " + swapfile.getFid() + " 的数据在T_RM_WORKPROC_MATERIAL中找到" + relationItem.size() + "条对应关系;( MES物料编码:" + swapfile.getMaterialcode() + " ,MES物料名称:" + swapfile.getMaterialname() + " ,MES产线编码：" + swapfile.getProdline() + " )");
				logger.info("关联项：");
                for (int u = 0; u < relationItem.size(); u++) {
                    logger.info(relationItem.get(u).getItemid()+";");
                }
			} else {
				TRmWorkprocMaterial twm = new TRmWorkprocMaterial();
				// 自动新增原材料、以及工序原材料关联
				if(relationItem.size() < 1) {
					logger.info("[错误][未找到关联项]" + DateUtils.dateStr(new Date(), "yyyy-MM-dd HH:mm:ss") + " ：IF_MES_EMS_SWAPFILE中 FID 为 " + swapfile.getFid() + " 的数据在T_RM_WORKPROC_MATERIAL中未找到对应关系;( MES物料编码:" + swapfile.getMaterialcode() + " ,MES物料名称:" + swapfile.getMaterialname() + " ,MES产线编码：" + swapfile.getProdline() + " )，系统自动新增" );
					String bcode = swapfile.getMaterialcode(); // MES物料编码
					String mname = swapfile.getMaterialname(); // MES物料名称
					String mline = swapfile.getProdline(); // MES产线编码
					Map<String,Object> mp = new HashMap<String,Object>();
					mp.put("bcode", bcode);
					mp.put("name", mname);
					String mid = ""; // EMS原料ID
					List<TRmMaterial> lm = tRmMaterialMapper.selectByParameters(mp);
					if (lm!=null && lm.size() >0){
						mid = lm.get(0).getId();
					} else {
						TRmMaterial model = new TRmMaterial();
						String maxId = tRmMaterialService.getMaxId();
				        maxId = String.format("%03d", Integer.parseInt(maxId) + 1);
				        model.setId("Y"+maxId);
				        model.setSeqno(maxId);
				        model.setName(mname);
				        model.setBcode(bcode);
				        model.setRemark("MES自动新增");
				        model.setCreatetime(new Date());
				        model.setCreateman("系统");
				        model = tRmMaterialService.add(model);
				        mid = model.getId();
					}
					String itemid = "";
					String wid = "";
					//if (mline.endsWith("GX1")) { // 一高线-ZY9102
					//	// MES工序与EMS工序没有关联，这里防止修改工序后造成数据错误，增加一次判断，下同
					//	TRmWorkproc tw = tRmWorkprocService.getById("ZY9102");
					//	if(tw!=null && tw.getName().equalsIgnoreCase("一高线")){
					//		wid = "ZY9102";
					//		itemid = wid + mid + "R";
					//	}
					//} else if (mline.endsWith("GX3")) { // 三高线-ZY9103
					//	// MES工序与EMS工序没有关联，这里防止修改工序后造成数据错误，增加一次判断，下同
					//	TRmWorkproc tw = tRmWorkprocService.getById("ZY9103");
					//	if(tw!=null && tw.getName().equalsIgnoreCase("三高线")){
					//		wid = "ZY9103";
					//		itemid = wid + mid + "R";
					//	}
					//} else if (mline.endsWith("GX2")) { // 二高线-ZY9201
					//	// MES工序与EMS工序没有关联，这里防止修改工序后造成数据错误，增加一次判断，下同
					//	TRmWorkproc tw = tRmWorkprocService.getById("ZY9201");
					//	if(tw!=null && tw.getName().equalsIgnoreCase("二高线")){
					//		wid = "ZY9201";
					//		itemid = wid + mid + "R";
					//	}
					//} else if(mline.endsWith("GX4") || mline.endsWith("GX5")) { // 四五高线
					//	TRmWorkproc tw = tRmWorkprocService.getById("ZY9202");
					//	if(tw!=null && tw.getName().equalsIgnoreCase("四五高线")){
					//		wid = "ZY9202";
					//		itemid = wid + mid + "R";
					//	}
					//} else if(mline.endsWith("QT1")) { // 一球团-ZY6100
					//	TRmWorkproc tw = tRmWorkprocService.getById("ZY6100");
					//	if(tw!=null && tw.getName().equalsIgnoreCase("一球团")){
					//		wid = "ZY6100";
					//		itemid = wid + mid + "R";
					//	}
					//} else if(mline.endsWith("QT2")) { // 二球团-ZY6200
					//	TRmWorkproc tw = tRmWorkprocService.getById("ZY6200");
					//	if(tw!=null && tw.getName().equalsIgnoreCase("二球团")){
					//		wid = "ZY6200";
					//		itemid = wid + mid + "R";
					//	}
					//} else if(mline.endsWith("BC1")) { // 一棒材-ZY9101
					//	wid = "ZY9101";
					//	TRmWorkproc tw = tRmWorkprocService.getById(wid);
					//	if(tw!=null && tw.getName().equalsIgnoreCase("棒材线")){
					//		itemid = wid + mid + "R";
					//	}
					//} else if(mline.endsWith("GL3")) { // 二炼铁2#1280高炉-ZY7202
					//	wid = "ZY7202";
					//	TRmWorkproc tw = tRmWorkprocService.getById(wid);
					//	if(tw!=null && tw.getName().equalsIgnoreCase("二炼铁2#1280高炉")){
					//		itemid = wid + mid + "R";
					//	}
					//} else if(mline.endsWith("JH1")) { // 一焦化-ZY4100
					//	wid = "ZY4100";
					//	TRmWorkproc tw = tRmWorkprocService.getById(wid);
					//	if(tw!=null && tw.getName().equalsIgnoreCase("一焦化")){
					//		itemid = wid + mid + "R";
					//	}
					//} else if(mline.endsWith("JH2")) { // 二焦化-ZY4200
					//	wid = "ZY4200";
					//	TRmWorkproc tw = tRmWorkprocService.getById(wid);
					//	if(tw!=null && tw.getName().equalsIgnoreCase("二焦化")){
					//		itemid = wid + mid + "R";
					//	}
					//} else if(mline.endsWith("LG1")) { // 一炼钢 - ZY8100
					//	wid = "ZY8100";
					//	TRmWorkproc tw = tRmWorkprocService.getById(wid);
					//	if(tw!=null && tw.getName().equalsIgnoreCase("一炼钢")){
					//		itemid = wid + mid + "R";
					//	}
					//} else if(mline.endsWith("LG2")) { // 二炼钢-ZY8200
					//	wid = "ZY8200";
					//	TRmWorkproc tw = tRmWorkprocService.getById(wid);
					//	if(tw!=null && tw.getName().equalsIgnoreCase("二炼钢")){
					//		itemid = wid + mid + "R";
					//	}
					//}
					if(!itemid.isEmpty() && !mid.isEmpty()){
						twm = tRmWorkprocMaterialService.getById(itemid);
						if(twm!=null){
							if(twm.getMesProdline() == null || twm.getMesProdline().isEmpty()){
								twm.setMesProdline(mline);
								twm.setMesMaterialcode(bcode);
							}else{
								twm.setMesProdline(twm.getMesProdline() + "," + mline);
								twm.setMesMaterialcode(bcode);
							}
							twm = tRmWorkprocMaterialService.modify(twm);
						}else{
							twm = new TRmWorkprocMaterial();
							twm.setId(itemid);
							twm.setMesMaterialcode(bcode);
							twm.setMaterialid(mid);
							twm.setWorkprocid(wid);
							twm.setUseflag("1");
							twm.setMesProdline(mline);
							twm.setCode("0");
							twm.setSeqno("10");
							twm.setItemtype("R");
							twm.setDigits(Short.valueOf("2"));
							twm.setUnitid("008"); // 单位：吨
							twm.setCreateman("系统");
							twm.setCreatetime(new Date());
							twm = tRmWorkprocMaterialService.add(twm);
							// 增加公式
							Formula formula = new Formula();
					        formula.setClock("202001");
					        formula.setCode(itemid);
					        formula.setDescription(tRmWorkprocMaterialService.getName(itemid));
					        formula.setIsavailable("1");
					        formula.setRevisor("系统");
					        formula.setRevisetime(DateUtils.getCurrentTime("yyyy-MM-dd HH:mm:ss"));
					        formula.setSourcecode("R(T_RM_WORKPROC_MATERIAL_VALUE," + itemid + ")");
					        formula.setTablename("T_RM_WORKPROC_MATERIAL_VALUE");
					        formulaService.add(formula);
						}
						logger.info("[新增成功]" + DateUtils.dateStr(new Date(), "yyyy-MM-dd HH:mm:ss") + " ：T_RM_WORKPROC_MATERIAL的itemid 为 " + itemid);
					} else {
						failure++;
						logger.info("[错误][新增失败]" + DateUtils.dateStr(new Date(), "yyyy-MM-dd HH:mm:ss") + " ：IF_MES_EMS_SWAPFILE中 FID 为 " + swapfile.getFid() + " 的数据在T_RM_WORKPROC_MATERIAL中未找到对应关系;( MES物料编码:" + swapfile.getMaterialcode() + " ,MES物料名称:" + swapfile.getMaterialname() + " ,MES产线编码：" + swapfile.getProdline() + " )" );
						continue;
					}
				} else {
					twm = relationItem.get(0);
				}
                // code = "1" 是由公式生成的项，放弃添加
                if (twm.getCode()!=null && twm.getCode().equals("1")) {
                    abandon++;
                    logger.info("[放弃添加]" + DateUtils.dateStr(new Date(), "yyyy-MM-dd HH:mm:ss") + " ：IF_MES_EMS_SWAPFILE中 FID 为 " + swapfile.getFid() + " 的数据项被配置成由公式自动生成，所以放弃添加。( MES物料编码:" + swapfile.getMaterialcode() + " ,MES物料名称:" + swapfile.getMaterialname() + " ,MES产线编码：" + swapfile.getProdline() + " )");
                    logger.info("关联项：" + twm.toString());
                } else if (twm.getCode()!=null && twm.getCode().equals("0")) {
                    // 数据添加至T_RM_WORKPROC_MATERIAL_VALUE
                    HashMap<String, Object> insertObj = new HashMap<String, Object>();
                    insertObj.put("clock", DateUtils.dateToString(swapfile.getProdate(), "yyyy-MM-dd"));
                    insertObj.put("timegranid", "DAY");
                    insertObj.put("itemid", twm.getItemid());
                    insertObj.put("qty", swapfile.getQty());
                    insertObj.put("fid", swapfile.getFid());
					insertObj.put("userid", "系统");
					insertObj.put("updatetime", DateUtils.dateStr(new Date(), "yyyy-MM-dd HH:mm:ss"));
                    try {
                        int upSize = tRmWorkprocMaterialValueMapper.updateValue(insertObj);
                        if (upSize == 0) {
                            tRmWorkprocMaterialValueMapper.insertValue(insertObj);
                        }
                        success++;
                        // 反写IF_MES_EMS_SWAPFILE的status
                        HashMap<String, Object> updateObj = new HashMap<String, Object>();
                        updateObj.put("fid", swapfile.getFid());
                        updateObj.put("status", "1");
                        ifMesEmsSwapfileService.updateStatus(updateObj);
                    } catch (Exception e) {
                        failure++;
                        logger.info("[错误][添加失败]" + DateUtils.dateStr(new Date(), "yyyy-MM-dd HH:mm:ss") + " ：IF_MES_EMS_SWAPFILE中 FID 为 " + swapfile.getFid() + " 的数据添加至T_RM_WORKPROC_MATERIAL_VALUE时失败;" );
                        logger.info("添加失败的数据为：" + insertObj.toString());
                        e.printStackTrace();
                    }
                    // 如果是昨天之前的数据，重新计算关联项数据
                    try {
                    	Date pdate = new SimpleDateFormat("yyyy-MM-dd").parse(swapfile.getProdate());
                    	Calendar calendar = Calendar.getInstance();
                    	calendar.add(Calendar.DAY_OF_YEAR, -1);
                    	Date yesterday = new SimpleDateFormat("yyyy-MM-dd").parse(new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime()));
                    	if(pdate.before(yesterday)){
                    		formulaService.reCalculate(twm.getItemid(), DateUtils.dateToString(swapfile.getProdate(), "yyyy-MM-dd"), "DAY", DateUtils.dateToString(swapfile.getProdate(), "yyyy-MM-dd"));
                    	}
                    } catch (Exception e) {
                    	e.printStackTrace();
                    }
                }
			}
		}
		logger.info("[投入数据添加完毕]" + DateUtils.dateStr(new Date(), "yyyy-MM-dd HH:mm:ss") + "：数据添加成功" + success + "条(其中修改数据为" + delSize + "条)，放弃" + abandon + "条，失败" + failure + "条;");
	}
	
	/**
	 * 原料购入0数据处理（type=4）
	 */
	public void synchronousData4() {
		int success = 0;
		int failure = 0;
        int delSize = 0;
        int abandon = 0;
		HashMap<String, Object> selectObj = new HashMap<String, Object>();
		selectObj.put("type", "4");
        List<IfMesEmsSwapfile> list = ifMesEmsSwapfileService.selectNewMaterial(selectObj); // 获取未读取的投入数据
		for (int i = 0; i < list.size(); i++) {
			IfMesEmsSwapfile swapfile = list.get(i);
			// 找出需要修改的项
			if (swapfile.getStatus().equals("9")) {
				// 在T_RM_WORKPROC_MATERIAL中查找匹配的itemId
				HashMap<String, Object> itemObj = new HashMap<String, Object>();
				itemObj.put("mesMaterialcode", swapfile.getMaterialcode());
				itemObj.put("workprocid", "ZYG000");
				itemObj.put("itemtype", "R");
				itemObj.put("code", "0");
                List<TRmWorkprocMaterial> relationItem = tRmWorkprocMaterialService.query(itemObj);
                if (relationItem.size() == 1 && relationItem.get(0).getCode().equals("0")) {
                	String itemid = relationItem.get(0).getItemid();
                	// 更新数据项
                	HashMap<String, Object> delObj = new HashMap<String, Object>();
                    delObj.put("clock", DateUtils.dateToString(swapfile.getProdate(), "yyyy-MM-dd"));
                    delObj.put("itemid", itemid);
                    delObj.put("timegranid", "DAY");
                    TRmWorkprocMaterialValue tRmWorkprocMaterialValue = tRmWorkprocMaterialValueMapper.selectByPrimaryKey(delObj);
                    if (tRmWorkprocMaterialValue != null) {
                    	delSize++;
                        logger.info("[更改][原料购入数据更改]" + DateUtils.dateStr(new Date(), "yyyy-MM-dd HH:mm:ss") + " ：T_RM_WORKPROC_MATERIAL_VALUE表中数据将要更新;");
                        logger.info("将要更改的原数据项为：" + tRmWorkprocMaterialValue.toString());
                        tRmWorkprocMaterialValueMapper.deleteByPrimaryKey(delObj);
                    }
                }
			}
		}
		for (int i = 0; i < list.size(); i++) {
			IfMesEmsSwapfile swapfile = list.get(i);
			if(swapfile.getMaterialcode()==null || swapfile.getMaterialcode().trim().isEmpty()){
				failure++;
				logger.info("[错误][物料编码为空]" + DateUtils.dateStr(new Date(), "yyyy-MM-dd HH:mm:ss") + " ：IF_MES_EMS_SWAPFILE中 FID 为 " + swapfile.getFid());
				continue;
			}
			// 在T_RM_WORKPROC_MATERIAL中查找匹配的itemId
			HashMap<String, Object> itemObj = new HashMap<String, Object>();
			itemObj.put("mesMaterialcode", swapfile.getMaterialcode());
			itemObj.put("workprocid", "ZYG000");
			itemObj.put("itemtype", "R");
			itemObj.put("code", "0");
			List<TRmWorkprocMaterial> relationItem = tRmWorkprocMaterialService.query(itemObj);
			if (relationItem.size() > 1) {
				failure++;
				logger.info("[错误][多条的关联项]" + DateUtils.dateStr(new Date(), "yyyy-MM-dd HH:mm:ss") + " ：IF_MES_EMS_SWAPFILE中 FID 为 " + swapfile.getFid() + " 的数据在T_RM_WORKPROC_MATERIAL中找到" + relationItem.size() + "条对应关系;( MES物料编码:" + swapfile.getMaterialcode() + " ,MES物料名称:" + swapfile.getMaterialname() + " ,MES产线编码：" + swapfile.getProdline() + " )");
			} else {
				TRmWorkprocMaterial twm = new TRmWorkprocMaterial();
				// 自动新增原材料、以及工序原材料关联
				if(relationItem.size() < 1) {
					logger.info("[错误][未找到关联项]" + DateUtils.dateStr(new Date(), "yyyy-MM-dd HH:mm:ss") + " ：IF_MES_EMS_SWAPFILE中 FID 为 " + swapfile.getFid() + " 的数据在T_RM_WORKPROC_MATERIAL中未找到对应关系;( MES物料编码:" + swapfile.getMaterialcode() + " ,MES物料名称:" + swapfile.getMaterialname() + " ,MES产线编码：" + swapfile.getProdline() + " )，系统自动新增" );
					String bcode = swapfile.getMaterialcode(); // MES物料编码
					String mname = swapfile.getMaterialname(); // MES物料名称
					String mline = swapfile.getProdline(); // MES产线编码
					Map<String,Object> mp = new HashMap<String,Object>();
					mp.put("bcode", bcode);
					mp.put("name", mname);
					String mid = ""; // EMS原料ID
					List<TRmMaterial> lm = tRmMaterialMapper.selectByParameters(mp);
					if (lm!=null && lm.size() >0){
						mid = lm.get(0).getId();
					} else {
						TRmMaterial model = new TRmMaterial();
						String maxId = tRmMaterialService.getMaxId();
				        maxId = String.format("%03d", Integer.parseInt(maxId) + 1);
				        model.setId("Y"+maxId);
				        model.setSeqno(maxId);
				        model.setName(mname);
				        model.setBcode(bcode);
				        model.setRemark("MES自动新增");
				        model.setCreatetime(new Date());
				        model.setCreateman("系统");
				        model = tRmMaterialService.add(model);
				        mid = model.getId();
					}
					String wid = "ZYG000";
					String itemid = wid + mid + "R";
					if(!itemid.isEmpty() && !mid.isEmpty()){
						twm = tRmWorkprocMaterialService.getById(itemid);
						if(twm!=null){
							if(twm.getMesProdline() == null || twm.getMesProdline().isEmpty()){
								twm.setMesProdline(mline);
								twm.setMesMaterialcode(bcode);
							}else{
								twm.setMesProdline(twm.getMesProdline() + "," + mline);
								twm.setMesMaterialcode(bcode);
							}
							twm = tRmWorkprocMaterialService.modify(twm);
						}else{
							twm = new TRmWorkprocMaterial();
							twm.setId(itemid);
							twm.setMesMaterialcode(bcode);
							twm.setMaterialid(mid);
							twm.setWorkprocid(wid);
							twm.setUseflag("1");
							twm.setMesProdline(mline);
							twm.setCode("0");
							twm.setSeqno("10");
							twm.setItemtype("R");
							twm.setDigits(Short.valueOf("2"));
							twm.setUnitid("008"); // 单位：吨
							twm.setCreateman("系统");
							twm.setCreatetime(new Date());
							twm = tRmWorkprocMaterialService.add(twm);
							// 增加公式
							Formula formula = new Formula();
					        formula.setClock("202001");
					        formula.setCode(itemid);
					        formula.setDescription(tRmWorkprocMaterialService.getName(itemid));
					        formula.setIsavailable("1");
					        formula.setRevisor("系统");
					        formula.setRevisetime(DateUtils.getCurrentTime("yyyy-MM-dd HH:mm:ss"));
					        formula.setSourcecode("R(T_RM_WORKPROC_MATERIAL_VALUE," + itemid + ")");
					        formula.setTablename("T_RM_WORKPROC_MATERIAL_VALUE");
					        formulaService.add(formula);
						}
						logger.info("[新增成功]" + DateUtils.dateStr(new Date(), "yyyy-MM-dd HH:mm:ss") + " ：T_RM_WORKPROC_MATERIAL的itemid 为 " + itemid);
					} else {
						failure++;
						logger.info("[错误][新增失败]" + DateUtils.dateStr(new Date(), "yyyy-MM-dd HH:mm:ss") + " ：IF_MES_EMS_SWAPFILE中 FID 为 " + swapfile.getFid() + " 的数据在T_RM_WORKPROC_MATERIAL中未找到对应关系;( MES物料编码:" + swapfile.getMaterialcode() + " ,MES物料名称:" + swapfile.getMaterialname() + " ,MES产线编码：" + swapfile.getProdline() + " )" );
						continue;
					}
				} else {
					twm = relationItem.get(0);
				}
                // code = "1" 是由公式生成的项，放弃添加
                if (twm.getCode()!=null && twm.getCode().equals("1")) {
                    abandon++;
                    logger.info("[放弃添加]" + DateUtils.dateStr(new Date(), "yyyy-MM-dd HH:mm:ss") + " ：IF_MES_EMS_SWAPFILE中 FID 为 " + swapfile.getFid() + " 的数据项被配置成由公式自动生成，所以放弃添加。( MES物料编码:" + swapfile.getMaterialcode() + " ,MES物料名称:" + swapfile.getMaterialname() + " ,MES产线编码：" + swapfile.getProdline() + " )");
                    logger.info("关联项：" + twm.toString());
                } else if (twm.getCode()!=null && twm.getCode().equals("0")) {
                	Short digits = twm.getDigits() == null ? 2 : twm.getDigits();
                    // 更新数据T_RM_WORKPROC_MATERIAL_VALUE
                	HashMap<String, Object> ids = new HashMap<String, Object>();
                	ids.put("clock", DateUtils.dateToString(swapfile.getProdate(), "yyyy-MM-dd"));
                	ids.put("itemid", twm.getItemid());
                	ids.put("timegranid", "DAY");
                    TRmWorkprocMaterialValue tv = tRmWorkprocMaterialValueMapper.selectByPrimaryKey(ids);
    				if(tv!=null){
    					tv.setActualvalue(swapfile.getQty());
    		            tv.setApportvalue(swapfile.getQty().add(tv.getCorrectvalue()!=null?tv.getCorrectvalue():BigDecimal.ZERO).setScale(digits, RoundingMode.HALF_UP));
    		            tv.setBz("MES-" + new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(new Date()) + " fid:" + swapfile.getFid());
    		            tRmWorkprocMaterialValueMapper.updateByPrimaryKeySelective(tv);
    				}else{
    					tv = new TRmWorkprocMaterialValue();
    					tv.setId(ids);
    		            //计算值
    	            	tv.setActualvalue(swapfile.getQty());
    		            //修正值
    	            	tv.setCorrectvalue(new BigDecimal(0));
    		            //最终值
    	            	tv.setApportvalue(swapfile.getQty());
    	            	tv.setBz("MES-" + new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(new Date()) + " fid:" + swapfile.getFid());
    	            	tRmWorkprocMaterialValueMapper.insert(tv);
    				}
    				success++;
    				// 反写IF_MES_EMS_SWAPFILE的status
                    HashMap<String, Object> updateObj = new HashMap<String, Object>();
                    updateObj.put("fid", swapfile.getFid());
                    updateObj.put("status", "1");
                    ifMesEmsSwapfileService.updateStatus(updateObj);
    				// 如果是昨天之前的数据，重新计算关联项数据
                    try {
                    	Date pdate = new SimpleDateFormat("yyyy-MM-dd").parse(swapfile.getProdate());
                    	Calendar calendar = Calendar.getInstance();
                    	calendar.add(Calendar.DAY_OF_YEAR, -1);
                    	Date yesterday = new SimpleDateFormat("yyyy-MM-dd").parse(new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime()));
                    	if(pdate.before(yesterday)){
                    		formulaService.reCalculate(twm.getItemid(), DateUtils.dateToString(swapfile.getProdate(), "yyyy-MM-dd"), "DAY", DateUtils.dateToString(swapfile.getProdate(), "yyyy-MM-dd"));
                    	}
                    } catch (Exception e) {
                    	e.printStackTrace();
                    }
                }
			}
		}
		logger.info("[原料购入数据添加完毕]" + DateUtils.dateStr(new Date(), "yyyy-MM-dd HH:mm:ss") + "：数据添加成功" + success + "条(其中修改数据为" + delSize + "条)，放弃" + abandon + "条，失败" + failure + "条;");
	}
	
	/**
	 * 原料库存-数据处理（type=5）
	 */
	public void synchronousData5() {
		int success = 0;
		int failure = 0;
        int delSize = 0;
        int abandon = 0;
		HashMap<String, Object> selectObj = new HashMap<String, Object>();
		selectObj.put("type", "5");
        List<IfMesEmsSwapfile> list = ifMesEmsSwapfileService.selectNewMaterial(selectObj); // 获取未读取的投入数据
		for (int i = 0; i < list.size(); i++) {
			IfMesEmsSwapfile swapfile = list.get(i);
			// 找出需要修改的项
			if (swapfile.getStatus().equals("9")) {
				// 在T_RM_WORKPROC_MATERIAL中查找匹配的itemId
				HashMap<String, Object> itemObj = new HashMap<String, Object>();
				itemObj.put("mesMaterialcode", swapfile.getMaterialcode());
				itemObj.put("workprocid", "ZYF000");
				itemObj.put("itemtype", "R");
				itemObj.put("code", "0");
                List<TRmWorkprocMaterial> relationItem = tRmWorkprocMaterialService.query(itemObj);
                if (relationItem.size() == 1 && relationItem.get(0).getCode().equals("0")) {
                	String itemid = relationItem.get(0).getItemid();
                	// 更新数据项
                	HashMap<String, Object> delObj = new HashMap<String, Object>();
                    delObj.put("clock", DateUtils.dateToString(swapfile.getProdate(), "yyyy-MM-dd"));
                    delObj.put("itemid", itemid);
                    delObj.put("timegranid", "DAY");
                    TRmWorkprocMaterialValue tRmWorkprocMaterialValue = tRmWorkprocMaterialValueMapper.selectByPrimaryKey(delObj);
                    if (tRmWorkprocMaterialValue != null) {
                    	delSize++;
                        logger.info("[更改][原料库存数据更改]" + DateUtils.dateStr(new Date(), "yyyy-MM-dd HH:mm:ss") + " ：T_RM_WORKPROC_MATERIAL_VALUE表中数据将要更新;");
                        logger.info("将要更改的原数据项为：" + tRmWorkprocMaterialValue.toString());
                        tRmWorkprocMaterialValueMapper.deleteByPrimaryKey(delObj);
                    }
                }
			}
		}
		for (int i = 0; i < list.size(); i++) {
			IfMesEmsSwapfile swapfile = list.get(i);
			if(swapfile.getMaterialcode()==null || swapfile.getMaterialcode().trim().isEmpty()){
				failure++;
				logger.info("[错误][物料编码为空]" + DateUtils.dateStr(new Date(), "yyyy-MM-dd HH:mm:ss") + " ：IF_MES_EMS_SWAPFILE中 FID 为 " + swapfile.getFid());
				continue;
			}
			// 在T_RM_WORKPROC_MATERIAL中查找匹配的itemId
			HashMap<String, Object> itemObj = new HashMap<String, Object>();
			itemObj.put("mesMaterialcode", swapfile.getMaterialcode());
			itemObj.put("workprocid", "ZYF000");
			itemObj.put("itemtype", "R");
			itemObj.put("code", "0");
			List<TRmWorkprocMaterial> relationItem = tRmWorkprocMaterialService.query(itemObj);
			if (relationItem.size() > 1) {
				failure++;
				logger.info("[错误][多条的关联项]" + DateUtils.dateStr(new Date(), "yyyy-MM-dd HH:mm:ss") + " ：IF_MES_EMS_SWAPFILE中 FID 为 " + swapfile.getFid() + " 的数据在T_RM_WORKPROC_MATERIAL中找到" + relationItem.size() + "条对应关系;( MES物料编码:" + swapfile.getMaterialcode() + " ,MES物料名称:" + swapfile.getMaterialname() + " ,MES产线编码：" + swapfile.getProdline() + " )");
			} else {
				TRmWorkprocMaterial twm = new TRmWorkprocMaterial();
				// 自动新增原材料、以及工序原材料关联
				if(relationItem.size() < 1) {
					logger.info("[错误][未找到关联项]" + DateUtils.dateStr(new Date(), "yyyy-MM-dd HH:mm:ss") + " ：IF_MES_EMS_SWAPFILE中 FID 为 " + swapfile.getFid() + " 的数据在T_RM_WORKPROC_MATERIAL中未找到对应关系;( MES物料编码:" + swapfile.getMaterialcode() + " ,MES物料名称:" + swapfile.getMaterialname() + " ,MES产线编码：" + swapfile.getProdline() + " )，系统自动新增" );
					String bcode = swapfile.getMaterialcode(); // MES物料编码
					String mname = swapfile.getMaterialname(); // MES物料名称
					String mline = swapfile.getProdline(); // MES产线编码
					Map<String,Object> mp = new HashMap<String,Object>();
					mp.put("bcode", bcode);
					mp.put("name", mname);
					String mid = ""; // EMS原料ID
					List<TRmMaterial> lm = tRmMaterialMapper.selectByParameters(mp);
					if (lm!=null && lm.size() >0){
						mid = lm.get(0).getId();
					} else {
						TRmMaterial model = new TRmMaterial();
						String maxId = tRmMaterialService.getMaxId();
				        maxId = String.format("%03d", Integer.parseInt(maxId) + 1);
				        model.setId("Y"+maxId);
				        model.setSeqno(maxId);
				        model.setName(mname);
				        model.setBcode(bcode);
				        model.setRemark("MES自动新增");
				        model.setCreatetime(new Date());
				        model.setCreateman("系统");
				        model = tRmMaterialService.add(model);
				        mid = model.getId();
					}
					String wid = "ZYF000";
					String itemid = wid + mid + "R";
					if(!itemid.isEmpty() && !mid.isEmpty()){
						twm = tRmWorkprocMaterialService.getById(itemid);
						if(twm!=null){
							if(twm.getMesProdline() == null || twm.getMesProdline().isEmpty()){
								twm.setMesProdline(mline);
								twm.setMesMaterialcode(bcode);
							}else{
								twm.setMesProdline(twm.getMesProdline() + "," + mline);
								twm.setMesMaterialcode(bcode);
							}
							twm = tRmWorkprocMaterialService.modify(twm);
						}else{
							twm = new TRmWorkprocMaterial();
							twm.setId(itemid);
							twm.setMesMaterialcode(bcode);
							twm.setMaterialid(mid);
							twm.setWorkprocid(wid);
							twm.setUseflag("1");
							twm.setMesProdline(mline);
							twm.setCode("0");
							twm.setSeqno("10");
							twm.setItemtype("R");
							twm.setDigits(Short.valueOf("2"));
							twm.setUnitid("008"); // 单位：吨
							twm.setCreateman("系统");
							twm.setCreatetime(new Date());
							twm = tRmWorkprocMaterialService.add(twm);
							// 增加公式
							Formula formula = new Formula();
					        formula.setClock("202001");
					        formula.setCode(itemid);
					        formula.setDescription(tRmWorkprocMaterialService.getName(itemid));
					        formula.setIsavailable("1");
					        formula.setRevisor("系统");
					        formula.setRevisetime(DateUtils.getCurrentTime("yyyy-MM-dd HH:mm:ss"));
					        formula.setSourcecode("R(T_RM_WORKPROC_MATERIAL_VALUE," + itemid + ")");
					        formula.setTablename("T_RM_WORKPROC_MATERIAL_VALUE");
					        formulaService.add(formula);
						}
						logger.info("[新增成功]" + DateUtils.dateStr(new Date(), "yyyy-MM-dd HH:mm:ss") + " ：T_RM_WORKPROC_MATERIAL的itemid 为 " + itemid);
					} else {
						failure++;
						logger.info("[错误][新增失败]" + DateUtils.dateStr(new Date(), "yyyy-MM-dd HH:mm:ss") + " ：IF_MES_EMS_SWAPFILE中 FID 为 " + swapfile.getFid() + " 的数据在T_RM_WORKPROC_MATERIAL中未找到对应关系;( MES物料编码:" + swapfile.getMaterialcode() + " ,MES物料名称:" + swapfile.getMaterialname() + " ,MES产线编码：" + swapfile.getProdline() + " )" );
						continue;
					}
				} else {
					twm = relationItem.get(0);
				}
                // code = "1" 是由公式生成的项，放弃添加
                if (twm.getCode()!=null && twm.getCode().equals("1")) {
                    abandon++;
                    logger.info("[放弃添加]" + DateUtils.dateStr(new Date(), "yyyy-MM-dd HH:mm:ss") + " ：IF_MES_EMS_SWAPFILE中 FID 为 " + swapfile.getFid() + " 的数据项被配置成由公式自动生成，所以放弃添加。( MES物料编码:" + swapfile.getMaterialcode() + " ,MES物料名称:" + swapfile.getMaterialname() + " ,MES产线编码：" + swapfile.getProdline() + " )");
                    logger.info("关联项：" + twm.toString());
                } else if (twm.getCode()!=null && twm.getCode().equals("0")) {
                	Short digits = twm.getDigits() == null ? 2 : twm.getDigits();
                    // 更新数据T_RM_WORKPROC_MATERIAL_VALUE
                	HashMap<String, Object> ids = new HashMap<String, Object>();
                	ids.put("clock", DateUtils.dateToString(swapfile.getProdate(), "yyyy-MM-dd"));
                	ids.put("itemid", twm.getItemid());
                	ids.put("timegranid", "DAY");
                    TRmWorkprocMaterialValue tv = tRmWorkprocMaterialValueMapper.selectByPrimaryKey(ids);
    				if(tv!=null){
    					tv.setActualvalue(swapfile.getQty());
    		            tv.setApportvalue(swapfile.getQty().add(tv.getCorrectvalue()!=null?tv.getCorrectvalue():BigDecimal.ZERO).setScale(digits, RoundingMode.HALF_UP));
    		            tv.setBz("MES-" + new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(new Date()) + " fid:" + swapfile.getFid());
    		            tRmWorkprocMaterialValueMapper.updateByPrimaryKeySelective(tv);
    				}else{
    					tv = new TRmWorkprocMaterialValue();
    					tv.setId(ids);
    		            //计算值
    	            	tv.setActualvalue(swapfile.getQty());
    		            //修正值
    	            	tv.setCorrectvalue(new BigDecimal(0));
    		            //最终值
    	            	tv.setApportvalue(swapfile.getQty());
    	            	tv.setBz("MES-" + new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(new Date()) + " fid:" + swapfile.getFid());
    	            	tRmWorkprocMaterialValueMapper.insert(tv);
    				}
    				success++;
    				// 反写IF_MES_EMS_SWAPFILE的status
                    HashMap<String, Object> updateObj = new HashMap<String, Object>();
                    updateObj.put("fid", swapfile.getFid());
                    updateObj.put("status", "1");
                    ifMesEmsSwapfileService.updateStatus(updateObj);
    				// 如果是昨天之前的数据，重新计算关联项数据
                    try {
                    	Date pdate = new SimpleDateFormat("yyyy-MM-dd").parse(swapfile.getProdate());
                    	Calendar calendar = Calendar.getInstance();
                    	calendar.add(Calendar.DAY_OF_YEAR, -1);
                    	Date yesterday = new SimpleDateFormat("yyyy-MM-dd").parse(new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime()));
                    	if(pdate.before(yesterday)){
                    		formulaService.reCalculate(twm.getItemid(), DateUtils.dateToString(swapfile.getProdate(), "yyyy-MM-dd"), "DAY", DateUtils.dateToString(swapfile.getProdate(), "yyyy-MM-dd"));
                    	}
                    } catch (Exception e) {
                    	e.printStackTrace();
                    }
                }
			}
		}
		logger.info("[原料库存数据添加完毕]" + DateUtils.dateStr(new Date(), "yyyy-MM-dd HH:mm:ss") + "：数据添加成功" + success + "条(其中修改数据为" + delSize + "条)，放弃" + abandon + "条，失败" + failure + "条;");
	}

    @Override
    // @Transactional(rollbackFor = Exception.class)
    public void setDate(Date date) {
    	this.synchronousData();
    	this.synchronousData4();
    	this.synchronousData5();
    	Calendar calendar = Calendar.getInstance();
    	calendar.setTime(date);
        // 获取项目信息-用于每日计算
        Set<TRmWorkprocMaterial> models = tRmWorkprocMaterialService.getIdAndDigits();
        for (TRmWorkprocMaterial tm : models) {
        	HashMap<String, Object> id = new HashMap<String, Object>();
        	id.put("itemid", tm.getItemid());
        	Short digits = tm.getDigits()==null?2:tm.getDigits();
        	String clock = "";
        	// 先计算日数据,只有code为1的需要计算
        	if(tm.getCode().equals("1")) {
        		calendar.add(Calendar.DAY_OF_YEAR, -1);
	            clock = new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime());
	            calendar.add(Calendar.DAY_OF_YEAR, 1);
            	id.put("clock", clock);
            	id.put("timegranid", "DAY");
        		// 获取原数据
            	TRmWorkprocMaterialValue tv = tRmWorkprocMaterialValueMapper.selectByPrimaryKey(id);
            	//获取最终值
                Double val= formulaService.getValByItemid(tm.getItemid(), "DAY", clock, 0);
                if(val<0){
                	val=0.0;
                    logger.info("id:"+tm.getItemid()+"计算错误");
                }
                // 获取产量
                Map<String, BigDecimal> outPut = tRmWorkprocProductValueService.getOutPut(tm.getWorkprocid(),clock,"DAY","R");
                Double sjcl = outPut.get("SJCL").doubleValue();
            	if(tv == null){
            		tv = new TRmWorkprocMaterialValue();
            		tv.setClock(clock);
            		tv.setItemid(tm.getItemid());
            		tv.setTimegranid("DAY");
                    tv.setActualvalue(new BigDecimal(val));
                    tv.setApportvalue(new BigDecimal(val));
                    tv.setCorrectvalue(BigDecimal.ZERO);
                    tv.setUcvalue(BigDecimalUtil.divide(val, sjcl, digits.intValue()));
                    this.insert(tv);
            	} else {
            		// 存在数据做更新
        			tv.setActualvalue(new BigDecimal(val));
        			if(tv.getCorrectvalue()!=null){
        				tv.setApportvalue(new BigDecimal(val).add(tv.getCorrectvalue()));
					}else{
						tv.setApportvalue(new BigDecimal(val));
					}
        			tv.setUcvalue(BigDecimalUtil.divide(tv.getActualvalue().doubleValue(), sjcl, digits.intValue()));
        			tRmWorkprocMaterialValueMapper.updateByPrimaryKeySelective(tv);
            	}
        	}
        	// 月初统计上月数据
        	if(calendar.get(Calendar.DAY_OF_MONTH) <= 3) {
        		calendar.add(Calendar.MONTH, -1);
	            clock = new SimpleDateFormat("yyyy-MM").format(calendar.getTime());
	            calendar.add(Calendar.MONTH, 1);
        		id.put("clock", clock);
        		id.put("timegranid", "MONTH");
        		// 获取原数据
            	TRmWorkprocMaterialValue tv = tRmWorkprocMaterialValueMapper.selectByPrimaryKey(id);
        		Double val = 0d;
        		if(tm.getCode().equals("1")) {
        			// 公式计算类型
        			val = formulaService.getValByItemid(tm.getItemid(), "MONTH", clock, 0);
        		} else {
        			// 月数据等于，日数据之和
        			val = this.getSumvalue(tm.getItemid(),clock,"DAY");
        		}
        		// 获取产量
                Map<String, BigDecimal> outPut = tRmWorkprocProductValueService.getOutPut(tm.getWorkprocid(),clock,"MONTH","R");
                Double sjcl = outPut.get("SJCL").doubleValue();
            	if(tv == null){
            		tv = new TRmWorkprocMaterialValue();
            		tv.setClock(clock);
            		tv.setItemid(tm.getItemid());
            		tv.setTimegranid("MONTH");
            		tv.setActualvalue(new BigDecimal(val));
                    tv.setApportvalue(new BigDecimal(val));
                    tv.setCorrectvalue(BigDecimal.ZERO);
                    tv.setUcvalue(BigDecimalUtil.divide(val, sjcl, digits.intValue()));
                    this.insert(tv);
            	}else {
            		// 存在数据做更新
        			tv.setActualvalue(new BigDecimal(val));
        			if(tv.getCorrectvalue()!=null){
        				tv.setApportvalue(new BigDecimal(val).add(tv.getCorrectvalue()));
					}else{
						tv.setApportvalue(new BigDecimal(val));
					}
        			tv.setUcvalue(BigDecimalUtil.divide(tv.getActualvalue().doubleValue(), sjcl, digits.intValue()));
        			tRmWorkprocMaterialValueMapper.updateByPrimaryKeySelective(tv);
            	}
        	}
        	// 年初统计去年数据
        	if(calendar.get(Calendar.DAY_OF_YEAR) <= 5) {
        		calendar.add(Calendar.YEAR, -1);
	            clock = new SimpleDateFormat("yyyy").format(calendar.getTime());
	            calendar.add(Calendar.YEAR, 1);
        		id.put("clock", clock);
        		id.put("timegranid", "YEAR");
        		// 获取原数据
				TRmWorkprocMaterialValue tv = tRmWorkprocMaterialValueMapper.selectByPrimaryKey(id);
        		Double val = 0d;
        		if(tm.getCode().equals("1")) {
        			// 公式计算类型
        			val = formulaService.getValByItemid(tm.getItemid(), "YEAR", clock, 0);
        		} else {
        			// 年数据等于，月数据之和
        			val = this.getSumvalue(tm.getItemid(),clock,"MONTH");
        		}
        		// 获取产量
                Map<String, BigDecimal> outPut = tRmWorkprocProductValueService.getOutPut(tm.getWorkprocid(),clock,"YEAR","R");
                Double sjcl = outPut.get("SJCL").doubleValue();
				if (tv == null) {
					tv = new TRmWorkprocMaterialValue();
            		tv.setClock(clock);
            		tv.setItemid(tm.getItemid());
            		tv.setTimegranid("YEAR");
            		tv.setActualvalue(new BigDecimal(val));
                    tv.setApportvalue(new BigDecimal(val));
                    tv.setCorrectvalue(BigDecimal.ZERO);
                    tv.setUcvalue(BigDecimalUtil.divide(val, sjcl, digits.intValue()));
                    this.insert(tv);
				} else {
					// 存在数据做更新
        			tv.setActualvalue(new BigDecimal(val));
        			if(tv.getCorrectvalue()!=null){
        				tv.setApportvalue(new BigDecimal(val).add(tv.getCorrectvalue()));
					}else{
						tv.setApportvalue(new BigDecimal(val));
					}
        			tv.setUcvalue(BigDecimalUtil.divide(tv.getActualvalue().doubleValue(), sjcl, digits.intValue()));
        			tRmWorkprocMaterialValueMapper.updateByPrimaryKeySelective(tv);
				}
        	}
        }
        logger.info("工序与原材料数据统计定时任务结束.....");
    }

    @Override
    public Double getSumvalue(HashMap<String, Object> params) {
        return tRmWorkprocMaterialValueMapper.getSumvalue(params);
    }

    @Override
    public int insert(TRmWorkprocMaterialValue tRmWorkprocMaterialValue) {
        return tRmWorkprocMaterialValueMapper.insert(tRmWorkprocMaterialValue);
    }

    @Override
    public Map<String, Object> getMonthOutPut(HashMap<String, Object> params) {
        return tRmWorkprocMaterialValueMapper.getMonthOutPut(params);
    }
    public Double getSumvalue(String itemid,String clock,String timegranid) {
    	HashMap<String, Object> maps = new HashMap<>();
    	maps.put("itemid", itemid);
    	maps.put("clock", clock);
    	maps.put("timegranid", timegranid);
    	Double sumvalue = tRmWorkprocMaterialValueMapper.getSumvalue(maps);
    	if(null == sumvalue) {
    		return 0.0;
    	}
    	return sumvalue;
    }

	@Override
	public String restatData(String itemid, String clock, String timegranid) {
		TRmWorkprocMaterial twm = tRmWorkprocMaterialService.getById(itemid);
		Short digits = twm.getDigits() == null ? 2 : twm.getDigits();
		String code = twm.getCode();
		String mesMaterialcode = twm.getMesMaterialcode();
		String mes_prodline = twm.getMesProdline();
		if (code.equals("0") && (mesMaterialcode ==null || mes_prodline ==null || mesMaterialcode.isEmpty() || mes_prodline.isEmpty())) {
			logger.info("原材料[" + itemid + "]MES物料编码或者产线信息不完整");
			return "原料编码或者产线信息不完整";
		}
		try {
			if(timegranid.equalsIgnoreCase("DAY")){
				HashMap<String, Object> hpm = new HashMap<String, Object>();
				hpm.put("clock", clock);
				hpm.put("itemid", itemid);
				hpm.put("timegranid", timegranid);
				hpm.put("itemtype", itemid.substring(itemid.length()-1, itemid.length()));
				hpm.put("materialcode", mesMaterialcode);
				hpm.put("prodline", mes_prodline);
				// 计算值
	            Double actualvalue = 0d;
	            String ids = "";
				if(code.equals("0")){
	                Map<String, Object> vl =  tRmWorkprocMaterialValueMapper.getItemval(hpm);
	                actualvalue = new BigDecimal(vl.get("VAL").toString()).setScale(digits, RoundingMode.HALF_UP).doubleValue();
	                ids = vl.get("IDS")==null?"":vl.get("IDS").toString();
				}else if(code.equals("1")){
					// 公式计算型
					actualvalue = formulaService.getValByItemid(itemid, timegranid, clock, 0);
				}
				TRmWorkprocMaterialValue tv = tRmWorkprocMaterialValueMapper.selectByPrimaryKey(hpm);
				if(tv!=null){
					tv.setActualvalue(new BigDecimal(actualvalue));
		            tv.setApportvalue(BigDecimalUtil.add(tv.getCorrectvalue()!=null?tv.getCorrectvalue().doubleValue():0d, actualvalue).setScale(digits, RoundingMode.HALF_UP));
		            if (!ids.isEmpty()){
		            	tv.setBz("MES-" + new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(new Date()) + " fid:" + ids);
		            }
		            tRmWorkprocMaterialValueMapper.updateByPrimaryKeySelective(tv);
				}else{
					tv = new TRmWorkprocMaterialValue();
	            	tv.setItemid(itemid);
	            	tv.setClock(clock);
	            	tv.setTimegranid(timegranid);
		            //计算值
	            	tv.setActualvalue(new BigDecimal(actualvalue));
		            //修正值
	            	tv.setCorrectvalue(new BigDecimal(0));
		            //最终值
	            	tv.setApportvalue(new BigDecimal(actualvalue));
	            	tRmWorkprocMaterialValueMapper.insert(tv);
				}
			} else if((timegranid.equalsIgnoreCase("MONTH") || timegranid.equalsIgnoreCase("YEAR"))){
				HashMap<String, Object> id = new HashMap<String, Object>();
	    		id.put("clock", clock);
	    		id.put("timegranid", timegranid);
	    		id.put("itemid", itemid);
	    		HashMap<String, Object> maps = new HashMap<>();
	        	if(timegranid.equalsIgnoreCase("MONTH")){
		            maps.put("itemid", itemid);
		            maps.put("clock", clock);
		            maps.put("timegranid", "DAY");
	        	}else if(timegranid.equalsIgnoreCase("YEAR")){
	        		maps.put("itemid", itemid);
		            maps.put("clock", clock);
		            maps.put("timegranid", "MONTH");
	        	}
	        	// 计算值
	        	BigDecimal actualvalue = BigDecimal.ZERO;
	        	if(code.equals("0")){
	        		// 小粒度累加
	        		actualvalue = new BigDecimal(tRmWorkprocMaterialValueMapper.getSumvalue(maps)).setScale(digits, RoundingMode.HALF_UP);
				}else if(code.equals("1")){
					// 公式计算型
					actualvalue = new BigDecimal(formulaService.getValByItemid(itemid, timegranid, clock, 0)).setScale(digits, RoundingMode.HALF_UP);
				}
	            TRmWorkprocMaterialValue tv = tRmWorkprocMaterialValueMapper.selectByPrimaryKey(id);
	            if(tv!=null && tv.getActualvalue().doubleValue() != actualvalue.doubleValue()){
					tv.setActualvalue(actualvalue);
		            tv.setApportvalue(BigDecimalUtil.add(tv.getCorrectvalue()!=null?tv.getCorrectvalue().doubleValue():0d, actualvalue.doubleValue()).setScale(digits, RoundingMode.HALF_UP));
		            tRmWorkprocMaterialValueMapper.updateByPrimaryKeySelective(tv);
	            }else if(tv==null){
	            	tv = new TRmWorkprocMaterialValue();
	            	tv.setItemid(itemid);
	            	tv.setClock(clock);
	            	tv.setTimegranid(timegranid);
		            //计算值
	            	tv.setActualvalue(actualvalue);
		            //修正值
	            	tv.setCorrectvalue(new BigDecimal(0));
		            //最终值
	            	tv.setApportvalue(actualvalue);
	            	tRmWorkprocMaterialValueMapper.insert(tv);
	            }
			}
		} catch (Exception e) {
			logger.error("统计错误：itemid-" + itemid + ",clock-" + clock);
			e.printStackTrace();
		}
		return null;
	}

}