package com.steerinfo.ems.trmcalpoint.controller;

import com.steerinfo.auth.utils.JwtUtil;
import com.steerinfo.ems.Utils.DateUtils;
import com.steerinfo.ems.formula.model.Formula;
import com.steerinfo.ems.formula.service.IFormulaService;
import com.steerinfo.ems.trmcalpoint.model.TRmCalpoint;
import com.steerinfo.ems.trmcalpoint.service.ITRmCalpointService;
import com.steerinfo.ems.trmelectricitylocation.mapper.TRmElectricityLocationMapper;
import com.steerinfo.ems.trmelectricitylocation.model.TRmElectricityLocation;
import com.steerinfo.ems.trmenergy.model.TRmEnergy;
import com.steerinfo.ems.trmenergy.service.ITRmEnergyService;
import com.steerinfo.ems.trmenergyproperty.model.TRmEnergyProperty;
import com.steerinfo.ems.trmenergyproperty.service.ITRmEnergyPropertyService;
import com.steerinfo.ems.trmlocation.model.TRmLocation;
import com.steerinfo.ems.trmlocation.service.ITRmLocationService;
import com.steerinfo.ems.trmstation.model.TRmStation;
import com.steerinfo.ems.trmstation.service.ITRmStationService;
import com.steerinfo.framework.controller.BaseRESTfulController;
import com.steerinfo.framework.controller.RESTfulResult;
import com.steerinfo.framework.service.pagehelper.PageList;
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.web.bind.annotation.*;

import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * TRmCalpoint RESTful接口：
 * @author 王金涛
 * @version 1.0-SNAPSHORT 2019-10-11
 * 类描述
 * 修订历史：
 * 日期：2019-10-11
 * 作者：王金涛
 * 参考：
 * 描述：TRmCalpoint RESTful接口
 * @see null
 * @Copyright 湖南视拓信息技术股份有限公司. All rights reserved.
 */
@RestController
@RequestMapping("/${api.version}/trmcalpoints")
public class TRmCalpointController extends BaseRESTfulController {

    private static final Logger LOGGER = LoggerFactory.getLogger(TRmCalpointController.class);

    @Autowired
    ITRmCalpointService tRmCalpointService;
    @Autowired
    ITRmEnergyService tRmEnergyService;
    @Autowired
    ITRmLocationService tRmLocationService;
    @Autowired
    ITRmEnergyPropertyService tRmEnergyPropertyService;
    @Autowired
    IFormulaService formulaService;
    @Autowired
    ITRmStationService tRmStationService;
    @Autowired
    private TRmElectricityLocationMapper tRmElectricityLocationMapper;

