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

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.ems.trmdfvalue.model.TRmDfValue;
import com.steerinfo.ems.Utils.BigDecimalUtil;
import com.steerinfo.ems.Utils.DateUtils;
import com.steerinfo.ems.formula.service.IFormulaService;
import com.steerinfo.ems.trmactitem.model.TRmActItem;
import com.steerinfo.ems.trmactitem.service.ITRmActItemService;
import com.steerinfo.ems.trmactvalue.service.impl.TRmActValueServiceImpl;
import com.steerinfo.ems.trmdfvalue.mapper.TRmDfValueMapper;
import com.steerinfo.ems.trmdfvalue.service.ITRmDfValueService;
import com.steerinfo.ems.trmindexitem.mapper.TRmIndexItemMapper;
import com.steerinfo.ems.trmindexitem.service.ITRmIndexItemService;
import com.steerinfo.ems.trmindexvalue.model.TRmIndexValue;
import com.steerinfo.ems.trmindexvalue.service.ITRmIndexValueService;

import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;

/**
 * TRmDfValue服务实现：
 * @author generator
 * @version 1.0-SNAPSHORT 2020-10-30 10:34
 * 类描述
 * 修订历史：
 * 日期：2020-10-30
 * 作者：generator
 * 参考：
 * 描述：TRmDfValue服务实现
 * @see null
 * @Copyright 湖南视拓信息技术股份有限公司. All rights reserved.
 */
@Service(value = "tRmDfValueService")
public class TRmDfValueServiceImpl extends BaseServiceImpl<TRmDfValue, HashMap<String, Object>> implements ITRmDfValueService {
	
	private static final Logger logger = LoggerFactory.getLogger(TRmActValueServiceImpl.class);

    @Autowired
    private TRmDfValueMapper tRmDfValueMapper;
    @Autowired
    private ITRmActItemService tRmActItemService;
    @Autowired
    private IFormulaService formulaService;
    @Autowired
    ITRmIndexItemService tRmIndexItemService;
    @Autowired
    ITRmIndexValueService tRmIndexValueService;
    @Autowired
    private TRmIndexItemMapper tRmIndexItemMapper;
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    protected IBaseMapper<TRmDfValue, HashMap<String, Object>> getMapper() {
        return tRmDfValueMapper;
    }
    
	@Override
	public PageList<Map<String, Object>> getProjectwDataForPage(HashMap<String, Object> parmas, Integer pageNum,
			Integer pageSize) {
		PageHelper.startPage(pageNum, pageSize);
        List<Map<String, Object>> actitemDetalts = tRmDfValueMapper.getProjectwData(parmas);
        PageList<Map<String,Object>> plist = new PageList<Map<String,Object>>(actitemDetalts);
        return plist;
	}
	
	@Override
	public void state(Date d) {
    	// 获取上报项目
        List<TRmActItem> wt = tRmActItemService.getitems("F");
        Calendar c = Calendar.getInstance();
        c.setTime(d);
        c.add(Calendar.DAY_OF_YEAR, -1);
        String clockd = new SimpleDateFormat("yyyy-MM-dd").format(c.getTime());
        c.add(Calendar.DAY_OF_MONTH,  1);
        c.add(Calendar.MONTH, -1); // 减1月获得上月
        String clockm = new SimpleDateFormat("yyyy-MM").format(c.getTime());
        c.add(Calendar.MONTH, 1); // 回到当前月
        c.add(Calendar.YEAR, -1); // 去年
        String clocky = new SimpleDateFormat("yyyy").format(c.getTime());
//        // 每日0点生成当天生成上月数据
//     	if(c.get(Calendar.HOUR_OF_DAY) == 0){
//     		for (TRmActItem tRmActItem : wt) {
//     			this.restatData(tRmActItem.getItemid(), clockd, "DAY", "系统", null, "");
//     			this.restatData(tRmActItem.getItemid(), clockm, "MONTH", "系统", null, "");
//     		}
//     	}
        // 生成昨日数据
        for (TRmActItem tRmActItem : wt) {
        	this.restatData(tRmActItem.getItemid(), clockd, "DAY", "系统", null, "");
        }
 		// 每月前3天生成上月数据
		if(c.get(Calendar.DAY_OF_MONTH) <= 2){
			for (TRmActItem tRmActItem : wt) {
				this.restatData(tRmActItem.getItemid(), clockm, "MONTH", "系统", null, "");
			}
		}
		// 每年前3天生成去年数据
		if(c.get(Calendar.DAY_OF_YEAR) <= 3){
			for (TRmActItem tRmActItem : wt) {
				this.restatData(tRmActItem.getItemid(), clocky, "YEAR", "系统", null, "");
			}
		}
		logger.info("财务数据定时任务结束....");
	}
	
