package com.yeejoin.equipmanage.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yeejoin.equipmanage.common.entity.*;
import com.yeejoin.equipmanage.common.entity.dto.TopographyLineDTO;
import com.yeejoin.equipmanage.common.entity.dto.TopographyNodeDTO;
import com.yeejoin.equipmanage.common.entity.dto.TopographyNodeDetailDTO;
import com.yeejoin.equipmanage.common.entity.dto.TopographyTreeDTO;
import com.yeejoin.equipmanage.common.entity.vo.EquipmentIndexVO;
import com.yeejoin.equipmanage.common.enums.TopoNodeTypeEnum;
import com.yeejoin.equipmanage.common.utils.*;
import com.yeejoin.equipmanage.common.vo.*;
import com.yeejoin.equipmanage.fegin.IotFeign;
import com.yeejoin.equipmanage.mapper.*;
import com.yeejoin.equipmanage.service.*;
import com.yeejoin.equipmanage.service.impl.TopographyNodeDetailService;
import com.yeejoin.equipmanage.service.impl.TopographyService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.models.auth.In;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.typroject.tyboot.core.foundation.enumeration.UserType;
import org.typroject.tyboot.core.foundation.utils.DateTimeUtil;
import org.typroject.tyboot.core.restful.doc.TycloudOperation;
import org.typroject.tyboot.core.restful.utils.ResponseHelper;
import org.typroject.tyboot.core.restful.utils.ResponseModel;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

import static org.typroject.tyboot.core.foundation.utils.DateTimeUtil.ISO8601_DATE_HOUR_MIN_SEC;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 子杨
 * @since 2021-10-14
 */

@RestController
@Api(tags = "网络拓扑Api")
@RequestMapping(value = "/topography")
public class TopographyController extends AbstractBaseController {

    private final Logger logger = LogManager.getLogger(TopographyController.class);

    @Autowired
    private TopographyService topographyService;

    @Autowired
    private TopographyNodeDetailService topographyNodeDetailService;

    @Autowired
    IEquipmentSpecificAlarmService equipmentSpecificAlarmService;

    @Autowired
    IEquipmentDetailService iEquipmentDetailService;
    @Autowired
    EquipmentDetailMapper equipmentDetailMapper;
    @Autowired
    private StockDetailMapper stockDetailMapper;
    @Autowired
    IStockService iStockService;
    @Autowired
    IEquipmentSpecificSerivce equipmentSpecificService;
    @Autowired
    IEquipmentSpecificAlarmLogService equipmentSpecificAlarmLogService;
    @Autowired
    EquipmentSpecificAlarmMapper equipmentSpecificAlarmMapper;
    @Autowired
    FireFightingSystemMapper fireFightingSystemMapper;
    @Autowired
    IEquipmentSpecificAlarmService iEquipmentSpecificAlarmService;
    @Autowired
    IEquipmentIndexService equipmentIndexService;
    @Autowired
    EquipmentSpecificIndexMapper equipmentSpecificIndexMapper;
    @Autowired
    IEquipmentService iEquipmentService;
    @Autowired
    IEquipmentIndexService iEquipmentIndexService;
    @Autowired
    IotFeign iotFeign;
    @Value("${iot.vehicle.track}")
    private String iotServerName;

    @Value("${water.level.indexKey}")
    private String waterLevelIndexKey;

//	/**
//     * 拓扑图-树
//     *
//     * @param type 节点类型
//     * @return 
//     */
//    @TycloudOperation(ApiLevel = UserType.AGENCY)
//    @ApiOperation(value = "拓扑图-树", notes = "拓扑图-树")
//    @RequestMapping(value = "/tree", method = RequestMethod.GET)
//    public ResponseModel<List<TopographyTreeDTO>> tree() {
//    	//获取当前登录人的公司code
//    	ReginParams reginParams	=getSelectedOrgInfo();
//    	List<TopographyTreeDTO> list = topographyService.getTree(reginParams.getCompany().getOrgCode(),TopoNodeTypeEnum.PAMS.getType());
//        return ResponseHelper.buildResponse(list);
//    }
//    
//    
//    /**
//     * 拓扑图
//     *
//     * @param type 节点类型
//     * @return 
//     */
//    @GetMapping(value = "/nodes/{treeid}", produces = "application/json;charset=UTF-8")
//    @TycloudOperation(ApiLevel = UserType.AGENCY)
//    @ApiOperation(value = "拓扑图", notes = "拓扑图")
//    public ResponseModel<Map<String,Object>>  getNodesByTreeid(@ApiParam(value = "树id", required = false) @PathVariable String treeid) {
//    	//获取当前登录人的公司code
//    	ReginParams reginParams	=getSelectedOrgInfo();	
//    	List<TopographyNodeDTO> nodes = topographyService.getNodes(reginParams.getCompany().getOrgCode(),treeid,TopoNodeTypeEnum.PAMS.getType());
//    	List<TopographyLineDTO> links = topographyService.getLinks(reginParams.getCompany().getOrgCode(),treeid,TopoNodeTypeEnum.PAMS.getType());
//    	Map<String,Object> results = new HashMap<>();
//    	results.put("nodeData", nodes);
//    	results.put("linkData", links);
//    	return ResponseHelper.buildResponse(results);
//    }
//    
//    /**
//     * 自建系统树
//     *
//     * @param type 节点类型
//     * @return 
//     */
//    @GetMapping(value = "/selftree", produces = "application/json;charset=UTF-8")
//    @TycloudOperation(ApiLevel = UserType.AGENCY)
//    @ApiOperation(value = "拓扑图-树", notes = "拓扑图-树")
//    public CommonResponse selfTree() {
//    	//获取当前登录人的公司code
//    	ReginParams reginParams	=getSelectedOrgInfo();
//    	List<TopographyTreeDTO> list = topographyService.getTree(reginParams.getCompany().getOrgCode(),TopoNodeTypeEnum.自建系统.getType());
//        return ResponseHelper.buildResponse(list);
//    }
//    
//    /**
//     * 自建系统拓扑图
//     *
//     * @param type 节点类型
//     * @return 
//     */
//    @GetMapping(value = "/selfnodes/{treeid}", produces = "application/json;charset=UTF-8")
//    @TycloudOperation(ApiLevel = UserType.AGENCY)
//    @ApiOperation(value = "拓扑图", notes = "拓扑图")
//    public CommonResponse getSelfNodesByTreeid(@ApiParam(value = "树id", required = false) @PathVariable String treeid) {
//    	//获取当前登录人的公司code
//    	ReginParams reginParams	=getSelectedOrgInfo();	
//    	List<TopographyNodeDTO> nodes = topographyService.getNodes("%#"+reginParams.getCompany().getOrgCode(),treeid,TopoNodeTypeEnum.自建系统.getType());
//    	List<TopographyLineDTO> links = topographyService.getLinks(reginParams.getCompany().getOrgCode(),treeid,TopoNodeTypeEnum.自建系统.getType());
//    	Map<String,Object> results = new HashMap<>();
//    	results.put("nodeData", nodes);
//    	results.put("linkData", links);
//    	return ResponseHelper.buildResponse(results);
//    }
//    
//    
//    /**
//     * 保存自建系统
//     *
//     * @param type 节点类型
//     * @return 
//     */
//    @PostMapping(value = "/selfnodes", produces = "application/json;charset=UTF-8")
//    @TycloudOperation(ApiLevel = UserType.AGENCY)
//    @ApiOperation(value = "保存动环拓扑图", notes = "保存动环拓扑图")
//    public CommonResponse saveselfnodes(@ApiParam(value = "", required = false) @RequestBody JSONObject topography) {
//    	JSONArray nodes = topography.getJSONArray("nodeData");
//    	List<TopographyNodeDTO> nodeData = JSON.parseArray(JSON.toJSONString(nodes), TopographyNodeDTO.class);
//    	
//    	        //获取当前登录人的公司code
//    			ReginParams reginParams	=getSelectedOrgInfo();
//    			if(reginParams.getDepartment()!=null){
//    				topographyService.saveNodes(topographyService.getSelfOrgCode(),nodeData);
//    			}else{
//    				topographyService.saveNodes(topographyService.getSelfOrgCode(),nodeData);
//    				
//    			}
//    	
//    	return ResponseHelper.buildResponse();
//    }
//    
//    
//    /**
//     * 保存拓扑图
//     *
//     * @param type 节点类型
//     * @return 
//     */
//    @PostMapping(value = "/nodes", produces = "application/json;charset=UTF-8")
//    @TycloudOperation(ApiLevel = UserType.AGENCY)
//    @ApiOperation(value = "保存拓扑图", notes = "保存拓扑图")
//    public CommonResponse saveNodes(@ApiParam(value = "", required = false) @RequestBody JSONObject topography) {
//    	JSONArray nodes = topography.getJSONArray("nodeData");
//    	List<TopographyNodeDTO> nodeData = JSON.parseArray(JSON.toJSONString(nodes), TopographyNodeDTO.class);
//    	 //获取当前登录人的公司code
//		ReginParams reginParams	=getSelectedOrgInfo();
//		if(reginParams.getDepartment()!=null){
//			topographyService.saveNodes(reginParams.getDepartment().getOrgCode(),nodeData);
//		}else{
//			topographyService.saveNodes(reginParams.getCompany().getOrgCode(),nodeData);
//			
//		}    	
//		return ResponseHelper.buildResponse();
//    }
//    
//    /**
//     * 异常
//     *
//     * @return 
//     * @throws Exception 
//     */
//    @PostMapping(value = "/testAbnormal", produces = "application/json;charset=UTF-8")
//    @TycloudOperation(ApiLevel = UserType.AGENCY)
//    @ApiOperation(value = "推送异常", notes = "推送异常")
//    public CommonResponse testAbnormal(@RequestBody AbnormalParam param) throws Exception {
//    	topographyService.testAbnormal(param);
//        return ResponseHelper.buildResponse();
//    }

