package com.steerinfo.ems.trmactvalue.controller;

import com.steerinfo.auth.utils.JwtUtil;
import com.steerinfo.ems.Utils.BigDecimalUtil;
import com.steerinfo.ems.Utils.DateUtils;
import com.steerinfo.ems.Utils.EmsEAiUtil;
import com.steerinfo.ems.Utils.StrUtils;
import com.steerinfo.ems.emseaihoursumtab1.mapper.EmsEAiHourSumTab1Mapper;
import com.steerinfo.ems.emseaihoursumtab1.model.EmsEAiHourSumTab1;
import com.steerinfo.ems.emseaihoursumtab1org.mapper.EmsEAiHourSumTab1OrgMapper;
import com.steerinfo.ems.emseaihoursumtab1org.model.EmsEAiHourSumTab1Org;
import com.steerinfo.ems.emsetiming.mapper.EmsETimingMapper;
import com.steerinfo.ems.formula.service.IFormulaService;
import com.steerinfo.ems.ifemsmesactitem.model.IfEmsMesActitem;
import com.steerinfo.ems.ifemsmesactitem.service.IIfEmsMesActitemService;
import com.steerinfo.ems.ifmesemsproductorder.service.IIfMesEmsProductorderService;
import com.steerinfo.ems.ifmesemsswapfile.model.IfMesEmsSwapfile;
import com.steerinfo.ems.ifmesemsswapfile.service.IIfMesEmsSwapfileService;
import com.steerinfo.ems.trmactitem.mapper.TRmActItemMapper;
import com.steerinfo.ems.trmactitem.model.TRmActItem;
import com.steerinfo.ems.trmactitem.service.ITRmActItemService;
import com.steerinfo.framework.controller.BaseRESTfulController;
import com.steerinfo.framework.controller.RESTfulResult;
import com.steerinfo.framework.service.pagehelper.PageList;
import com.steerinfo.ems.trmactvalue.mapper.TRmActValueMapper;
import com.steerinfo.ems.trmactvalue.model.TRmActValue;
import com.steerinfo.ems.trmactvalue.service.ITRmActValueService;
import com.steerinfo.ems.trmcalpoint.mapper.TRmCalpointMapper;
import com.steerinfo.ems.trmcalpoint.model.TRmCalpoint;
import com.steerinfo.ems.trmcalpoint.service.ITRmCalpointService;
import com.steerinfo.ems.trmindexitem.mapper.TRmIndexItemMapper;
import com.steerinfo.ems.trmindexitem.model.TRmIndexItem;
import com.steerinfo.ems.trmtransfereactvalue.mapper.TRmTransfereActValueMapper;
import com.steerinfo.ems.trmtransfereactvalue.model.TRmTransfereActValue;
import com.steerinfo.ems.trmtransfereactvalue.service.ITRmTransfereActValueService;
import com.steerinfo.ems.trmworkprocmaterial.mapper.TRmWorkprocMaterialMapper;
import com.steerinfo.ems.trmworkprocmaterial.model.TRmWorkprocMaterial;
import com.steerinfo.ems.trmworkprocmaterialvalue.service.ITRmWorkprocMaterialValueService;
import com.steerinfo.ems.trmworkprocproduct.mapper.TRmWorkprocProductMapper;
import com.steerinfo.ems.trmworkprocproduct.model.TRmWorkprocProduct;
import com.steerinfo.ems.trmworkprocproductvalue.service.ITRmWorkprocProductValueService;
import com.steerinfo.ems.usagedata.mapper.UsageDataMapper;
import com.steerinfo.ems.usagedata.model.UsageData;
import com.steerinfo.ems.usagedataconfig.model.UsageDataConfig;
import com.steerinfo.ems.usagedataconfig.service.IUsageDataConfigService;

import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;

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

/**
 * TRmActValue RESTful接口：
 * @author generator
 * @version 1.0-SNAPSHORT 2019-10-19 09:10
 * 类描述
 * 修订历史：
 * 日期：2019-10-19
 * 作者：generator
 * 参考：
 * 描述：TRmActValue RESTful接口
 * @see null
 * @Copyright 湖南视拓信息技术股份有限公司. All rights reserved.
 */
@RestController
@RequestMapping("/${api.version}/trmactvalues")
public class TRmActValueController extends BaseRESTfulController {
	private static final Logger logger = LoggerFactory.getLogger(TRmActValueController.class);
	
