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 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.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.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * <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;

//	/**
//     * 拓扑图-树
//     *
//     * @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);
        } 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<iotDatalist.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);

                                SimpleDateFormat sdf = new SimpleDateFormat(DateUtils.DATE_TIME_T_PATTERN);
                                SimpleDateFormat sdf1 = new SimpleDateFormat(DateUtils.DATE_TIME_PATTERN);
                                sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
                                Date  date1=sdf.parse(String.valueOf(timeList.get(j-1).getValue()));
                                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 endDate) throws ParseException {
        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);
        } catch (Exception e) {
            e.printStackTrace();
        }
        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);
                    }
                }
            }

            List<IotDataVO> timeList = vos.stream().filter(x -> x.getKey().equals("time")).collect(Collectors.toList());
            List<Date> dates = new ArrayList<>();
            for (IotDataVO vo : timeList) {
                SimpleDateFormat sdf = new SimpleDateFormat(DateUtils.DATE_TIME_T_PATTERN);
                SimpleDateFormat sdf1 = new SimpleDateFormat(DateUtils.DATE_TIME_PATTERN);
                logger.info("返回时间===================================(" + vo.getValue() + ") =======================================");
                sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
                Date  date=sdf.parse(String.valueOf(vo.getValue()));

//                String time= sdf.format(date);
                String time= DateTimeUtil.format(date, DateTimeUtil.ISO_DATE_HOUR24_MIN_SEC);
                dates.add(sdf1.parse(time));
                logger.info("返回时间===================================(" + sdf1.parse(time) + ") =======================================");
            }
            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(dates);
                            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<>();
                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(dates);
                    res.add(vo);
                }

                for (IotIndexResVo s : res) {
                    s.setIotData(map.get(s.getNameKey()));
                    s.setTimes(dates);
                }
                return CommonResponseUtil.success(res);
            }
        }
        return CommonResponseUtil.success();
    }




}