    /**
     * 网络拓扑图-树
     *
     * @param
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "网络拓扑图-树", notes = "网络拓扑图-树")
    @RequestMapping(value = "/webTree", method = RequestMethod.GET)
    public ResponseModel<Collection<TopographyTreeDTO>> webTree() {
        //获取当前登录人的公司code
        Collection<TopographyTreeDTO> list = topographyService.getTree(TopoNodeTypeEnum.网络拓扑图.getType());
        return ResponseHelper.buildResponse(list);
    }

    /**
     * 网络拓扑图
     *
     * @param
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "网络拓扑图", notes = "拓扑图")
    @RequestMapping(value = "/webNodes/{treeid}", method = RequestMethod.GET)
    public ResponseModel<Map<String, Object>> webNodes(@ApiParam(value = "树id", required = false) @PathVariable String treeid) {

        //获取当前登录人的公司code
        List<TopographyNodeDTO> nodes = topographyService.getNodes(treeid, TopoNodeTypeEnum.网络拓扑图.getType());
        List<TopographyLineDTO> links = topographyService.getLinks(treeid, TopoNodeTypeEnum.网络拓扑图.getType());
        Map<String, Object> results = new HashMap<>();
        results.put("nodeData", nodes);
        results.put("linkData", links);
        return ResponseHelper.buildResponse(results);
    }

//    @DeleteMapping("/webTree/{treeid}")
//	    @TycloudOperation(ApiLevel = UserType.AGENCY)
//    @ApiOperation(value = "删除树数据", notes = "删除树数据")
//	public CommonResponse delWebTree(@ApiParam(value = "树id", required = false) @PathVariable String treeid) {
//    	topographyService.delWebTree(treeid);
//    	//获取当前登录人的公司code
//    	ReginParams reginParams	=getSelectedOrgInfo();
//		return ResponseHelper.buildResponse(topographyService.getTree(reginParams.getCompany().getOrgCode(),TopoNodeTypeEnum.网络拓扑图.getType()));
//	}
//	
//	@PostMapping("/addWebTree")
//	    @TycloudOperation(ApiLevel = UserType.AGENCY)
//    @ApiOperation(value = "添加树数据", notes = "添加树数据")
//	public CommonResponse addWebTree(@RequestBody TopographyTreeDTO tree) {
//		//获取当前登录人的公司code
//		ReginParams reginParams	=getSelectedOrgInfo();
//		if(reginParams.getDepartment()!=null){
//			tree.setOrgCode(reginParams.getDepartment().getOrgCode());
//		}else{
//			tree.setOrgCode(reginParams.getCompany().getOrgCode());
//		}
//		
//		topographyService.addWebTree(tree);
//		
//		return ResponseHelper.buildResponse(topographyService.getTree(reginParams.getCompany().getOrgCode(),TopoNodeTypeEnum.网络拓扑图.getType()));
//	}

    /**
     * 保存网络拓扑图
     *
     * @param
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "保存网络拓扑图", notes = "保存网络拓扑图")
    @RequestMapping(value = "/webNodes", method = RequestMethod.POST)
    public ResponseModel<Boolean> saveWebNodes(@ApiParam(value = "", required = false) @RequestBody JSONObject topography) {
        JSONArray nodes = topography.getJSONArray("nodeData");
        List<TopographyNodeDTO> nodeData = JSON.parseArray(JSON.toJSONString(nodes), TopographyNodeDTO.class);
        topographyService.saveNodes(nodeData);
        return ResponseHelper.buildResponse(true);
    }

    /**
     * 节点详情
     *
     * @param
     * @return
     */
    @SuppressWarnings("rawtypes")
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "节点详情", notes = "节点详情")
    @RequestMapping(value = "/nodeDetail/{nodeid}", method = RequestMethod.GET)
    public ResponseModel<List<Map>> nodeDetail(@ApiParam(value = "nodeid", required = false) @PathVariable String nodeid) {
        List<Map> nodeDetail = topographyService.getNodeDetail(nodeid);
        return ResponseHelper.buildResponse(nodeDetail);
    }