    @ApiOperation(value="获取列表", notes="分页查询")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "pageNum", value = "查询页数", required = false, dataType = "Integer"),
        @ApiImplicitParam(name = "pageSize", value = "每页记录数", required = false, dataType = "Integer")
    })
    //@RequiresPermissions("trmcalpoint:view")
    @GetMapping(value = "/")
    public RESTfulResult list(@RequestParam HashMap parmas,Integer pageNum, Integer pageSize){
        PageList<TRmCalpoint> list = tRmCalpointService.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("trmcalpoint:view")
    @GetMapping(value = "/like/")
    public RESTfulResult listLike(@RequestParam HashMap parmas,Integer pageNum, Integer pageSize){
    	if(parmas.get("locateid") != null && !parmas.get("locateid").toString().isEmpty()){
            String locateid = parmas.get("locateid").toString();
            if(!locateid.startsWith("'")){
            	locateid = "'" + locateid.replaceAll(",", "','").replaceAll("，", "','") + "'";
            }
            parmas.put("locateid", locateid);
        }
        if(parmas.get("itemid") != null && !parmas.get("itemid").toString().isEmpty()){
            String itemid = parmas.get("itemid").toString();
            if(!itemid.startsWith("'")){
                itemid = "'" + itemid.replaceAll(",", "','").replaceAll("，", "','") + "'";
            }
            parmas.put("itemid", itemid);
        }
    	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("energytypeid") != null && !parmas.get("energytypeid").toString().isEmpty()){
            String energytypeid = parmas.get("energytypeid").toString();
            if(!energytypeid.startsWith("'")){
            	energytypeid = "'" + energytypeid.replaceAll(",", "','").replaceAll("，", "','") + "'";
            }
            parmas.put("energytypeid", energytypeid);
        }
    	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.get("costid") != null && !parmas.get("costid").toString().isEmpty()){
            String costid = parmas.get("costid").toString();
            if(!costid.startsWith("'")){
                costid = "'" + costid.replaceAll(",", "','").replaceAll("，", "','") + "'";
            }
            parmas.put("costid", costid);
        }
        PageList<TRmCalpoint> list = tRmCalpointService.queryLikeForPage(parmas, pageNum, pageSize);
        return success(list);
    }
    
    @ApiOperation(value="创建", notes="根据TRmCalpoint对象创建")
    @ApiImplicitParam(name = "tRmCalpoint", value = "详细实体tRmCalpoint", required = true, dataType = "TRmCalpoint")
    //@RequiresPermissions("trmcalpoint:create")
    @PostMapping(value = "/")
    public RESTfulResult add(@ModelAttribute TRmCalpoint model){
        if(model.getEnergytypeid() == null || "".equals(model.getEnergytypeid())){
            return failed(null, "能介类型不能为空");
        }else if(model.getEnergyid() == null || "".equals(model.getEnergyid())){
            return failed(null, "能介信息不能为空");
        }else if(model.getPropertyid() == null || "".equals(model.getPropertyid())){
            return failed(null, "能介属性不能为空");
        }else if (model.getItemtype() == null || "".equals(model.getItemtype())) {
            return failed(null, "手抄或者自动不能为空");
        }else if (model.getLocateid() == null || "".equals(model.getLocateid())) {
            return failed(null, "位置不能为空");
        }
        if(model.getEnergytypeid().equalsIgnoreCase("E") && (model.getNetworkid() == null || "".equals(model.getNetworkid()))){
        	return failed(null, "能介电的计量点站所不能为空");
        }
        
        TRmEnergy tRmEnergy = tRmEnergyService.getById(model.getEnergyid());
        TRmEnergyProperty tRmEnergyProperty = tRmEnergyPropertyService.getById(model.getPropertyid());
        TRmLocation tRmLocation = tRmLocationService.getById(model.getLocateid());
        int maxid = 0;
        if(model.getEnergytypeid().equalsIgnoreCase("E")){
        	if(model.getItemname()==null || model.getItemname().isEmpty()){
        		TRmStation tRmStation = tRmStationService.getById(model.getNetworkid());
        		model.setItemname(tRmStation.getName() + tRmEnergy.getName() + tRmEnergyProperty.getName());
        	}
        	String mid = tRmCalpointService.getMaxId(model.getNetworkid() + model.getEnergyid() + model.getPropertyid());
        	maxid = mid == null ? 0 : Integer.parseInt(mid);
        	String ls = (maxid + 1) < 1000 ? String.format("%04d", maxid + 1) : (maxid + 1) + "";
            model.setItemid(model.getNetworkid() + model.getEnergyid() + model.getPropertyid() + ls);
        }else{
        	if(model.getItemname()==null || model.getItemname().isEmpty()){
        		model.setItemname(tRmLocation.getName() + tRmEnergy.getName() + tRmEnergyProperty.getName());
        	}
        	String mid = tRmCalpointService.getMaxId(model.getLocateid() + model.getEnergyid() + model.getPropertyid());
        	maxid = mid == null ? 0 : Integer.parseInt(mid);
        	String ls = (maxid + 1) < 1000 ? String.format("%04d", maxid + 1) : (maxid + 1) + "";
            model.setItemid(model.getLocateid() + model.getEnergyid() + model.getPropertyid() + ls);
        }
        if(model.getTagAlias() == null || "".equals(model.getTagAlias())) {
            model.setTagAlias(tRmLocation.getName() + tRmEnergy.getName() + tRmEnergyProperty.getName());
        }
        if(model.getRecTime() == null || "".equals(model.getRecTime())){
            model.setRecTime(DateUtils.getCurrentTime("yyyy-MM-dd HH:mm:ss"));
        }
        TRmCalpoint tRmCalpoint = tRmCalpointService.add(model);
        Formula formula = new Formula();
        formula.setCode(model.getItemid());
        String itemdesc = model.getItemdesc(); // 项目描述
        formula.setDescription(itemdesc!=null && !itemdesc.trim().isEmpty() ? itemdesc : model.getTagAlias());
        // formula.setClock(DateUtils.getCurrentTime("yyyyMM"));
        formula.setClock("202001");
        formula.setIsavailable("1");
        formula.setRevisetime(DateUtils.getCurrentTime("yyyy-MM-dd HH:mm:ss"));
        formula.setTablename("T_RM_CALPOINT_VALUE");
        formula.setSourcecode("R(T_RM_CALPOINT_VALUE," + model.getItemid() + ")");
        formula.setRevisor(JwtUtil.getUseridByToken());
        formulaService.add(formula);
        return success(tRmCalpoint);
    }

    @ApiOperation(value="获取详细信息", notes="根据url的id来获取详细信息")
    @ApiImplicitParam(paramType = "path", name = "id", value = "ID", required = true, dataType = "String")
    //@RequiresPermissions("trmcalpoint:view")
    @GetMapping(value = "/{id}")
    public RESTfulResult get(@PathVariable String id){
        TRmCalpoint tRmCalpoint = tRmCalpointService.getById(id);
        return success(tRmCalpoint);
    }

    @ApiOperation(value="更新详细信息", notes="根据url的id来指定更新对象，并根据传过来的tRmCalpoint信息来更新详细信息")
    @ApiImplicitParams({
        @ApiImplicitParam(paramType = "path", name = "id", value = "ID", required = true, dataType = "String"),
        @ApiImplicitParam(name = "tRmCalpoint", value = "详细实体tRmCalpoint", required = true, dataType = "TRmCalpoint")
    })
    //@RequiresPermissions("trmcalpoint:update")
    @PutMapping(value = "/{id}", produces  = "application/json;charset=UTF-8")
    public RESTfulResult update(@PathVariable String id, @RequestBody TRmCalpoint model){
        if(model.getEnergytypeid() == null || "".equals(model.getEnergytypeid())){
            return failed(null, "能介类型不能为空");
        }
        if(model.getEnergyid() == null || "".equals(model.getEnergyid())){
            return failed(null, "能介信息不能为空");
        }
        if(model.getPropertyid() == null || "".equals(model.getPropertyid())){
            return failed(null, "能介属性不能为空");
        }
        if (model.getItemtype() == null || "".equals(model.getItemtype())) {
            return failed(null, "手抄或者自动不能为空");
        }
        if (model.getLocateid() == null || "".equals(model.getLocateid())) {
            return failed(null, "位置不能为空");
        }
        if (model.getMintimegranid() == null || "".equals(model.getMintimegranid())) {
            return failed(null, "最小时间粒度不能为空");
        }
        if(model.getEnergytypeid().equalsIgnoreCase("E") && (model.getNetworkid() == null || "".equals(model.getNetworkid()))){
        	return failed(null, "能介电的计量点站所不能为空");
        }
        TRmElectricityLocation tl = tRmElectricityLocationMapper.getByItemid(model.getItemid());
        if (tl!=null) {
        	if(!model.getEnergyid().equalsIgnoreCase("E001")){
        		return failed(null, "转供电计量点能介为电正向有功");
        	}
        	if(!model.getItemtype().equalsIgnoreCase("MANUAL")){
        		return failed(null, "转供电计量点为手动");
        	}
        	if(!model.getUnitid().equalsIgnoreCase("006")){
        		return failed(null, "转供电计量点单位为千瓦时");
        	}
        }
        model.setItemid(id);
        List<Formula> formulaList = formulaService.getAssociatedFormula(id);
        if("0".equals(model.getUseflag()) && formulaList != null && formulaList.size() > 0){
            String ids = "";
            for (Formula forms : formulaList){
                ids += forms.getCode() + ",";
            }
            return failed(null, "该计量点被" + formulaList.size() + "条公式所使用,公式名:" + ids);
        }
        Map<String, Object> formulaparam = new HashMap<>();
        formulaparam.put("clock", DateUtils.getCurrentTime("yyyyMM"));
        formulaparam.put("code", model.getItemid());
        formulaparam.put("tablename", "T_RM_CALPOINT_VALUE");
        Formula newestformula = formulaService.getByParams(formulaparam);
        TRmCalpoint old = tRmCalpointService.getById(model.getItemid());
        if("1".equals(model.getUseflag()) && formulaService.checkFormula(newestformula) !=""){
            return failed(null, "公式不合法,无法启用,不合法原因是" + formulaService.checkFormula(newestformula));
        }
        // 修改最小时间粒度
        String msg = "";
        if("1".equals(model.getUseflag()) && !old.getMintimegranid().equalsIgnoreCase(model.getMintimegranid())){
        	msg = formulaService.checkFormulaMint(newestformula, model.getMintimegranid());
        }
        TRmLocation tRmLocation = tRmLocationService.getById(model.getLocateid());
        TRmEnergy tRmEnergy = tRmEnergyService.getById(model.getEnergyid());
        TRmEnergyProperty tRmEnergyProperty = tRmEnergyPropertyService.getById(model.getPropertyid());
        if(model.getEnergytypeid().equalsIgnoreCase("E") && (model.getItemname()==null || model.getItemname().isEmpty())){
        	TRmStation tRmStation = tRmStationService.getById(model.getNetworkid());
        	model.setItemname(tRmStation.getName() + tRmEnergy.getName() + tRmEnergyProperty.getName());
        }else if(model.getItemname() == null || model.getItemname().isEmpty()){
        	model.setItemname(tRmLocation.getName() + tRmEnergy.getName() + tRmEnergyProperty.getName());
        }
        if(model.getTagAlias()==null || model.getTagAlias().isEmpty()){
        	model.setTagAlias(model.getItemname());
        }
        if(tl!=null){
        	tl.setBcode(model.getTagid()); // 电度表编号
        	tl.setItemname(model.getItemname());
        	tl.setLocation(model.getLocateid());
        	tl.setWorkshop(model.getNetworkid()); // 站所
        	tl.setMods(model.getTagModulus().intValue());
        	tl.setWorkprocid(model.getCostid());
        	tRmElectricityLocationMapper.updateByPrimaryKeySelective(tl);
        }
        LOGGER.info("计量点维护表修改前数据是" + old.toString());
        TRmCalpoint tRmCalpoint = tRmCalpointService.modify(model);
        LOGGER.info("计量点维护表修改后数据是" + tRmCalpoint.toString());
        // 修改公式描述和是否启用（计量点公式描述为计量点别名）
        Map<String, Object> pm = new HashMap<>();
        pm.put("code", model.getItemid());
        String itemdesc = model.getItemdesc(); // 项目描述
        pm.put("description", itemdesc!=null && !itemdesc.trim().isEmpty() ? itemdesc : model.getTagAlias());
        pm.put("isavailable", model.getUseflag());
        formulaService.updateDesBycode(pm);
        if(!msg.isEmpty()){
        	return success(null, msg);
        }else{
        	return success();
        }
    }

    @ApiOperation(value="删除", notes="根据url的id来指定删除对象")
    @ApiImplicitParam(paramType = "path", name = "id", value = "ID", required = true, dataType = "String")
    //@RequiresPermissions("trmcalpoint:delete")
    @DeleteMapping(value = "/{id}")
    public RESTfulResult delete(@PathVariable String id){
        String[] ids = id.split(",");
        for (int i = 0; i < ids.length; i++) {
        	List<Formula> list = formulaService.getFormulaByCode(ids[i]);
        	if(list!=null && list.size()>0){
        		String item="";
        		for(Formula fa:list){
        			item += "[" + fa.getClock() +"版本，项目编号"+ fa.getCode() + "],";
        		}
        		item = item.substring(0,item.length()-1);
        		return failed(null, item + " 公式中包含计量点 " + ids[i] + "，请先处理");
        	}
        }
        if(ids.length >= 1){
        	tRmCalpointService.delCalpoint(ids);
            return success();
        }else{
        	return failed(null, "请输入要删除的计量点编号");
        }
    }
    
    @ApiOperation(value="获得计量层级列表", notes="能源调度管理-计量点数据管理-计量点数据录入页面，计量层级下拉框数据")
    @GetMapping(value = "/getRmCalpoint")
    public RESTfulResult getTimegran(){
        List<Map> list = tRmCalpointService.getRmCalpoint();
        return success(list);
    }
    
    @ApiOperation(value="获得计量点数据", notes="能源调度管理-计量点数据管理-准点数据查询")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "clock", value = "开始时间", required = false, dataType = "String"),
        @ApiImplicitParam(name = "clocke", value = "每结束时间", required = false, dataType = "String"),
        @ApiImplicitParam(name = "itemid", value = "计量点，多个以,隔开", required = false, dataType = "String"),
        @ApiImplicitParam(name = "datatype", value = "数据类型，sum:累计值,ontime:准点值", required = false, dataType = "String")
    })
    @GetMapping(value = "/getRmCalpointVal")
    public RESTfulResult getRmCalpointVal(String clock,String clocke,String itemid,String datatype){
    	if(clock == null || clock.isEmpty()){
    		return failed(null, "请传入开始时间");
    	}
    	if(clocke == null || clocke.isEmpty()){
    		return failed(null, "请传入结束时间");
    	}
    	if(itemid == null || itemid.isEmpty()){
    		return failed(null, "请传入计量点编号");
    	}
    	if(datatype == null || datatype.isEmpty()){
    		return failed(null, "请传入数据类型");
    	}
    	String[] ids = itemid.split(",");
    	String failmsg = "";
    	String failmsg2 = "";
    	for(int i=0; i<ids.length; i++){
			String id = ids[i];
			TRmCalpoint tRmCalpoint = tRmCalpointService.getById(id);
			if(tRmCalpoint == null){
				return failed(null, "计量点" + id + "不存在");
			}
			String itemname = tRmCalpoint.getItemname();
			String tagTable = tRmCalpoint.getTagTable()==null? "" :tRmCalpoint.getTagTable().trim(); // 小时表
			String tagCol = tRmCalpoint.getTagCol()==null? "" :tRmCalpoint.getTagCol().trim(); // 小时表字段
			String itemtype = tRmCalpoint.getItemtype();
			if (!itemtype.equalsIgnoreCase("AUTO")){
				failmsg += itemname + ",";
			} else if(tagTable.isEmpty() || tagCol.isEmpty()){
				failmsg2 += itemname + ",";
			}
		}
    	if(!failmsg.isEmpty() || !failmsg2.isEmpty()){
    		failmsg = "计量点：";
    		if(!failmsg.isEmpty()){
    			failmsg = "(" + failmsg.substring(0, failmsg.length()-1) + ")不是自动采集模式，没有准点值； ";
    		}
    		if(!failmsg2.isEmpty()){
    			failmsg = "(" + failmsg2.substring(0, failmsg2.length()-1) + ")没有配置准点数据表或数据列；";
    		}
    		return failed(null, failmsg);
    	}
    	List<Map<String, Object>> list = tRmCalpointService.getRmCalpointVal(clock,clocke,itemid,datatype);
		return success(list);
    }
    //十分钟
    @GetMapping(value = "/getRmCalpointValTim")
    public RESTfulResult getRmCalpointValTim(String clock,String clocke,String itemid,String datatype){
        if(clock == null || clock.isEmpty()){
            return failed(null, "请传入开始时间");
        }
        if(clocke == null || clocke.isEmpty()){
            return failed(null, "请传入结束时间");
        }
        if(itemid == null || itemid.isEmpty()){
            return failed(null, "请传入计量点编号");
        }
        if(datatype == null || datatype.isEmpty()){
            return failed(null, "请传入数据类型");
        }
        String[] ids = itemid.split(",");
        String failmsg = "";
        String failmsg2 = "";
        for(int i=0; i<ids.length; i++){
            String id = ids[i];
            TRmCalpoint tRmCalpoint = tRmCalpointService.getById(id);
            if(tRmCalpoint == null){
                return failed(null, "计量点" + id + "不存在");
            }
            String itemname = tRmCalpoint.getItemname();
            String tagTable = tRmCalpoint.getBtype2()==null? "" :tRmCalpoint.getBtype2().trim(); // 备用描述2
            String[] tens = tagTable.split("\\.");
            if(tens.length!=2){
                return failed("十分钟表字段配置错误");
            }
            String tenTab = tens[0]; // 十分钟表
            String tenCol = tens[1];  // 十分钟字段
            String itemtype = tRmCalpoint.getItemtype();
            if (!itemtype.equalsIgnoreCase("AUTO")){
                failmsg += itemname + ",";
            } else if(tenTab.isEmpty() || tenCol.isEmpty()){
                failmsg2 += itemname + ",";
            }
        }
        if(!failmsg.isEmpty() || !failmsg2.isEmpty()){
            failmsg = "计量点：";
            if(!failmsg.isEmpty()){
                failmsg = "(" + failmsg.substring(0, failmsg.length()-1) + ")不是自动采集模式，没有准点值； ";
            }
            if(!failmsg2.isEmpty()){
                failmsg = "(" + failmsg2.substring(0, failmsg2.length()-1) + ")没有配置准点数据表或数据列；";
            }
            return failed(null, failmsg);
        }
        List<Map<String, Object>> list = tRmCalpointService.getRmCalpointValTim(clock,clocke,itemid,datatype);
        return success(list);
    }
    
    @ApiOperation(value="能源调度管理-计量点数据管理-计量点数据录入列表", notes="分页查询")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "pageNum", value = "查询页数", required = false, dataType = "Integer"),
        @ApiImplicitParam(name = "pageSize", value = "每页记录数", required = false, dataType = "Integer")
    })
    @GetMapping(value = "/getDate312ForPage")
    public RESTfulResult getDate312ForPage(@RequestParam HashMap<String, Object> parmas,Integer pageNum, Integer pageSize){
    	if(parmas.containsKey("locateid") && parmas.get("locateid") != null && !"".equals(parmas.get("locateid").toString())){
            String locateid = parmas.get("locateid").toString();
            if(locateid.indexOf(",") == -1){
                parmas.put("locateid", "and locateid = '" + locateid + "'");
            } else {
            	locateid = "and locateid in ('" + locateid.replaceAll(",", "','") + "')";
                parmas.put("locateid", locateid);
            }
        }
    	if(parmas.containsKey("propertyid") && parmas.get("propertyid") != null && !"".equals(parmas.get("propertyid").toString())){
            String propertyid = parmas.get("propertyid").toString();
            if(propertyid.indexOf(",") == -1){
                parmas.put("propertyid", "and propertyid = '" + propertyid + "'");
            } else {
            	propertyid = "and propertyid in ('" + propertyid.replaceAll(",", "','") + "')";
                parmas.put("propertyid", propertyid);
            }
        }
    	if(parmas.containsKey("energytypeid") && parmas.get("energytypeid") != null && !"".equals(parmas.get("energytypeid").toString())){
            String energytypeid = parmas.get("energytypeid").toString();
            if(energytypeid.indexOf(",") == -1){
                parmas.put("energytypeid", "and t.energytypeid = '" + energytypeid + "'");
            } else {
            	energytypeid = "and t.energytypeid in ('" + energytypeid.replaceAll(",", "','") + "')";
                parmas.put("energytypeid", energytypeid);
            }
        }
    	if(parmas.containsKey("energyid") && parmas.get("energyid") != null && !"".equals(parmas.get("energyid").toString())){
            String energyid = parmas.get("energyid").toString();
            if(energyid.indexOf(",") == -1){
                parmas.put("energyid", "and energyid = '" + energyid + "'");
            } else {
            	energyid = "and energyid in ('" + energyid.replaceAll(",", "','") + "')";
                parmas.put("energyid", energyid);
            }
        }
        if(parmas.get("itemid") != null && !parmas.get("itemid").toString().isEmpty()){
            String itemid = parmas.get("itemid").toString();
            if(!itemid.startsWith("'")){
            	itemid = "'" + itemid.replaceAll(",", "','").replaceAll("，", "','") + "'";
            }
            parmas.put("itemid", itemid); 
        }
    	
        PageList<Map<String, Object>> list = tRmCalpointService.getDate312ForPage(parmas, pageNum, pageSize);
        return success(list);
    }
    
    @ApiOperation(value="能源调度管理-计量点数据管理-计量点数据趋势图", notes="json格式")
    @PostMapping(value = "/getDate312ForChart")
    public RESTfulResult getDate312ForChart(@RequestBody HashMap<String, Object> parmas){
    	if(parmas.get("size") == null){
    		return failed(null, "请传入记录数");
    	}
    	int size = Integer.valueOf(parmas.get("size").toString());
    	List<Map<String, Object>> lt = tRmCalpointService.getDate312ForChart((List<Map<String, Object>>)parmas.get("list"), size);
        return success(lt);
    }

    @ApiOperation(value="系统接口管理-能耗数据管理", notes="查询")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "pageNum", value = "查询页数", required = false, dataType = "Integer"),
        @ApiImplicitParam(name = "pageSize", value = "每页记录数", required = false, dataType = "Integer")
    })
    @GetMapping(value = "/getInIdDate312")
    public RESTfulResult getInIdDate312(@RequestParam HashMap<String, Object> parmas){
        if(parmas.containsKey("itemid")) {
            String itemids = parmas.get("itemid").toString();
            itemids = itemids.replaceAll(",", "', '");
            parmas.put("itemid", itemids);
        }
        List<Map<String, Object>> list = tRmCalpointService.getInIdDate312(parmas);
        return success(list);
    }
    
    @ApiOperation(value="系统管理重新生成小时数据（动力、水）", notes="")
    @GetMapping(value = "/reHourData")
    public RESTfulResult reHourData(@RequestParam HashMap<String, Object> parmas){
    	String itemid = "";
    	String clock = "";
    	String clocke = "";
        if(parmas.containsKey("itemid")) {
        	itemid = parmas.get("itemid").toString(); 
            if(itemid.isEmpty()) {
            	return failed(null, "请传入计量点ID");
            }
        }
        else {
    		return failed(null, "请传入计量点ID");
    	}
        if(parmas.containsKey("clock")){
        	clock = parmas.get("clock").toString();
        	if(clock.isEmpty()) {
        		return failed(null, "请传入开始时间");
        	}
    	}else {
    		return failed(null, "请传入开始时间");
    	}
    	if(parmas.containsKey("clocke")){
        	clocke = parmas.get("clocke").toString();
        	if(clocke.isEmpty()) {
        		return failed(null, "请传入结束时间");
        	}
    	}else {
    		return failed(null, "请传入结束时间");
    	}
        String ret = tRmCalpointService.restatHourDate(itemid, clock, clocke);
        return success(ret);
    }
    
    @ApiOperation(value="系统管理重新生成小时数据（电）", notes="")
    @GetMapping(value = "/reHourDataE")
    public RESTfulResult reHourDataE(@RequestParam HashMap<String, Object> parmas){
    	String clock = "";
    	String clocke = "";
        if(parmas.containsKey("clock")){
        	clock = parmas.get("clock").toString();
        	if(clock.isEmpty()) {
        		return failed(null, "请传入开始时间");
        	}
    	}else {
    		return failed(null, "请传入开始时间");
    	}
    	if(parmas.containsKey("clocke")){
        	clocke = parmas.get("clocke").toString();
        	if(clocke.isEmpty()) {
        		return failed(null, "请传入结束时间");
        	}
    	}else {
    		return failed(null, "请传入结束时间");
    	}
        String ret = tRmCalpointService.restatHourDateE(clock, clocke);
        return success(ret);
    }
}
