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.amos.component.feign.model.FeignClientResult;
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.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.http.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.typroject.tyboot.core.foundation.enumeration.UserType;
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.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * <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
    private RestTemplate restTemplate;
    @Autowired
    FireFightingSystemMapper fireFightingSystemMapper;
    @Autowired
    IEquipmentSpecificAlarmService iEquipmentSpecificAlarmService;
    @Autowired
    IEquipmentIndexService equipmentIndexService;
    @Autowired
    EquipmentSpecificIndexMapper equipmentSpecificIndexMapper;
    @Autowired
    IEquipmentService iEquipmentService;
    @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) {
        TopographyNodeDetailDTO detailDTO = topographyNodeDetailService.queryByNodeid(id);
        if (null == id || null == detailDTO || !StringUtil.isNotEmpty(detailDTO.getEqpId())) {
            throw new RuntimeException("节点信息错误或此节点下未绑定装备！");
        }
        String 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) int status,
                                      @RequestParam(required = false) String beginDate, @RequestParam(required = false) String endDate,
                                      CommonPageable commonPageable) {
        TopographyNodeDetailDTO detailDTO = topographyNodeDetailService.queryByNodeid(id);
        if (null == id || null == detailDTO || !StringUtil.isNotEmpty(detailDTO.getEqpId())) {
            throw new RuntimeException("节点信息错误或此节点下未绑定装备！");
        }
        EquipmentSpecific equipmentSpecific = equipmentSpecificService.getById(detailDTO.getEqpId());
        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(String.valueOf(equipmentSpecific.getId())) ? StringUtils.trimToNull(String.valueOf(equipmentSpecific.getId())) : 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);
        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) {
        TopographyNodeDetailDTO detailDTO = topographyNodeDetailService.queryByNodeid(id);
        if (null == id || null == detailDTO || !StringUtil.isNotEmpty(detailDTO.getEqpId())) {
            throw new RuntimeException("节点信息错误或此节点下未绑定装备！");
        }
        String 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 beginDate,
                                             @RequestParam(required = false) String endDate) {
        TopographyNodeDetailDTO detailDTO = topographyNodeDetailService.queryByNodeid(id);
        if (null == id || null == detailDTO || !StringUtil.isNotEmpty(detailDTO.getEqpId())) {
            throw new RuntimeException("节点信息错误或此节点下未绑定装备！");
        }
        String 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("装备物联编码错误，请确认！");
        }
        LonAndLatEntityVo lonAndLatEntityVo = new LonAndLatEntityVo();
        String url = iotServerName;
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Content-Type", "application/json");
        headers.set("product", getProduct());
        headers.set("token", getToken());
        headers.set("appKey", getAppKey());
        HttpEntity httpEntity = new HttpEntity<>(lonAndLatEntityVo, headers);
        ResponseEntity<FeignClientResult> feignClientResult = null;
        try {
            feignClientResult = restTemplate.exchange("http://" + url
                            + "/iot/v1/livedata/list?timeStart=" + beginDate + "&timeEnd=" + endDate + "&productKey=" + prefix + "&deviceName=" + suffix,
                    HttpMethod.GET, httpEntity, FeignClientResult.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (null != feignClientResult && feignClientResult.getBody().getStatus() == 200) {
            List<TopographyIotVo> list = new ArrayList<>();
            if (null != feignClientResult.getBody().getResult()) {
                String json = JSON.toJSONString(feignClientResult.getBody().getResult());
                JSONObject jsonObject = JSONObject.parseObject(json);
                Iterator it = jsonObject.entrySet().iterator();
                List<IotDataVO> iotDatalist = new ArrayList<IotDataVO>();
                while (it.hasNext()) {
                    IotDataVO iotDataVO = new IotDataVO();
                    Map.Entry<String, Object> entry = (Map.Entry<String, Object>) it.next();
                    if (!"name".equals(entry.getKey()) || !"deviceName".equals(entry.getKey()) || !"time".equals(entry.getKey())) {
                        iotDataVO.setKey(entry.getKey());
                        iotDataVO.setValue(entry.getValue());
                    }
                    iotDatalist.add(iotDataVO);
                }
                List<EquipmentSpecificIndex> indexes = equipmentSpecificIndexMapper.getEquipmentSpeIndexByIotCode(iotCode);
                if (0 <indexes.size()) {
                    iotDatalist.forEach(iotDataVO -> {
                            TopographyIotVo iotVo = new TopographyIotVo();
                            List<TopographyIotDataVO> lists = new ArrayList<TopographyIotDataVO>();
                            indexes.forEach(x -> {
                                iotVo.setTime(x.getUpdateDate());
                                if (x.getNameKey().equals(iotDataVO.getKey())) {
                                    TopographyIotDataVO dataVO = new TopographyIotDataVO();
                                    dataVO.setName(x.getIndexName());
                                    dataVO.setValue(x.getValue());
                                    dataVO.setUnit(x.getIndexUnitName());
                                    lists.add(dataVO);
                                }
                            });
                            iotVo.setList(lists);
                            list.add(iotVo);
                    });
                }
            }
            return CommonResponseUtil.success(list);
        } else {
            logger.error("注：iotCode为 (" + iotCode + ") 的装备不存在于物联系统中！");
            return CommonResponseUtil.success();
        }
    }

    public static Map<String, String> mapStringToMap(String str) {
        str = str.substring(1, str.length() - 1);
        String[] strs = str.split(",");
        Map<String, String> map = new HashMap<String, String>();
        for (String string : strs) {
            String key = string.split("=")[0];
            String value = string.split("=")[1];
            map.put(key, value);
        }
        return map;
    }

}
