package com.steerinfo.ems.coredasabnormalinfo.controller;

import com.steerinfo.framework.controller.BaseRESTfulController;
import com.steerinfo.framework.controller.RESTfulResult;
import com.steerinfo.framework.service.pagehelper.PageList;
import com.steerinfo.framework.utils.collection.ListUtils;
import com.steerinfo.ems.coredasabnormalinfo.mapper.CoredasAbnormalInfoMapper;
import com.steerinfo.ems.coredasabnormalinfo.model.CoredasAbnormalInfo;
import com.steerinfo.ems.coredasabnormalinfo.service.ICoredasAbnormalInfoService;
import com.steerinfo.ems.zghbjkbz.controller.ZghbjkbzController;

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.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.ArrayList;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;

/**
 * CoredasAbnormalInfo RESTful接口：
 * @author generator
 * @version 1.0-SNAPSHORT 2021-04-20 10:09
 * 类描述
 * 修订历史：
 * 日期：2021-04-20
 * 作者：generator
 * 参考：
 * 描述：CoredasAbnormalInfo RESTful接口
 * @see null
 * @Copyright 湖南视拓信息技术股份有限公司. All rights reserved.
 */
@RestController
@RequestMapping("/${api.version}/coredasabnormalinfos")
public class CoredasAbnormalInfoController extends BaseRESTfulController {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(CoredasAbnormalInfoController.class);

    @Autowired
    ICoredasAbnormalInfoService coredasAbnormalInfoService;
    
    @Autowired
    private CoredasAbnormalInfoMapper coredasAbnormalInfoMapper;
    
    @Autowired
    private JdbcTemplate jdbcTemplate;

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

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

    @ApiOperation(value="更新详细信息", notes="根据url的id来指定更新对象，并根据传过来的coredasAbnormalInfo信息来更新详细信息")
    @ApiImplicitParams({
        @ApiImplicitParam(paramType = "path", name = "id", value = "ID", required = true, dataType = "String"),
        @ApiImplicitParam(name = "coredasAbnormalInfo", value = "详细实体coredasAbnormalInfo", required = true, dataType = "CoredasAbnormalInfo")
    })
    //@RequiresPermissions("coredasabnormalinfo:update")
    @PutMapping(value = "/", produces  = "application/json;charset=UTF-8")
    public RESTfulResult update(@RequestBody List<Map<String,Object>> mapList){
    	try {
    		for(Map<String,Object> m:mapList){
        		String col = m.get("col").toString();
        		String tableName = m.get("TABLE_NAME").toString();
        		String flag = m.get("FLAG").toString();
        		String st = m.get("ST").toString();
        		String vald = m.get("VALD").toString();
        		String valu = m.get("VALU").toString();
        		String sql = "update " + tableName + "_STANDARD set " + col + "_DOWN=" + vald + "," + col + "_UP=" + valu+ "," + col + "_FLAG=" + flag+ ","
        				+ col + "_ENDTIME=to_date('" + st + "','yyyy-MM-dd hh24:mi:ss')";
        		// LOGGER.info("sql:" + sql);
        		jdbcTemplate.update(sql);
        	}
    	}catch(Exception e) {
    		LOGGER.error("更新错误", e);
    		return failed(null, "系统错误，请联系管理样");
		}
        return success();
    }

    @ApiOperation(value="删除", notes="根据url的id来指定删除对象")
    @ApiImplicitParam(paramType = "path", name = "id", value = "ID", required = true, dataType = "String")
    //@RequiresPermissions("coredasabnormalinfo:delete")
    @DeleteMapping(value = "/{id}")//String
    public RESTfulResult delete(@PathVariable String id){
    	List<String> list = Arrays.asList(id.split(","));
    	if(ListUtils.isNotEmpty(list)) {
	    	List<String> ids = ListUtils.convertList(list);
			  coredasAbnormalInfoService.delete(ids);
    	}
      return success();
    }
    
    @ApiOperation(value = "获取能源瞬时监控-标准",notes = "")
    @GetMapping("/getCoredasStd")
    public RESTfulResult getCoredasStd(@RequestParam Map<String,Object> parmas){
    	//long st = new Date().getTime();
    	Map<String, Object> res = new HashMap<String, Object>();
        // 能源标准数据
        List<Map<String, Object>> coredasStdDatas = coredasAbnormalInfoService.getCoredasStdData(parmas);
        // 监控的能源名称、字段
        List<Map<String, Object>> emsCoredas = coredasAbnormalInfoService.getEmsCoredas(parmas);
        Map<String, Object> coredasStdData = coredasStdDatas.size()>0?coredasStdDatas.get(0):new HashMap<String, Object>();
        for(Map<String, Object> m : emsCoredas){
        	String col = m.get("COLUMN_NAME").toString();
        	m.put("col", col);
        	String colu = (col+"_UP").toUpperCase(); // 上限值字段
        	String cold = (col+"_DOWN").toUpperCase(); // 下限值字段
        	String colf = (col+"_FLAG").toUpperCase(); // 是否报警字段
        	String cole = (col+"_ENDTIME").toUpperCase(); // 报警开始时间
        	// 标准上限值
        	String valu = coredasStdData.get(colu)==null?"":coredasStdData.get(colu).toString();
        	m.put("VALU", valu);
        	// 标准下限值
        	String vald = coredasStdData.get(cold)==null?"":coredasStdData.get(cold).toString();
        	m.put("VALD", vald);
        	//  是否报警
        	m.put("FLAG", coredasStdData.get(colf)==null?"":coredasStdData.get(colf).toString());
        	//  报警开始时间
        	m.put("ST", coredasStdData.get(cole)==null?"":new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format((Date)coredasStdData.get(cole)));
        }
        res.put("data", emsCoredas);
        return success(res);
    }
    