	@Override
	public void state1(Date d) {
    	// 获取上报项目
        List<TRmActItem> wt = tRmActItemService.getitems("F");
        Calendar c = Calendar.getInstance();
        c.setTime(d);
        c.add(Calendar.DAY_OF_MONTH, -1);
        String clockd = new SimpleDateFormat("yyyy-MM-dd").format(c.getTime());
//        // 每日9点补全上一天产量数据
//     	if(c.get(Calendar.HOUR_OF_DAY) == 9){
//     		for (TRmActItem tRmActItem : wt) {
//     			this.restatData(tRmActItem.getItemid(), clockd, "DAY", "系统", null, "");
//     		}
//     	}
        for (TRmActItem tRmActItem : wt) {
 			this.restatData(tRmActItem.getItemid(), clockd, "DAY", "系统", null, "");
 		}
		logger.info("财务数据上一天产量补全定时任务结束....");
	}
	
	@Override
	public String restatData(String itemid, String clock, String timegranid, String opuser, Double dwcl, String bz) {
		if(!itemid.endsWith("F")){
			return "项目编号错误";
		}
		TRmActItem t = tRmActItemService.getById(itemid);
		if(t!=null){
			try {
				Integer bd = t.getDefaultvalue()==null ?0:t.getDefaultvalue(); // 波动系数
				Short digits = t.getDigits() == null ? 2 : t.getDigits(); // 精度
	    		// 关联产量编号-（系统数据由此读取）
	    		String fid = t.getFid()==null?"":t.getFid().trim();
	    		// 系统数据
	    		BigDecimal productvalue = null;
	    		// 财务最终值-波动前
	    		BigDecimal apportvalue = null;
	    		// 财务最终值-波动后
	    		BigDecimal apportwvalue = null;
	    		// 指标项目-系统数据  特殊处理
	    		String eneryid = "Y181";
	    		// 实际波动系数-保留5位小数
	    		BigDecimal bdvalue = new BigDecimal("1");
	    		// 计算 系统数据-productvalue
	    		if(!fid.isEmpty()){
	    			if(eneryid.equalsIgnoreCase(t.getEnergyid())) {  // 指标项目-公式计算
	        			String clockz = clock;
	        			String timegranidz = timegranid;
	        			if(timegranid.equalsIgnoreCase("DAY")) {
	        				clockz = clock.substring(0,7);
	        				timegranidz = "MONTH";
	        			}
	        			HashMap<String, Object> zid = new HashMap<String, Object>();
	        			zid.put("clock", clockz);
	        			zid.put("timegranid", timegranidz);
	        			zid.put("itemid", fid);
	        			TRmIndexValue tiv = tRmIndexValueService.getById(zid);
	        			if (tiv!=null && tiv.getApportvalue()!=null) {
	        				productvalue = tiv.getApportvalue();
	        			}
	        		} else {
	        			if(fid.indexOf(',') >= 0) {
	        				String fidArray[] = fid.split(",");
							for(int i = 0; i< fidArray.length; i++) {
								if(fidArray[i] != null && !fidArray[i].isEmpty()) {
									Double rval = formulaService.readValByItemid(fidArray[i],timegranid, clock, 0);
									if(rval != null) {
										if(productvalue==null){
											productvalue = new BigDecimal(Double.toString(rval));
										}else{
											productvalue = productvalue.add(new BigDecimal(Double.toString(rval)));
										}
									}
								}
							}
	        			}else{
	        				Double rval = formulaService.readValByItemid(fid,timegranid, clock, 0);
	        				if(rval != null) {
	        					productvalue = new BigDecimal(Double.toString(rval));
	        				}
	        			}
	        		}
	    			// 设置精度
	    			if (productvalue!=null){
	    				productvalue = productvalue.setScale(digits.intValue(), BigDecimal.ROUND_HALF_UP);
	    			}
	    		}
	    		// 计算财务最终值-根据公式计算
	    		/**
	    		 * 指标项目-日粒度-公式计算
	    		 * 非指标项目-日粒度-公式计算*波动系数，月年粒度-低粒度累加
	    		 */
	    		String fs = formulaService.getFormula(itemid, clock);
	    		if(fs==null){
					return "公式错误";
				}else{
					if(eneryid.equalsIgnoreCase(t.getEnergyid())) {  // 指标项目-公式计算
						// 财务最终值-波动前，通过公式计算
						apportvalue = new BigDecimal(Double.toString(formulaService.getValByItemid(itemid, timegranid, clock, 0)));
						apportwvalue = apportvalue.setScale(digits, RoundingMode.HALF_UP);
					}else{
						if(timegranid.equalsIgnoreCase("DAY")) {
							// 财务最终值-波动前，通过公式计算
							apportvalue = new BigDecimal(Double.toString(formulaService.getValByItemid(itemid, timegranid, clock, 0)));
							// 实绩波动系数,除100
							BigDecimal bdval = BigDecimalUtil.divide(bd.doubleValue(), 100d, 2);
							// 波动实绩值（绝对值） = 波动系数*(0~1随机数)*(财务最终值-波动前)
							BigDecimal fva = new BigDecimal(Math.random()).multiply(bdval);
							// 增加还是减少
							Double rad = Math.random();
							if(rad>=0.5d){ // 增加
								bdvalue = bdvalue.add(fva).setScale(5, RoundingMode.HALF_UP);
							}else{ // 减少
								bdvalue = bdvalue.subtract(fva).setScale(5, RoundingMode.HALF_UP);
							}
							apportwvalue = apportvalue.multiply(bdvalue).setScale(digits, RoundingMode.HALF_UP);
						}else{
							// 月、年粒度为低粒度数据累加
							HashMap<String, Object> params = new HashMap<>();
				        	if(timegranid.equalsIgnoreCase("MONTH")){
				        		params.put("itemid", itemid);
				        		params.put("clock", clock);
				        		params.put("timegranid", "DAY");
				        	}else if(timegranid.equalsIgnoreCase("YEAR")){
				        		params.put("itemid", itemid);
				        		params.put("clock", clock);
					            params.put("timegranid", "MONTH");
				        	}
				        	Double sumval = tRmDfValueMapper.getSumwvalue(params);
				        	apportvalue = new BigDecimal(Double.toString(sumval));
				        	apportwvalue = apportvalue.setScale(digits, RoundingMode.HALF_UP);
						}
					}
				}
	    		HashMap<String, Object> id = new HashMap<String, Object>();
	    		id.put("clock", clock);
	    		id.put("timegranid", timegranid);
	    		id.put("itemid", itemid);
	    		TRmDfValue tv = tRmDfValueMapper.selectByPrimaryKey(id);
				if(tv != null){
					// 财务最终值-波动前
					tv.setApportvalue(apportvalue);
		            // 财务最终值-波动后
		            tv.setApportwvalue(apportwvalue);
		            // 系统数据
		            tv.setProductvalue(productvalue);
		            // 实际波动系数
		            tv.setStdwvalue(bdvalue);
					tRmDfValueMapper.updateByPrimaryKeySelective(tv);
				}else{
					tv = new TRmDfValue();
					tv.setId(id);
					// 财务最终值-波动前
					tv.setApportvalue(apportvalue);
		            // 财务最终值-波动后
		            tv.setApportwvalue(apportwvalue);
		            // 系统数据
		            tv.setProductvalue(productvalue);
		            // 实际波动系数
		            tv.setStdwvalue(bdvalue);
		            tv.setCreateman(opuser);
		            tv.setRecTime(DateUtils.dateStr(new Date(),"yyyy-MM-dd HH:mm:ss"));
					tv.setUpuser(opuser);
					tv.setBz(bz);
					tv.setUptime(DateUtils.dateStr(new Date(),"yyyy-MM-dd HH:mm:ss"));
					tRmDfValueMapper.insert(tv);
				}
			} catch (Exception e) {
				logger.error("系统异常:", e);
				return "重新计算失败";
	        }
			// 如果是产量变化，联动计算相关项目
			/*
			 * if(fs.startsWith("R")){ formulaService.reCalculate(itemid, clock, timegranid,
			 * clock); // 产量确认，联动计算指标（根据波动关联对象fluitemid关联） Map<String, Object> m = new
			 * HashMap<String, Object>(); m.put("useflag", "1"); m.put("itemflag", "3");
			 * m.put("parentid", "NYDF001001"); m.put("fluitemid", itemid);
			 * List<TRmIndexItem> l = tRmIndexItemMapper.selectByParasForFla(m);
			 * for(TRmIndexItem tii:l){ tRmIndexValueService.restatData(tii.getItemid(),
			 * clock, timegranid, opuser); } }
			 */
		}
		return null;
	}