    @Autowired
    ITRmActValueService tRmActValueService;
    @Autowired
    IIfEmsMesActitemService ifEmsMesActitemService;
    @Autowired
    IFormulaService formulaService;
    @Autowired
    ITRmActItemService tRmActItemService;
    @Autowired
    private ITRmWorkprocProductValueService tRmWorkprocProductValueService;
    @Autowired
    private TRmActValueMapper tRmActValueMapper;
    @Autowired
    private TRmActItemMapper tRmActItemMapper;
    @Autowired
    private TRmCalpointMapper tRmCalpointMapper;
    @Autowired
    private TRmWorkprocMaterialMapper tRmWorkprocMaterialMapper;
    @Autowired
    private TRmWorkprocProductMapper tRmWorkprocProductMapper;
    @Autowired
    private TRmIndexItemMapper tRmIndexItemMapper;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private EmsEAiHourSumTab1Mapper emsEAiHourSumTab1Mapper;
    @Autowired
    private EmsEAiHourSumTab1OrgMapper emsEAiHourSumTab1OrgMapper;
    @Autowired
    private EmsETimingMapper emsETimingMapper;
    @Autowired
    IUsageDataConfigService usageDataConfigService;
    @Autowired
    private UsageDataMapper usageDataMapper;
    @Autowired
    ITRmWorkprocMaterialValueService tRmWorkprocMaterialValueService;
    @Autowired
    IIfMesEmsSwapfileService ifMesEmsSwapfileService;
    @Autowired
    TRmTransfereActValueMapper tRmTransfereActValueMapper;
    @Autowired
    ITRmTransfereActValueService tRmTransfereActValueService;
    @Autowired
    IIfMesEmsProductorderService ifMesEmsProductorderService;
    @Autowired
    ITRmCalpointService tRmCalpointService;
    