//    /**
//     * 动环拓扑图-树
//     *
//     * @param type 节点类型
//     * @return 
//     */
//    @GetMapping(value = "/donghuanTree", produces = "application/json;charset=UTF-8")
//    @TycloudOperation(ApiLevel = UserType.AGENCY)
//    @ApiOperation(value = "动环拓扑图-树", notes = "动环拓扑图-树")
//    public CommonResponse donghuanTree() {
//    	//获取当前登录人的公司code
//    	ReginParams reginParams	=getSelectedOrgInfo();
//    	List<TopographyTreeDTO> list = topographyService.getTree("%#"+reginParams.getCompany().getOrgCode(),TopoNodeTypeEnum.动环监控.getType());
//        return ResponseHelper.buildResponse(list);
//    }
//    
//    /**
//     * 动环拓扑图
//     *
//     * @param type 节点类型
//     * @return 
//     */
//    @GetMapping(value = "/donghuanNodes/{treeid}", produces = "application/json;charset=UTF-8")
//    @TycloudOperation(ApiLevel = UserType.AGENCY)
//    @ApiOperation(value = "动环拓扑图", notes = "拓扑图")
//    public CommonResponse donghuanNodes(@ApiParam(value = "树id", required = false) @PathVariable String treeid) {
//    	//获取当前登录人的公司code
//    	ReginParams reginParams	=getSelectedOrgInfo();
//    	List<TopographyNodeDTO> nodes = topographyService.getNodes("%#"+reginParams.getCompany().getOrgCode(),treeid,TopoNodeTypeEnum.动环监控.getType());
//    	List<TopographyLineDTO> links = topographyService.getLinks(reginParams.getCompany().getOrgCode(),treeid,TopoNodeTypeEnum.动环监控.getType());
//    	Map<String,Object> results = new HashMap<>();
//    	results.put("nodeData", nodes);
//    	results.put("linkData", links);
//    	return ResponseHelper.buildResponse(results);
//    }
//    
//    /**
//     * 保存动环拓扑图
//     *
//     * @param type 节点类型
//     * @return 
//     */
//    @PostMapping(value = "/donghuanNodes", produces = "application/json;charset=UTF-8")
//    @TycloudOperation(ApiLevel = UserType.AGENCY)
//    @ApiOperation(value = "保存动环拓扑图", notes = "保存动环拓扑图")
//    public CommonResponse savedonghuanNodes(@ApiParam(value = "", required = false) @RequestBody JSONObject topography) {
//    	JSONArray nodes = topography.getJSONArray("nodeData");
//    	List<TopographyNodeDTO> nodeData = JSON.parseArray(JSON.toJSONString(nodes), TopographyNodeDTO.class);
//    	
//    	       //获取当前登录人的公司code
//    			ReginParams reginParams	=getSelectedOrgInfo();
//    			if(reginParams.getDepartment()!=null){
//    				topographyService.saveNodes(topographyService.getSelfOrgCode(),nodeData);
//    			}else{
//    				topographyService.saveNodes(topographyService.getSelfOrgCode(),nodeData);
//    				
//    			}
//    	
//    	return ResponseHelper.buildResponse();
//    }
//    
//    /**
//     * 获取设备监控拓扑图
//     *
//     * @param type 节点类型
//     * @return 
//     */
//    @GetMapping(value = "/deviceNodes", produces = "application/json;charset=UTF-8")
//    @TycloudOperation(ApiLevel = UserType.AGENCY)
//    @ApiOperation(value = "设备监控拓扑图", notes = "设备监控拓扑图")
//    public CommonResponse deviceNodes() {
//    	//获取当前登录人的公司code
//    	ReginParams reginParams	=getSelectedOrgInfo();
//    	List<Map> nodes = topographyService.getDeviceNodes(reginParams.getCompany().getOrgCode());    	
//    	List<TopographyLineDTO> links = topographyService.getDeviceLinks(reginParams.getCompany().getOrgCode());
//    	Map<String,Object> results = new HashMap<>();
//    	results.put("nodeData", nodes);
//    	results.put("linkData", links);
//    	return ResponseHelper.buildResponse(results);
//    }
//    
//    /**
//     * 保存设备监控拓扑图
//     *
//     * @param type 节点类型
//     * @return 
//     */
//    @PostMapping(value = "/deviceNodes", produces = "application/json;charset=UTF-8")
//    @TycloudOperation(ApiLevel = UserType.AGENCY)
//    @ApiOperation(value = "保存设备监控拓扑图", notes = "保存设备监控拓扑图")
//    public CommonResponse saveDeviceNodes(@ApiParam(value = "", required = false) @RequestBody JSONObject topography) {
//    	JSONArray nodes = topography.getJSONArray("nodeData");
//    	List<TopographyNodeDTO> nodeData = JSON.parseArray(JSON.toJSONString(nodes), TopographyNodeDTO.class);
//    	
//    	
//    	//获取当前登录人的公司code
//		ReginParams reginParams	=getSelectedOrgInfo();
//		if(reginParams.getDepartment()!=null){
//			topographyService.saveNodes(topographyService.getSelfOrgCode(),nodeData);
//		}else{
//			topographyService.saveNodes(topographyService.getSelfOrgCode(),nodeData);
//			
//		}
//    	return ResponseHelper.buildResponse();
//    }
//
//	/**
//	 *查询-树
//	 *
//	 * @param type 类型
//	 * @return
//	 */
//	@GetMapping(value = "/treeByType/{type}", produces = "application/json;charset=UTF-8")
//	    @TycloudOperation(ApiLevel = UserType.AGENCY)
//    @ApiOperation(value = "查询-树", notes = "查询-树")
//	public CommonResponse treeByType(@ApiParam(value = "查询类型：1-网络拓扑图；2-PAMS；3-动环监控；4-设备监控；5-自建系统；6-金融城域网；7-虚拟云平台监控", required = true)
//										 @PathVariable int type) {
//		//获取当前登录人的公司code
//		ReginParams reginParams	=getSelectedOrgInfo();
//		List<TopographyTreeDTO> list = topographyService.getTree("%#"+reginParams.getCompany().getOrgCode(), type);
//		return ResponseHelper.buildResponse(list);
//	}
//
//	/**
//	 * 查询拓扑图
//	 *
//	 * @param type 节点类型
//	 * @return
//	 */
//	@GetMapping(value = "/getNodesByTypeAndTreeId/{type}/{treeId}", produces = "application/json;charset=UTF-8")
//	    @TycloudOperation(ApiLevel = UserType.AGENCY)
//    @ApiOperation(value = "拓扑图", notes = "拓扑图")
//	public CommonResponse getNodesByTypeAndTreeId(@ApiParam(value = "类型", required = true) @PathVariable int type,
//			@ApiParam(value = "树id", required = false) @PathVariable String treeId) {
//		//获取当前登录人的公司code
//		ReginParams reginParams	=getSelectedOrgInfo();
//		List<TopographyNodeDTO> nodes = topographyService.getNodes("%#" + reginParams.getCompany().getOrgCode(),treeId,type);
//		List<TopographyLineDTO> links = topographyService.getLinks("%#" + reginParams.getCompany().getOrgCode(),treeId,type);
//		Map<String,Object> results = new HashMap<>();
//		results.put("nodeData", nodes);
//		results.put("linkData", links);
//		return ResponseHelper.buildResponse(results);
//	}
//
//	/**
//	 * 保存自建系统
//	 *
//	 * @param type 节点类型
//	 * @return
//	 */
//	@PostMapping(value = "/saveNodesByType/{type}", produces = "application/json;charset=UTF-8")
//	    @TycloudOperation(ApiLevel = UserType.AGENCY)
//    @ApiOperation(value = "保存动环拓扑图", notes = "保存动环拓扑图")
//	public CommonResponse saveNodesByType(@ApiParam(value = "类型", required = true) @PathVariable int type,
//										  @ApiParam(value = "", required = false) @RequestBody JSONObject topography) {
//		JSONArray nodes = topography.getJSONArray("nodeData");
//		List<TopographyNodeDTO> nodeData = JSON.parseArray(JSON.toJSONString(nodes), TopographyNodeDTO.class);
//		//获取当前登录人的公司code
//		ReginParams reginParams	=getSelectedOrgInfo();
//		if(reginParams.getDepartment()!=null){
//			topographyService.saveNodes(topographyService.getSelfOrgCode(),nodeData);
//		}else{
//			topographyService.saveNodes(topographyService.getSelfOrgCode(),nodeData);
//		}
//		return CommonResponseUtil.success();
//	}

    /***
     *
     * 根拓补节点id查询详情
     *
     * **/
    @RequestMapping(value = "/equipment/detail", method = RequestMethod.GET)
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "根据节点id查询详情", notes = "根据节点id查询详情")
    public EquipmentDate selectEquipmentDateById(@RequestParam(required = false) String id, @RequestParam(required = false) String equipSpeId) {
        String eqpId;
        if (StringUtil.isNotEmpty(equipSpeId)) {
            eqpId = equipSpeId;
        } else {
            TopographyNodeDetailDTO detailDTO = topographyNodeDetailService.queryByNodeid(id);
            if (null == detailDTO || !StringUtil.isNotEmpty(detailDTO.getEqpId())) {
                throw new RuntimeException("节点信息错误或此节点下未绑定装备！");
            }
            eqpId = detailDTO.getEqpId();
        }
        EquipmentDate equipmentDate = new EquipmentDate();
        EquipmentSpecific equipmentSpecific = equipmentSpecificService.getById(eqpId);
        QueryWrapper<EquipmentSpecificAlarm> wrapper = new QueryWrapper<>();
        wrapper.eq("equipment_specific_id", eqpId);
        wrapper.orderByDesc("create_date");
        List<EquipmentSpecificAlarm> list = equipmentSpecificAlarmService.getBaseMapper().selectList(wrapper);
        EquipmentSpecificAlarm alarm;
        if (0 < list.size()) {
            alarm = list.get(0);
            equipmentSpecific.setStatus(alarm.getStatus());
        } else {
            equipmentSpecific.setStatus(0);
        }
        equipmentSpecific.setFullqrCode("01#" + equipmentSpecific.getQrCode());
        String sysName = this.getSystemNameBySpeId(equipmentSpecific);
        equipmentSpecific.setSystemName(sysName);
        EquipmentDetail equipmentDetail = iEquipmentDetailService.getOneById(equipmentSpecific.getEquipmentDetailId());
        StockDetail stockDetail = null;
        //消防装备默认分支
        List<StockDetail> stockDetails = stockDetailMapper.selectList(new LambdaQueryWrapper<StockDetail>().eq(StockDetail::getEquipmentSpecificId, eqpId));
        if (!stockDetails.isEmpty()) {
            stockDetail = stockDetails.get(0);
            equipmentSpecific.setStockDetail(stockDetail);
        }
        if (stockDetail != null) {
            equipmentSpecific.setStock(iStockService.getById(stockDetail.getStockId()));
        }
        equipmentDate.setEquipmentDetail(equipmentDetail);
        equipmentDate.setEquipmentSpecific(equipmentSpecific);
        return equipmentDate;
    }

    public String getSystemNameBySpeId(EquipmentSpecific equipmentSpecific) {
        List<FireFightingSystemEntity> sys = new ArrayList<>();
        String[] ids;
        String sysIds = equipmentSpecific.getSystemId();
        if (StringUtil.isNotEmpty(sysIds)) {
            if (-1 != sysIds.indexOf(",")) {
                ids = sysIds.split(",");
                sys = fireFightingSystemMapper.getFightingSysByIds(ids);
            } else {
                FireFightingSystemEntity entity = fireFightingSystemMapper.selectById(Long.valueOf(sysIds));
                sys.add(entity);
            }
        }
        StringBuilder sb = new StringBuilder();
        sys.forEach(x -> {
            if (0 < sb.length()) {
                sb.append(",");
            }
            sb.append(x.getName());
        });
        return sb.toString();
    }

    /***
     *
     * 根拓补节点id查询告警信息（未恢复或者所有）
     *
     * **/
    @RequestMapping(value = "/equipment/alarm", method = RequestMethod.GET)
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "根据节点id查询告警信息", notes = "根据节点id查询告警信息")
    public ResponseModel getAlarmInfo(@RequestParam(required = false) String id,
                                      @RequestParam(required = false) String equipSpeId,
                                      @RequestParam(required = false) int status,
                                      @RequestParam(required = false) String confirmType,
                                      @RequestParam(required = false) String cleanStatus,
                                      @RequestParam(required = false) String beginDate,
                                      @RequestParam(required = false) String endDate,
                                      CommonPageable commonPageable) {
        String eqpId;
        if (StringUtil.isNotEmpty(equipSpeId)) {
            eqpId = equipSpeId;
        } else {
            TopographyNodeDetailDTO detailDTO = topographyNodeDetailService.queryByNodeid(id);
            if (null == id || null == detailDTO || !StringUtil.isNotEmpty(detailDTO.getEqpId())) {
                throw new RuntimeException("节点信息错误或此节点下未绑定装备！");
            }
            EquipmentSpecific equipmentSpecific = equipmentSpecificService.getById(detailDTO.getEqpId());
            eqpId = String.valueOf(equipmentSpecific.getId());
        }
        List<CommonRequest> queryRequests = new ArrayList<>();
        CommonRequest request = new CommonRequest();
        request.setName("beginDate");
        request.setValue(StringUtil.isNotEmpty(beginDate) ? StringUtils.trimToNull(beginDate).substring(0, 10) + " 00:00:00" : null);
        queryRequests.add(request);
        CommonRequest request1 = new CommonRequest();
        request1.setName("endDate");
        request1.setValue(StringUtil.isNotEmpty(endDate) ? StringUtils.trimToNull(endDate).substring(0, 10) + " 23:59:59" : null);
        queryRequests.add(request1);
        CommonRequest request2 = new CommonRequest();
        request2.setName("id");
        request2.setValue(StringUtil.isNotEmpty(eqpId) ? StringUtils.trimToNull(eqpId) : null);
        queryRequests.add(request2);
        CommonRequest request3 = new CommonRequest();
        request3.setName("status");
        request3.setValue(StringUtil.isNotEmpty(status) ? StringUtils.trimToNull(String.valueOf(status)) : null);
        queryRequests.add(request3);
        // confirmType: '' 为全部数据 0 为未确认 1为已确认
        CommonRequest request4 = new CommonRequest();
        request4.setName("confirmType");
        request4.setValue(StringUtil.isNotEmpty(confirmType) ? StringUtils.trimToNull(confirmType) : null);
        queryRequests.add(request4);
        // cleanStatus: '' 为全部数据 1 为已消除 2为未消除
        CommonRequest request5 = new CommonRequest();
        request5.setName("cleanStatus");
        request5.setValue(StringUtil.isNotEmpty(cleanStatus) ? StringUtils.trimToNull(cleanStatus) : null);
        queryRequests.add(request5);
        CommonPageInfoParam param = CommonPageParamUtil.fillCommonPageInfoParam(queryRequests, commonPageable);
        Page<TopographyAlarmVo> list = iEquipmentSpecificAlarmService.listAlarmsPageForTopography(param);
        return CommonResponseUtil.success(list);
    }

    /**
     * 根拓补节点id查询当前节点最新物联信息
     **/
    @RequestMapping(value = "/equipment/iot/info", method = RequestMethod.GET)
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "根据节点id查询当前物联信息", notes = "根据节点id查询当前物联信息")
    public Map<String, Object> getEquipmentIotInfo(@RequestParam(required = false) String id, @RequestParam(required = false) String equipSpeId) {
        String eqpId;
        if (StringUtil.isNotEmpty(equipSpeId)) {
            eqpId = equipSpeId;
        } else {
            TopographyNodeDetailDTO detailDTO = topographyNodeDetailService.queryByNodeid(id);
            if (null == detailDTO || !StringUtil.isNotEmpty(detailDTO.getEqpId())) {
                throw new RuntimeException("节点信息错误或此节点下未绑定装备！");
            }
            eqpId = detailDTO.getEqpId();
        }
        EquipmentSpecific equipmentSpecific = equipmentSpecificService.getById(eqpId);
        EquipmentDetail equipmentDetail = iEquipmentDetailService.getById(equipmentSpecific.getEquipmentDetailId());
        Long equipmentId = equipmentDetail.getEquipmentId();
        HashMap<String, List> map = new HashMap<>();
        ConcurrentHashMap map1 = new ConcurrentHashMap();
        List<String> list = equipmentIndexService.getGruopName(equipmentId);
        list.forEach(x -> {
            QueryWrapper<EquipmentIndex> wrapper = new QueryWrapper<>();
            wrapper.eq("equipment_id", equipmentId);
            wrapper.eq("group_name", x);
            wrapper.orderByAsc("sort_num");
            List<EquProperty> properList = new ArrayList<>();
            equipmentIndexService.list(wrapper).forEach(y -> {
                EquProperty equProperty = new EquProperty();
                equProperty.setEquipmentIndexId(y.getId());
                equProperty.setIsIot(y.getIsIot());
                equProperty.setPerfQuotaName(y.getPerfQuotaName());
                equProperty.setEquipmentIndexName(y.getPerfQuotaName());
                equProperty.setGroupName(y.getGroupName());
                equProperty.setValue(y.getPerfValue());
                equProperty.setUnitName(y.getUnitName());
                equProperty.setEquipmentIndexKey(y.getPerfQuotaDefinitionId());
                properList.add(equProperty);
            });
            map.put(x, properList);
        });
        QueryWrapper<EquipmentIndex> wrappernull = new QueryWrapper<>();
        wrappernull.isNull("group_name").or().eq("group_name", " ");
        wrappernull.eq("equipment_id", equipmentId);
        wrappernull.orderByAsc("sort_num");
        List<EquProperty> properList = new ArrayList<>();
        equipmentIndexService.list(wrappernull).forEach(y -> {
            EquProperty equProperty = new EquProperty();
            equProperty.setEquipmentIndexId(y.getId());
            equProperty.setPerfQuotaName(y.getPerfQuotaName());
            equProperty.setEquipmentIndexName(y.getPerfQuotaName());
            equProperty.setIsIot(y.getIsIot());
            equProperty.setGroupName(y.getGroupName());
            equProperty.setValue(y.getPerfValue());
            equProperty.setUnitName(y.getUnitName());
            equProperty.setEquipmentIndexKey(y.getPerfQuotaDefinitionId());
            properList.add(equProperty);
        });
        properList.forEach(e -> {
            List<EquipmentIndexVO> equipmentIndexList = equipmentSpecificIndexMapper.getEquipIndexByIndexId(e.getEquipmentIndexId(), equipmentSpecific.getId());
            if (equipmentIndexList.size() > 0) {
                if (StringUtil.isNotEmpty(equipmentIndexList.get(0).getValue())) {
                    e.setValue(equipmentIndexList.get(0).getValue());
                } else {
                    e.setValue("");
                }
            } else {
                e.setValue("");
            }
        });
        //判断map中是否有key为’其他‘的数据，提取单独处理
        List<EquProperty> otherProperList = map.get("其他");
        if (otherProperList != null && otherProperList.size() > 0) {
            otherProperList.addAll(properList);
            map.put("其他", otherProperList);
        } else {
            map.put("其他", properList);
        }
        Equipment byId = iEquipmentService.getById(equipmentId);

        Map<String, Object> re = new HashMap<>();
        re.put("res", map);
//        re.put("pre", byId.getPrefQuota()); // 非核心参数此处不需要
        return re;
    }

    /***
     *
     * 根拓补节点id查询当前节点物联数据记录
     *
     * **/
    @RequestMapping(value = "/equipment/info", method = RequestMethod.GET)
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "根据节点id查询当前节点物联数据记录", notes = "根据节点id查询当前节点物联数据记录")
    public ResponseModel getEquipmentIotInfo(@RequestParam(required = false) String id,
                                             @RequestParam(required = false) String equipSpeId,
                                             @RequestParam(required = false) String beginDate,
                                             @RequestParam(required = false) String endDate) {
        String eqpId;
        if (StringUtil.isNotEmpty(equipSpeId)) {
            eqpId = equipSpeId;
        } else {
            TopographyNodeDetailDTO detailDTO = topographyNodeDetailService.queryByNodeid(id);
            if (null == detailDTO || !StringUtil.isNotEmpty(detailDTO.getEqpId())) {
                throw new RuntimeException("节点信息错误或此节点下未绑定装备！");
            }
            eqpId = detailDTO.getEqpId();
        }
        EquipmentSpecific equipmentSpecific = equipmentSpecificService.getById(eqpId);
        String iotCode = equipmentSpecific.getIotCode();
        String prefix = null;
        String suffix = null;
        if (iotCode.length() > 8) {
            prefix = iotCode.substring(0, 8);
            suffix = iotCode.substring(8);
        } else {
            return CommonResponseUtil.failure("装备物联编码错误，请确认！");
        }
        ResponseModel entity = null;
        try {
            entity = iotFeign.selectList(getAppKey(), getProduct(), getToken(), beginDate, endDate, prefix, suffix, null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (200 == entity.getStatus() && !ObjectUtils.isEmpty(entity.getResult())) {
            List<TopographyIotVo> list = new ArrayList<>();
            String json = JSON.toJSONString(entity.getResult());
            List<Map<String, String>> listObject = (List<Map<String, String>>) JSONArray.parse(json);
            List<IotDataVO> iotDatalist = new ArrayList<>();
            for (Map<String, String> mapList : listObject) {
                for (Map.Entry entry : mapList.entrySet()) {
                    if (!"name".equals(entry.getKey()) && !"deviceName".equals(entry.getKey())) {
                        IotDataVO iotDataVO = new IotDataVO();
                        iotDataVO.setKey(String.valueOf(entry.getKey()));
                        iotDataVO.setValue(entry.getValue());
                        iotDatalist.add(iotDataVO);
                    }
                }
            }
            List<IotDataVO> timeList = iotDatalist.stream().filter(x -> "time".equals(x.getKey())).collect(Collectors.toList());
            List<EquipmentSpecificIndex> indexes = equipmentSpecificIndexMapper.getEquipmentSpeIndexByIotCode(iotCode);

            if (0 < indexes.size()) {
                int j = 0;
                Map<String, Object> map = new HashMap<>();


                for (int i = 0; i < timeList.size(); i++) {
                    TopographyIotVo iotVo = new TopographyIotVo();
                    List<TopographyIotDataVO> lists = new ArrayList<>();
//                    if (i == 0) {
//                        map.put(iotDatalist.get(i).getKey(), iotDatalist.get(i).getValue());
//                    }
//                    if (map.containsKey(iotDatalist.get(i).getKey())) {
//                        j++;
//                    }
                    for (EquipmentSpecificIndex x : indexes) {
                        if (x.getNameKey().equals(iotDatalist.get(i).getKey())) {
                            TopographyIotDataVO dataVO = new TopographyIotDataVO();
                            dataVO.setId(x.getId());
                            dataVO.setName(x.getIndexName());
                            dataVO.setValue(x.getValue());
                            dataVO.setUnit(x.getIndexUnitName());
                            lists.add(dataVO);
                            iotVo.setList(lists);
                            try {
                                //Date date = DateUtils.dateParse(String.valueOf(timeList.get(j-1).getValue()), DateUtils.DATE_TIME_T_PATTERN);

                                String value = String.valueOf(timeList.get(i).getValue());
                                String strDate = value.substring(0, 19);
                                SimpleDateFormat sdf = new SimpleDateFormat(ISO8601_DATE_HOUR_MIN_SEC);
                                SimpleDateFormat sdf1 = new SimpleDateFormat(DateUtils.DATE_TIME_PATTERN);
                                sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
                                Date date1 = sdf.parse(strDate);
                                String time = DateTimeUtil.format(date1, DateTimeUtil.ISO_DATE_HOUR24_MIN_SEC);

                                iotVo.setTime(sdf1.parse(time));
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            list.add(iotVo);
                        }
                    }
                }
            }
            List<TopographyIotVo> result = list.stream().sorted(Comparator.comparing(TopographyIotVo::getTime).reversed()).collect(Collectors.toList());
            return CommonResponseUtil.success(result);
        } else {
            logger.error("查询物联日志数据为空或iotCode为 (" + iotCode + ") 的装备不存在于物联系统中！");
            return CommonResponseUtil.success();
        }
    }

    /***
     *
     * 根拓补节点id查询当前节点物联指标趋势
     *
     * **/
    @RequestMapping(value = "/equipment/tren", method = RequestMethod.GET)
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "根据节点id查询当前节点物联指标趋势", notes = "根据节点id查询当前节点物联指标趋势")
    public ResponseModel getEquipmentIndexTrendInfo(@RequestParam(required = false) String id,
                                                    @RequestParam(required = false) String equipSpeId,
                                                    @RequestParam(required = false) String beginDate,
                                                    @RequestParam(required = false) String fieldKey,
                                                    @RequestParam(required = false) String isTrend,
                                                    @RequestParam(required = false) String endDate) throws ParseException {

        Map<String, List<IotIndexResVo>> resultMap = new HashMap<>();
        List<String> split = Arrays.asList(equipSpeId.split(","));
        List<IotIndexResVo> finalRes = new ArrayList<>();
        List<IotIndexResVo> finalResContainsWaterLevel = new ArrayList<>();
        List<IotIndexResVo> resultResContainsWater = new ArrayList<>();
        Map<String, String> iotCodeMap = new HashMap<>();
        for (String specId : split) {
            String eqpId;
            String iotCode = null;
            if (null != fieldKey || null != isTrend) {
                EquipmentSpecific equipmentSpecific = equipmentSpecificService.getById(specId);
                iotCode = equipmentSpecific.getIotCode();
                iotCodeMap.put(specId, iotCode);

                List<EquipmentIndex> equipmentSpecifics = equipmentIndexService.getPerfQutoaIotList(Long.valueOf(specId));

                if (equipmentSpecifics.size() == 0) {
                    return CommonResponseUtil.success();
                }
                if ("true".equals(isTrend)) {
                    fieldKey = equipmentSpecifics.stream().filter(equipmentIndex -> equipmentIndex.getIsTrend()).map(EquipmentIndex::getPerfQuotaDefinitionId).collect(Collectors.joining(","));
                }
            } else {
                if (StringUtil.isNotEmpty(specId)) {
                    eqpId = specId;
                } else {
                    TopographyNodeDetailDTO detailDTO = topographyNodeDetailService.queryByNodeid(id);
                    if (null == detailDTO || !StringUtil.isNotEmpty(detailDTO.getEqpId())) {
                        throw new RuntimeException("节点信息错误或此节点下未绑定装备！");
                    }
                    eqpId = detailDTO.getEqpId();
                }

                EquipmentSpecific equipmentSpecific = equipmentSpecificService.getById(eqpId);
                iotCode = equipmentSpecific.getIotCode();
            }
            String prefix = null;
            String suffix = null;
            if (StringUtil.isNotEmpty(iotCode) && iotCode.length() > 8) {
                prefix = iotCode.substring(0, 8);
                suffix = iotCode.substring(8);
            } else {
                return CommonResponseUtil.failure("装备物联编码不存在或编码错误，请确认！");
            }
            ResponseModel entity = null;
            try {
                entity = iotFeign.selectList(getAppKey(), getProduct(), getToken(), beginDate, endDate, prefix, suffix, fieldKey);
            } catch (Exception e) {
                throw new RuntimeException("调用AMOS-API-IOT服务失败，请检查服务是否正常！");
            }
            if (200 == entity.getStatus() && !ObjectUtils.isEmpty(entity.getResult())) {
                String json = JSON.toJSONString(entity.getResult());
                List<Map<String, String>> listObject = (List<Map<String, String>>) JSONArray.parse(json);
                List<IotDataVO> vos = new ArrayList<>();
                for (Map<String, String> mapList : listObject) {
                    for (Map.Entry entry : mapList.entrySet()) {
                        if (!"name".equals(entry.getKey()) && !"deviceName".equals(entry.getKey())) {
                            IotDataVO vo = new IotDataVO();
                            vo.setKey(String.valueOf(entry.getKey()));
                            vo.setValue(String.valueOf(entry.getValue()));
                            vos.add(vo);
                        }
                    }
                }
                Map<String, List<Date>> dateMap = new HashMap<>();
                for (int i = 0; i < vos.size(); i = i + 2) {
                    Date useDate = null;
                    String indexKey = null;
                    if (vos.get(i).getKey().equals("time")) {
                        useDate = dateParse(vos.get(i).getValue().toString());
                        indexKey = String.valueOf(vos.get(i + 1).getKey());
                    } else {
                        useDate = dateParse(vos.get(i).getValue().toString());
                        indexKey = String.valueOf(vos.get(i).getKey());
                    }
                    if (!dateMap.containsKey(indexKey)) {
                        ArrayList<Date> dates1 = new ArrayList<>();
                        dates1.add(useDate);
                        dateMap.put(indexKey, dates1);
                    } else {
                        dateMap.get(indexKey).add(useDate);
                    }
                }
                List<EquipmentSpecificIndex> indexes = equipmentSpecificIndexMapper.getEquipmentSpeIndexByIotCodeAndTrend(iotCode);
                if (0 < indexes.size()) {
                    List<TopographyIotIndexTrendVo> list = new ArrayList<>();
                    vos.forEach(iotDataVO -> {
                        indexes.forEach(x -> {
                            if (x.getNameKey().equals(iotDataVO.getKey())) {
                                TopographyIotIndexTrendVo vo = new TopographyIotIndexTrendVo();
                                vo.setId(x.getId());
                                vo.setName(x.getIndexName());
                                vo.setNameKey(x.getNameKey());
                                vo.setUnit(x.getIndexUnitName());
                                vo.setTimes(dateMap.get(x.getNameKey()));
                                vo.setIotData(iotDataVO);
                                list.add(vo);
                            }
                        });
                    });
                    Map<String, List<TopographyIotIndexTrendVo>> maps = list.stream().collect(Collectors.groupingBy(x -> x.getIotData().getKey()));
                    Map<String, List<IotDataVO>> map = new HashMap<>();
                    for (String str : maps.keySet()) {
                        map.put(str, maps.get(str).stream().map(TopographyIotIndexTrendVo::getIotData).collect(Collectors.toList()));
                    }

                    Map<String, Long> mapIndex = new HashMap<>();

                    for (String str : maps.keySet()) {
                        mapIndex.put(str, maps.get(str).get(0).getId());
                    }
                    List<IotIndexResVo> res = new ArrayList<>();
                    List<IotIndexResVo> resContainsWaterLevelList = new ArrayList<>();
                    for (String s : mapIndex.keySet()) {
                        IotIndexResVo vo = new IotIndexResVo();
                        LambdaQueryWrapper<EquipmentIndex> queryWrapper = new LambdaQueryWrapper<>();
                        queryWrapper.eq(EquipmentIndex::getId, mapIndex.get(s));
                        EquipmentIndex index = iEquipmentIndexService.getOne(queryWrapper);
                        vo.setIotData(map.get(s));
                        vo.setId(index.getId());
                        vo.setName(index.getPerfQuotaName());
                        vo.setNameKey(index.getPerfQuotaDefinitionId());
                        vo.setUnit(index.getUnitName());
                        vo.setTimes(dateMap.get(index.getPerfQuotaDefinitionId()));
                        vo.setEquipId(specId);
                        if (waterLevelIndexKey.contains(vo.getNameKey())) {
                            resContainsWaterLevelList.add(vo);
                        } else {
                            res.add(vo);
                        }
                    }
                    for (IotIndexResVo s : res) {
                        s.setIotData(map.get(s.getNameKey()));
                        s.setTimes(dateMap.get(s.getNameKey()));
                    }
                    finalRes.addAll(res);
                    finalResContainsWaterLevel.addAll(resContainsWaterLevelList);
                }
            }
        }

        List<Date> containsWaterDates = new ArrayList<>();
        Map<String, Map<Date, IotDataVO>> iotDataAndDateMap = new HashMap<>();
        finalResContainsWaterLevel.stream().forEach(item -> {
            if (!CollectionUtils.isEmpty(item.getTimes())) {
                containsWaterDates.addAll(item.getTimes());
                Map<Date, IotDataVO> dateDataMap = new HashMap<>();
                for (int i = 0; i < item.getTimes().size(); i++) {
                    dateDataMap.put(item.getTimes().get(i), item.getIotData().get(i));
                }
                iotDataAndDateMap.put(item.getId() + item.getEquipId(), dateDataMap);
            }
        });
        List<Date> collect = containsWaterDates.stream().distinct().sorted(Comparator.comparing(t -> t)).collect(Collectors.toList());
        IotIndexResVo iotIndexRes = null;
        Map<String, List<IotDataVO>> map = new HashMap<>();
        for (IotIndexResVo indexResVo : finalResContainsWaterLevel) {
            iotIndexRes = new IotIndexResVo();
            iotIndexRes.setName(indexResVo.getName());
            iotIndexRes.setTimes(collect);
            iotIndexRes.setId(indexResVo.getId());
            iotIndexRes.setNameKey(indexResVo.getNameKey());
            iotIndexRes.setUnit(indexResVo.getUnit());
            Map<Date, IotDataVO> dateIotDataVOMap = iotDataAndDateMap.get(indexResVo.getId() + indexResVo.getEquipId());
            List<IotDataVO> list = new ArrayList<>();
            collect.forEach(item -> {
                IotDataVO iotDataVO = new IotDataVO();
                iotDataVO.setKey(indexResVo.getIotData().get(0).getKey());
                iotDataVO.setValue(0);
                if (dateIotDataVOMap.containsKey(item)) {
                    iotDataVO.setValue(dateIotDataVOMap.get(item).getValue());
                } else {
                    String currentIotCode = iotCodeMap.get(indexResVo.getEquipId());
                    String currentPrefix = currentIotCode.substring(0, 8);
                    String currentSuffix = currentIotCode.substring(8);

                    ResponseModel entity = null;
                    try {
                        entity = iotFeign.selectPage(getAppKey(), getProduct(), getToken(), "2000-01-01 00:00:00", endDate, currentPrefix, currentSuffix, indexResVo.getIotData().get(0).getKey(), 0, 1);
                    } catch (Exception e) {
                        throw new RuntimeException("调用AMOS-API-IOT服务失败，请检查服务是否正常！");
                    }
                    if (200 == entity.getStatus() && !ObjectUtils.isEmpty(entity.getResult())) {
                        String json = JSON.toJSONString(entity.getResult());
                        Map<String, Object> listObject = (Map<String, Object>) JSONArray.parse(json);
                        List<Map<String, String>> listData = (List<Map<String, String>>) listObject.get("records");
                        if (!CollectionUtils.isEmpty(listData)) {

                            for (Map.Entry<String, String> stringStringEntry : listData.get(0).entrySet()) {
                                if (indexResVo.getIotData().get(0).getKey().equals(stringStringEntry.getKey())) {
                                    iotDataVO.setValue(String.valueOf(stringStringEntry.getValue()));
                                }
                            }

                        } else {
                            iotDataVO.setValue(0);
                        }
                    } else {
                        iotDataVO.setValue(0);
                    }
                }
                list.add(iotDataVO);
            });
            map.put(indexResVo.getEquipId(), list);
        }
        List<IotDataVO> list = new ArrayList<>();
        int j = 0;
        for (Map.Entry<String, List<IotDataVO>> stringListEntry : map.entrySet()) {
            if (j == 0) {
                list = stringListEntry.getValue();
            } else {
                for (int i = 0; i < stringListEntry.getValue().size(); i++) {
                    Object last = list.get(i).getValue();
                    Object current = stringListEntry.getValue().get(i).getValue();

                    BigDecimal value1 = new BigDecimal(String.valueOf(last));
                    BigDecimal value2 = new BigDecimal(String.valueOf(current));
                    BigDecimal add = value1.add(value2);
                    BigDecimal divide = add.divide(new BigDecimal(2), 2, BigDecimal.ROUND_DOWN);
                    list.get(i).setValue(divide);
                }
            }
            j++;
        }
        if (!CollectionUtils.isEmpty(list)) {
            iotIndexRes.setIotData(list);
        }
        if (!ObjectUtils.isEmpty(iotIndexRes)) {
            resultResContainsWater.add(iotIndexRes);
        }
        resultMap.put("noMergeList", finalRes);
        resultMap.put("mergeList", resultResContainsWater);
        return CommonResponseUtil.success(resultMap);
    }


    /***
     *
     * 根据设备id获取当前设备的物联指标趋势
     *
     * **/
    @RequestMapping(value = "/equipment/trenIot", method = RequestMethod.GET)
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "根据设备id获取当前设备的物联指标趋势", notes = "根据设备id获取当前设备的物联指标趋势")
    public ResponseModel getEquipmentIndexTrendIotInfo(@RequestParam(required = false) String totalType,
                                                       @RequestParam(required = false) String equipId,
                                                       @RequestParam(required = false) String fieldKey,
                                                       @RequestParam(required = false) String isTrend,
                                                       @RequestParam(required = false) String beginDate,
                                                       @RequestParam(required = false) String endDate) throws Exception {



        EquipmentSpecific equipmentSpecific = equipmentSpecificService.getById(equipId);
        String iotCode = equipmentSpecific.getIotCode();

        List<EquipmentIndex> equipmentSpecifics = equipmentIndexService.getPerfQutoaIotList(Long.valueOf(equipId));

        if (equipmentSpecifics.size() == 0) {
            return CommonResponseUtil.success();
        }
        String allKeys;
        String names;
        Map<String, String> map = new HashMap<>();
        List<IotIndexItemVo> iotIndexItemVos = new ArrayList<>();

        equipmentSpecifics.stream().forEach((e)->{
            IotIndexItemVo itemVo = new IotIndexItemVo();
            if(!e.getIsTrend()) {
                map.put(e.getPerfQuotaDefinitionId(),e.getPerfQuotaName());
                itemVo.setKey(e.getPerfQuotaDefinitionId());
                itemVo.setName(e.getPerfQuotaName());
                itemVo.setColor(e.getEmergencyLevelColor());
                iotIndexItemVos.add(itemVo);
            }
        });


        allKeys = equipmentSpecifics.stream().filter(equipmentIndex -> !equipmentIndex.getIsTrend()).map(EquipmentIndex::getPerfQuotaDefinitionId).collect(Collectors.joining(","));
        names = equipmentSpecifics.stream().filter(equipmentIndex -> !equipmentIndex.getIsTrend()).map(EquipmentIndex::getPerfQuotaName).collect(Collectors.joining(","));

        String parmfieldKey = "";
        String parmfieldName = "";
        if(StringUtils.isEmpty(fieldKey) ) {
            parmfieldKey = allKeys;
        } else {
            parmfieldKey = fieldKey;
            for(String s: fieldKey.split(",") ) {
                parmfieldName = parmfieldName + map.get(s) + ",";
            }
        }

        String prefix = null;
        String suffix = null;
        if (StringUtil.isNotEmpty(iotCode) && iotCode.length() > 8) {
            prefix = iotCode.substring(0, 8);
            suffix = iotCode.substring(8);
        } else {
            return CommonResponseUtil.failure("装备物联编码不存在或编码错误，请确认！");
        }
        ResponseModel entity = null;
        String[] filedKeyArr = parmfieldKey.split(",");
        List<IotIndexResMinotVo> res = new ArrayList<>();
        IotIndexResMinotFinalVo indexResMinotFinalVo = new IotIndexResMinotFinalVo();
        List<Date> datesFinal = new ArrayList<>();
        for (String st : filedKeyArr) {
            try {
                entity = iotFeign.selectList(getAppKey(), getProduct(), getToken(), beginDate, endDate, prefix, suffix, st);
            } catch (Exception e) {
                throw new RuntimeException("调用AMOS-API-IOT服务失败，请检查服务是否正常！");
            }
            if (200 == entity.getStatus() && !ObjectUtils.isEmpty(entity.getResult())) {
                String json = JSON.toJSONString(entity.getResult());
                List<Map<String, String>> listObject = (List<Map<String, String>>) JSONArray.parse(json);
                List<IotDataVO> vos = new ArrayList<>();

                Map<String, String> timeAndValue = new HashMap<>();
                for (Map<String, String> mapList : listObject) {
                    for (Map.Entry entry : mapList.entrySet()) {
                        if (!"name".equals(entry.getKey()) && !"deviceName".equals(entry.getKey())) {
                            IotDataVO vo = new IotDataVO();
                            vo.setKey(String.valueOf(entry.getKey()));
                            vo.setValue(String.valueOf(entry.getValue()));
                            vos.add(vo);
                        }
                    }
                    if (mapList.containsKey(st)) {
                        timeAndValue.put(mapList.get("time"), mapList.get(st));
                    }
                }

                List<IotDataVO> timeList = vos.stream().filter(x -> x.getKey().equals("time")).collect(Collectors.toList());
                List<String> dates = new ArrayList<>();

                for (IotDataVO vo : timeList) {
                    String value = String.valueOf(vo.getValue());
                    dates.add(value);
               }

                List<IotDataVO> dataList = new ArrayList<>();

                // 处理遥信 时间处理
                if (totalType.equals("hour")) {
                    handle(datesFinal, dates, beginDate, st, dataList, timeAndValue);
                } else if (totalType.equals("day")) {
                    handleDay(datesFinal, beginDate, endDate, st, dates, dataList, timeAndValue);
                } else if (totalType.equals("week")) {
                    handWeek(beginDate, st,dates,dataList,timeAndValue);
                } else {
                    handMonth(beginDate, st,dates,dataList,timeAndValue);
                }

                IotIndexResMinotVo iotIndexResVo = new IotIndexResMinotVo();
                iotIndexResVo.setIotData(dataList);
                res.add(iotIndexResVo);
            }
        }

        List<IotIndexResItemVo> iotData = new ArrayList<>();

        for(IotIndexResMinotVo s : res) {
            IotIndexResItemVo itemVo = new IotIndexResItemVo();
            List<Integer> list = new ArrayList<>();
            for (IotDataVO v: s.getIotData()) {
                list.add(Integer.parseInt(v.getValue().toString()));
                itemVo.setName(map.get(v.getKey()));
                itemVo.setKey(v.getKey());
            }
            itemVo.setData(list.stream().mapToInt(i->i).toArray());
            iotData.add(itemVo);
        }

        if(totalType.equals("week") || totalType.equals("month") || totalType.equals("hour") || totalType.equals("day")) {
            List<String> times = null;
            if(totalType.equals("week")) {
                times = DateUtils.getWeeksMap(DateUtils.dateToStringMonth(beginDate));
            } else if(totalType.equals("month")) {
                String year = beginDate.substring(0,4);
                times = new ArrayList<>();
                for(int i =1; i <= 12; i++) {
                    if(i < 10) {
                        String m = year + "-" + "0" + i;
                        times.add(m);
                    } else {
                        String m = year  + "-"  + i;
                        times.add(m);
                    }
                }

            } else if(totalType.equals("hour") || totalType.equals("day")) {
                times = new ArrayList<>();
                if(totalType.equals("hour")) {
                    String[] arr = DateUtils.TWENTY_FOUR;
                    Date date = DateUtils.dateParse(beginDate,DateUtils.DATE_PATTERN);
                    String dateDayT = DateUtils.dateFormat(date, DateUtils.DATE_PATTERN);
                    if (datesFinal.size() == 0) {
                        for (String str : arr) {
                            String dateDay = dateDayT;
                            dateDay = dateDay + str;
                            datesFinal.add(DateUtils.dateParse(dateDay, DateUtils.DATE_TIME_PATTERN));
                        }
                    }
                } else {
                    if (datesFinal.size() == 0) {
                        datesFinal.addAll(DateUtils.findDaysStr(DateUtils.dateToString(beginDate), DateUtils.dateToString(endDate)));
                    }
                }


                for (Date date : datesFinal) {
                    times.add(DateUtils.convertDateToString(date, totalType.equals("hour") ? DateUtils.HOUR_PATTERN : DateUtils.DATE_PATTERN));
                }
            }

            if(iotData.size() == 0) {
                fullData(iotIndexItemVos,iotData,times,map);
            }

            indexResMinotFinalVo.setTimes(times);
            indexResMinotFinalVo.setNameKey(StringUtils.isEmpty(fieldKey) ? allKeys.split(",") : fieldKey.split(","));
            indexResMinotFinalVo.setName(StringUtils.isEmpty(fieldKey) ? names.split(",") : parmfieldName.split(","));
            indexResMinotFinalVo.setItems(iotIndexItemVos);
            indexResMinotFinalVo.setIotData(iotData);
        }

        return CommonResponseUtil.success(indexResMinotFinalVo);
    }

    private List<IotIndexResItemVo> doIndexData(List<IotIndexResItemVo> iotData, Map<String, String> typeNameMap, Map<String, String> typeCodeAndIndexKeyMap) {
        iotData.stream().forEach(item -> {
            item.setKey(typeCodeAndIndexKeyMap.get(item.getKey()));
            item.setName(typeNameMap.get(item.getKey()));
        });

        Map<String, IotIndexResItemVo> map = new HashMap<>();
        List<IotIndexResItemVo> iotDataNew = new ArrayList<>();
        for (IotIndexResItemVo iotDatum : iotData) {
            if (!map.containsKey(iotDatum.getKey())) {
                map.put(iotDatum.getKey(), iotDatum);
            } else {
                IotIndexResItemVo iotIndexResItemVo = map.get(iotDatum.getKey());
                int i = 0;
                for (int datum : iotIndexResItemVo.getData()) {
                    iotIndexResItemVo.getData()[i] = datum + iotDatum.getData()[i];

                    i++;
                }
            }
        }
        for (Map.Entry<String, IotIndexResItemVo> stringIotIndexResItemVoEntry : map.entrySet()) {
            iotDataNew.add(stringIotIndexResItemVoEntry.getValue());
        }
        return iotDataNew;
    }
    private void fullData(List<IotIndexItemVo> iotIndexItemVos, List<IotIndexResItemVo> iotData, List<String>  times, Map<String, String> map ) {
        for(IotIndexItemVo iVo: iotIndexItemVos) {
            IotIndexResItemVo itVo = new IotIndexResItemVo();
            itVo.setName(map.get(iVo.getKey()));
            itVo.setKey(iVo.getKey());
            List<Integer> list = new ArrayList<>();
            for (int i = 1; i <= times.size() ; i++) {
                list.add(0);
            }
            itVo.setData(list.stream().mapToInt(i->i).toArray());
            iotData.add(itVo);
        }
    }

    private void handMonth( String beginDate,  String nameKey, List<String> dates, List<IotDataVO> dataList, Map<String, String> timeAndValue) throws Exception {
        for(int i =1; i <= 12; i++) {
            int num = 0;
            Date bDate = DateUtils.getCurrentMonthStartTime(DateUtils.dateParse(DateUtils.dateToStringY(beginDate) + "-" + i,DateUtils.MONTH_PATTERN));
            Date dDate = DateUtils.getCurrentMonthEndTime(DateUtils.dateParse(DateUtils.dateToStringY(beginDate) + "-" + i,DateUtils.MONTH_PATTERN));
            for (String dat : dates) {
                if (DateUtils.belongCalendar(dateParse(dat), bDate, dDate)) {
                    if ("true".equals(timeAndValue.get(dat))) {
                        num++;
                    }
                }
            }
            IotDataVO iotDataVO = new IotDataVO();
            iotDataVO.setKey(nameKey);
            iotDataVO.setValue(num);
            dataList.add(iotDataVO);
        }
    }

    private void handWeek( String beginDate,  String nameKey, List<String> dates, List<IotDataVO> dataList, Map<String, String> timeAndValue) throws Exception {
        List<String> weeks = DateUtils.getWeeks(DateUtils.dateToStringMonth(beginDate));

        for(String s:weeks) {
            int num = 0;
            String[] arr = s.split("-");
            Date bDate;
            Date dDate;
            String sStr = "";
            String eStr = "";
            if(Integer.parseInt(arr[0]) < 10 ) {
                sStr = "0" + arr[0];
            } else {
                sStr = arr[0];
            }
            if(Integer.parseInt(arr[1]) < 10 ) {
                eStr = "0" + arr[1];
            } else {
                eStr = arr[1];
            }
            if(arr[0].equals(arr[1])) {

                bDate = DateUtils.dateParse(DateUtils.dateToStringMonth(beginDate) + "-" + sStr + " 00:00:00" ,DateUtils.DATE_TIME_PATTERN);
                dDate = DateUtils.dateParse(DateUtils.dateToStringMonth(beginDate) + "-" + eStr + " 23:59:59"
                        ,DateUtils.DATE_TIME_PATTERN);
            } else {

                bDate = DateUtils.dateParse(DateUtils.dateToStringMonth(beginDate) + "-" + sStr + " 00:00:00",DateUtils.DATE_TIME_PATTERN);
                dDate = DateUtils.dateParse(DateUtils.dateToStringMonth(beginDate) + "-" + eStr + " 23:59:59",DateUtils.DATE_TIME_PATTERN);
            }


            for (String dat : dates) {
                if (DateUtils.belongCalendar(dateParse(dat), bDate, dDate)) {
                    if (("true".equals(timeAndValue.get(dat))) || (!"true".equals(timeAndValue.get(dat)) && !"false".equals(timeAndValue.get(dat)))) {
                        num++;
                    }
                }
            }
            IotDataVO iotDataVO = new IotDataVO();
            iotDataVO.setKey(nameKey);
            iotDataVO.setValue(num);
            dataList.add(iotDataVO);
        }
    }

    private void handleDay(List<Date> datesFinal, String beginDate, String endDate, String nameKey, List<String> dates, List<IotDataVO> dataList, Map<String, String> timeAndValue
    ) throws ParseException {
        if (datesFinal.size() == 0) {
            datesFinal.addAll(DateUtils.findDaysStr(DateUtils.dateToString(beginDate), DateUtils.dateToString(endDate)));
        }

        if (timeAndValue.size() > 0) {
            finalHandle(datesFinal, nameKey, dates, dataList, timeAndValue);
        }
    }

    private void handle(List<Date> datesFinal, List<String> dates,  String beginDate, String nameKey, List<IotDataVO> dataList,
                        Map<String, String> timeAndValue) throws ParseException {

        String[] arr = DateUtils.TWENTY_FOUR;
        Date date = DateUtils.dateParse(beginDate,DateUtils.DATE_PATTERN);
        String dateDayT = DateUtils.dateFormat(date, DateUtils.DATE_PATTERN);
        if (datesFinal.size() == 0) {
            for (String str : arr) {
                String dateDay = dateDayT;
                dateDay = dateDay + str;
                datesFinal.add(DateUtils.dateParse(dateDay, DateUtils.DATE_TIME_PATTERN));
            }
        }

        if (timeAndValue.size() > 0) {
            finalHandle(datesFinal, nameKey, dates, dataList, timeAndValue);
        }

    }

    private void finalHandle(List<Date> datesFinal, String nameKey, List<String> dates, List<IotDataVO> dataList, Map<String, String> timeAndValue) throws ParseException {
        for (int i = 0; i < datesFinal.size(); i++) {
            int num = 0;
            for (String dat : dates) {
                if (i == datesFinal.size() - 1) {
                    if (DateUtils.belongCalendar(dateParse(dat), datesFinal.get(i),
                            DateUtils.getCurrentDayEndTime(datesFinal.get(i)))) {
                        if ("true".equals(timeAndValue.get(dat))) {
                            num++;
                        }
                    }
                } else {
                    if (DateUtils.belongCalendar(dateParse(dat), datesFinal.get(i), datesFinal.get(i + 1))) {
                        if ("true".equals(timeAndValue.get(dat))) {
                            num++;
                        }
                    }
                }
            }
            IotDataVO iotDataVO = new IotDataVO();
            iotDataVO.setKey(nameKey);
            iotDataVO.setValue(num);
            dataList.add(iotDataVO);
        }
    }


    private Date dateParse(String value) throws ParseException {
        String strDate = value.substring(0, 19);
        SimpleDateFormat sdf = new SimpleDateFormat(ISO8601_DATE_HOUR_MIN_SEC);
        SimpleDateFormat sdf1 = new SimpleDateFormat(DateUtils.DATE_TIME_PATTERN);
        sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
        Date date = sdf.parse(strDate);
        String time = DateTimeUtil.format(date, DateTimeUtil.ISO_DATE_HOUR24_MIN_SEC);
        return  sdf1.parse(time);
    }

    /***
     *
     * 根据设备id获取当前设备的物联指标趋势 【水源页面用】
     *
     * **/
    @RequestMapping(value = "/equipment/trenIotByWater", method = RequestMethod.GET)
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "根据设备id获取当前设备的物联指标趋势【水源页面】", notes = "根据设备id获取当前设备的物联指标趋势【水源页面】")
    public ResponseModel trenIotByWater(@RequestParam(required = false) String totalType,
                                                       @RequestParam(required = false) String equipId,
                                                       @RequestParam(required = false) String fieldKey,
                                                       @RequestParam(required = false) String isTrend,
                                                       @RequestParam(required = false) String beginDate,
                                                       @RequestParam(required = false) String endDate) throws Exception {



        List<String> split= Arrays.asList(equipId.split(","));
        String allKeys = null;
        String names = null;
        List<IotIndexItemVo> iotIndexItemVos = new ArrayList<>();
        List<IotIndexItemVo> iotIndexItemVoListNew = new ArrayList<>();
        Map<String, String> keyIotMap = new HashMap<>();
        Map<String, String> map = new HashMap<>();
        Map<String, String> typeNameMap = new HashMap<>();
        Map<String, String> typeCodeAndIndexKeyMap = new HashMap<>();
        List<String> typeCodeList = new ArrayList<>();
        List<String> typeNameList = new ArrayList<>();

        List<String> indexKeyList = new ArrayList<>();
        for (String specificId  : split) {
            EquipmentSpecific equipmentSpecific = equipmentSpecificService.getById(specificId);
            String iotCode = equipmentSpecific.getIotCode();

            List<EquipmentIndex> equipmentSpecifics = equipmentIndexService.getPerfQutoaIotList(Long.valueOf(specificId));

            if (equipmentSpecifics.size() == 0) {
                return CommonResponseUtil.success();
            }

            equipmentSpecifics.stream().forEach((e)->{
                IotIndexItemVo itemVo = new IotIndexItemVo();
                IotIndexItemVo indexItemVo = new IotIndexItemVo();
                if(!e.getIsTrend()) {

                    if (!typeNameMap.containsKey(e.getTypeCode())) {
                        indexItemVo.setKey(e.getTypeCode());
                        indexItemVo.setName(e.getTypeName());
                        indexItemVo.setColor(e.getEmergencyLevelColor());
                        iotIndexItemVoListNew.add(indexItemVo);
                    }

                    map.put(e.getPerfQuotaDefinitionId(),e.getPerfQuotaName());
                    typeNameMap.put(e.getTypeCode(), e.getTypeName());
                    itemVo.setKey(e.getPerfQuotaDefinitionId());
                    itemVo.setName(e.getPerfQuotaName());
                    itemVo.setColor(e.getEmergencyLevelColor());
                    keyIotMap.put(e.getPerfQuotaDefinitionId() + iotCode, iotCode);
                    iotIndexItemVos.add(itemVo);

                    typeCodeAndIndexKeyMap.put(e.getPerfQuotaDefinitionId(), e.getTypeCode());
                }
            });

            if (!CollectionUtils.isEmpty(equipmentSpecifics.stream().filter(equipmentIndex -> !equipmentIndex.getIsTrend()).map(EquipmentIndex::getTypeCode).distinct().collect(Collectors.toList()))) {
                typeCodeList.addAll(equipmentSpecifics.stream().filter(equipmentIndex -> !equipmentIndex.getIsTrend()).map(EquipmentIndex::getTypeCode).distinct().collect(Collectors.toList()));
            }
            if (!CollectionUtils.isEmpty(equipmentSpecifics.stream().filter(equipmentIndex -> !equipmentIndex.getIsTrend()).map(EquipmentIndex::getTypeName).distinct().collect(Collectors.toList()))) {
                typeNameList.addAll(equipmentSpecifics.stream().filter(equipmentIndex -> !equipmentIndex.getIsTrend()).map(EquipmentIndex::getTypeName).distinct().collect(Collectors.toList()));
            }
            if (!CollectionUtils.isEmpty(equipmentSpecifics.stream().filter(equipmentIndex -> !equipmentIndex.getIsTrend()).map(t -> {
                return t.getPerfQuotaDefinitionId() + iotCode;
            }).distinct().collect(Collectors.toList()))) {
                indexKeyList.addAll(equipmentSpecifics.stream().filter(equipmentIndex -> !equipmentIndex.getIsTrend()).map(t -> {
                    return t.getPerfQuotaDefinitionId() + iotCode;
                }).distinct().collect(Collectors.toList()));            }
        }
        allKeys = typeCodeList.stream().distinct().collect(Collectors.joining(","));
        names = typeNameList.stream().distinct().collect(Collectors.joining(","));
        String parmfieldKey = "";
        String parmfieldName = "";
        if(StringUtils.isEmpty(fieldKey) ) {
            parmfieldKey = allKeys;
            parmfieldName = names;
        } else {
            parmfieldKey = fieldKey;
            for(String s: fieldKey.split(",") ) {
                parmfieldName = parmfieldName + typeNameMap.get(s) + ",";
            }
        }
        ResponseModel entity = null;
        String[] filedKeyArr = parmfieldKey.split(",");
        List<IotIndexResMinotVo> res = new ArrayList<>();
        IotIndexResMinotFinalVo indexResMinotFinalVo = new IotIndexResMinotFinalVo();
        List<Date> datesFinal = new ArrayList<>();
        for (String indexKey : indexKeyList) {
            String prefix = null;
            String suffix = null;
            String iotCode = keyIotMap.get(indexKey);
            String st = "";
            if (StringUtil.isNotEmpty(iotCode) && iotCode.length() > 8) {
                prefix = iotCode.substring(0, 8);
                suffix = iotCode.substring(8);
                st = indexKey.substring(0, indexKey.length() - 16);
            } else {
                return CommonResponseUtil.failure("装备物联编码不存在或编码错误，请确认！");
            }
            try {
                entity = iotFeign.selectList(getAppKey(), getProduct(), getToken(), beginDate, endDate, prefix, suffix, st);
            } catch (Exception e) {
                throw new RuntimeException("调用AMOS-API-IOT服务失败，请检查服务是否正常！");
            }
            if (200 == entity.getStatus() && !ObjectUtils.isEmpty(entity.getResult())) {
                String json = JSON.toJSONString(entity.getResult());
                List<Map<String, String>> listObject = (List<Map<String, String>>) JSONArray.parse(json);
                List<IotDataVO> vos = new ArrayList<>();

                Map<String, String> timeAndValue = new HashMap<>();
                for (Map<String, String> mapList : listObject) {
                    for (Map.Entry entry : mapList.entrySet()) {
                        if (!"name".equals(entry.getKey()) && !"deviceName".equals(entry.getKey())) {
                            IotDataVO vo = new IotDataVO();
                            vo.setKey(String.valueOf(entry.getKey()));
                            vo.setValue(String.valueOf(entry.getValue()));
                            vos.add(vo);
                        }
                    }
                    if (mapList.containsKey(st)) {
                        timeAndValue.put(mapList.get("time"), mapList.get(st));
                    }
                }

                List<IotDataVO> timeList = vos.stream().filter(x -> x.getKey().equals("time")).collect(Collectors.toList());
                List<String> dates = new ArrayList<>();

                for (IotDataVO vo : timeList) {
                    String value = String.valueOf(vo.getValue());
                    dates.add(value);
                }

                List<IotDataVO> dataList = new ArrayList<>();

                // 处理遥信 时间处理
                if (totalType.equals("hour")) {
                    handle(datesFinal, dates, beginDate, st, dataList, timeAndValue);
                } else if (totalType.equals("day")) {
                    handleDay(datesFinal, beginDate, endDate, st, dates, dataList, timeAndValue);
                } else if (totalType.equals("week")) {
                    handWeek(beginDate, st,dates,dataList,timeAndValue);
                } else {
                    handMonth(beginDate, st,dates,dataList,timeAndValue);
                }

                IotIndexResMinotVo iotIndexResVo = new IotIndexResMinotVo();
                iotIndexResVo.setIotData(dataList);
                res.add(iotIndexResVo);
            }
        }

        List<IotIndexResItemVo> iotData = new ArrayList<>();

        for(IotIndexResMinotVo s : res) {
            IotIndexResItemVo itemVo = new IotIndexResItemVo();
            List<Integer> list = new ArrayList<>();
            for (IotDataVO v: s.getIotData()) {
                list.add(Integer.parseInt(v.getValue().toString()));
                itemVo.setName(map.get(v.getKey()));
                itemVo.setKey(v.getKey());
            }
            itemVo.setData(list.stream().mapToInt(i->i).toArray());
            iotData.add(itemVo);
        }

        if(totalType.equals("week") || totalType.equals("month") || totalType.equals("hour") || totalType.equals("day")) {
            List<String> times = null;
            if(totalType.equals("week")) {
                times = DateUtils.getWeeksMap(DateUtils.dateToStringMonth(beginDate));
            } else if(totalType.equals("month")) {
                String year = beginDate.substring(0,4);
                times = new ArrayList<>();
                for(int i =1; i <= 12; i++) {
                    if(i < 10) {
                        String m = year + "-" + "0" + i;
                        times.add(m);
                    } else {
                        String m = year  + "-"  + i;
                        times.add(m);
                    }
                }

            } else if(totalType.equals("hour") || totalType.equals("day")) {
                times = new ArrayList<>();
                if(totalType.equals("hour")) {
                    String[] arr = DateUtils.TWENTY_FOUR;
                    Date date = DateUtils.dateParse(beginDate,DateUtils.DATE_PATTERN);
                    String dateDayT = DateUtils.dateFormat(date, DateUtils.DATE_PATTERN);
                    if (datesFinal.size() == 0) {
                        for (String str : arr) {
                            String dateDay = dateDayT;
                            dateDay = dateDay + str;
                            datesFinal.add(DateUtils.dateParse(dateDay, DateUtils.DATE_TIME_PATTERN));
                        }
                    }
                } else {
                    if (datesFinal.size() == 0) {
                        datesFinal.addAll(DateUtils.findDaysStr(DateUtils.dateToString(beginDate), DateUtils.dateToString(endDate)));
                    }
                }


                for (Date date : datesFinal) {
                    times.add(DateUtils.convertDateToString(date, totalType.equals("hour") ? DateUtils.HOUR_PATTERN : DateUtils.DATE_PATTERN));
                }
            }

            if(iotData.size() == 0) {
                fullData(iotIndexItemVos,iotData,times,map);
            }
            List<IotIndexResItemVo> iotIndexResItemVos = doIndexData(iotData, typeNameMap, typeCodeAndIndexKeyMap);
            indexResMinotFinalVo.setTimes(times);
            indexResMinotFinalVo.setNameKey(StringUtils.isEmpty(fieldKey) ? allKeys.toString().split(",") : fieldKey.split(","));
            indexResMinotFinalVo.setName(StringUtils.isEmpty(fieldKey) ? names.toString().split(",") : parmfieldName.split(","));
            indexResMinotFinalVo.setItems(iotIndexItemVoListNew);
            indexResMinotFinalVo.setIotData(iotIndexResItemVos);
        }

        return CommonResponseUtil.success(indexResMinotFinalVo);
    }
}