	@Override
	public void modifyByApv(TRmDfValue model) {
		/*
		TRmActItem t = tRmActItemService.getById(model.getItemid());
		// 上报产量
		BigDecimal productwvalue = model.getProductwvalue();
		// 上报最终值
		BigDecimal apportwvalue = model.getApportwvalue();
		// 单位换算
		Integer rate = t.getDefaultvalue()==null?1:t.getDefaultvalue();
		// 单耗
		BigDecimal ucwvalue = BigDecimalUtil.divide(BigDecimalUtil.mul(apportwvalue.doubleValue(), rate.doubleValue()).doubleValue(), productwvalue.doubleValue(), 6);
		model.setMftime(DateUtils.dateStr(new Date(),"yyyy-MM-dd HH:mm:ss"));
		model.setMfuser(JwtUtil.getUseridByToken());
		// 修改单耗指标数据与指标
		HashMap<String, Object> parmas = new HashMap<String, Object>();
    	parmas.put("energyid", t.getEnergyid());
    	parmas.put("workprocid", t.getWorkprocid());
    	parmas.put("propertyid", t.getPropertyid());
    	parmas.put("parentid", "NYDF001001");
    	
    	TRmIndexItem tii = tRmIndexItemService.getByParams(parmas);
    	int digits = 2;
    	if(tii!=null){
    		digits =  tii.getDigits()==null?2:tii.getDigits().intValue();
    		HashMap<String, Object> id = new HashMap<String, Object>();
    		id.put("clock", model.getClock());
    		id.put("timegranid", "MONTH");
    		id.put("itemid", tii.getItemid());
    		TRmIndexValue tv = tRmIndexValueService.getById(id);
    		if(tv!=null){
    			tv.setApportvalue(ucwvalue.setScale(digits, BigDecimal.ROUND_HALF_UP));
    			if(tv.getActualvalue()!=null){
    				tv.setCorrectvalue(ucwvalue.subtract(tv.getActualvalue()));
    			}
    			tv.setUpman(JwtUtil.getUseridByToken());
    			tv.setUptime(DateUtils.dateStr(new Date(),"yyyy-MM-dd HH:mm:ss"));
    			tRmIndexValueService.modify(tv);
    		}else{
    			tv = new TRmIndexValue();
    			tv.setId(id);
    			tv.setActualvalue(ucwvalue);
    			tv.setApportvalue(ucwvalue);
    			tv.setCorrectvalue(BigDecimal.ZERO);
    			tv.setRecTime(DateUtils.dateStr(new Date(),"yyyy-MM-dd HH:mm:ss"));
    			tv.setRecUser(JwtUtil.getUseridByToken());
    			tRmIndexValueService.add(tv);
    		}
    		// 如果是修改上月数据，增加或者修改公式
//    		Calendar c = Calendar.getInstance();
//    		c.add(Calendar.MONTH, -1);
//    		if(new SimpleDateFormat("yyyy-MM").format(c.getTime()).equals(model.getClock())){
//    			Formula f = formulaService.getFormulaLatest(tii.getItemid());
//    			String clk = model.getClock().split("-")[0] + model.getClock().split("-")[1];
//    			if(f!=null && f.getClock().equals(clk)){
//    				// 修改
//    				f.setSourcecode(ucwvalue.toPlainString());
//    				f.setRevisetime(DateUtils.getCurrentTime("yyyy-MM-dd HH:mm:ss"));
//    				f.setRevisor(JwtUtil.getUseridByToken());
//    				formulaService.modify(f);
//    			}else{
//    				// 新增公式
//    				f = new Formula();
//    				f.setClock(clk);
//    				f.setCode(tii.getItemid());
//    				f.setDescription(tii.getItemname());
//    				f.setSourcecode(ucwvalue.toPlainString());
//    				f.setIsavailable("1");
//    				f.setRevisetime(DateUtils.getCurrentTime("yyyy-MM-dd HH:mm:ss"));
//    				f.setTablename("T_RM_INDEX_VALUE");
//    				f.setRevisor(JwtUtil.getUseridByToken());
//    				formulaService.add(f);
//    			}
//    		}
    	}
    	model.setUcwvalue(ucwvalue.setScale(digits, BigDecimal.ROUND_HALF_UP));
    	*/
    	tRmDfValueMapper.updateByPrimaryKeySelective(model);
	}
	