    @ApiOperation(value="获取列表", notes="分页查询")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "pageNum", value = "查询页数", required = false, dataType = "Integer"),
        @ApiImplicitParam(name = "pageSize", value = "每页记录数", required = false, dataType = "Integer")
    })
    //@RequiresPermissions("trmactvalue:view")
    @GetMapping(value = "/")
    public RESTfulResult list(@RequestParam HashMap parmas,Integer pageNum, Integer pageSize){
        PageList<TRmActValue> list = tRmActValueService.queryForPage(parmas, pageNum, pageSize);
        return success(list);
    }

    @ApiOperation(value="获取列表", notes="分页模糊查询")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "pageNum", value = "查询页数", required = false, dataType = "Integer"),
        @ApiImplicitParam(name = "pageSize", value = "每页记录数", required = false, dataType = "Integer")
    })
    //@RequiresPermissions("trmactvalue:view")
    @GetMapping(value = "/like/")
    public RESTfulResult listLike(@RequestParam HashMap parmas,Integer pageNum, Integer pageSize){
        PageList<TRmActValue> list = tRmActValueService.queryLikeForPage(parmas, pageNum, pageSize);
        return success(list);
    }
    
    @ApiOperation(value="创建", notes="根据TRmActValue对象创建")
    @ApiImplicitParam(name = "tRmActValue", value = "详细实体tRmActValue", required = true, dataType = "TRmActValue")
    //@RequiresPermissions("trmactvalue:create")
    @PostMapping(value = "/")
    public RESTfulResult add(@ModelAttribute TRmActValue model){
        TRmActValue tRmActValue = tRmActValueService.add(model);
        return success(tRmActValue);
    }

    @ApiOperation(value="获取详细信息", notes="根据url的id来获取详细信息")
    @ApiImplicitParam(paramType = "path", name = "id", value = "ID", required = true, dataType = "String")
    //@RequiresPermissions("trmactvalue:view")
    @PostMapping(value = "/info", produces  = "application/json;charset=UTF-8")
    public RESTfulResult get(@RequestBody TRmActValue model){
    	if(model.getClock() == null || model.getClock().isEmpty()){
    		return failed(null, "请传入时间");
    	}
    	if(model.getTimegranid() == null || model.getTimegranid().isEmpty()){
    		return failed(null, "请传入时间粒度");
    	}
    	if(model.getItemid() == null || model.getItemid().isEmpty()){
    		return failed(null, "请传入项目编号");
    	}
    	HashMap<String, Object> m = new HashMap<String, Object>();
    	m.put("clock", model.getClock());
    	m.put("timegranid", model.getTimegranid());
    	m.put("itemid", model.getItemid());
        model.setId(m);
        TRmActValue tRmActValue = tRmActValueService.getById(m);
        return success(tRmActValue);
    }

    @ApiOperation(value="更新详细信息", notes="根据url的id来指定更新对象，并根据传过来的tRmActValue信息来更新详细信息")
    @ApiImplicitParams({
        @ApiImplicitParam(paramType = "path", name = "id", value = "ID", required = true, dataType = "String"),
        @ApiImplicitParam(name = "tRmActValue", value = "详细实体tRmActValue", required = true, dataType = "TRmActValue")
    })
    //@RequiresPermissions("trmactvalue:update")
    @PutMapping(value = "/update", produces  = "application/json;charset=UTF-8")
    public RESTfulResult update(@RequestBody TRmActValue model){
        if(null != model.getFid()){
            IfEmsMesActitem ifEmsMesActitem = ifEmsMesActitemService.getById(model.getFid());
            if(ifEmsMesActitem.getState()=="1"){
                return failed(500,"【"+model.getItemid()+"】已上传MES,不允许修改，请联系管理员");
            }
            if(ifEmsMesActitem.getState()=="2"){
                return  failed(500,"【"+model.getItemid()+"】MES已接收,不允许修改，请联系管理员");
            }
        }
        TRmActValue tRmActValue = tRmActValueService.modify(model);
        return success(tRmActValue);
    }
    
    @ApiOperation(value="更新详细信息", notes="根据url的id来指定更新对象，并根据传过来的tRmActValue信息来更新详细信息")
    @ApiImplicitParams({
        @ApiImplicitParam(paramType = "path", name = "id", value = "ID", required = true, dataType = "String"),
        @ApiImplicitParam(name = "tRmActValue", value = "详细实体tRmActValue", required = true, dataType = "TRmActValue")
    })
    //@RequiresPermissions("trmactvalue:update")
    @PutMapping(value = "/batchupdate", produces  = "application/json;charset=UTF-8")
    public RESTfulResult batchupdate(@RequestBody TRmActValue[] models){
    	int failnum = 0;
        ArrayList<String> failmsgs = new ArrayList<String>();
        for (int i = 0; i< models.length; i++) {
        	TRmActValue model = models[i];
        	try {
	        	if(null != model.getFid()){
	                IfEmsMesActitem ifEmsMesActitem = ifEmsMesActitemService.getById(model.getFid());
	                if(ifEmsMesActitem.getState()=="1"){
	                    //return failed(500,"【"+model.getItemid()+"】已上传MES,不允许修改，请联系管理员");
	                	throw new Exception("【"+model.getItemid()+"】已上传MES,不允许修改，请联系管理员");
	                }
	                if(ifEmsMesActitem.getState()=="2"){
	                    //return  failed(500,"【"+model.getItemid()+"】MES已接收,不允许修改，请联系管理员");
	                    throw new Exception("【"+model.getItemid()+"】MES已接收,不允许修改，请联系管理员");
	                }
	            }
	        	model.setUserid(JwtUtil.getUseridByToken());
	            model.setUptime(DateUtils.dateStr(new Date(),"yyyy-MM-dd HH:mm:ss"));
	            tRmActValueService.modify(model);
        	}catch(Exception e){
                failnum++;
                failmsgs.add(model.getItemid());
                logger.error("数据修改出现错误,错误原因是" + e + ",id是" + model.getItemid());
            }
        	
        	if(failnum > 0){
                logger.info("本次共修改" + models.length + "条数据,其中成功" + (models.length - failnum) + "条,失败" + failnum + "条");
                return success(failmsgs, "101","本次共修改" + models.length + "条数据,其中成功" + (models.length - failnum) + "条,失败" + failnum + "条,失败的id:" + failmsgs.toString());
            }
    	}
        return success();
    }

    @ApiOperation(value="删除", notes="根据url的id来指定删除对象")
    @ApiImplicitParam(paramType = "path", name = "id", value = "ID", required = true, dataType = "String")
    //@RequiresPermissions("trmactvalue:delete")
    @DeleteMapping(value = "/delete", produces  = "application/json;charset=UTF-8")
    public RESTfulResult delete(@RequestBody TRmActValue model){
    	if(model.getClock() == null || model.getClock().isEmpty()){
    		return failed(null, "请传入时间");
    	}
    	if(model.getTimegranid() == null || model.getTimegranid().isEmpty()){
    		return failed(null, "请传入时间粒度");
    	}
    	if(model.getItemid() == null || model.getItemid().isEmpty()){
    		return failed(null, "请传入项目编号");
    	}
    	HashMap<String, Object> m = new HashMap<String, Object>();
    	m.put("clock", model.getClock());
    	m.put("timegranid", model.getTimegranid());
    	m.put("itemid", model.getItemid());
        model.setId(m);
        tRmActValueService.delete(m);
        return success();
    }
    
    @ApiOperation(value="获得供需实绩对比分析数据", notes="能源综合分析-供需实绩分析-供需实绩对比分析页面，分页查询")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "pageNum", value = "查询页数", required = false, dataType = "Integer"),
        @ApiImplicitParam(name = "pageSize", value = "每页记录数", required = false, dataType = "Integer")
    })
    @GetMapping(value = "/getDate611ForPage")
    public RESTfulResult getDate611ForPage(@RequestParam HashMap<String, Object> parmas,Integer pageNum, Integer pageSize){
    	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);
		}
    	PageList<Map<String, Object>> list = tRmActValueService.getDate611ForPage(parmas, pageNum, pageSize);
        return success(list);
    }
    
    @ApiOperation(value="获得供需实绩跟踪及趋势分析数据", notes="能源综合分析-供需实绩分析-供需实绩跟踪及趋势分析页面,分页查询")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "pageNum", value = "查询页数", required = false, dataType = "Integer"),
        @ApiImplicitParam(name = "pageSize", value = "每页记录数", required = false, dataType = "Integer"),
        @ApiImplicitParam(name = "pageNum2", value = "查询页数2", required = false, dataType = "Integer"),
        @ApiImplicitParam(name = "pageSize2", value = "每页记录数2", required = false, dataType = "Integer")
    })
    @GetMapping(value = "/getDate612ForPage")
    public RESTfulResult getDate612ForPage(@RequestParam HashMap<String, Object> parmas,Integer pageNum, Integer pageSize,Integer pageNum2, Integer pageSize2){
    	if (parmas == null || parmas.get("ds").toString().isEmpty()) {
    		return failed(null, "请选择数据源");
    	}
    	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);
		}
    	List<Map<String, Object>> list = tRmActValueService.getDate6121ForPage(parmas, pageNum, pageSize);
    	List<Map<String, Object>> list2 = tRmActValueService.getDate6122ForPage(parmas, pageNum2, pageSize2);
    	Map<String, Object> m = new HashMap<String, Object>();
    	m.put("result1", list);
    	m.put("result2", list2);
        return success(m);
    }
	
	@ApiOperation(value="重新生成项目数据", notes="重新生成项目数据，包括计量点、实绩、计划、平衡等")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "itemid", value = "项目ID,多个用逗号隔开", required = false, dataType = "String"),
        @ApiImplicitParam(name = "clock", value = "起始时间", required = false, dataType = "String"),
        @ApiImplicitParam(name = "timegranid", value = "时间粒度", required = false, dataType = "String"),
        @ApiImplicitParam(name = "clockend", value = "结束时间，可为空", required = false, dataType = "String")
    })
	@GetMapping("/restatDate")
	public RESTfulResult restatDate(@RequestParam HashMap<String,Object> parmas) {
		if (parmas == null) {
    		return failed(null, "请传入参数");
    	}
		if (parmas.get("itemid")==null || parmas.get("itemid").toString().isEmpty()) {
    		return failed(null, "请传入项目ID");
    	}
		if (parmas.get("clock")==null || parmas.get("clock").toString().isEmpty()) {
    		return failed(null, "请传入起始时间");
    	}
		if (parmas.get("timegranid")==null || parmas.get("timegranid").toString().isEmpty()) {
    		return failed(null, "请传入时间粒度");
    	}
		String aid = parmas.get("itemid").toString();
		String clock = parmas.get("clock").toString();
		String timegranid = parmas.get("timegranid").toString();
		String clockend = parmas.get("clockend")==null?"":parmas.get("clockend").toString();
		List<String> ids = StrUtils.strToList(aid);
		String res = "";
		for(String id:ids){
			res = formulaService.reItemVal(id,clock,timegranid,clockend);
		}
		if(!res.isEmpty()){
			return failed(null, res);
		}
		return success();
	}
	
	@ApiOperation(value="重新计算实绩项目数据")
    @GetMapping(value = "/restatActr")
    public RESTfulResult restatActr(@RequestParam HashMap<String, Object> parmas, String clock, String clocke, String timegranid){
		if (clock==null || clock.isEmpty()) {
    		return failed(null, "请传入起始时间");
    	}
		if (timegranid==null || timegranid.isEmpty()) {
    		return failed(null, "请传入时间粒度");
    	}
		parmas.put("itemtype", "R");
		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("energyid") != null && !parmas.get("energyid").toString().isEmpty()){
            String energyid = parmas.get("energyid").toString();
            if(!energyid.startsWith("'")){
            	energyid = "'" + energyid.replaceAll(",", "','").replaceAll("，", "','") + "'";
            }
            parmas.put("energyid", energyid);
        }
    	if(parmas.get("propertyid") != null && !parmas.get("propertyid").toString().isEmpty()){
            String propertyid = parmas.get("propertyid").toString();
            if(!propertyid.startsWith("'")){
            	propertyid = "'" + propertyid.replaceAll(",", "','").replaceAll("，", "','") + "'";
            }
            parmas.put("propertyid", propertyid);
        }
    	if(parmas.containsKey("itemid") && parmas.get("itemid") != null && !"".equals(parmas.get("itemid").toString())){
            String itemid = parmas.get("itemid").toString();
            if(!itemid.startsWith("'")){
            	itemid = "'" + itemid.replaceAll(",", "','").replaceAll("，", "','") + "'";
            }
            parmas.put("itemid", itemid);
        }
		// 查询需要统计的计量点信息
		List<TRmActItem> l = tRmActItemMapper.selectActr(parmas);
		int size = l.size();
		logger.info("需要处理的项目数：" + size);
		String res = "";
		for(int i = 0; i<l.size(); i++){
			TRmActItem t = l.get(i);
			res = formulaService.reItemVal(t.getItemid(),clock,timegranid,clocke);
			logger.info("剩下要处理的项目数：" + (size-1-i));
		}
		if(!res.isEmpty()){
			return failed(null, res);
		}
        return success();
    }
	
	@ApiOperation(value="批量重新计算", notes="根据url的id来指定更新对象，并根据传过来的TRmActValue信息来更新详细信息")
    @ApiImplicitParam(name = "TRmActValue", value = "详细实体TRmActValue", required = true, dataType = "TRmActValue")
    //@RequiresPermissions("trmcalpointvalue:update")
    @PutMapping(value = "/batchCompute", produces  = "application/json;charset=UTF-8")
    public RESTfulResult batchCompute(@RequestBody TRmActValue[] model){
    	if(model.length<1){
    		return failed(null, "请勾选数据");
    	}
    	for (int i = 0; i< model.length; i++) {
    		TRmActValue tv = model[i];
    		tRmActValueService.restatData(tv.getItemid(), tv.getClock(), tv.getTimegranid(), JwtUtil.getUseridByToken());
    	}
    	return success();
    }
	
	@ApiOperation(value="重新计算项目数据")
    @GetMapping(value = "/reData")
    public RESTfulResult reData(@RequestParam HashMap<String, Object> parmas, String clock, String clocke, String timegranid){
		if (clock==null || clock.isEmpty()) {
    		return failed(null, "请传入起始时间");
    	}
    	if (clocke==null || clocke.isEmpty()) {
    		return failed(null, "请传入结束时间");
    	}
		if (timegranid==null || timegranid.isEmpty()) {
			return failed(null, "请传入时间粒度");
    	}
		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("energyid") != null && !parmas.get("energyid").toString().isEmpty()){
            String energyid = parmas.get("energyid").toString();
            if(!energyid.startsWith("'")){
            	energyid = "'" + energyid.replaceAll(",", "','").replaceAll("，", "','") + "'";
            }
            parmas.put("energyid", energyid);
        }
    	if(parmas.get("propertyid") != null && !parmas.get("propertyid").toString().isEmpty()){
            String propertyid = parmas.get("propertyid").toString();
            if(!propertyid.startsWith("'")){
            	propertyid = "'" + propertyid.replaceAll(",", "','").replaceAll("，", "','") + "'";
            }
            parmas.put("propertyid", propertyid);
        }
    	if(parmas.containsKey("itemid") && parmas.get("itemid") != null && !"".equals(parmas.get("itemid").toString())){
            String itemid = parmas.get("itemid").toString();
            if(!itemid.startsWith("'")){
            	itemid = "'" + itemid.replaceAll(",", "','").replaceAll("，", "','") + "'";
            }
            parmas.put("itemid", itemid);
        }
		String res = "";
		parmas.put("itemtype", "R");
		parmas.put("useflag", "1");
		// 查询需要统计的项目信息
		List<TRmActItem> l = tRmActItemMapper.selectActr(parmas);
		int size = l.size();
		for(int i = 0; i<l.size(); i++){
			if(res.isEmpty()){
				res = formulaService.reItemVal(l.get(i).getItemid(),clock,timegranid,clocke);
			}else{
				formulaService.reItemVal(l.get(i).getItemid(),clock,timegranid,clocke);
			}
			logger.info("剩下要处理的项目数：" + (size-1-i) + "(" + size + ")");
		}
		if(!res.isEmpty()){
			return success(null, res);
		}
        return success();
    }
	
	@ApiOperation(value="重新计算项目数据")

    @GetMapping(value = "/reDatas")
    public RESTfulResult reDatas(@RequestParam HashMap<String, Object> parmas, String tb, String clock, String clocke, String timegranid){
		if (clock==null || clock.isEmpty()) {
    		return failed(null, "请传入起始时间");
    	}
		if (tb==null || tb.isEmpty()) {
    		return failed(null, "请传入重新计算的表名");
    	}
		if (timegranid==null || timegranid.isEmpty()) {
			timegranid = "DAY";
    	}
		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("energyid") != null && !parmas.get("energyid").toString().isEmpty()){
            String energyid = parmas.get("energyid").toString();
            if(!energyid.startsWith("'")){
            	energyid = "'" + energyid.replaceAll(",", "','").replaceAll("，", "','") + "'";
            }
            parmas.put("energyid", energyid);
        }
    	if(parmas.get("propertyid") != null && !parmas.get("propertyid").toString().isEmpty()){
            String propertyid = parmas.get("propertyid").toString();
            if(!propertyid.startsWith("'")){
            	propertyid = "'" + propertyid.replaceAll(",", "','").replaceAll("，", "','") + "'";
            }
            parmas.put("propertyid", propertyid);
        }
    	if(parmas.containsKey("itemid") && parmas.get("itemid") != null && !"".equals(parmas.get("itemid").toString())){
            String itemid = parmas.get("itemid").toString();
            if(!itemid.startsWith("'")){
            	itemid = "'" + itemid.replaceAll(",", "','").replaceAll("，", "','") + "'";
            }
            parmas.put("itemid", itemid);
        }
		String res = "";
		if(tb.equalsIgnoreCase("T_RM_CALPOINT_VALUE")){
			parmas.put("useflag", "1");
			// 查询需要统计的计量点信息
			List<TRmCalpoint> l = tRmCalpointMapper.selectCalpoints(parmas);
			int size = l.size();
			logger.info("需要处理的项目数：" + size);
			for(int i = 0; i<l.size(); i++){
				res = formulaService.reItemVal(l.get(i).getItemid(),clock,timegranid,clocke);
				logger.info("剩下要处理的项目数：" + (size-1-i));
			}
		} else if(tb.equalsIgnoreCase("T_RM_ACT_VALUE")){
			parmas.put("itemtype", "R");
			// 查询需要统计的项目信息
			List<TRmActItem> l = tRmActItemMapper.selectActr(parmas);
			int size = l.size();
			logger.info("需要处理的项目数：" + size);
			for(int i = 0; i<l.size(); i++){
				res = formulaService.reItemVal(l.get(i).getItemid(),clock,timegranid,clocke);
				logger.info("res：" + res);
				logger.info("剩下要处理的项目数：" + (size-1-i));
			}
		} else if(tb.equalsIgnoreCase("T_RM_BALANCE_VALUE")){
			parmas.put("itemtype", "B");
			// 查询需要统计的项目信息
			List<TRmActItem> l = tRmActItemMapper.selectActr(parmas);
			int size = l.size();
			logger.info("需要处理的项目数：" + size);
			for(int i = 0; i<l.size(); i++){
				res = formulaService.reItemVal(l.get(i).getItemid(),clock,timegranid,clocke);
				logger.info("剩下要处理的项目数：" + (size-1-i));
			}
		} else if(tb.equalsIgnoreCase("T_RM_PLAN_VALUE")){
			parmas.put("itemtype", "P");
			// 查询需要统计的项目信息
			List<TRmActItem> l = tRmActItemMapper.selectActr(parmas);
			int size = l.size();
			logger.info("需要处理的项目数：" + size);
			for(int i = 0; i<l.size(); i++){
				res = formulaService.reItemVal(l.get(i).getItemid(),clock,timegranid,clocke);
				logger.info("剩下要处理的项目数：" + (size-1-i));
			}
		} else if(tb.equalsIgnoreCase("T_RM_WORKPROC_MATERIAL_VALUE")){
			parmas.put("useflag", "1");
			List<TRmWorkprocMaterial> l = tRmWorkprocMaterialMapper.selectByParameters(parmas);
			int size = l.size();
			logger.info("需要处理的项目数：" + size);
			for(int i = 0; i<l.size(); i++){
				res = formulaService.reItemVal(l.get(i).getItemid(),clock,timegranid,clocke);
				logger.info("剩下要处理的项目数：" + (size-1-i));
			}
		} else if(tb.equalsIgnoreCase("T_RM_WORKPROC_PRODUCT_VALUE")){
			parmas.put("useflag", "1");
			List<TRmWorkprocProduct> l = tRmWorkprocProductMapper.selectByParameters(parmas);
			int size = l.size();
			logger.info("需要处理的项目数：" + size);
			for(int i = 0; i<l.size(); i++){
				res = formulaService.reItemVal(l.get(i).getItemid(),clock,timegranid,clocke);
				logger.info("剩下要处理的项目数：" + (size-1-i));
			}
		} else if(tb.equalsIgnoreCase("T_RM_INDEX_VALUE")){
			parmas.put("useflag", "1");
			parmas.put("itemflag", "3");
			List<TRmIndexItem> l = tRmIndexItemMapper.selectByParameters(parmas);
			int size = l.size();
			logger.info("需要处理的项目数：" + size);
			for(int i = 0; i<l.size(); i++){
				res = formulaService.reItemVal(l.get(i).getItemid(),clock,timegranid,clocke);
				logger.info("剩下要处理的项目数：" + (size-1-i));
			}
		} else if(tb.equalsIgnoreCase("T_RM_DW_VALUE")){
			parmas.put("itemtype", "W");
			// 查询需要统计的项目信息
			List<TRmActItem> l = tRmActItemMapper.selectActr(parmas);
			int size = l.size();
			logger.info("需要处理的项目数：" + size);
			for(int i = 0; i<l.size(); i++){
				res = formulaService.reItemVal(l.get(i).getItemid(),clock,timegranid,clocke);
				logger.info("剩下要处理的项目数：" + (size-1-i));
			}
		} else if(tb.equalsIgnoreCase("HOUR")){
			if(clocke==null || clocke.isEmpty()){
				clocke = clock;
			}
			parmas.put("useflag", "1");
			// 查询需要统计的计量点信息
			List<TRmCalpoint> l = tRmCalpointMapper.selectCalpoints(parmas);
			int size = l.size();
			logger.info("需要处理的项目数：" + size);
			for(int i = 0; i<l.size(); i++){
				String r = tRmCalpointService.restatHourDate(l.get(i).getItemid(), clock, clocke);
				if(res.isEmpty()){
					res = r;
				}
				logger.info("剩下要处理的项目数：" + (size-1-i));
			}
		}
		if(!res.isEmpty()){
			return failed(null, res);
		}
        return success();
    }
	
	@GetMapping("/bbb")
	public RESTfulResult getstate() {
		tRmActValueService.statDataforDay();
		return success();
	}
	
	@GetMapping(value = "/iff/")
    public RESTfulResult ifmesems(String clocks, String clocke){
		if (clocks==null || clocks.isEmpty()) {
    		return failed(null, "请传入起始时间");
    	}
		if (clocke==null || clocke.isEmpty()) {
    		return failed(null, "请传入结束时间");
    	}
		// System.out.println(clocks);
		// System.out.println(clocke);
    	//String sql = "select * from EMS_E_TIMING t where t.clock > '2020-05-31 23:00' and clock < '2020-07-08 00:00' order by clock";
		String sql = "select * from EMS_E_TIMING t where t.clock > '"+clocks+"' and clock < '"+clocke+"' order by clock";
    	List<Map<String, Object>> l = jdbcTemplate.queryForList(sql);
    	int size = l.size();
    	for(int i=2;i<size;i++){
    		Map<String, Object> m1 = l.get(i-1);
    		Map<String, String> m = new HashMap<String, String>();
    		Map<String, Object> m2 = l.get(i);
    		String clock = m2.get("CLOCK").toString();
    		for(String key : m2.keySet()){
    			if(clock.endsWith("5") && (key.startsWith("F7") || key.startsWith("R7"))){
    				continue;
    			}
    			if(key.startsWith("F7") || key.startsWith("R7")){
    				m1 = l.get(i-2);
    				String val1 = m1.get(key)==null?"":m1.get(key).toString();
        			String val2 = m2.get(key)==null?"":m2.get(key).toString();
        			if(val2.isEmpty() && !val1.isEmpty()){
        				boolean b=true;
        				int n = 2;
        				while(b && n<7){
        					if(i+n > size-1){
        						break;
        					}
        					Map<String, Object> m3 = l.get(i+n);
        					if(m3.get(key)!=null && !m3.get(key).toString().isEmpty()){
        						Double d1 = Double.valueOf(val1);
        						Double d3 = Double.valueOf(m3.get(key).toString());
        						if(d3.doubleValue() >= d1.doubleValue()){
        							BigDecimal jj = new BigDecimal(Double.toString(d3)).subtract(new BigDecimal(Double.toString(d1)));
        							BigDecimal adv = BigDecimalUtil.divide(jj.doubleValue(), Double.valueOf((n/2+1)+""), 3);
        							BigDecimal val = new BigDecimal(Double.toString(d1)).add(adv).setScale(2, BigDecimal.ROUND_HALF_UP);
        							m.put(key, val.toString());
        							b = false;
        						}else{
        							break;
        						}
        					}else{
        						n = n+2;
        					}
        				}
        			}
    			}else if(key.startsWith("F") || key.startsWith("R")){
        			String val1 = m1.get(key)==null?"":m1.get(key).toString();
        			String val2 = m2.get(key)==null?"":m2.get(key).toString();
        			if(val2.isEmpty() && !val1.isEmpty()){
        				boolean b=true;
        				int n = 1;
        				while(b && n<10){
        					if(i+n > size-1){
        						break;
        					}
        					Map<String, Object> m3 = l.get(i+n);
        					if(m3.get(key)!=null && !m3.get(key).toString().isEmpty()){
        						Double d1 = Double.valueOf(val1);
        						Double d3 = Double.valueOf(m3.get(key).toString());
        						if(d3.doubleValue() >= d1.doubleValue()){
        							BigDecimal jj = new BigDecimal(Double.toString(d3)).subtract(new BigDecimal(Double.toString(d1)));
        							BigDecimal adv = BigDecimalUtil.divide(jj.doubleValue(), Double.valueOf((n+1)+""), 3);
        							BigDecimal val = new BigDecimal(Double.toString(d1)).add(adv).setScale(2, BigDecimal.ROUND_HALF_UP);
        							m.put(key, val.toString());
        							b = false;
        						}else{
        							break;
        						}
        					}else{
        						n++;
        					}
        				}
        			}
        		}
        	}
    		if(!m.isEmpty()){
    			String colval = "";
    	    	for(Map.Entry<String, String> entry : m.entrySet()){
    	    		colval += entry.getKey() + "=" + entry.getValue() + ",";
    	    		sql = "update EMS_E_TIMING set "+colval.substring(0,colval.length()-1)+" where clock = '"+clock+"'";
    	    		jdbcTemplate.update(sql);
    	    	}
    	    	// System.out.println(sql);
    		}
    	}
    	return success();
    }
	
	@GetMapping(value = "/ife/")
    public RESTfulResult ife(String clocks, String clocke){
		if (clocks==null || clocks.isEmpty()) {
    		return failed(null, "请传入起始时间");
    	}
		if (clocke==null || clocke.isEmpty()) {
    		return failed(null, "请传入结束时间");
    	}
		Date startDay = new Date();
		Date endDay = new Date();
		SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH");
		try {
			startDay = sf.parse(clocks);
			endDay = sf.parse(clocke);
		} catch (Exception e) {
			return  failed();
		}
		while(!startDay.after(endDay)){
			String clk = sf.format(startDay);
			// 从EMS_E_TIMING读取小时准点值
			Map<String, Object> mp = emsETimingMapper.getHourPointVal(clk+":00");
			// 整点数据
			EmsEAiHourSumTab1Org eeho = new EmsEAiHourSumTab1Org();
            if(mp!=null && mp.size()>0){
            	eeho.setClock(clk);
            	eeho.setInsertTime(new Date());
            	eeho = EmsEAiUtil.setValByMap(eeho, mp);
                int rs = emsEAiHourSumTab1OrgMapper.updateByPrimaryKeySelective(eeho);
                if (rs == 0){
                	eeho.setInsertTime(new Date());
                	emsEAiHourSumTab1OrgMapper.insert(eeho);
                }
            }
			// 上一个小时
            String clkl = sf.format(new Date(startDay.getTime() - 3600*1000L));
            // 小时累计值 = 当前小时准点值 - 前1小时小时准点值
			EmsEAiHourSumTab1Org eehol = emsEAiHourSumTab1OrgMapper.selectByPrimaryKey(clkl);
			if(eehol==null || eehol.getClock()==null || eehol.getClock().isEmpty() || eeho.getClock()==null || eeho.getClock().isEmpty()){
				logger.error("数据表EMS_E_AI_HOUR_SUM_TAB1_ORG缺少数据：" + clk);
			}else{
				EmsEAiHourSumTab1 eeh = new EmsEAiHourSumTab1();
				eeh.setClock(clkl);
				eeh = EmsEAiUtil.setVal(eeh, eeho, eehol);
				int rs = emsEAiHourSumTab1Mapper.updateByPrimaryKeySelective(eeh);
				if (rs == 0){
					eeh.setInsertTime(new Date());
                	emsEAiHourSumTab1Mapper.insert(eeh);
                }
			}
			startDay = new Date(startDay.getTime() + 3600*1000L);
		}
		return success();
	}
    
    @GetMapping("/usage")
	public RESTfulResult usage(String clocks, String clocke) {
    	if (clocks==null || clocks.isEmpty()) {
    		return failed(null, "请传入起始时间");
    	}
		if (clocke==null || clocke.isEmpty()) {
    		return failed(null, "请传入结束时间");
    	}
		int addSize = 0;
        int errorSize = 0;
		Date startDay = new Date();
		Date endDay = new Date();
		SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
		try {
			startDay = sf.parse(clocks);
			endDay = sf.parse(clocke);
		} catch (Exception e) {
			return  failed();
		}
		List<UsageDataConfig> list = usageDataConfigService.getAutoData();
		while(!startDay.after(endDay)){
			String clock = sf.format(startDay);
	        outer:for (int i = 0; i < list.size(); i++) {
	        	UsageDataConfig item = list.get(i);
	            String energyCode = item.getEnergyCode();
	            if (energyCode == null || energyCode.length() == 0) {
	                logger.info("[配置错误][ " + item.getNote() + " ]的energyCode配置错误，放弃新增");
	                errorSize++;
	                continue;
	            }
	            if (item.getProdline() == null || item.getProdline().length() == 0) {
	                logger.info("[配置错误][ " + item.getNote() + " ]的prodline配置错误，放弃新增");
	                errorSize++;
	                continue;
	            }
	            if (!energyCode.startsWith("DL")) {
	            	System.out.println("只重新统计电数据");
	                continue;
	            }
	            HashMap<String, Object> m = new HashMap<String, Object>();
	            m.put("dataCode", energyCode);
	            m.put("dt", clock);
	            // 查询该数据当天是否存在
	            List<UsageData> selectData = usageDataMapper.selectDataCodeAndDt(m);
	            if(!selectData.isEmpty()){
	                logger.info("[USAGE_DATA]表已存在[ " + item.getNote() + " ]当天的相关信息，不进行新增");
	                // logger.info(selectData.toString());
	            } else {
	            	String prodlines = item.getProdline().trim();
					BigDecimal sum = BigDecimal.ZERO;
					String memo = "";
					String ids[] = prodlines.split(",");
					for (String itemid : ids) {
						Double db = formulaService.getValByItemid(itemid, "DAY", clock, 0);
						if (db < 0) {
							errorSize++;
							logger.info("[可能存在的问题][ " + item.getNote() + ":" + itemid + "-" + clock + " ]数据错误，放弃新增");
							continue outer;
						}
						sum = sum.add(BigDecimal.valueOf(db));
						memo += itemid + "(" + formulaService.getFormulaLatest(itemid).getDescription() + ")" + "+";
					}
					memo = memo.isEmpty()?"":memo.substring(0,memo.length()-1);
	                HashMap<String, Object> model = new HashMap<String, Object>();
	                model.put("dataCode", energyCode);
	                model.put("dataName", item.getNote());
	                model.put("dt", clock);
	                model.put("usage", sum);
	                model.put("unit", item.getUnit());
	                model.put("granularity", "DAY");
	                model.put("czr", "MES");
	                model.put("memo", memo);
	                usageDataMapper.insert(model);
	                addSize++;
	            }
	        }
			startDay = new Date(startDay.getTime() + 24*3600*1000L);
		}
		return success("本次新增" + addSize + "条,失败" + errorSize + "条。");
	}
    
    @GetMapping(value = "/statPm/")
    public RESTfulResult statPm(){
    	tRmWorkprocProductValueService.setDate(new Date());
		tRmWorkprocMaterialValueService.setDate(new Date());
    	return success();
    }
    
    @ApiOperation(value="立即从MES同步数据", notes="从MES同步投入产出数据、生产计划数据")
    @GetMapping(value = "/synMes")
    public RESTfulResult synchronousMesAnEmsData(){
        String s = ifMesEmsSwapfileService.synchronousMesAnEmsData();
        String s2 = ifMesEmsProductorderService.synchronousMesAnEmsData();
        return success(s + "，生产计划数据：" + s2);
    }
    
    @ApiOperation(value="转供电数据写入", notes="转供电数据写入")
    @GetMapping(value = "/synte")
    public RESTfulResult synte(){
    	HashMap<String, Object> param = new HashMap<String, Object>();
    	param.put("state", "1");
    	List<TRmTransfereActValue> l = tRmTransfereActValueMapper.selectByParameters(param);
    	for(TRmTransfereActValue t : l){
    		tRmTransfereActValueService.updateCal(t);
    	}
        return success();
    }
}