    @ApiOperation(value = "获取能源瞬时数据-初始化",notes = "")
    @GetMapping("/getCoredasData")
    public RESTfulResult getCoredasData(@RequestParam Map<String,Object> parmas,Integer pageNum, Integer pageSize){
    	//long st = new Date().getTime();
    	Map<String, Object> res = new HashMap<String, Object>();
    	// 能源瞬时数据
    	List<Map<String, Object>> coredasDatas = coredasAbnormalInfoMapper.getCoredasData(parmas);
        // 能源标准数据
        List<Map<String, Object>> coredasStdDatas = coredasAbnormalInfoService.getCoredasStdData(parmas);
        // 瞬时数据-全部
        List<Map<String, Object>> emsCoredas = coredasAbnormalInfoService.getEmsCoredas(parmas);
        // 瞬时数据-超标
        List<Map<String, Object>> emsCoredasWarn = new ArrayList<Map<String, Object>>();
        Map<String, Object> coredasData = coredasDatas.size()>0?coredasDatas.get(0):new HashMap<String, Object>();
        Map<String, Object> coredasStdData = coredasStdDatas.size()>0?coredasStdDatas.get(0):new HashMap<String, Object>();
        for(Map<String, Object> m : emsCoredas){
        	String col = m.get("COLUMN_NAME").toString();
        	m.put("col", col);
        	// 实绩值
        	String val = coredasData.get("col")==null?"":coredasData.get("col").toString();
        	m.put("VAL", val);
        	String colu = (col+"_UP").toUpperCase(); // 上限值字段
        	String cold = (col+"_DOWN").toUpperCase(); // 下限值字段
        	String colf = (col+"_FLAG").toUpperCase(); // 是否报警字段
        	String cole = (col+"_ENDTIME").toUpperCase(); // 报警开始时间
        	// 标准上限值
        	String valu = coredasStdData.get(colu)==null?"":coredasStdData.get(colu).toString();
        	m.put("VALU", valu);
        	// 标准下限值
        	String vald = coredasStdData.get(cold)==null?"":coredasStdData.get(cold).toString();
        	m.put("VALD", vald);
        	//  是否报警
        	m.put("FLAG", coredasStdData.get(colf)==null?"":coredasStdData.get(colf).toString());
        	//  报警开始时间
        	m.put("ST", coredasStdData.get(cole)==null?"":new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format((Date)coredasStdData.get(cole)));
        	if(!val.isEmpty() && !valu.isEmpty() && !vald.isEmpty()){
        		// 超标
        		if(new BigDecimal(val).doubleValue() > new BigDecimal(valu).doubleValue() || new BigDecimal(val).doubleValue() < new BigDecimal(vald).doubleValue()){
        			emsCoredasWarn.add(m);
        		}
        	}
        }
        res.put("data", emsCoredas);
        res.put("dataWarn", emsCoredasWarn);
        res.put("time", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        //System.out.println(new Date().getTime() - st);
        return success(res);
    }
    
    @ApiOperation(value = "获取能源瞬时数据-定时",notes = "")
    @GetMapping("/nyData")
    public RESTfulResult nyData(@RequestParam Map<String,Object> parmas){
    	//long st = new Date().getTime();
    	Map<String, Object> res = new HashMap<String, Object>();
    	// 能源瞬时数据
        List<Map<String, Object>> coredasDatas = coredasAbnormalInfoMapper.getCoredasData(parmas);
        res.put("data", coredasDatas.size()>0?coredasDatas.get(0):new HashMap<String, Object>());
        res.put("time", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        //System.out.println(new Date().getTime() - st);
        return success(res);
    }
    
    @ApiOperation(value = "查询历史报警数据",notes = "")
    @GetMapping("/getCoredasDataHis")
    public RESTfulResult getCoredasDataHis(@RequestParam Map<String,Object> parmas,Integer pageNum, Integer pageSize){
    	if(parmas==null || !parmas.containsKey("clock") || parmas.get("clock").toString().isEmpty()
    			|| !parmas.containsKey("clocke") || parmas.get("clocke").toString().isEmpty()){
    		return failed(null, "请选择时间");
        }
        PageList<CoredasAbnormalInfo> list = coredasAbnormalInfoService.getEmsCoredasWarnHis(parmas, pageNum, pageSize);
        return success(list);
    }
}
