package com.steerinfo.ems.trmtransfereactvalue.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.trmtransfereactvalue.model.TRmTransfereActValue;
import com.steerinfo.auth.utils.JwtUtil;
import com.steerinfo.ems.Utils.BigDecimalUtil;
import com.steerinfo.ems.emscalpointvalue.mapper.EmsCalpointValueMapper;
import com.steerinfo.ems.emscalpointvalue.model.EmsCalpointValue;
import com.steerinfo.ems.formula.service.IFormulaService;
import com.steerinfo.ems.trmcalpoint.mapper.TRmCalpointMapper;
import com.steerinfo.ems.trmcalpoint.model.TRmCalpoint;
import com.steerinfo.ems.trmcalpointvalue.mapper.TRmCalpointValueMapper;
import com.steerinfo.ems.trmcalpointvalue.model.TRmCalpointValue;
import com.steerinfo.ems.trmcalpointvalue.service.ITRmCalpointValueService;
import com.steerinfo.ems.trmelectricitylocation.model.TRmElectricityLocation;
import com.steerinfo.ems.trmelectricitylocation.service.ITRmElectricityLocationService;
import com.steerinfo.ems.trmtransfereactvalue.mapper.TRmTransfereActValueMapper;
import com.steerinfo.ems.trmtransfereactvalue.service.ITRmTransfereActValueService;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
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;

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

	private static final Logger logger = LoggerFactory.getLogger(TRmTransfereActValueServiceImpl.class);
	
	@Autowired
    private TRmTransfereActValueMapper tRmTransfereActValueMapper;
	
	@Autowired
	private ITRmElectricityLocationService tRmElectricityLocationService;
	
	@Autowired
    private TRmCalpointValueMapper tRmCalpointValueMapper;
	
	@Autowired
	private TRmCalpointMapper tRmCalpointMapper;
	
	@Autowired
    ITRmCalpointValueService tRmCalpointValueService;
	
	@Autowired
    private IFormulaService formulaService;
	
	@Autowired
    private EmsCalpointValueMapper emsCalpointValueMapper;

    @Override
    protected IBaseMapper<TRmTransfereActValue, String> getMapper() {
        return tRmTransfereActValueMapper;
    }
    
    @Autowired
    private JdbcTemplate jdbcTemplate;

	@Override
	public void updateOrInsert(TRmTransfereActValue model) {
		String userId = JwtUtil.getUseridByToken();
		// 修改数据
    	if(model.getId()!=null && !model.getId().isEmpty()){
    		model.setCreater(userId);
			model.setState("1");
    		model.setCreatetim(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
    		tRmTransfereActValueMapper.updateByPrimaryKeySelective(model);
    	}else{ // 新增数据
    		model.setCreater(userId);
    		model.setCreatetim(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
    		model.setState("1");
    		model.setId("");
    		this.add(model);
    	}
    	String itemid = model.getItemid();
    	TRmCalpoint tRmCalpoint = tRmCalpointMapper.selectByPrimaryKey(itemid);
    	String clock = model.getClock();
		String clocke = model.getClocke();
		Short digits = tRmCalpoint.getDigits() == null ? 3 : tRmCalpoint.getDigits(); // 精度
		Date startDay = null; // 计算开始日期
		Date endDay = null; // 计算结束日期
		try {
			startDay = new SimpleDateFormat("yyyy-MM-dd").parse(clock);
			endDay = new SimpleDateFormat("yyyy-MM-dd").parse(clocke);
		} catch (ParseException e) {
			return;
		}
		String month = clock.substring(0, 7);
		Calendar cal = Calendar.getInstance();
		cal.setTime(endDay);
		cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));
		// 如果不是整月数据，并且已经有月数据，不拆分数据到日计量点, 解决跨月数据分摊影响数据准确性的ukjg
		if(this.hasMonthData(month, itemid) && !(clock.endsWith("01") && clocke.equals(new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime())))){
			return;
		}
		long dates = (endDay.getTime() - startDay.getTime())/(24*3600*1000);
		dates +=1;
		// 日计算值
		BigDecimal avc = BigDecimalUtil.divide(model.getRealvalue().doubleValue(), Double.valueOf(dates+""), 5).setScale(digits, RoundingMode.DOWN);
		// 最后一天计算值,总值ac-其他天数据之和
        BigDecimal lavc = model.getRealvalue().subtract(avc.multiply(new BigDecimal((dates-1) + ""))).setScale(digits, RoundingMode.HALF_UP);
        // 遍历日数据
        Calendar cal1 = Calendar.getInstance();
        Calendar cal2 = Calendar.getInstance();
        cal1.setTime(startDay);
        cal2.setTime(endDay);
        while(!cal1.after(cal2)){
			HashMap<String, Object> id = new HashMap<String, Object>();
			id.put("clock", new SimpleDateFormat("yyyy-MM-dd").format(cal1.getTime()));
			id.put("itemid", itemid);
			id.put("timegranid", "DAY");
			TRmCalpointValue tc = tRmCalpointValueMapper.selectByPrimaryKey(id);
			BigDecimal acb = BigDecimal.ZERO;// 计算值
			if(cal2.getTime().getTime() - cal1.getTime().getTime() > 0){
				acb = avc;
			}else{
				// 最后一天
				acb = lavc;
			}
			// 如果有人工录入数据，以人工录入数据为准
			HashMap<String, Object> cid = new HashMap<String, Object>();
			cid.put("clock", new SimpleDateFormat("yyyy-MM-dd").format(cal1.getTime()));
			cid.put("itemid", itemid);
			EmsCalpointValue ecv = emsCalpointValueMapper.selectByPrimaryKey(cid);
			// 如果已经有数据，更新
			if(tc!=null){
				if (ecv==null) {
					tc.setActualvalue(acb);
					// 最终值=计算值+修正值
					if (tc.getCorrectvalue() != null) {
						tc.setApportvalue(acb.add(tc.getCorrectvalue()));
					} else {
						tc.setApportvalue(acb);
					}
					tc.setBz("转供电录入,自动分配");
					tc.setRecTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
					tRmCalpointValueMapper.updateByPrimaryKeySelective(tc);
					try {
						// 重新计算关联项目数据
						formulaService.reCalculate(itemid, tc.getClock(), "DAY", tc.getClock());
					} catch (Exception e) {
						logger.error("重新计算错误：itemid="+ itemid + ",clock()" +  tc.getClock());
						e.printStackTrace();
					}
				}
			}else{
				tc = new TRmCalpointValue();
				tc.setClock(new SimpleDateFormat("yyyy-MM-dd").format(cal1.getTime()));
				tc.setTimegranid("DAY");
				tc.setItemid(itemid);
				tc.setItemname(tRmCalpoint.getItemname());
				tc.setApportvalue(acb); // 最终值
				tc.setCorrectvalue(BigDecimal.ZERO); // 修正值
				tc.setActualvalue(acb); // 计算值
				tc.setRecTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
				tc.setBz("转供电录入,自动分配");
				if(ecv!=null && ecv.getApportvalue()!=null){
					tc.setBz(ecv.getBz()!=null?ecv.getBz():"人工录入，自动修改");
					tc.setApportvalue(ecv.getApportvalue().setScale(digits, BigDecimal.ROUND_HALF_UP));
					tc.setCorrectvalue(ecv.getApportvalue().setScale(digits, BigDecimal.ROUND_HALF_UP));
				}
				tRmCalpointValueMapper.insert(tc);
			}
			cal1.add(Calendar.DAY_OF_YEAR, 1);
		}
        // 数据中有月的最后5天的数据,重新计算月数据
 		cal1.setTime(startDay);
 		cal1.set(Calendar.DAY_OF_MONTH, 1);
 		cal1.add(Calendar.MONTH, 1);
 		cal1.add(Calendar.DAY_OF_YEAR, -5);
 		while(!cal1.after(cal2)){
 			tRmCalpointValueService.restatCalpData(itemid, new SimpleDateFormat("yyyy-MM").format(cal1.getTime()), "MONTH", userId);
 			cal1.add(Calendar.MONTH, 1);
 		}
 		// 重新计算年数据-有12月数据，开始重新计算年数据
 		cal1.setTime(startDay);
 		cal1.set(Calendar.DAY_OF_MONTH, 1);
 		cal1.set(Calendar.MONTH, 11);
 		if(!cal1.after(cal2)){
 			tRmCalpointValueService.restatCalpData(itemid, new SimpleDateFormat("yyyy").format(startDay), "YEAR", userId);
 		}
	}
	
	@Override
	public void checkValue(TRmTransfereActValue t) {
		String userId = JwtUtil.getUseridByToken();
		t.setCheckuser(userId);
		t.setChecktim(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
		tRmTransfereActValueMapper.updateByPrimaryKeySelective(t);
//		TRmCalpoint tRmCalpoint = tRmCalpointMapper.selectByPrimaryKey(t.getItemid());
//		String clock = t.getClock();
//		String clocke = t.getClocke();
//		Short digits = tRmCalpoint.getDigits() == null ? 3 : tRmCalpoint.getDigits(); // 精度
//		Date startDay = null; // 计算开始日期
//		Date endDay = null; // 计算结束日期
//		try {
//			startDay = new SimpleDateFormat("yyyy-MM-dd").parse(clock);
//			endDay = new SimpleDateFormat("yyyy-MM-dd").parse(clocke);
//		} catch (ParseException e) {
//			return;
//		}
//		long dates = (endDay.getTime() - startDay.getTime())/(24*3600*1000);
//		dates +=1;
//		// 日计算值
//		BigDecimal avc = BigDecimalUtil.divide(t.getRealvalue().doubleValue(), Double.valueOf(dates+""), 5).setScale(digits, RoundingMode.DOWN);
//		// 最后一天计算值,总值ac-其他天数据之和
//        BigDecimal lavc = t.getRealvalue().subtract(avc.multiply(new BigDecimal((dates-1) + ""))).setScale(digits, RoundingMode.HALF_UP);
//        // 遍历日数据
//        Calendar cal1 = Calendar.getInstance();
//        Calendar cal2 = Calendar.getInstance();
//        cal1.setTime(startDay);
//        cal2.setTime(endDay);
//		while(!cal1.after(cal2)){
//			HashMap<String, Object> id = new HashMap<String, Object>();
//			id.put("clock", new SimpleDateFormat("yyyy-MM-dd").format(cal1.getTime()));
//			id.put("itemid", t.getItemid());
//			id.put("timegranid", "DAY");
//			TRmCalpointValue tc = tRmCalpointValueMapper.selectByPrimaryKey(id);
//			BigDecimal acb = BigDecimal.ZERO;// 计算值
//			// 审核通过
//			if(t.getState().equals("2")){
//				if(cal2.getTime().getTime() - cal1.getTime().getTime() > 0){
//					acb = avc;
//				}else{
//					// 最后一天
//					acb = lavc;
//				}
//			}
//			if(tc!=null){
//				tc.setActualvalue(acb);
//				// 最终值=计算值+修正值
//				if (tc.getCorrectvalue() != null) {
//					tc.setApportvalue(acb.add(tc.getCorrectvalue()));
//				} else {
//					tc.setApportvalue(acb);
//				}
//				tc.setBz(t.getState().equals("2") ? "审核通过,自动分配":"撤销审核");
//				tc.setRecTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
//				tRmCalpointValueMapper.updateByPrimaryKeySelective(tc);
//			}else{
//				tc = new TRmCalpointValue();
//				tc.setClock(new SimpleDateFormat("yyyy-MM-dd").format(cal1.getTime()));
//				tc.setTimegranid("DAY");
//				tc.setItemid(t.getItemid());
//				tc.setItemname(tRmCalpoint.getItemname());
//				tc.setApportvalue(acb); // 最终值
//				tc.setCorrectvalue(BigDecimal.ZERO); // 修正值
//				tc.setActualvalue(acb); // 计算值
//				tc.setRecTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
//				tc.setBz(t.getState().equals("2") ? "审核通过,自动分配":"撤销审核");
//				tRmCalpointValueMapper.insert(tc);
//			}
//			cal1.add(Calendar.DAY_OF_YEAR, 1);
//		}
//		// 数据中有月的最后5天的数据,重新计算月数据
//		cal1.setTime(startDay);
//		cal1.set(Calendar.DAY_OF_MONTH, 1);
//		cal1.add(Calendar.MONTH, 1);
//		cal1.add(Calendar.DAY_OF_YEAR, -5);
//		while(!cal1.after(cal2)){
//			tRmCalpointValueService.restatCalpData(t.getItemid(), new SimpleDateFormat("yyyy-MM").format(cal1.getTime()), "MONTH");
//			cal1.add(Calendar.MONTH, 1);
//		}
//		// 重新计算年数据-有12月数据，开始重新计算年数据
//		cal1.setTime(startDay);
//		cal1.set(Calendar.DAY_OF_MONTH, 1);
//		cal1.set(Calendar.MONTH, 11);
//		if(!cal1.after(cal2)){
//			tRmCalpointValueService.restatCalpData(t.getItemid(), new SimpleDateFormat("yyyy").format(startDay), "YEAR");
//		}
	}
	
	// 审核202200607
	public void checkValue2(TRmTransfereActValue t) {
		String userId = JwtUtil.getUseridByToken();
		t.setCheckuser(userId);
		t.setChecktim(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
		tRmTransfereActValueMapper.updateByPrimaryKeySelective(t);
		HashMap<String, Object> cid = new HashMap<String, Object>();
		cid.put("clock", t.getClock());
		cid.put("itemid", t.getItemid());
		cid.put("timegranid", "MONTH");
		// 计量点数据
		TRmCalpointValue tc = tRmCalpointValueMapper.selectByPrimaryKey(cid);
		// 审核通过
		if(t.getState().equals("2")){
			if(tc!=null){
				tc.setApportvalue(t.getRealvalue()); // 最终值
				tc.setActualvalue(t.getRealvalue()); // 计算值
				tc.setCorrectvalue(BigDecimal.ZERO); // 修正值
				tc.setUptime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
				tc.setMintvalue(t.getMintvalue());
				tc.setMendvalue(t.getMendvalue());
				tc.setBz("审核通过");
				tc.setUpman(t.getCheckuser()); // 修改人
				tRmCalpointValueMapper.updateByPrimaryKeySelective(tc);
			}else{
				tc = new TRmCalpointValue();
				tc.setApportvalue(t.getRealvalue()); // 最终值
				tc.setActualvalue(t.getRealvalue()); // 计算值
				tc.setCorrectvalue(BigDecimal.ZERO); // 修正值
				tc.setMintvalue(t.getMintvalue());
				tc.setMendvalue(t.getMendvalue());
				tc.setBz("审核通过");
				tc.setCrman(t.getCheckuser());
				tc.setRecTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())); // 创建时间
				tc.setClock(t.getClock());
				tc.setTimegranid("MONTH");
				tc.setItemid(t.getItemid());
				tc.setItemname(tRmCalpointMapper.selectByPrimaryKey(t.getItemid()).getItemname());
				tRmCalpointValueMapper.insert(tc);
			}
		}else if(t.getState().equals("1")){ // 撤销审核
			if(tc!=null){
				tc.setApportvalue(BigDecimal.ZERO); // 最终值
				tc.setActualvalue(BigDecimal.ZERO); // 计算值
				tc.setCorrectvalue(BigDecimal.ZERO); // 修正值
				tc.setUpman(t.getCheckuser()); // 修改人
				tc.setUptime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
				tc.setMintvalue(BigDecimal.ZERO);
				tc.setMendvalue(BigDecimal.ZERO);
				tc.setBz("撤销审核");
				tRmCalpointValueMapper.updateByPrimaryKeySelective(tc);
			}
		}
	}
	
	@Override
	@Transactional(rollbackFor=Exception.class)
	public void createRecord() {
		logger.info(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "宾馆转供电记录定时获取任务执行开始");
		String userId = JwtUtil.getUseridByToken();
		String LocationId = "86";   //宾馆外供电ID
		
		try {
			Date dateNow = null;
			Date dateLast = null;
			SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM");
			
			Calendar cal = Calendar.getInstance();  
			cal.setTime(new Date());  
			cal.add(Calendar.MONTH, -1);
			dateNow = cal.getTime();
			cal.add(Calendar.MONTH, -1);
			dateLast = cal.getTime();
			
			//查看是否已经存在记录
			String sqlHas = "select count(CLOCK) from T_RM_TRANSFERE_ACT_VALUE where CLOCK = ? and LOCATIONID = ?";
			
			Integer iCount = jdbcTemplate.queryForObject(sqlHas, new Object[] {formatter.format(dateNow), LocationId}, Integer.class);
			if(iCount >0) {
				logger.info("记录已经存在,任务结束");
			}else {
				String sqlLast = "select t.F16205 from EMS_E_TIMING t where substr(clock,0,7) = ? and rownum = 1 order by clock desc";
				String sqlCurrent = "select t.F16205 from EMS_E_TIMING t where substr(clock,0,7) = ? and rownum = 1 order by clock desc";
				
				TRmElectricityLocation t = tRmElectricityLocationService.getById(LocationId);
				if(t.getId().equalsIgnoreCase(LocationId) == false) {
					logger.info("获取不到外供电地点基本信息，任务中止");
				}else {
					BigDecimal lastValue = jdbcTemplate.queryForObject(sqlLast, new Object[]{formatter.format(dateLast)}, BigDecimal.class);
					BigDecimal currentValue = jdbcTemplate.queryForObject(sqlCurrent, new Object[]{formatter.format(dateNow)}, BigDecimal.class);
					BigDecimal mods = new BigDecimal(t.getMods());
					lastValue.setScale(2, BigDecimal.ROUND_HALF_UP);
					currentValue.setScale(2, BigDecimal.ROUND_HALF_UP);
					BigDecimal apportvalue = currentValue.subtract(lastValue).multiply(mods);
					apportvalue.setScale(0, BigDecimal.ROUND_HALF_UP);
					
					TRmTransfereActValue model = new TRmTransfereActValue();
					model.setId("");
					model.setClock(formatter.format(dateNow));
					model.setCreater(userId);
					model.setCreatetim(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
		    		model.setState("1");
		    		model.setMintvalue(lastValue);
		    		model.setMendvalue(currentValue);
		    		model.setApportvalue(apportvalue);
		    		model.setWastage(BigDecimal.valueOf(0));
		    		model.setSecondvalue(BigDecimal.valueOf(0));
		    		model.setRealvalue(apportvalue);
		    		model.setLocation(t.getLocation());
		    		model.setWorkprocid(t.getWorkprocid());
		    		model.setLocationid(LocationId);
		    		model.setWorkshop("");
		    		model.setBz("");
		    		model.setCheckuser("");
		    		model.setCreatetim("");
		    		this.add(model);
					logger.info(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "宾馆转供电记录定时获取任务执行完毕");
				}
			}
		} catch (Exception e) {
	        //e.printStackTrace();
	        throw new RuntimeException("出错了:" + e.getMessage());
	    }
	}

	@Override
	public PageList<Map<String, Object>> getDateEditForPage(HashMap<String, Object> parmas, Integer pageNum,
			Integer pageSize) {
		PageHelper.startPage(pageNum, pageSize);
		if(parmas.get("networkid")!=null && !parmas.get("networkid").toString().isEmpty()){
			String networkid = parmas.get("networkid").toString();
			if(!networkid.startsWith("'")){
				networkid = "'" + networkid.replaceAll(",", "','").replaceAll("，", "','") + "'";
			}
			parmas.put("networkid", networkid);
		}
		if(parmas.get("workprocid")!=null && !parmas.get("workprocid").toString().isEmpty()){
			String workprocid = parmas.get("workprocid").toString();
			if(!workprocid.startsWith("'")){
				workprocid = "'" + workprocid.replaceAll(",", "','").replaceAll("，", "','") + "'";
			}
			parmas.put("workprocid", workprocid);
		}
		if(parmas.get("location")!=null && !parmas.get("location").toString().isEmpty()){
			String location = parmas.get("location").toString();
			if(!location.startsWith("'")){
				location = "'" + location.replaceAll(",", "','").replaceAll("，", "','") + "'";
			}
			parmas.put("location", location);
		}
        List<Map<String, Object>> rows = tRmTransfereActValueMapper.getDateEdit(parmas);
        PageList<Map<String, Object>> pageInfo = new PageList<Map<String, Object>>(rows);
        return pageInfo;
	}

	@Override
	public PageList<Map<String, Object>> getDateForPage(HashMap<String, Object> parmas, Integer pageNum,
			Integer pageSize) {
		PageHelper.startPage(pageNum, pageSize);
		if(parmas.get("networkid")!=null && !parmas.get("networkid").toString().isEmpty()){
			String networkid = parmas.get("networkid").toString();
			if(!networkid.startsWith("'")){
				networkid = "'" + networkid.replaceAll(",", "','").replaceAll("，", "','") + "'";
			}
			parmas.put("networkid", networkid);
		}
		if(parmas.get("workprocid")!=null && !parmas.get("workprocid").toString().isEmpty()){
			String workprocid = parmas.get("workprocid").toString();
			if(!workprocid.startsWith("'")){
				workprocid = "'" + workprocid.replaceAll(",", "','").replaceAll("，", "','") + "'";
			}
			parmas.put("workprocid", workprocid);
		}
		if(parmas.get("location")!=null && !parmas.get("location").toString().isEmpty()){
			String location = parmas.get("location").toString();
			if(!location.startsWith("'")){
				location = "'" + location.replaceAll(",", "','").replaceAll("，", "','") + "'";
			}
			parmas.put("location", location);
		}
		
		if(parmas.get("exactsearch")!=null && !parmas.get("exactsearch").toString().isEmpty()){
			String exactsearch = parmas.get("exactsearch").toString();
			String clock = parmas.get("clock").toString();
			String clocke = parmas.get("clocke").toString();
			String clockstr = "";
			if(exactsearch.compareTo("1") == 0){
				clockstr = String.format("and v.clock = '%s' and v.clocke = '%s'", clock, clocke);
			}else {
				clockstr = String.format("and v.clocke >= '%s' and v.clocke <= '%s'", clock, clocke);
			}
			parmas.put("clock1", clockstr);
		}
        List<Map<String, Object>> rows = tRmTransfereActValueMapper.getDate(parmas);
        PageList<Map<String, Object>> pageInfo = new PageList<Map<String, Object>>(rows);
        return pageInfo;
	}

	@Override
	public Long countDateEdit(HashMap<String, Object> parmas) {
		if(parmas.get("networkid")!=null && !parmas.get("networkid").toString().isEmpty()){
			String networkid = parmas.get("networkid").toString();
			if(!networkid.startsWith("'")){
				networkid = "'" + networkid.replaceAll(",", "','").replaceAll("，", "','") + "'";
			}
			parmas.put("networkid", networkid);
		}
		if(parmas.get("workprocid")!=null && !parmas.get("workprocid").toString().isEmpty()){
			String workprocid = parmas.get("workprocid").toString();
			if(!workprocid.startsWith("'")){
				workprocid = "'" + workprocid.replaceAll(",", "','").replaceAll("，", "','") + "'";
			}
			parmas.put("workprocid", workprocid);
		}
		if(parmas.get("location")!=null && !parmas.get("location").toString().isEmpty()){
			String location = parmas.get("location").toString();
			if(!location.startsWith("'")){
				location = "'" + location.replaceAll(",", "','").replaceAll("，", "','") + "'";
			}
			parmas.put("location", location);
		}
		return tRmTransfereActValueMapper.countDateEdit(parmas);
	}

	@Override
	public void updateCal(TRmTransfereActValue model) {
		String opuser = JwtUtil.getUseridByToken();
		String itemid = model.getItemid();
    	TRmCalpoint tRmCalpoint = tRmCalpointMapper.selectByPrimaryKey(itemid);
    	String clock = model.getClock();
		String clocke = model.getClocke();
		Short digits = tRmCalpoint.getDigits() == null ? 3 : tRmCalpoint.getDigits(); // 精度
		Date startDay = null; // 计算开始日期
		Date endDay = null; // 计算结束日期
		try {
			startDay = new SimpleDateFormat("yyyy-MM-dd").parse(clock);
			endDay = new SimpleDateFormat("yyyy-MM-dd").parse(clocke);
		} catch (ParseException e) {
			return;
		}
		long dates = (endDay.getTime() - startDay.getTime())/(24*3600*1000);
		dates +=1;
		// 日计算值
		BigDecimal avc = BigDecimalUtil.divide(model.getRealvalue().doubleValue(), Double.valueOf(dates+""), 5).setScale(digits, RoundingMode.DOWN);
		// 最后一天计算值,总值ac-其他天数据之和
        BigDecimal lavc = model.getRealvalue().subtract(avc.multiply(new BigDecimal((dates-1) + ""))).setScale(digits, RoundingMode.HALF_UP);
        // 遍历日数据
        Calendar cal1 = Calendar.getInstance();
        Calendar cal2 = Calendar.getInstance();
        cal1.setTime(startDay);
        cal2.setTime(endDay);
        while(!cal1.after(cal2)){
			HashMap<String, Object> id = new HashMap<String, Object>();
			id.put("clock", new SimpleDateFormat("yyyy-MM-dd").format(cal1.getTime()));
			id.put("itemid", itemid);
			id.put("timegranid", "DAY");
			TRmCalpointValue tc = tRmCalpointValueMapper.selectByPrimaryKey(id);
			BigDecimal acb = BigDecimal.ZERO;// 计算值
			if(cal2.getTime().getTime() - cal1.getTime().getTime() > 0){
				acb = avc;
			}else{
				// 最后一天
				acb = lavc;
			}
			// 如果已经有数据，不做修改
			if(tc!=null && tc.getApportvalue().doubleValue() == 0 && tc.getActualvalue().doubleValue() == 0 && acb.doubleValue() != 0){
				tc.setActualvalue(acb);
				// 最终值=计算值+修正值
				if (tc.getCorrectvalue() != null) {
					tc.setApportvalue(acb.add(tc.getCorrectvalue()));
				} else {
					tc.setApportvalue(acb);
				}
				tc.setBz("转供电录入,自动分配");
				tc.setRecTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
				tRmCalpointValueMapper.updateByPrimaryKeySelective(tc);
				// 重新计算关联项目数据
				formulaService.reCalculate(itemid, tc.getClock(), "DAY", tc.getClock());
			}else if(tc==null){
				tc = new TRmCalpointValue();
				tc.setClock(new SimpleDateFormat("yyyy-MM-dd").format(cal1.getTime()));
				tc.setTimegranid("DAY");
				tc.setItemid(itemid);
				tc.setItemname(tRmCalpoint.getItemname());
				tc.setApportvalue(acb); // 最终值
				tc.setCorrectvalue(BigDecimal.ZERO); // 修正值
				tc.setActualvalue(acb); // 计算值
				tc.setRecTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
				tc.setBz("转供电录入,自动分配");
				tRmCalpointValueMapper.insert(tc);
			}
			cal1.add(Calendar.DAY_OF_YEAR, 1);
		}
        // 数据中有月的最后2天的数据,重新计算月数据
 		cal1.setTime(startDay);
 		cal1.set(Calendar.DAY_OF_MONTH, 1);
 		cal1.add(Calendar.MONTH, 1);
 		cal1.add(Calendar.DAY_OF_YEAR, -2);
 		while(!cal1.after(cal2)){
 			tRmCalpointValueService.restatCalpData(itemid, new SimpleDateFormat("yyyy-MM").format(cal1.getTime()), "MONTH", opuser);
 			cal1.add(Calendar.MONTH, 1);
 		}
 		// 重新计算年数据-有12月数据，开始重新计算年数据
 		cal1.setTime(startDay);
 		cal1.set(Calendar.DAY_OF_MONTH, 1);
 		cal1.set(Calendar.MONTH, 11);
 		if(!cal1.after(cal2)){
 			tRmCalpointValueService.restatCalpData(itemid, new SimpleDateFormat("yyyy").format(startDay), "YEAR", opuser);
 		}
	}

	@Override
	public boolean hasMonthData(String month, String itemid) {
		Date d = new Date();
		String clock = month + "-01";
		String clocke = "";
		try {
			d = new SimpleDateFormat("yyyy-MM").parse(month);
			Calendar cal = Calendar.getInstance();
			cal.setTime(d);
			cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));
			clocke = new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime());
		} catch (Exception e) {
			return true;
		}
		Map<String, Object> m = new HashMap<String, Object>();
		m.put("itemid", itemid);
		m.put("clock", clock);
		m.put("clocke", clocke);
		List<TRmTransfereActValue> l = tRmTransfereActValueMapper.selectByParameters(m);
		if(l!=null && l.size()>0){
			return true;
		}else{
			return false;
		}
	}
}