	@Override
	public int getCount(Map<String, Object> params) {
		return tRmDfValueMapper.getCount(params);
	}

	@Override
	@Transactional(rollbackFor=Exception.class)
	public String updateByExl(File serverFile) throws Exception {
		Workbook workbook = null;
		// 导入月clock
		String clockm = "";
		try {
			workbook = WorkbookFactory.create(serverFile);
			int snum = workbook.getNumberOfSheets();
			// 约定内容格式
			if(snum!=8){
				return "sheet数据应该为8个";
			}
			if(!workbook.getSheetAt(7).getSheetName().equals("轧钢")){
				return "最后sheet应该为轧钢";
			}
			// 第一页，第3行，第5列为要导入的日期
			Row rday = workbook.getSheetAt(0).getRow(2);
			if(rday==null || rday.getCell(4)==null){
				return "获取excel日期失败，没有找到数据";
			}
			Cell cell_date = rday.getCell(4);
			if(!cell_date.getCellTypeEnum().equals(CellType.NUMERIC) || !HSSFDateUtil.isCellDateFormatted(cell_date)){
				return "获取excel日期失败，数据格式错误";
			}
			Date d = cell_date.getDateCellValue();
			// 获取该月天数
			Calendar cal = Calendar.getInstance();
			cal.setTime(d);
			int ts = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
			clockm = new SimpleDateFormat("yyyy-MM").format(d);
			HashMap<String, Object> params = new HashMap<String, Object>();
			params.put("clock", clockm);
			params.put("timegranid", "DAY");
			// 判断是否已经生成数据
    		int cd = tRmDfValueMapper.getCountD(params);
    		if(cd<1){
    			return "请先生成该月日数据";
    		}
    		// 判断是否已有财务数据
    		if(tRmDfValueMapper.getSumwvalue(params) > 0){
    			return "该月份已有财务上报数据，清零后可以再次上传";
    		}
    		// 月、年数据通过累计的项目
    		List<String> itemAdd = new ArrayList<String>();
    		// 月、年数据通过公式计算的项目
    		List<String> itemCal = new ArrayList<String>();
    		// 遍历sheet页
			for (int i = 0; i < snum; i++) {
				Sheet sheet = workbook.getSheetAt(i);
				if (i < snum - 1) { // 不是最后一个（轧钢）
					// 遍历读取行数据，从第5行开始
					for (int row = 4; row < sheet.getPhysicalNumberOfRows(); row++) {
						Row r = sheet.getRow(row);
						// 第3列为物料编码
						String itemid = r == null || r.getCell(2) == null ? "" : r.getCell(2).toString().trim();
						if (!itemid.isEmpty()) {
							// 长度为天数
							for (int c = 0; c < ts; c++) {
								// 第五列开始为数据
								Cell cell = r.getCell(c + 4);
								// 获取数据,只读取数值与公式
								if (cell != null && (cell.getCellTypeEnum().equals(CellType.FORMULA) || cell.getCellTypeEnum().equals(CellType.NUMERIC))) {
									Double val = 0d;
									try {
										val = cell.getNumericCellValue();
									}catch (IllegalStateException e) {
										logger.error("数据读取错误:", "sheet" + (i+1) + ",row" + (row+1) + ",cell" + (c + 5));
									}catch (NumberFormatException e) {
										logger.error("数据错误:", "sheet" + (i+1) + ",row" + (row+1) + ",cell" + (c + 5));
									}
									// 日clock
									String clockd = "";
									if (c + 1 < 10) {
										clockd = clockm + "-0" + (c + 1);
									} else {
										clockd = clockm + "-" + (c + 1);
									}
									HashMap<String, Object> id = new HashMap<String, Object>();
									id.put("clock", clockd);
									id.put("timegranid", "DAY");
									id.put("itemid", itemid);
									TRmDfValue tv = tRmDfValueMapper.selectByPrimaryKey(id);
									if (tv != null && val != null) {
										tv.setApportwvalue(new BigDecimal(Double.toString(val)));
										tRmDfValueMapper.updateByPrimaryKeySelective(tv);
									}
								}
							}
							// 公式中有除法的月、年数据用计算公式计算，否则累加
							String formula =  formulaService.getFormula(itemid, clockm);
							if (formula!=null && !formula.isEmpty()){
								if(formula.indexOf("/")>0){
									itemCal.add(itemid);
								}else{
									itemAdd.add(itemid);
								}
							}
						}
					}
				} else {
					// 最后一个sheet页（轧钢），第6行-第11行，第3-5列为物料编码
					for(int row = 5; row < 11; row++){
						Row r = sheet.getRow(row);
						if(r!=null){
							for(int k=2;k<5;k++){
								String itemid = r.getCell(k) == null ? "" : r.getCell(k).toString().trim();
								if(!itemid.isEmpty()){
									// 下个数据相隔10行，条数为天数,第k+5列为数据，第row行开始
									for (int c = 0; c < ts; c++) {
										Row r2 = sheet.getRow(c*10 + row);
										if(r2!=null){
											// 取数据,列+5
											Cell cell = r2.getCell(k + 5);
											// 只读取数值与公式
											if(cell!=null && (cell.getCellTypeEnum().equals(CellType.FORMULA) || cell.getCellTypeEnum().equals(CellType.NUMERIC))){
												Double val = 0d;
												try {
													val = cell.getNumericCellValue();
												}catch (IllegalStateException e) {
													logger.error("数据读取错误:", "sheet" + (i+1) + ",row" + (row+1) + ",cell" + (c + 5));
												}catch (NumberFormatException e) {
													logger.error("数据错误:", "sheet" + (i+1) + ",row" + (row+1) + ",cell" + (c + 5));
												}
												// 日clock
												String clockd = "";
												if (c + 1 < 10) {
													clockd = clockm + "-0" + (c + 1);
												} else {
													clockd = clockm + "-" + (c + 1);
												}
												HashMap<String, Object> id = new HashMap<String, Object>();
									    		id.put("clock", clockd);
									    		id.put("timegranid", "DAY");
									    		id.put("itemid", itemid);
												TRmDfValue tv = tRmDfValueMapper.selectByPrimaryKey(id);
												if(tv!=null && val!=null){
													tv.setApportwvalue(new BigDecimal(Double.toString(val)));
													tRmDfValueMapper.updateByPrimaryKeySelective(tv);
												}
											}
										}
									}
									// 公式中有除法的月、年数据用计算公式计算，否则累加
									String formula =  formulaService.getFormula(itemid, clockm);
									if (formula!=null && !formula.isEmpty()){
										if(formula.indexOf("/")>0){
											itemCal.add(itemid);
										}else{
											itemAdd.add(itemid);
										}
									}
								}
							}
						}
					}
				}
			}
			// 数据主键
			HashMap<String, Object> idm = new HashMap<String, Object>();
			idm.put("clock", clockm);
			idm.put("timegranid", "MONTH");
			// 统计月数据，先计算累加数据，后计算公式数据
			for(String itemid:itemAdd){
				idm.put("itemid", itemid);
				TRmDfValue tv = tRmDfValueMapper.selectByPrimaryKey(idm);
				if(tv!=null){
					// 累加日数据
					params.put("itemid", itemid);
					BigDecimal data = new BigDecimal(Double.toString(tRmDfValueMapper.getSumwvalue(params)));
					tv.setApportwvalue(data);
					
					System.out.print("1-------:" + itemid + "," + data + "-----");
					tRmDfValueMapper.updateByPrimaryKeySelective(tv);
				}
			}
			
			for(String itemid:itemCal){
				idm.put("itemid", itemid);
				TRmDfValue tv = tRmDfValueMapper.selectByPrimaryKey(idm);
				if(tv!=null){
					// 公式计算
					BigDecimal data = new BigDecimal(formulaService.getValByItemid(itemid, "MONTH", clockm, 0));
					tv.setApportwvalue(data);
					
					System.out.print("2-------:" + itemid + "," + data + "-----");
					tRmDfValueMapper.updateByPrimaryKeySelective(tv);
				}
			}
			
			//加减类指标
			for(int i = 0; i < 8; i++) {
				//ZY7100Y18119F,ZY7200Y18119F
				String itemid = "";
				if(i == 0) {
					itemid = "ZY7100Y18119F";
				}else if(i == 1) {
					itemid = "ZY7200Y18119F";
				}else if(i == 2) {
					itemid = "ZY9101Y18122F";
				}else if(i == 3) {
					itemid = "ZY9103Y18122F";
				}else if(i == 4) {
					itemid = "ZY9201Y18122F";
				}else if(i == 5) {
					itemid = "ZY9203Y18122F";
				}else if(i == 6) {
					itemid = "ZY9204Y18122F";
				}else if(i == 7) {
					itemid = "ZY9102Y18122F";
				}
				idm.put("itemid", itemid);
				TRmDfValue tv = tRmDfValueMapper.selectByPrimaryKey(idm);
				if(tv!=null){
					// 公式计算
					tv.setApportwvalue(new BigDecimal(formulaService.getValByItemid(itemid, "MONTH", clockm, 0)));
					tRmDfValueMapper.updateByPrimaryKeySelective(tv);
				}
			}
			
			// 如果是12月生成本年数据,先计算累加数据，后计算公式数据
			if(clockm.split("-")[1].equals("12")) {
				String clocky = clockm.split("-")[0];
				HashMap<String, Object> idy = new HashMap<String, Object>();
				idy.put("clock", clocky);
				idy.put("timegranid", "YEAR");
				for(String itemid:itemAdd){
					idy.put("itemid", itemid);
					TRmDfValue tv = tRmDfValueMapper.selectByPrimaryKey(idy);
					if(tv!=null){
						// 累加日数据
						params.put("itemid", itemid);
						params.put("clock", clocky);
						params.put("timegranid", "MONTH");
						tv.setApportwvalue(new BigDecimal(Double.toString(tRmDfValueMapper.getSumwvalue(params))));
						tRmDfValueMapper.updateByPrimaryKeySelective(tv);
					}
				}
				for(String itemid:itemCal){
					idy.put("itemid", itemid);
					TRmDfValue tv = tRmDfValueMapper.selectByPrimaryKey(idy);
					if(tv!=null){
						// 公式计算
						tv.setApportwvalue(new BigDecimal(formulaService.getValByItemid(itemid, "MONTH", clockm, 0)));
						tRmDfValueMapper.updateByPrimaryKeySelective(tv);
					}
				}
			}
		} catch (Exception e) {
			logger.error("系统异常:", e);
			throw new Exception("excel文件读取数据错误");
        } finally {
        	if(workbook!=null) {
                try {
                    workbook.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
		return clockm;
	}

	@Override
	public String delApportwvalue(String itemid, String clock, String timegranid) {
		int cout;
           cout=tRmDfValueMapper.delApportwvalue(itemid, clock, timegranid);
		return cout+"";
	}

}
