Commit 0465b044 authored by KeYong's avatar KeYong

Merge branch 'dev_upgrade' of 172.16.10.76:station/YeeAmosFireAutoSysRoot into eqintegration

# Conflicts: # YeeAmosFireAutoSysCommon/src/main/java/com/yeejoin/amos/fas/dao/entity/StationInfo.java
parents 00f018b8 fcd48005
package com.yeejoin.amos.fas.business.action;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.typroject.tyboot.core.foundation.context.RequestContext;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yeejoin.amos.component.rule.MethodParam;
import com.yeejoin.amos.component.rule.RuleActionBean;
import com.yeejoin.amos.component.rule.RuleMethod;
import com.yeejoin.amos.fas.business.action.el.ELEvaluationContext;
import com.yeejoin.amos.fas.business.action.model.ContingencyEvent;
import com.yeejoin.amos.fas.business.action.model.ContingencyRo;
import com.yeejoin.amos.fas.business.action.model.DeviceRo;
import com.yeejoin.amos.fas.business.action.model.SetpEnum;
import com.yeejoin.amos.fas.business.action.mq.WebMqttComponent;
import com.yeejoin.amos.fas.business.action.result.ActionResult;
import com.yeejoin.amos.fas.business.action.result.SafteyPlanResult;
import com.yeejoin.amos.fas.business.action.result.message.AbstractActionResultMessage;
import com.yeejoin.amos.fas.business.action.util.ContingencyLogPublisher;
import com.yeejoin.amos.fas.business.action.util.StepComparator;
import com.yeejoin.amos.fas.business.feign.IDutyModeServer;
import com.yeejoin.amos.fas.business.feign.RemoteSecurityService;
import com.yeejoin.amos.fas.business.service.impl.RuleRunigSnapshotServiceImpl;
import com.yeejoin.amos.fas.business.service.intfc.FireStengthService;
import com.yeejoin.amos.fas.business.service.intfc.IContingencyInstance;
import com.yeejoin.amos.fas.business.service.intfc.IRiskSourceService;
import com.yeejoin.amos.fas.business.service.model.ContingencyDeviceStatus;
import com.yeejoin.amos.fas.business.service.model.ToipResponse;
import com.yeejoin.amos.fas.business.util.CacheFactory;
import com.yeejoin.amos.fas.business.util.CacheMap;
import com.yeejoin.amos.fas.business.vo.Toke;
import com.yeejoin.amos.fas.core.util.CommonResponse;
import com.yeejoin.amos.fas.dao.entity.ContingencyPlanInstance;
@Component
@RuleActionBean(beanLabel = "动态预案" )
public class ContingencyAction implements CustomerAction {
private static String PACKAGEURL = "com.yeejoin.amos.fas.business.action.result.message.";
public static final Logger log = LoggerFactory.getLogger(ContingencyAction.class);
@Autowired
private WebMqttComponent webMqttComponent;
@Value("${auto-sys.push.type}")
private String pushType;
@Value("${spring.application.name}")
private String serviceName;
@Value("${station.name}")
private String stationName;
@Autowired
private IContingencyInstance iContingencyInstance;
@Autowired
private FireStengthService fireStrengthService;
@Autowired
private ContingencyLogPublisher contingencyLogPublisher;
@Autowired
private IRiskSourceService riskSourceService;
@Autowired
private IDutyModeServer dutyModeServer;
@Autowired
private RedisTemplate redisTemplate;
private static Map<String, String> OPERATE_RECORD_ID = new HashMap<>();
private static Map<String, Map<String, String>> stringStringMap = new HashMap<>();
static SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
public static ConcurrentHashMap<String, Map<String, Object>> pointCache = new ConcurrentHashMap<>();
private static CacheMap cacheMap = CacheFactory.newChacheMap();
private static final String TOKE = "TOKE";
@Autowired
private RemoteSecurityService remoteSecurityService;
//当值值班长(S1)、副值班长(S2)、值班员(A1,A2,A3)、白班值班员、保安人员、驻站消防队长(F1)
/* private static Map<String, String> positionMap = new HashMap<String, String>() {{
put("S1", "S1");
put("S2", "S2");
put("A1", "A1");
put("A2", "A2");
put("A3", "A3");
put("F1", "F1");
}};
*/
/**
* 预案文件中值为和数据字典中的对应关系
* 消防
* F1 消防队长 fireLeader
* F2..F6 队员 firePerson 规则配置中队员1...6:firePerson1...firePerson6
* FD .... 司机 fireDriver 规则配置中司机 1..6:fireDriver1...fireDriver6
* 运维
* S1 值班长 dutyLeader
* S2 副值班长 deputyDutyLeader
* B1..B6 值班员 dutyCivilian 规则配置中值班员1...6:dutyCivilian1...dutyCivilian6
* A1...A6 副值班员 deputyDutyCivilian 规则配置中副值班员1...6:deputyDutyCivilian1...deputyDutyCivilian6
*/
public Map<String, String> getStrengthMap(ContingencyRo contingencyRo) {
String batchNo = contingencyRo.getBatchNo();
String orgCode = contingencyRo.getEquipmentOrgCode();
Map<String, String> returnMap = stringStringMap.get(contingencyRo.getBatchNo());
if (CollectionUtils.isEmpty(returnMap)) {
stringStringMap = new HashMap<>();
returnMap = new HashMap<>();
Date curDate = new Date();
JSONObject param = new JSONObject();
param.put("dutyDate", curDate);
Toke toke = remoteSecurityService.getServerToken();
CommonResponse commonResponse = dutyModeServer.dutyListByDate(toke.getAppKey(), toke.getProduct(), toke.getToke(), orgCode, param.toJSONString());
// String result = HttpUtil.appendPostJson("duty/dutyListByDate", param.toJSONString());
// JSONObject jsonObject = JSONObject.parseObject(result);
// JSONArray dataList = JSONObject.parseObject(commonResponse.getDataList().toString());
String JSONStr = JSON.toJSONString(commonResponse.getDataList());
JSONArray dataList = JSONObject.parseArray(JSONStr);
log.info(String.format("请求值班系统返回dataList:%s", dataList));
if (!ObjectUtils.isEmpty(dataList)) {
Map<String, String> finalReturnMap = returnMap;
dataList.forEach(
x -> {
JSONObject obj = (JSONObject) x;
String name = obj.getString("position");
finalReturnMap.put(name, obj.getString("dutyName"));
}
);
}
stringStringMap.put(batchNo, returnMap);
}
log.info(String.format("returnMap:【 %s 】", returnMap));
return returnMap;
}
public void sendcmd(String msgType, Object contingency, SafteyPlanResult result) {
ContingencyRo ro = (ContingencyRo)contingency;
ro.setTelemetryMap(null);
ro.setTelesignallingMap(null);
Constructor<?> constructor;
try {
constructor = Class.forName(
PACKAGEURL + result.getClass().getSimpleName() + "Message")
.getConstructor(ActionResult.class);
AbstractActionResultMessage<?> action = (AbstractActionResultMessage<?>) constructor.newInstance(result);
if ("mqtt".equals(pushType.toLowerCase())) {
ToipResponse toipResponse = action.buildResponse(msgType, contingency, result.toJson());
String topic = String.format("/%s/%s/%s", serviceName, stationName,"plan");
log.info(String.format("mqtt[%s]:【 %s 】", topic, toipResponse.toJsonStr()));
webMqttComponent.publish(topic, toipResponse.toJsonStr());
ContingencyEvent event = new ContingencyEvent(this);
event.setMsgBody(toipResponse.toJsonStr());
event.setTopic(topic);
event.setMsgType(msgType);
event.setContingency(contingency);
contingencyLogPublisher.publish(event);
} else if ("websocket".equals(pushType.toLowerCase())){
action.execute(msgType, contingency);
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* @param stepCode 当前步骤编号
* @param stepName 当前步骤名称
* @param state 当前步骤状态
* @param nextStepCode 下一步编号
* @param nextStepName 下一步名称
* @param stepType 步骤类型,总览步骤、详细步骤
* @param paramObj 预案对象
*/
@RuleMethod(methodLabel = "步骤更新", project = "换流站消防专项预案")
public void stepInfo(@MethodParam(paramLabel = "当前编号") String stepCode,
// @MethodParam(paramLabel = "步骤类型") String stepType,
@MethodParam(paramLabel = "对象") Object paramObj) {
ContingencyRo contingencyRo = (ContingencyRo) paramObj;
stopSnapshop(contingencyRo);
SafteyPlanResult result = new SafteyPlanResult();
Map<String, Object> tempmap1 = new HashMap<>();
SetpEnum[] stepArr = SetpEnum.values();
ArrayList list = new ArrayList();
HashMap preStep = new HashMap();
StepComparator comparator = new StepComparator();
Arrays.sort(stepArr, comparator);
boolean flage = false;
SetpEnum pstep = null;
for (SetpEnum step : stepArr) {
if (Long.valueOf(step.getValue()) == Long.valueOf(stepCode)) {
if (!ObjectUtils.isEmpty(pstep)) {
preStep.put("stepCode", pstep.getValue());
preStep.put("stepName", pstep.getTitle());
}
flage = true;
}
if (flage) {
HashMap map = new HashMap();
map.put("stepCode", step.getValue());
map.put("stepName", step.getTitle());
list.add(map);
}
pstep = step;
}
tempmap1.put("step", list);
tempmap1.put("preStep", preStep);
result.add(tempmap1);
log.info("巡检消息发送规则" + JSONObject.toJSONString(result));
this.sendcmd("steparea", contingencyRo, result);
}
/**
* @param stepCode 当前步骤编号
* @param paramObj 预案对象
*/
@RuleMethod(methodLabel = "步骤更新保存", project = "换流站消防专项预案")
public void saveStepInfo(@MethodParam(paramLabel = "当前编号") String stepCode, @MethodParam(paramLabel = "对象") Object paramObj) {
ContingencyRo contingencyRo = (ContingencyRo) paramObj;
iContingencyInstance.updateStep(stepCode, contingencyRo.getBatchNo());
}
/**
* @param content 消息内容
* @param paramObj 预案对象
*/
@RuleMethod(methodLabel = "执行记录", project = "换流站消防专项预案")
public void messageRecord(@MethodParam(paramLabel = "消息内容") String content, @MethodParam(paramLabel = "对象") Object paramObj) {
ContingencyRo contingencyRo = (ContingencyRo) paramObj;
stopSnapshop(contingencyRo);
//转换content中的变量
content = instedParams(content, contingencyRo);
iContingencyInstance.createInstanceRecord(contingencyRo.getBatchNo(), "", "DEFAULT", content, "MESSAGE", "");
SafteyPlanResult result = new SafteyPlanResult();
Map<String, Object> tempmap1 = new HashMap<>();
try {
SimpleDateFormat sdf = new SimpleDateFormat("YYYY/MM/DD HH:mm:ss");
List<ContingencyPlanInstance> list = iContingencyInstance.queryForTimeLine(contingencyRo.getBatchNo(), "MESSAGE");
ArrayList records = new ArrayList<>();
if (!ObjectUtils.isEmpty(list)) {
list.forEach(action -> {
HashMap map = new HashMap();
map.put("time", sdf.format(action.getCreateDate()));
map.put("stepName", action.getContent());
records.add(map);
});
}
tempmap1.put("content", records);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
result.add(tempmap1);
this.sendcmd("recordarea", paramObj, result);
}
/**
* <pre>
* 智能辅助
* </pre>
*
* @param step 当前步骤
* @param icon 图标
* @param title 标题
* @param image 图片集合
* @param table 表格
* @param content 内容
* @param paramObj 预案对象
*/
@RuleMethod(methodLabel = "智能辅助", project = "换流站消防专项预案")
public void help(@MethodParam(paramLabel = "当前步骤") String step,
@MethodParam(paramLabel = "图标")String icon,
@MethodParam(paramLabel = "标题")String title,
@MethodParam(paramLabel = "图片集") String image,
@MethodParam(paramLabel = "表格数据") String table,
@MethodParam(paramLabel = "文本内容") String content,
@MethodParam(paramLabel = "对象") Object paramObj) {
ContingencyRo contingencyRo = (ContingencyRo) paramObj;
stopSnapshop(contingencyRo);
//转换智能辅助中的变量
content = instedParams(content, contingencyRo);
SafteyPlanResult result = new SafteyPlanResult();
Map<String, Object> tempmap1 = new HashMap<>();
tempmap1.put("icon", icon);
tempmap1.put("step", step);
tempmap1.put("title", title);
tempmap1.put("content", content);
tempmap1.put("image", image);
tempmap1.put("table", table);
// tempmap1.put("batchNo", contingencyRo.getBatchNo());
// tempmap1.put("contingencyRo", contingencyRo);
result.add(tempmap1);
this.sendcmd("helparea", paramObj, result);
}
private String instedParams(String content, ContingencyRo contingencyRo) {
Map<String, String> strengthMap = this.getStrengthMap(contingencyRo);
for (String key : strengthMap.keySet())
content = content.replaceAll("\\$\\{" + key + "}", strengthMap.get(key));
Field[] fields = contingencyRo.getClass().getDeclaredFields();
Method getMethod = null;
try {
for (Field field : fields) {
if (field.getName().equals("serialVersionUID"))
continue;
String fileNameInMethod = String.valueOf(field.getName().charAt(0)).toUpperCase() + field.getName().substring(1);
getMethod = contingencyRo.getClass().getMethod("get" + fileNameInMethod);
String value = String.valueOf(getMethod.invoke(contingencyRo));
content = content.replaceAll("\\$\\{" + field.getName() + "}", value);
}
content = getNative(content);
} catch (Exception e) {
e.printStackTrace();
}
return content;
}
public String getNative(String str)
{
Pattern p = Pattern.compile("\\$\\{(.*?)\\}");
Matcher m = p.matcher(str);
while (m.find())
{
String parameter = m.group();
Object parametervalue = ELEvaluationContext
.getValue(parameter.substring(1, parameter.length() - 1));
if(parametervalue != null)
str = str.replace(parameter,
parametervalue != null ? parametervalue.toString() : null);
}
return str;
}
/**
* 交互动作
*
* @param actionName 动作名称
* @param icon 图标
* @param tips 提示信息
* @param buttonJson 按钮json字符串
* @param paramObj 预案对象
*/
@RuleMethod(methodLabel = "交互动作", project = "换流站消防专项预案")
public void operation(@MethodParam(paramLabel = "动作名称") String actionName,
@MethodParam(paramLabel = "图标") String icon,
@MethodParam(paramLabel = "提示信息") String tips,
@MethodParam(paramLabel = "按钮json字符串") String buttonJson,
@MethodParam(paramLabel = "预案对象") Object paramObj) {
ContingencyRo contingencyRo = (ContingencyRo) paramObj;
stopSnapshop(contingencyRo);
//转换content中的变量
tips = instedParams(tips, contingencyRo);
SafteyPlanResult result = new SafteyPlanResult();
Map<String, Object> tempmap1 = new HashMap<>();
String contingencyPlanId = getContingencyPlanId(contingencyRo.getBatchNo(), actionName, icon, tips, buttonJson);
tempmap1.put("actionName", actionName);
tempmap1.put("icon", icon);
tempmap1.put("tips", tips);
tempmap1.put("button", buttonJson);
tempmap1.put("caseId", contingencyPlanId);
result.add(tempmap1);
this.sendcmd("optionarea", paramObj, result);
}
private boolean sendButton(String batchNo, String contingencyPlanId, String equipmentId, String actionName, String buttonJson) {
ObjectMapper objectMapper = new ObjectMapper();
/**
* batchNo
* stepCode
* buttonCode
* confirm
* contingencyPlanId
* stepState
*/
try {
Map button = objectMapper.readValue(buttonJson, Map.class);
Map operateInstance = (Map) ((List) button.get("operate")).get(0);
ContingencyDeviceStatus contingencyDeviceStatus = new ContingencyDeviceStatus();
contingencyDeviceStatus.setActionName(actionName);
contingencyDeviceStatus.setButtonCode(String.valueOf(operateInstance.get("code")));
contingencyDeviceStatus.setConfirm("CONFIRM");
contingencyDeviceStatus.setContingencyPlanId(contingencyPlanId);
contingencyDeviceStatus.setEquipmentId(equipmentId);
contingencyDeviceStatus.setStepCode(String.valueOf(button.get("stepCode")));
contingencyDeviceStatus.setStepState(String.valueOf(operateInstance.get("stepState")));
riskSourceService.queryContingencyDeviceStatus(contingencyDeviceStatus);
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
/**
* 保存交互动作
*
* @param actionName 动作名称
* @param icon 图标
* @param tips 提示信息
* @param buttonJson 按钮json字符串
* @param paramObj 预案对象
*/
@RuleMethod(methodLabel = "保存交互动作", project = "换流站消防专项预案")
public void saveOperation(@MethodParam(paramLabel = "动作名称") String actionName,
@MethodParam(paramLabel = "图标") String icon,
@MethodParam(paramLabel = "提示信息") String tips,
@MethodParam(paramLabel = "按钮json字符串") String buttonJson,
@MethodParam(paramLabel = "对象") Object paramObj) {
ContingencyRo contingencyRo = (ContingencyRo) paramObj;
stopSnapshop(contingencyRo);
//转换content中的变量
SafteyPlanResult result = new SafteyPlanResult();
Map<String, Object> tempmap1 = new HashMap<>();
try {
SimpleDateFormat sdf = new SimpleDateFormat("YYYY/MM/DD HH:mm:ss");
List<ContingencyPlanInstance> list = iContingencyInstance.queryForTimeLine(contingencyRo.getBatchNo(), "MESSAGE");
ArrayList records = new ArrayList<>();
if (!ObjectUtils.isEmpty(list)) {
list.forEach(action -> {
HashMap map = new HashMap();
map.put("time", sdf.format(action.getCreateDate()));
map.put("stepName", action.getContent());
records.add(map);
});
}
tempmap1.put("content", records);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
result.add(tempmap1);
this.sendcmd("recordarea", paramObj, result);
}
private String getContingencyPlanId(String batchNo, String actionName, String icon, String tips, String buttonJson) {
String cacheKey = batchNo + actionName;
String contingencyPlanId = null;
ContingencyPlanInstance contingencyPlanInstance = null;
if (OPERATE_RECORD_ID.get(cacheKey) == null) {
contingencyPlanInstance = iContingencyInstance.createInstanceRecord(batchNo, actionName, "DEFAULT", buttonJson, "OPERATE", icon);
contingencyPlanId = contingencyPlanInstance.getId();
OPERATE_RECORD_ID.put(cacheKey, contingencyPlanId);
} else {
contingencyPlanId = OPERATE_RECORD_ID.get(cacheKey);
OPERATE_RECORD_ID.remove(cacheKey);
}
return contingencyPlanId;
}
/**
* 地图动作推送
*
* @param actionName 动作名称标识
* @param paramObj 预案对象
*/
@RuleMethod(methodLabel = "地图动作", project = "换流站消防专项预案")
public void mapAction(@MethodParam(paramLabel = "动作名称标识") String actionName, @MethodParam(paramLabel = "参数") String paramJSON, @MethodParam(paramLabel = "对象") Object paramObj) {
ContingencyRo contingencyRo = (ContingencyRo) paramObj;
log.error("=======================================================================================");
stopSnapshop(contingencyRo);
SafteyPlanResult result = new SafteyPlanResult();
Map<String, Object> tempmap1 = new HashMap<>();
tempmap1.put("key", actionName);
tempmap1.put("content",paramJSON);
result.add(tempmap1);
this.sendcmd("maparea", paramObj, result);
}
@RuleMethod(methodLabel = "地图动画", project = "换流站消防专项预案")
public void mapCartoonAction(
@MethodParam(paramLabel = "动作名称标识") String actionName,
@MethodParam(paramLabel = "动作类型") String actionType,
@MethodParam(paramLabel = "动作类型参数") String paramJSON,
@MethodParam(paramLabel = "对象") Object paramObj) {
ContingencyRo contingencyRo = (ContingencyRo) paramObj;
log.error("=======================================================================================");
stopSnapshop(contingencyRo);
String parameter = instedParams(paramJSON, contingencyRo);
SafteyPlanResult result = new SafteyPlanResult();
Map<String, Object> tempmap1 = new HashMap<>();
tempmap1.put("key", actionName);
tempmap1.put("content",actionType);
tempmap1.put("parameter",parameter);
result.add(tempmap1);
this.sendcmd("maparea", paramObj, result);
}
/**
* 顶部消息提示
*
* @param content 消息内容
* @param messageType 消息类型 messageType 黑色框消息类型CONTINGENCY,,滚动消息:CURRENTMESSAGE
* @param paramObj 预案对象
*/
@RuleMethod(methodLabel = "消息提示", project = "换流站消防专项预案")
public void topMessage(
@MethodParam(paramLabel = "标题") String title,
@MethodParam(paramLabel = "内容") String content,
@MethodParam(paramLabel = "图标") String icon,
@MethodParam(paramLabel = "类型") String messageType,
@MethodParam(paramLabel = "对象") Object paramObj) {
ContingencyRo contingencyRo = (ContingencyRo) paramObj;
stopSnapshop(contingencyRo);
SafteyPlanResult result = new SafteyPlanResult();
Map<String, Object> tempmap1 = new HashMap<>();
//转换content中的变量
content = instedParams(content, contingencyRo);
tempmap1.put("content", content);
tempmap1.put("type", messageType);//消息类型 messageType 黑色框消息类型 CONTINGENCY,,滚动消息:CURRENTMESSAGE
tempmap1.put("title", title);
tempmap1.put("icon", icon);
result.add(tempmap1);
this.sendcmd("message", paramObj, result);
}
/**
* 启动预案
*
* @param paramObj 预案对象
*/
@RuleMethod(methodLabel = "启动预案", project = "换流站消防专项预案")
public void startPlan(@MethodParam(paramLabel = "对象") Object paramObj) {
ContingencyRo contingencyRo = (ContingencyRo) paramObj;
stopSnapshop(contingencyRo);
SafteyPlanResult result = new SafteyPlanResult();
Map<String, Object> tempmap1 = new HashMap<>();
tempmap1.put("type", "event");
tempmap1.put("content", "startPlan");
result.add(tempmap1);
this.sendcmd("message", paramObj, result);
redisTemplate.opsForValue().set("contingencyRo", contingencyRo);
}
/**
* 启动预案
*
* @param paramObj 预案对象
*/
@RuleMethod(methodLabel = "结束预案", project = "换流站消防专项预案")
public void stopPlan(@MethodParam(paramLabel = "对象") Object paramObj) {
ContingencyRo contingencyRo = (ContingencyRo) paramObj;
stopSnapshop(contingencyRo);
SafteyPlanResult result = new SafteyPlanResult();
Map<String, Object> tempmap1 = new HashMap<>();
tempmap1.put("type", "event");
tempmap1.put("content", "stopPlan");
result.add(tempmap1);
this.sendcmd("message", paramObj, result);
redisTemplate.delete("contingencyRo");
}
@RuleMethod(methodLabel = "自动执行步骤", project = "换流站消防专项预案")
public void autoExecute(
@MethodParam(paramLabel = "动作名称") String actionName,
@MethodParam(paramLabel = "步骤编号") String stepCode,
@MethodParam(paramLabel = "按钮编码") String buttonCode,
@MethodParam(paramLabel = "步骤状态") String stepState,
@MethodParam(paramLabel = "预案对象") Object paramObj) {
ContingencyRo contingencyRo = (ContingencyRo) paramObj;
ContingencyPlanInstance contingencyPlanInstance = iContingencyInstance.createInstanceRecord(contingencyRo.getBatchNo(), actionName, "DEFAULT", "", "OPERATE", "");
Toke toke = remoteSecurityService.getServerToken();
// Toke toke = cacheMap.getValue(TOKE);
// if (toke == null) {
// toke = remoteSecurityService.come();
// Long times = (long) (20 * 24 * 60 * 60);
// cacheMap.setex(TOKE, toke, times);
// }
RequestContext.setToken(toke.getToke());
RequestContext.setProduct(toke.getProduct());
try {
iContingencyInstance.setButtonExecuted(contingencyRo.getBatchNo(),contingencyPlanInstance.getId(),buttonCode,"CONFIRM");
iContingencyInstance.fire(contingencyRo.getBatchNo(),stepCode, contingencyPlanInstance.getId(),buttonCode, "CONFIRM", stepState);
} catch (Exception e) {
e.printStackTrace();
}
}
@RuleMethod(methodLabel = "添加步骤执行", project = "换流站消防专项预案")
public void addExecute(
@MethodParam(paramLabel = "步骤编号") String stepCode,
@MethodParam(paramLabel = "按钮编码") String buttonCode,
@MethodParam(paramLabel = "设备数据") Object paramObj) {
SafteyPlanResult result = new SafteyPlanResult();
Map<String, Object> tempmap1 = new HashMap<>();
Map<String, Object> content = new HashMap<>();
content.put("stepCode", stepCode);
content.put("buttonCode", buttonCode);
DeviceRo ro = (DeviceRo)paramObj;
Map<String, Object> equipemtnPoints = pointCache.get(ro.getEquipmentId());
if (ObjectUtils.isEmpty(equipemtnPoints)) {
equipemtnPoints = new HashMap<>();
}
equipemtnPoints.put(stepCode+"-"+buttonCode, content);
tempmap1.put("type", "buttonCache");
tempmap1.put("content", equipemtnPoints.values());
result.add(tempmap1);
this.sendcmd("message", ro, result);
}
@RuleMethod(methodLabel = "清除步骤执行", project = "换流站消防专项预案")
public void clearExecute(
@MethodParam(paramLabel = "步骤编号") String stepCode,
@MethodParam(paramLabel = "按钮编码") String buttonCode,
@MethodParam(paramLabel = "设备数据") Object paramObj) {
SafteyPlanResult result = new SafteyPlanResult();
Map<String, Object> tempmap1 = new HashMap<>();
Map<String, Object> content = new HashMap<>();
content.put("stepCode", stepCode);
content.put("buttonCode", buttonCode);
DeviceRo ro = (DeviceRo)paramObj;
Map<String, Object> equipemtnPoints = pointCache.get(ro.getEquipmentId());
if (!ObjectUtils.isEmpty(equipemtnPoints)) {
equipemtnPoints.remove(stepCode+"-"+buttonCode);
}
tempmap1.put("type", "buttonCache");
if (!ObjectUtils.isEmpty(equipemtnPoints)) {
tempmap1.put("content", equipemtnPoints.values());
} else {
tempmap1.put("content", new ArrayList());
}
result.add(tempmap1);
this.sendcmd("message", ro, result);
}
@RuleMethod(methodLabel = "同步自动执行步骤", project = "换流站消防专项预案")
public void sendExecute(@MethodParam(paramLabel = "预案对象") Object paramObj) {
SafteyPlanResult result = new SafteyPlanResult();
Map<String, Object> tempmap1 = new HashMap<>();
ContingencyRo contingencyRo = (ContingencyRo) paramObj;
Map<String, Object> equipemtnPoints = pointCache.get(contingencyRo.getEquipmentId());
tempmap1.put("type", "buttonCache");
tempmap1.put("content", equipemtnPoints.values());
result.add(tempmap1);
this.sendcmd("message", paramObj, result);
}
public void sendcmd(String msgType, DeviceRo deviceRo, SafteyPlanResult result) {
Constructor<?> constructor;
try {
constructor = Class.forName(
PACKAGEURL + result.getClass().getSimpleName() + "Message")
.getConstructor(ActionResult.class);
AbstractActionResultMessage<?> action = (AbstractActionResultMessage<?>) constructor.newInstance(result);
if ("mqtt".equals(pushType.toLowerCase())) {
ToipResponse toipResponse = action.buildResponse(msgType, deviceRo, result.toJson());
String topic = String.format("/%s/%s/%s", serviceName, stationName,"plan");
log.info(String.format("mqtt[%s]:【 %s 】", topic, toipResponse.toJsonStr()));
webMqttComponent.publish(topic, toipResponse.toJsonStr());
ContingencyEvent event = new ContingencyEvent(this);
event.setMsgBody(toipResponse.toJsonStr());
event.setTopic(topic);
event.setMsgType(msgType);
event.setContingency(deviceRo);
contingencyLogPublisher.publish(event);
} else if ("websocket".equals(pushType.toLowerCase())){
action.execute(msgType, deviceRo);
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void stopSnapshop(ContingencyRo contingencyRo) {
if (RuleRunigSnapshotServiceImpl.getReplayBatchNo() != null && !RuleRunigSnapshotServiceImpl.getReplayBatchNo().equals(contingencyRo.getBatchNo()))
RuleRunigSnapshotServiceImpl.setReplayBatchNoToNull();
}
}
package com.yeejoin.amos.fas.business.action;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.typroject.tyboot.core.foundation.context.RequestContext;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yeejoin.amos.component.rule.MethodParam;
import com.yeejoin.amos.component.rule.RuleActionBean;
import com.yeejoin.amos.component.rule.RuleMethod;
import com.yeejoin.amos.fas.business.action.el.ELEvaluationContext;
import com.yeejoin.amos.fas.business.action.model.ContingencyEvent;
import com.yeejoin.amos.fas.business.action.model.ContingencyRo;
import com.yeejoin.amos.fas.business.action.model.DeviceRo;
import com.yeejoin.amos.fas.business.action.model.SetpEnum;
import com.yeejoin.amos.fas.business.action.mq.WebMqttComponent;
import com.yeejoin.amos.fas.business.action.result.ActionResult;
import com.yeejoin.amos.fas.business.action.result.SafteyPlanResult;
import com.yeejoin.amos.fas.business.action.result.message.AbstractActionResultMessage;
import com.yeejoin.amos.fas.business.action.util.ContingencyLogPublisher;
import com.yeejoin.amos.fas.business.action.util.StepComparator;
import com.yeejoin.amos.fas.business.feign.IDutyModeServer;
import com.yeejoin.amos.fas.business.feign.RemoteSecurityService;
import com.yeejoin.amos.fas.business.service.impl.RuleRunigSnapshotServiceImpl;
import com.yeejoin.amos.fas.business.service.intfc.FireStengthService;
import com.yeejoin.amos.fas.business.service.intfc.IContingencyInstance;
import com.yeejoin.amos.fas.business.service.intfc.IRiskSourceService;
import com.yeejoin.amos.fas.business.service.model.ContingencyDeviceStatus;
import com.yeejoin.amos.fas.business.service.model.ToipResponse;
import com.yeejoin.amos.fas.business.util.CacheFactory;
import com.yeejoin.amos.fas.business.util.CacheMap;
import com.yeejoin.amos.fas.business.vo.Toke;
import com.yeejoin.amos.fas.core.util.CommonResponse;
import com.yeejoin.amos.fas.dao.entity.ContingencyPlanInstance;
@Component
@RuleActionBean(beanLabel = "动态预案" )
public class ContingencyAction implements CustomerAction {
private static String PACKAGEURL = "com.yeejoin.amos.fas.business.action.result.message.";
public static final Logger log = LoggerFactory.getLogger(ContingencyAction.class);
@Autowired
private WebMqttComponent webMqttComponent;
@Value("${auto-sys.push.type}")
private String pushType;
@Value("${spring.application.name}")
private String serviceName;
@Value("${station.name}")
private String stationName;
@Autowired
private IContingencyInstance iContingencyInstance;
@Autowired
private FireStengthService fireStrengthService;
@Autowired
private ContingencyLogPublisher contingencyLogPublisher;
@Autowired
private IRiskSourceService riskSourceService;
@Autowired
private IDutyModeServer dutyModeServer;
@Autowired
private RedisTemplate redisTemplate;
private static Map<String, String> OPERATE_RECORD_ID = new HashMap<>();
private static Map<String, Map<String, String>> stringStringMap = new HashMap<>();
static SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
public static ConcurrentHashMap<String, Map<String, Object>> pointCache = new ConcurrentHashMap<>();
private static CacheMap cacheMap = CacheFactory.newChacheMap();
private static final String TOKE = "TOKE";
@Autowired
private RemoteSecurityService remoteSecurityService;
//当值值班长(S1)、副值班长(S2)、值班员(A1,A2,A3)、白班值班员、保安人员、驻站消防队长(F1)
/* private static Map<String, String> positionMap = new HashMap<String, String>() {{
put("S1", "S1");
put("S2", "S2");
put("A1", "A1");
put("A2", "A2");
put("A3", "A3");
put("F1", "F1");
}};
*/
/**
* 预案文件中值为和数据字典中的对应关系
* 消防
* F1 消防队长 fireLeader
* F2..F6 队员 firePerson 规则配置中队员1...6:firePerson1...firePerson6
* FD .... 司机 fireDriver 规则配置中司机 1..6:fireDriver1...fireDriver6
* 运维
* S1 值班长 dutyLeader
* S2 副值班长 deputyDutyLeader
* B1..B6 值班员 dutyCivilian 规则配置中值班员1...6:dutyCivilian1...dutyCivilian6
* A1...A6 副值班员 deputyDutyCivilian 规则配置中副值班员1...6:deputyDutyCivilian1...deputyDutyCivilian6
*/
public Map<String, String> getStrengthMap(ContingencyRo contingencyRo) {
String batchNo = contingencyRo.getBatchNo();
String orgCode = contingencyRo.getEquipmentOrgCode();
Map<String, String> returnMap = stringStringMap.get(contingencyRo.getBatchNo());
if (CollectionUtils.isEmpty(returnMap)) {
stringStringMap = new HashMap<>();
returnMap = new HashMap<>();
Date curDate = new Date();
JSONObject param = new JSONObject();
param.put("dutyDate", curDate);
Toke toke = remoteSecurityService.getServerToken();
CommonResponse commonResponse = dutyModeServer.dutyListByDate(toke.getAppKey(), toke.getProduct(), toke.getToke(), orgCode, param.toJSONString());
// String result = HttpUtil.appendPostJson("duty/dutyListByDate", param.toJSONString());
// JSONObject jsonObject = JSONObject.parseObject(result);
// JSONArray dataList = JSONObject.parseObject(commonResponse.getDataList().toString());
String JSONStr = JSON.toJSONString(commonResponse.getDataList());
JSONArray dataList = JSONObject.parseArray(JSONStr);
log.info(String.format("请求值班系统返回dataList:%s", dataList));
if (!ObjectUtils.isEmpty(dataList)) {
Map<String, String> finalReturnMap = returnMap;
dataList.forEach(
x -> {
JSONObject obj = (JSONObject) x;
String name = obj.getString("position");
finalReturnMap.put(name, obj.getString("dutyName"));
}
);
}
stringStringMap.put(batchNo, returnMap);
}
log.info(String.format("returnMap:【 %s 】", returnMap));
return returnMap;
}
public void sendcmd(String msgType, Object contingency, SafteyPlanResult result) {
ContingencyRo ro = (ContingencyRo)contingency;
ro.setTelemetryMap(null);
ro.setTelesignallingMap(null);
Constructor<?> constructor;
try {
constructor = Class.forName(
PACKAGEURL + result.getClass().getSimpleName() + "Message")
.getConstructor(ActionResult.class);
AbstractActionResultMessage<?> action = (AbstractActionResultMessage<?>) constructor.newInstance(result);
if ("mqtt".equals(pushType.toLowerCase())) {
ToipResponse toipResponse = action.buildResponse(msgType, contingency, result.toJson());
String topic = String.format("/%s/%s/%s", serviceName, stationName,"plan");
log.info(String.format("mqtt[%s]:【 %s 】", topic, toipResponse.toJsonStr()));
webMqttComponent.publish(topic, toipResponse.toJsonStr());
ContingencyEvent event = new ContingencyEvent(this);
event.setMsgBody(toipResponse.toJsonStr());
event.setTopic(topic);
event.setMsgType(msgType);
event.setContingency(contingency);
contingencyLogPublisher.publish(event);
} else if ("websocket".equals(pushType.toLowerCase())){
action.execute(msgType, contingency);
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* @param stepCode 当前步骤编号
* @param stepName 当前步骤名称
* @param state 当前步骤状态
* @param nextStepCode 下一步编号
* @param nextStepName 下一步名称
* @param stepType 步骤类型,总览步骤、详细步骤
* @param paramObj 预案对象
*/
@RuleMethod(methodLabel = "步骤更新", project = "换流站消防专项预案")
public void stepInfo(@MethodParam(paramLabel = "当前编号") String stepCode,
// @MethodParam(paramLabel = "步骤类型") String stepType,
@MethodParam(paramLabel = "对象") Object paramObj) {
ContingencyRo contingencyRo = (ContingencyRo) paramObj;
stopSnapshop(contingencyRo);
SafteyPlanResult result = new SafteyPlanResult();
Map<String, Object> tempmap1 = new HashMap<>();
SetpEnum[] stepArr = SetpEnum.values();
ArrayList list = new ArrayList();
HashMap preStep = new HashMap();
StepComparator comparator = new StepComparator();
Arrays.sort(stepArr, comparator);
boolean flage = false;
SetpEnum pstep = null;
for (SetpEnum step : stepArr) {
if (Long.valueOf(step.getValue()) == Long.valueOf(stepCode)) {
if (!ObjectUtils.isEmpty(pstep)) {
preStep.put("stepCode", pstep.getValue());
preStep.put("stepName", pstep.getTitle());
}
flage = true;
}
if (flage) {
HashMap map = new HashMap();
map.put("stepCode", step.getValue());
map.put("stepName", step.getTitle());
list.add(map);
}
pstep = step;
}
tempmap1.put("step", list);
tempmap1.put("preStep", preStep);
result.add(tempmap1);
log.info("巡检消息发送规则" + JSONObject.toJSONString(result));
this.sendcmd("steparea", contingencyRo, result);
}
/**
* @param stepCode 当前步骤编号
* @param paramObj 预案对象
*/
@RuleMethod(methodLabel = "步骤更新保存", project = "换流站消防专项预案")
public void saveStepInfo(@MethodParam(paramLabel = "当前编号") String stepCode, @MethodParam(paramLabel = "对象") Object paramObj) {
ContingencyRo contingencyRo = (ContingencyRo) paramObj;
iContingencyInstance.updateStep(stepCode, contingencyRo.getBatchNo());
}
/**
* @param content 消息内容
* @param paramObj 预案对象
*/
@RuleMethod(methodLabel = "执行记录", project = "换流站消防专项预案")
public void messageRecord(@MethodParam(paramLabel = "消息内容") String content, @MethodParam(paramLabel = "对象") Object paramObj) {
ContingencyRo contingencyRo = (ContingencyRo) paramObj;
stopSnapshop(contingencyRo);
//转换content中的变量
content = instedParams(content, contingencyRo);
iContingencyInstance.createInstanceRecord(contingencyRo.getBatchNo(), "", "DEFAULT", content, "MESSAGE", "");
SafteyPlanResult result = new SafteyPlanResult();
Map<String, Object> tempmap1 = new HashMap<>();
try {
SimpleDateFormat sdf = new SimpleDateFormat("YYYY/MM/DD HH:mm:ss");
List<ContingencyPlanInstance> list = iContingencyInstance.queryForTimeLine(contingencyRo.getBatchNo(), "MESSAGE");
ArrayList records = new ArrayList<>();
if (!ObjectUtils.isEmpty(list)) {
list.forEach(action -> {
HashMap map = new HashMap();
map.put("time", sdf.format(action.getCreateDate()));
map.put("stepName", action.getContent());
records.add(map);
});
}
tempmap1.put("content", records);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
result.add(tempmap1);
this.sendcmd("recordarea", paramObj, result);
}
/**
* <pre>
* 智能辅助
* </pre>
*
* @param step 当前步骤
* @param icon 图标
* @param title 标题
* @param image 图片集合
* @param table 表格
* @param content 内容
* @param paramObj 预案对象
*/
@RuleMethod(methodLabel = "智能辅助", project = "换流站消防专项预案")
public void help(@MethodParam(paramLabel = "当前步骤") String step,
@MethodParam(paramLabel = "图标")String icon,
@MethodParam(paramLabel = "标题")String title,
@MethodParam(paramLabel = "图片集") String image,
@MethodParam(paramLabel = "表格数据") String table,
@MethodParam(paramLabel = "文本内容") String content,
@MethodParam(paramLabel = "对象") Object paramObj) {
ContingencyRo contingencyRo = (ContingencyRo) paramObj;
stopSnapshop(contingencyRo);
//转换智能辅助中的变量
content = instedParams(content, contingencyRo);
SafteyPlanResult result = new SafteyPlanResult();
Map<String, Object> tempmap1 = new HashMap<>();
tempmap1.put("icon", icon);
tempmap1.put("step", step);
tempmap1.put("title", title);
tempmap1.put("content", content);
tempmap1.put("image", image);
tempmap1.put("table", table);
// tempmap1.put("batchNo", contingencyRo.getBatchNo());
// tempmap1.put("contingencyRo", contingencyRo);
result.add(tempmap1);
this.sendcmd("helparea", paramObj, result);
}
private String instedParams(String content, ContingencyRo contingencyRo) {
Map<String, String> strengthMap = this.getStrengthMap(contingencyRo);
for (String key : strengthMap.keySet())
content = content.replaceAll("\\$\\{" + key + "}", strengthMap.get(key));
Field[] fields = contingencyRo.getClass().getDeclaredFields();
Method getMethod = null;
try {
for (Field field : fields) {
if (field.getName().equals("serialVersionUID"))
continue;
String fileNameInMethod = String.valueOf(field.getName().charAt(0)).toUpperCase() + field.getName().substring(1);
getMethod = contingencyRo.getClass().getMethod("get" + fileNameInMethod);
String value = String.valueOf(getMethod.invoke(contingencyRo));
content = content.replaceAll("\\$\\{" + field.getName() + "}", value);
}
content = getNative(content);
} catch (Exception e) {
e.printStackTrace();
}
return content;
}
public String getNative(String str)
{
Pattern p = Pattern.compile("\\$\\{(.*?)\\}");
Matcher m = p.matcher(str);
while (m.find())
{
String parameter = m.group();
Object parametervalue = ELEvaluationContext
.getValue(parameter.substring(1, parameter.length() - 1));
if(parametervalue != null)
str = str.replace(parameter,
parametervalue != null ? parametervalue.toString() : null);
}
return str;
}
/**
* 交互动作
*
* @param actionName 动作名称
* @param icon 图标
* @param tips 提示信息
* @param buttonJson 按钮json字符串
* @param paramObj 预案对象
*/
@RuleMethod(methodLabel = "交互动作", project = "换流站消防专项预案")
public void operation(@MethodParam(paramLabel = "动作名称") String actionName,
@MethodParam(paramLabel = "图标") String icon,
@MethodParam(paramLabel = "提示信息") String tips,
@MethodParam(paramLabel = "按钮json字符串") String buttonJson,
@MethodParam(paramLabel = "预案对象") Object paramObj) {
ContingencyRo contingencyRo = (ContingencyRo) paramObj;
stopSnapshop(contingencyRo);
//转换content中的变量
tips = instedParams(tips, contingencyRo);
SafteyPlanResult result = new SafteyPlanResult();
Map<String, Object> tempmap1 = new HashMap<>();
String contingencyPlanId = getContingencyPlanId(contingencyRo.getBatchNo(), actionName, icon, tips, buttonJson);
tempmap1.put("actionName", actionName);
tempmap1.put("icon", icon);
tempmap1.put("tips", tips);
tempmap1.put("button", buttonJson);
tempmap1.put("caseId", contingencyPlanId);
result.add(tempmap1);
this.sendcmd("optionarea", paramObj, result);
}
private boolean sendButton(String batchNo, String contingencyPlanId, String equipmentId, String actionName, String buttonJson) {
ObjectMapper objectMapper = new ObjectMapper();
/**
* batchNo
* stepCode
* buttonCode
* confirm
* contingencyPlanId
* stepState
*/
try {
Map button = objectMapper.readValue(buttonJson, Map.class);
Map operateInstance = (Map) ((List) button.get("operate")).get(0);
ContingencyDeviceStatus contingencyDeviceStatus = new ContingencyDeviceStatus();
contingencyDeviceStatus.setActionName(actionName);
contingencyDeviceStatus.setButtonCode(String.valueOf(operateInstance.get("code")));
contingencyDeviceStatus.setConfirm("CONFIRM");
contingencyDeviceStatus.setContingencyPlanId(contingencyPlanId);
contingencyDeviceStatus.setEquipmentId(equipmentId);
contingencyDeviceStatus.setStepCode(String.valueOf(button.get("stepCode")));
contingencyDeviceStatus.setStepState(String.valueOf(operateInstance.get("stepState")));
riskSourceService.queryContingencyDeviceStatus(contingencyDeviceStatus);
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
/**
* 保存交互动作
*
* @param actionName 动作名称
* @param icon 图标
* @param tips 提示信息
* @param buttonJson 按钮json字符串
* @param paramObj 预案对象
*/
@RuleMethod(methodLabel = "保存交互动作", project = "换流站消防专项预案")
public void saveOperation(@MethodParam(paramLabel = "动作名称") String actionName,
@MethodParam(paramLabel = "图标") String icon,
@MethodParam(paramLabel = "提示信息") String tips,
@MethodParam(paramLabel = "按钮json字符串") String buttonJson,
@MethodParam(paramLabel = "对象") Object paramObj) {
ContingencyRo contingencyRo = (ContingencyRo) paramObj;
stopSnapshop(contingencyRo);
//转换content中的变量
SafteyPlanResult result = new SafteyPlanResult();
Map<String, Object> tempmap1 = new HashMap<>();
try {
SimpleDateFormat sdf = new SimpleDateFormat("YYYY/MM/DD HH:mm:ss");
List<ContingencyPlanInstance> list = iContingencyInstance.queryForTimeLine(contingencyRo.getBatchNo(), "MESSAGE");
ArrayList records = new ArrayList<>();
if (!ObjectUtils.isEmpty(list)) {
list.forEach(action -> {
HashMap map = new HashMap();
map.put("time", sdf.format(action.getCreateDate()));
map.put("stepName", action.getContent());
records.add(map);
});
}
tempmap1.put("content", records);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
result.add(tempmap1);
this.sendcmd("recordarea", paramObj, result);
}
private String getContingencyPlanId(String batchNo, String actionName, String icon, String tips, String buttonJson) {
String cacheKey = batchNo + actionName;
String contingencyPlanId = null;
ContingencyPlanInstance contingencyPlanInstance = null;
if (OPERATE_RECORD_ID.get(cacheKey) == null) {
contingencyPlanInstance = iContingencyInstance.createInstanceRecord(batchNo, actionName, "DEFAULT", buttonJson, "OPERATE", icon);
contingencyPlanId = contingencyPlanInstance.getId();
OPERATE_RECORD_ID.put(cacheKey, contingencyPlanId);
} else {
contingencyPlanId = OPERATE_RECORD_ID.get(cacheKey);
OPERATE_RECORD_ID.remove(cacheKey);
}
return contingencyPlanId;
}
/**
* 地图动作推送
*
* @param actionName 动作名称标识
* @param paramObj 预案对象
*/
@RuleMethod(methodLabel = "地图动作", project = "换流站消防专项预案")
public void mapAction(@MethodParam(paramLabel = "动作名称标识") String actionName, @MethodParam(paramLabel = "参数") String paramJSON, @MethodParam(paramLabel = "对象") Object paramObj) {
ContingencyRo contingencyRo = (ContingencyRo) paramObj;
log.error("=======================================================================================");
stopSnapshop(contingencyRo);
SafteyPlanResult result = new SafteyPlanResult();
Map<String, Object> tempmap1 = new HashMap<>();
tempmap1.put("key", actionName);
tempmap1.put("content",paramJSON);
result.add(tempmap1);
this.sendcmd("maparea", paramObj, result);
}
@RuleMethod(methodLabel = "地图动画", project = "换流站消防专项预案")
public void mapCartoonAction(
@MethodParam(paramLabel = "动作名称标识") String actionName,
@MethodParam(paramLabel = "动作类型") String actionType,
@MethodParam(paramLabel = "动作类型参数") String paramJSON,
@MethodParam(paramLabel = "对象") Object paramObj) {
ContingencyRo contingencyRo = (ContingencyRo) paramObj;
log.error("=======================================================================================");
stopSnapshop(contingencyRo);
String parameter = instedParams(paramJSON, contingencyRo);
SafteyPlanResult result = new SafteyPlanResult();
Map<String, Object> tempmap1 = new HashMap<>();
tempmap1.put("key", actionName);
tempmap1.put("content",actionType);
tempmap1.put("parameter",parameter);
result.add(tempmap1);
this.sendcmd("maparea", paramObj, result);
}
/**
* 顶部消息提示
*
* @param content 消息内容
* @param messageType 消息类型 messageType 黑色框消息类型CONTINGENCY,,滚动消息:CURRENTMESSAGE
* @param paramObj 预案对象
*/
@RuleMethod(methodLabel = "消息提示", project = "换流站消防专项预案")
public void topMessage(
@MethodParam(paramLabel = "标题") String title,
@MethodParam(paramLabel = "内容") String content,
@MethodParam(paramLabel = "图标") String icon,
@MethodParam(paramLabel = "类型") String messageType,
@MethodParam(paramLabel = "对象") Object paramObj) {
ContingencyRo contingencyRo = (ContingencyRo) paramObj;
stopSnapshop(contingencyRo);
SafteyPlanResult result = new SafteyPlanResult();
Map<String, Object> tempmap1 = new HashMap<>();
//转换content中的变量
content = instedParams(content, contingencyRo);
tempmap1.put("content", content);
tempmap1.put("type", messageType);//消息类型 messageType 黑色框消息类型 CONTINGENCY,,滚动消息:CURRENTMESSAGE
tempmap1.put("title", title);
tempmap1.put("icon", icon);
result.add(tempmap1);
this.sendcmd("message", paramObj, result);
}
/**
* 启动预案
*
* @param paramObj 预案对象
*/
@RuleMethod(methodLabel = "启动预案", project = "换流站消防专项预案")
public void startPlan(@MethodParam(paramLabel = "对象") Object paramObj) {
ContingencyRo contingencyRo = (ContingencyRo) paramObj;
stopSnapshop(contingencyRo);
SafteyPlanResult result = new SafteyPlanResult();
Map<String, Object> tempmap1 = new HashMap<>();
tempmap1.put("type", "event");
tempmap1.put("content", "startPlan");
result.add(tempmap1);
this.sendcmd("message", paramObj, result);
redisTemplate.opsForValue().set("contingencyRo", contingencyRo);
}
/**
* 启动预案
*
* @param paramObj 预案对象
*/
@RuleMethod(methodLabel = "结束预案", project = "换流站消防专项预案")
public void stopPlan(@MethodParam(paramLabel = "对象") Object paramObj) {
ContingencyRo contingencyRo = (ContingencyRo) paramObj;
stopSnapshop(contingencyRo);
SafteyPlanResult result = new SafteyPlanResult();
Map<String, Object> tempmap1 = new HashMap<>();
tempmap1.put("type", "event");
tempmap1.put("content", "stopPlan");
result.add(tempmap1);
this.sendcmd("message", paramObj, result);
redisTemplate.delete("contingencyRo");
}
@RuleMethod(methodLabel = "自动执行步骤", project = "换流站消防专项预案")
public void autoExecute(
@MethodParam(paramLabel = "动作名称") String actionName,
@MethodParam(paramLabel = "步骤编号") String stepCode,
@MethodParam(paramLabel = "按钮编码") String buttonCode,
@MethodParam(paramLabel = "步骤状态") String stepState,
@MethodParam(paramLabel = "预案对象") Object paramObj) {
ContingencyRo contingencyRo = (ContingencyRo) paramObj;
ContingencyPlanInstance contingencyPlanInstance = iContingencyInstance.createInstanceRecord(contingencyRo.getBatchNo(), actionName, "DEFAULT", "", "OPERATE", "");
Toke toke = remoteSecurityService.getServerToken();
// Toke toke = cacheMap.getValue(TOKE);
// if (toke == null) {
// toke = remoteSecurityService.come();
// Long times = (long) (20 * 24 * 60 * 60);
// cacheMap.setex(TOKE, toke, times);
// }
RequestContext.setToken(toke.getToke());
RequestContext.setProduct(toke.getProduct());
try {
iContingencyInstance.setButtonExecuted(contingencyRo.getBatchNo(),contingencyPlanInstance.getId(),buttonCode,"CONFIRM");
iContingencyInstance.fire(contingencyRo.getBatchNo(),stepCode, contingencyPlanInstance.getId(),buttonCode, "CONFIRM", stepState);
} catch (Exception e) {
e.printStackTrace();
}
}
@RuleMethod(methodLabel = "添加步骤执行", project = "换流站消防专项预案")
public void addExecute(
@MethodParam(paramLabel = "步骤编号") String stepCode,
@MethodParam(paramLabel = "按钮编码") String buttonCode,
@MethodParam(paramLabel = "设备数据") Object paramObj) {
SafteyPlanResult result = new SafteyPlanResult();
Map<String, Object> tempmap1 = new HashMap<>();
Map<String, Object> content = new HashMap<>();
content.put("stepCode", stepCode);
content.put("buttonCode", buttonCode);
DeviceRo ro = (DeviceRo)paramObj;
Map<String, Object> equipemtnPoints = pointCache.get(ro.getEquipmentId());
if (ObjectUtils.isEmpty(equipemtnPoints)) {
equipemtnPoints = new HashMap<>();
}
equipemtnPoints.put(stepCode+"-"+buttonCode, content);
tempmap1.put("type", "buttonCache");
tempmap1.put("content", equipemtnPoints.values());
result.add(tempmap1);
this.sendcmd("message", ro, result);
}
@RuleMethod(methodLabel = "清除步骤执行", project = "换流站消防专项预案")
public void clearExecute(
@MethodParam(paramLabel = "步骤编号") String stepCode,
@MethodParam(paramLabel = "按钮编码") String buttonCode,
@MethodParam(paramLabel = "设备数据") Object paramObj) {
SafteyPlanResult result = new SafteyPlanResult();
Map<String, Object> tempmap1 = new HashMap<>();
Map<String, Object> content = new HashMap<>();
content.put("stepCode", stepCode);
content.put("buttonCode", buttonCode);
DeviceRo ro = (DeviceRo)paramObj;
Map<String, Object> equipemtnPoints = pointCache.get(ro.getEquipmentId());
if (!ObjectUtils.isEmpty(equipemtnPoints)) {
equipemtnPoints.remove(stepCode+"-"+buttonCode);
}
tempmap1.put("type", "buttonCache");
if (!ObjectUtils.isEmpty(equipemtnPoints)) {
tempmap1.put("content", equipemtnPoints.values());
} else {
tempmap1.put("content", new ArrayList());
}
result.add(tempmap1);
this.sendcmd("message", ro, result);
}
@RuleMethod(methodLabel = "同步自动执行步骤", project = "换流站消防专项预案")
public void sendExecute(@MethodParam(paramLabel = "预案对象") Object paramObj) {
SafteyPlanResult result = new SafteyPlanResult();
Map<String, Object> tempmap1 = new HashMap<>();
ContingencyRo contingencyRo = (ContingencyRo) paramObj;
Map<String, Object> equipemtnPoints = pointCache.get(contingencyRo.getEquipmentId());
tempmap1.put("type", "buttonCache");
tempmap1.put("content", equipemtnPoints.values());
result.add(tempmap1);
this.sendcmd("message", paramObj, result);
}
public void sendcmd(String msgType, DeviceRo deviceRo, SafteyPlanResult result) {
Constructor<?> constructor;
try {
constructor = Class.forName(
PACKAGEURL + result.getClass().getSimpleName() + "Message")
.getConstructor(ActionResult.class);
AbstractActionResultMessage<?> action = (AbstractActionResultMessage<?>) constructor.newInstance(result);
if ("mqtt".equals(pushType.toLowerCase())) {
ToipResponse toipResponse = action.buildResponse(msgType, deviceRo, result.toJson());
String topic = String.format("/%s/%s/%s", serviceName, stationName,"plan");
log.info(String.format("mqtt[%s]:【 %s 】", topic, toipResponse.toJsonStr()));
webMqttComponent.publish(topic, toipResponse.toJsonStr());
ContingencyEvent event = new ContingencyEvent(this);
event.setMsgBody(toipResponse.toJsonStr());
event.setTopic(topic);
event.setMsgType(msgType);
event.setContingency(deviceRo);
contingencyLogPublisher.publish(event);
} else if ("websocket".equals(pushType.toLowerCase())){
action.execute(msgType, deviceRo);
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void stopSnapshop(ContingencyRo contingencyRo) {
if (RuleRunigSnapshotServiceImpl.getReplayBatchNo() != null && !RuleRunigSnapshotServiceImpl.getReplayBatchNo().equals(contingencyRo.getBatchNo()))
RuleRunigSnapshotServiceImpl.setReplayBatchNoToNull();
}
}
package com.yeejoin.amos.fas.business.action;
import com.yeejoin.amos.fas.business.service.intfc.IEquipmentHandlerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import com.yeejoin.amos.fas.business.action.model.ContingencyEvent;
import com.yeejoin.amos.fas.business.service.intfc.IRuleRunningSnapshotService;
@Component
public class ContingencyLogListener implements ApplicationListener<ContingencyEvent>{
@Autowired
IRuleRunningSnapshotService ruleRunningSnapshotService;
// @Autowired
// @Lazy
// IEquipmentHandlerService equipmentHandlerService;
@Override
public void onApplicationEvent(ContingencyEvent event) {
ruleRunningSnapshotService.reacordPlan(event.getTopic(), event.getMsgType(), event.getMsgBody(), event.getContingency());
// equipmentHandlerService.subscribeTopic();
}
}
package com.yeejoin.amos.fas.business.action;
import com.yeejoin.amos.fas.business.service.intfc.IEquipmentHandlerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import com.yeejoin.amos.fas.business.action.model.ContingencyEvent;
import com.yeejoin.amos.fas.business.service.intfc.IRuleRunningSnapshotService;
@Component
public class ContingencyLogListener implements ApplicationListener<ContingencyEvent>{
@Autowired
IRuleRunningSnapshotService ruleRunningSnapshotService;
// @Autowired
// @Lazy
// IEquipmentHandlerService equipmentHandlerService;
@Override
public void onApplicationEvent(ContingencyEvent event) {
ruleRunningSnapshotService.reacordPlan(event.getTopic(), event.getMsgType(), event.getMsgBody(), event.getContingency());
// equipmentHandlerService.subscribeTopic();
}
}
package com.yeejoin.amos.fas.business.action;
import java.lang.reflect.Constructor;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import com.yeejoin.amos.component.rule.MethodParam;
import com.yeejoin.amos.component.rule.RuleActionBean;
import com.yeejoin.amos.component.rule.RuleMethod;
import com.yeejoin.amos.fas.business.action.mq.WebMqttComponent;
import com.yeejoin.amos.fas.business.action.result.ActionResult;
import com.yeejoin.amos.fas.business.action.result.BubbleTipResult;
import com.yeejoin.amos.fas.business.action.result.message.AbstractActionResultMessage;
import com.yeejoin.amos.fas.business.action.result.message.ActionResultMessage;
import com.yeejoin.amos.fas.business.service.model.ToipResponse;
/**
*
* <pre>
* 风险态势图动作
* </pre>
*
* @author amos
* @version $Id: RiskSituationAction.java, v 0.1 2019年5月16日 下午5:26:27 amos Exp $
*/
@Component
@RuleActionBean(beanLabel = "动态预案")
public class RiskSituationAction implements CustomerAction
{
private static String PACKAGEURL = "com.yeejoin.amos.fas.business.action.result.message.";
@Autowired
private WebMqttComponent webMqttComponent;
@Value("${auto-sys.push.type}")
private String pushType;
@Value("${spring.application.name}")
private String serviceName;
@Value("${station.name}")
private String stationName;
@RuleMethod(methodLabel = "气泡提示", project = "换流站消防专项预案")
public void sendBubbleTip(@MethodParam(paramLabel = "bizobj对象") Object bizobj,
@MethodParam(paramLabel = "是否显示名称") Boolean showInfo,
@MethodParam(paramLabel = "标题") String title)
{
BubbleTipResult result = new BubbleTipResult();
Map<String, Object> tempmap1 = new HashMap<>();
tempmap1.put("bizobj", bizobj);
result.add(tempmap1);
//是否显示气泡
Map<String, Object> tempmap2 = new HashMap<>();
tempmap2.put("showInfo", showInfo);
result.add(tempmap2);
//显示title提示
Map<String, Object> tempmap3 = new HashMap<>();
tempmap3.put("title", title);
result.add(tempmap3);
Constructor<?> constructor;
try
{
constructor = Class.forName(
PACKAGEURL + result.getClass().getSimpleName() + "Message")
.getConstructor(ActionResult.class);
AbstractActionResultMessage<?> action = (AbstractActionResultMessage<?>) constructor.newInstance(result);
String msgType = "bubbleTip";
if ("mqtt".equals(pushType.toLowerCase())) {
ToipResponse toipResponse = action.buildResponse(msgType, bizobj, result);
String topic = String.format("/%s/%s/%s", serviceName, stationName,"rule");
webMqttComponent.publish(topic, toipResponse.toJsonStr());
} else {
Object obj = action.execute(msgType, bizobj);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
@RuleMethod(methodLabel = "区域颜色改变", project = "换流站消防专项预案")
public void regionChange(@MethodParam(paramLabel = "bizobj对象") Object bizobj, @MethodParam(paramLabel = "颜色") String colour)
{
BubbleTipResult result = new BubbleTipResult();
Map<String, Object> tempmap1 = new HashMap<>();
tempmap1.put("bizobj", bizobj);
result.add(tempmap1);
//更改颜色
Map<String, Object> tempmap2 = new HashMap<>();
tempmap2.put("colour", colour);
result.add(tempmap2);
Constructor<?> constructor;
try
{
constructor = Class.forName(
PACKAGEURL + result.getClass().getSimpleName() + "Message")
.getConstructor(ActionResult.class);
AbstractActionResultMessage<?> action = (AbstractActionResultMessage<?>) constructor.newInstance(result);
String msgType = "changeColor";
if ("mqtt".equals(pushType.toLowerCase())) {
ToipResponse toipResponse = action.buildResponse(msgType, bizobj, result);
webMqttComponent.publish("", toipResponse.toJsonStr());
} else {
action.execute(msgType, bizobj);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
//@ExposeAction(value = "区域闪烁",snapshot = false)
@RuleMethod(methodLabel = "区域闪烁", project = "换流站消防专项预案")
public void regionFlicker(@MethodParam(paramLabel = "bizobj对象") Object bizobj, @MethodParam(paramLabel = "闪烁频率") Integer frequency)
{
BubbleTipResult result = new BubbleTipResult();
Map<String, Object> tempmap1 = new HashMap<>();
result.add(tempmap1);
//更改颜色
Map<String, Object> tempmap2 = new HashMap<>();
tempmap2.put("frequency", frequency);
result.add(tempmap2);
Constructor<?> constructor;
try
{
constructor = Class.forName(
PACKAGEURL + result.getClass().getSimpleName() + "Message")
.getConstructor(ActionResult.class);
AbstractActionResultMessage<?> action = (AbstractActionResultMessage<?>) constructor.newInstance(result);
String msgType = "message";
if ("mqtt".equals(pushType.toLowerCase())) {
ToipResponse toipResponse = action.buildResponse(msgType, bizobj, result);
webMqttComponent.publish("", toipResponse.toJsonStr());
} else {
action.execute(msgType, null);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
package com.yeejoin.amos.fas.business.action;
import java.lang.reflect.Constructor;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import com.yeejoin.amos.component.rule.MethodParam;
import com.yeejoin.amos.component.rule.RuleActionBean;
import com.yeejoin.amos.component.rule.RuleMethod;
import com.yeejoin.amos.fas.business.action.mq.WebMqttComponent;
import com.yeejoin.amos.fas.business.action.result.ActionResult;
import com.yeejoin.amos.fas.business.action.result.BubbleTipResult;
import com.yeejoin.amos.fas.business.action.result.message.AbstractActionResultMessage;
import com.yeejoin.amos.fas.business.action.result.message.ActionResultMessage;
import com.yeejoin.amos.fas.business.service.model.ToipResponse;
/**
*
* <pre>
* 风险态势图动作
* </pre>
*
* @author amos
* @version $Id: RiskSituationAction.java, v 0.1 2019年5月16日 下午5:26:27 amos Exp $
*/
@Component
@RuleActionBean(beanLabel = "动态预案")
public class RiskSituationAction implements CustomerAction
{
private static String PACKAGEURL = "com.yeejoin.amos.fas.business.action.result.message.";
@Autowired
private WebMqttComponent webMqttComponent;
@Value("${auto-sys.push.type}")
private String pushType;
@Value("${spring.application.name}")
private String serviceName;
@Value("${station.name}")
private String stationName;
@RuleMethod(methodLabel = "气泡提示", project = "换流站消防专项预案")
public void sendBubbleTip(@MethodParam(paramLabel = "bizobj对象") Object bizobj,
@MethodParam(paramLabel = "是否显示名称") Boolean showInfo,
@MethodParam(paramLabel = "标题") String title)
{
BubbleTipResult result = new BubbleTipResult();
Map<String, Object> tempmap1 = new HashMap<>();
tempmap1.put("bizobj", bizobj);
result.add(tempmap1);
//是否显示气泡
Map<String, Object> tempmap2 = new HashMap<>();
tempmap2.put("showInfo", showInfo);
result.add(tempmap2);
//显示title提示
Map<String, Object> tempmap3 = new HashMap<>();
tempmap3.put("title", title);
result.add(tempmap3);
Constructor<?> constructor;
try
{
constructor = Class.forName(
PACKAGEURL + result.getClass().getSimpleName() + "Message")
.getConstructor(ActionResult.class);
AbstractActionResultMessage<?> action = (AbstractActionResultMessage<?>) constructor.newInstance(result);
String msgType = "bubbleTip";
if ("mqtt".equals(pushType.toLowerCase())) {
ToipResponse toipResponse = action.buildResponse(msgType, bizobj, result);
String topic = String.format("/%s/%s/%s", serviceName, stationName,"rule");
webMqttComponent.publish(topic, toipResponse.toJsonStr());
} else {
Object obj = action.execute(msgType, bizobj);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
@RuleMethod(methodLabel = "区域颜色改变", project = "换流站消防专项预案")
public void regionChange(@MethodParam(paramLabel = "bizobj对象") Object bizobj, @MethodParam(paramLabel = "颜色") String colour)
{
BubbleTipResult result = new BubbleTipResult();
Map<String, Object> tempmap1 = new HashMap<>();
tempmap1.put("bizobj", bizobj);
result.add(tempmap1);
//更改颜色
Map<String, Object> tempmap2 = new HashMap<>();
tempmap2.put("colour", colour);
result.add(tempmap2);
Constructor<?> constructor;
try
{
constructor = Class.forName(
PACKAGEURL + result.getClass().getSimpleName() + "Message")
.getConstructor(ActionResult.class);
AbstractActionResultMessage<?> action = (AbstractActionResultMessage<?>) constructor.newInstance(result);
String msgType = "changeColor";
if ("mqtt".equals(pushType.toLowerCase())) {
ToipResponse toipResponse = action.buildResponse(msgType, bizobj, result);
webMqttComponent.publish("", toipResponse.toJsonStr());
} else {
action.execute(msgType, bizobj);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
//@ExposeAction(value = "区域闪烁",snapshot = false)
@RuleMethod(methodLabel = "区域闪烁", project = "换流站消防专项预案")
public void regionFlicker(@MethodParam(paramLabel = "bizobj对象") Object bizobj, @MethodParam(paramLabel = "闪烁频率") Integer frequency)
{
BubbleTipResult result = new BubbleTipResult();
Map<String, Object> tempmap1 = new HashMap<>();
result.add(tempmap1);
//更改颜色
Map<String, Object> tempmap2 = new HashMap<>();
tempmap2.put("frequency", frequency);
result.add(tempmap2);
Constructor<?> constructor;
try
{
constructor = Class.forName(
PACKAGEURL + result.getClass().getSimpleName() + "Message")
.getConstructor(ActionResult.class);
AbstractActionResultMessage<?> action = (AbstractActionResultMessage<?>) constructor.newInstance(result);
String msgType = "message";
if ("mqtt".equals(pushType.toLowerCase())) {
ToipResponse toipResponse = action.buildResponse(msgType, bizobj, result);
webMqttComponent.publish("", toipResponse.toJsonStr());
} else {
action.execute(msgType, null);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
package com.yeejoin.amos.fas.business.action;
import java.lang.reflect.Constructor;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import com.yeejoin.amos.fas.business.action.el.ELEvaluationContext;
import com.yeejoin.amos.fas.business.action.mq.WebMqttComponent;
import com.yeejoin.amos.fas.business.action.result.ActionResult;
import com.yeejoin.amos.fas.business.action.result.TipResult;
import com.yeejoin.amos.fas.business.action.result.message.AbstractActionResultMessage;
import com.yeejoin.amos.fas.business.action.util.DataItemUtil;
import com.yeejoin.amos.fas.business.service.intfc.IMessageService;
import com.yeejoin.amos.fas.business.service.model.ToipResponse;
/**
*
* <pre>
* 消息提示动作
* </pre>
*
* @author amos
* @version $Id: SimpleTipAction.java, v 0.1 2019年4月24日 下午2:47:37 amos Exp $
*/
@Component
public class SimpleTipAction implements CustomerAction
{
private static String PACKAGEURL = "com.yeejoin.amos.fas.business.action.result.message.";
@Autowired
private IMessageService messageService;
@Autowired
private WebMqttComponent webMqttComponent;
@Value("${auto-sys.push.type}")
private String pushType;
@Value("${spring.application.name}")
private String serviceName;
@Value("${station.name}")
private String stationName;
//@ExposeAction("消息提示")
public void sendMessageTip(Object bizobj, String title, String content, String type)
{
try
{
ELEvaluationContext.setVariable("bizobj",bizobj);
TipResult result = new TipResult();
result.add(bizobj);
Map<String, Object> tempmap1 = new HashMap<>();
tempmap1.put("title", title);
result.add(tempmap1);
Map<String, Object> tempmap2 = new HashMap<>();
content =DataItemUtil.getNative(content);
tempmap2.put("content", content);
result.add(tempmap2);
Constructor<?> constructor;
constructor = Class.forName(
PACKAGEURL + result.getClass().getSimpleName() + "Message")
.getConstructor(ActionResult.class);
AbstractActionResultMessage<?> action = (AbstractActionResultMessage<?>) constructor.newInstance(result);
String msgType = "message";
if ("mqtt".equals(pushType.toLowerCase())) {
ToipResponse toipResponse = action.buildResponse(msgType, bizobj, result);
String topic = String.format("/%s/%s/%s", serviceName, stationName,"rule");
webMqttComponent.publish(topic, toipResponse.toJsonStr());
} else {
action.execute(msgType, bizobj);
}
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// @SuppressWarnings("unchecked")
// private void saveMessageAction(AbstractActionResult abstractActionResult,String type)
// {
// Message message = new Message();
// List<Map<String, Object>> list = (List<Map<String, Object>>) abstractActionResult.getData();
// for(Map<String, Object> map : list) {
// for(String str: map.keySet()) {
// if(str.equals("content")) {
// message.setContent(map.get("content").toString());
// }else
// if (str.equals("title"))
// {
// message.setTitle(map.get("title").toString());
// }
// }
// if(!StringUtil.isNotEmpty(message.getContent())){
// continue;
// }
// if (abstractActionResult.getToipResponse().getBizObj() instanceof MessageRo) {
// MessageRo messageRo = (MessageRo)abstractActionResult.getToipResponse().getBizObj();
// message.setTime(messageRo.getDateTime());
// message.setBizId(messageRo.getId());
// }
// if (abstractActionResult.getToipResponse().getBizObj() instanceof RiskSourceRuleRo) {
// RiskSourceRuleRo riskSourceRuleRo = (RiskSourceRuleRo) abstractActionResult.getToipResponse().getBizObj();
// message.setTime(DateUtil.getNow());
// message.setBizId(StringUtil.isNotEmpty(riskSourceRuleRo.getId()) ?
// String.valueOf(riskSourceRuleRo.getId()) : "");
// }
// if (abstractActionResult.getToipResponse().getBizObj() instanceof ProtalDataRo) {
// ProtalDataRo protalDataRo = (ProtalDataRo) abstractActionResult.getToipResponse().getBizObj();
// message.setTime(DateUtil.getNow());
// message.setBizId(StringUtil.isNotEmpty(protalDataRo.getId()) ? String.valueOf(protalDataRo.getId()) : "");
// }
// if (abstractActionResult.getToipResponse().getBizObj() instanceof FireEquimentDataRo) {
// FireEquimentDataRo fireEquimentDataRo = (FireEquimentDataRo) abstractActionResult.getToipResponse().getBizObj();
// message.setTime(DateUtil.getNow());
// message.setBizId(StringUtil.isNotEmpty(fireEquimentDataRo.getId()) ? String.valueOf(fireEquimentDataRo.getId()) : "");
// }
// message.setBizclassName(abstractActionResult.getToipResponse().getBizObj().getClass().toString());
// message.setType(type);
// message.setId(UUID.randomUUID().toString());
// messageService.save(message);
// }
// }
}
package com.yeejoin.amos.fas.business.action;
import java.lang.reflect.Constructor;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import com.yeejoin.amos.fas.business.action.el.ELEvaluationContext;
import com.yeejoin.amos.fas.business.action.mq.WebMqttComponent;
import com.yeejoin.amos.fas.business.action.result.ActionResult;
import com.yeejoin.amos.fas.business.action.result.TipResult;
import com.yeejoin.amos.fas.business.action.result.message.AbstractActionResultMessage;
import com.yeejoin.amos.fas.business.action.util.DataItemUtil;
import com.yeejoin.amos.fas.business.service.intfc.IMessageService;
import com.yeejoin.amos.fas.business.service.model.ToipResponse;
/**
*
* <pre>
* 消息提示动作
* </pre>
*
* @author amos
* @version $Id: SimpleTipAction.java, v 0.1 2019年4月24日 下午2:47:37 amos Exp $
*/
@Component
public class SimpleTipAction implements CustomerAction
{
private static String PACKAGEURL = "com.yeejoin.amos.fas.business.action.result.message.";
@Autowired
private IMessageService messageService;
@Autowired
private WebMqttComponent webMqttComponent;
@Value("${auto-sys.push.type}")
private String pushType;
@Value("${spring.application.name}")
private String serviceName;
@Value("${station.name}")
private String stationName;
//@ExposeAction("消息提示")
public void sendMessageTip(Object bizobj, String title, String content, String type)
{
try
{
ELEvaluationContext.setVariable("bizobj",bizobj);
TipResult result = new TipResult();
result.add(bizobj);
Map<String, Object> tempmap1 = new HashMap<>();
tempmap1.put("title", title);
result.add(tempmap1);
Map<String, Object> tempmap2 = new HashMap<>();
content =DataItemUtil.getNative(content);
tempmap2.put("content", content);
result.add(tempmap2);
Constructor<?> constructor;
constructor = Class.forName(
PACKAGEURL + result.getClass().getSimpleName() + "Message")
.getConstructor(ActionResult.class);
AbstractActionResultMessage<?> action = (AbstractActionResultMessage<?>) constructor.newInstance(result);
String msgType = "message";
if ("mqtt".equals(pushType.toLowerCase())) {
ToipResponse toipResponse = action.buildResponse(msgType, bizobj, result);
String topic = String.format("/%s/%s/%s", serviceName, stationName,"rule");
webMqttComponent.publish(topic, toipResponse.toJsonStr());
} else {
action.execute(msgType, bizobj);
}
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// @SuppressWarnings("unchecked")
// private void saveMessageAction(AbstractActionResult abstractActionResult,String type)
// {
// Message message = new Message();
// List<Map<String, Object>> list = (List<Map<String, Object>>) abstractActionResult.getData();
// for(Map<String, Object> map : list) {
// for(String str: map.keySet()) {
// if(str.equals("content")) {
// message.setContent(map.get("content").toString());
// }else
// if (str.equals("title"))
// {
// message.setTitle(map.get("title").toString());
// }
// }
// if(!StringUtil.isNotEmpty(message.getContent())){
// continue;
// }
// if (abstractActionResult.getToipResponse().getBizObj() instanceof MessageRo) {
// MessageRo messageRo = (MessageRo)abstractActionResult.getToipResponse().getBizObj();
// message.setTime(messageRo.getDateTime());
// message.setBizId(messageRo.getId());
// }
// if (abstractActionResult.getToipResponse().getBizObj() instanceof RiskSourceRuleRo) {
// RiskSourceRuleRo riskSourceRuleRo = (RiskSourceRuleRo) abstractActionResult.getToipResponse().getBizObj();
// message.setTime(DateUtil.getNow());
// message.setBizId(StringUtil.isNotEmpty(riskSourceRuleRo.getId()) ?
// String.valueOf(riskSourceRuleRo.getId()) : "");
// }
// if (abstractActionResult.getToipResponse().getBizObj() instanceof ProtalDataRo) {
// ProtalDataRo protalDataRo = (ProtalDataRo) abstractActionResult.getToipResponse().getBizObj();
// message.setTime(DateUtil.getNow());
// message.setBizId(StringUtil.isNotEmpty(protalDataRo.getId()) ? String.valueOf(protalDataRo.getId()) : "");
// }
// if (abstractActionResult.getToipResponse().getBizObj() instanceof FireEquimentDataRo) {
// FireEquimentDataRo fireEquimentDataRo = (FireEquimentDataRo) abstractActionResult.getToipResponse().getBizObj();
// message.setTime(DateUtil.getNow());
// message.setBizId(StringUtil.isNotEmpty(fireEquimentDataRo.getId()) ? String.valueOf(fireEquimentDataRo.getId()) : "");
// }
// message.setBizclassName(abstractActionResult.getToipResponse().getBizObj().getClass().toString());
// message.setType(type);
// message.setId(UUID.randomUUID().toString());
// messageService.save(message);
// }
// }
}
......@@ -5,21 +5,23 @@ import com.yeejoin.amos.component.rule.RuleFact;
import lombok.Data;
import java.security.acl.LastOwnerException;
@RuleFact(value = "消防设备",project = "青海风险管控")
@Data
public class FireEquimentDataRo extends BasicsRo
{
/**
*
*
*/
private static final long serialVersionUID = 5243181171363622140L;
private long fireEquimentId;
private Long fireEquimentId;
private String fireEqumentName;
@Label("设备id")
private Long id;//监测点id
private String name;//名称
private String unit;//单位
private String value;//值 0 / 1
......
package com.yeejoin.amos.fas.business.controller;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.alibaba.fastjson.JSONObject;
import com.yeejoin.amos.fas.business.action.model.FireEquimentDataRo;
import com.yeejoin.amos.fas.business.action.model.ProtalDataRo;
import com.yeejoin.amos.fas.business.param.AlarmParam;
import com.yeejoin.amos.fas.business.param.FmeaBindParam;
import com.yeejoin.amos.fas.business.service.intfc.IRiskFactorService;
import com.yeejoin.amos.fas.business.service.intfc.IRiskSourceService;
import com.yeejoin.amos.fas.business.service.model.ContingencyDeviceStatus;
import com.yeejoin.amos.fas.business.vo.ReginParams;
import com.yeejoin.amos.fas.config.Permission;
import com.yeejoin.amos.fas.core.common.request.CommonPageable;
import com.yeejoin.amos.fas.core.common.response.RiskSourceTreeResponse;
import com.yeejoin.amos.fas.core.util.CommonResponse;
import com.yeejoin.amos.fas.core.util.CommonResponseUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
@RestController
@RequestMapping("/api/risksource")
@Api(tags = "风险点API")
public class RiskSourceController extends BaseController {
private final Logger log = LoggerFactory.getLogger(RiskSourceController.class);
private final static String IS_RISK_AREA = "TRUE";
@Autowired
IRiskFactorService iRiskFactorService;
@Autowired
IRiskSourceService riskSourceService;
@Permission
//@Authorization(ingore = true)
@ApiOperation(httpMethod = "GET", value = "查询风险点子项", notes = "查询风险点子项")
@RequestMapping(value = "/children/list", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
public CommonResponse queryRiskSourceByPage() {
return CommonResponseUtil.success(riskSourceService.queryForRegion());
}
@Permission
//@Authorization(ingore = true)
@ApiOperation(httpMethod = "GET", value = "三维图统计", notes = "三维图统计")
@RequestMapping(value = "/collection3d", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
public CommonResponse collection3d() {
return CommonResponseUtil.success(riskSourceService.queryFor3DStatistics());
}
/**
* 查询风险点RPN统计
*
* @return
*/
@Permission
@ApiOperation(httpMethod = "GET", value = "查询风险点RPN统计", notes = "查询风险点RPN统计")
@RequestMapping(value = "/rpn/list", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
public CommonResponse queryRPNReport() {
return CommonResponseUtil.success(riskSourceService.queryRPNReport());
}
/**
* 风险上升率
*
* @return
*/
@Permission
@ApiOperation(httpMethod = "GET", value = "风险上升率", notes = "风险上升率")
@RequestMapping(value = "/riseuprate", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
public CommonResponse queryForRiseUp() throws Exception {
return CommonResponseUtil.success(riskSourceService.queryForRiseUp());
}
/**
* 发生率严重度矩阵
*
* @return
*/
@Permission
@ApiOperation(httpMethod = "GET", value = "发生率严重度矩阵", notes = "发生率严重度矩阵")
@RequestMapping(value = "/matrix", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
public CommonResponse queryForMatrix() throws Exception {
return CommonResponseUtil.success(riskSourceService.queryForMatrix());
}
/**
* 获取风险点树型结构
*
* @return
*/
@Permission
//@Authorization(ingore = true)
@ApiOperation(httpMethod = "GET", value = "获取风险点树型结构", notes = "获取风险点树型结构")
@RequestMapping(value = "/riskSourceTress", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
public CommonResponse getRiskSourceTress() {
ReginParams reginParams = getSelectedOrgInfo();
String compCode = getOrgCode(reginParams);
List<RiskSourceTreeResponse> riskSources = riskSourceService.findRiskSourceTrees(compCode);
return CommonResponseUtil.success(getRiskSourcesTree(riskSources));
}
@Permission
@ApiOperation(value = "远程同步", notes = "将本地 风险模型推送到远程同步")
@PutMapping(value = "/synToEquipManage")
public CommonResponse synToEquipManage() {
ReginParams reginParams = getSelectedOrgInfo();
String compCode = getOrgCode(reginParams);
if (!riskSourceService.isSynEquipManage()) {
return CommonResponseUtil.failure("同步功能未开启");
}
List<RiskSourceTreeResponse> riskSources = riskSourceService.findRiskSourceTrees(compCode).stream().filter(source -> IS_RISK_AREA.equalsIgnoreCase(source.getIsRegion())).collect(Collectors.toList());
String synMsg = riskSourceService.synToEquipManage(getAppKey(), getProduct(), getToken(), SUCCESS, getRiskSourcesTree(riskSources));
if (synMsg != null) {
return CommonResponseUtil.failure(synMsg);
}
return CommonResponseUtil.success();
}
/**
* 获取区域树型结构
*
* @return
*/
@Permission
//@Authorization(ingore = true)
@ApiOperation(httpMethod = "GET", value = "获取区域树型结构", notes = "获取区域树型结构")
@RequestMapping(value = "/regionTress", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
public CommonResponse getRegionTress() {
ReginParams reginParams = getSelectedOrgInfo();
String compCode = getOrgCode(reginParams);
List<RiskSourceTreeResponse> riskSources = riskSourceService.findRiskSourceTrees(compCode);
return CommonResponseUtil.success(getRegionTree(riskSources));
}
@Permission
//@Authorization(ingore = true)
@ApiOperation(httpMethod = "GET", value = "统计级别为1的风险点下面", notes = "获取风险点树型结构")
@RequestMapping(value = "/query3DStatistics/{markerType}", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
public CommonResponse query3DStatistics(@PathVariable(value = "markerType", required = true) String markerType) throws Exception {
if ("riskSource".equals(markerType)) {
return riskSourceStatistics();
} else if ("risk".equals(markerType)) {
return riskStatistics();
} else if ("impEquipment".equals(markerType)) {
return equipStatistics();
} else if ("fireResource".equals(markerType)) {
String[] type = {"4", "3"};
return equipStatistics(type);
} else if ("monitorEquipment".equals(markerType)) {
String[] type = {"0"};
return equipStatistics(type);
} else if ("video".equals(markerType)) {
String[] type = {"2"};
return equipStatistics(type);
}
return CommonResponseUtil.failure("未定义类型");
}
@Permission
//@Authorization(ingore = true)
@ApiOperation(httpMethod = "GET", value = "统计级别为1的风险点下面", notes = "获取风险点树型结构")
@RequestMapping(value = "/riskSourceStatistics", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
public CommonResponse riskSourceStatistics() throws Exception {
ReginParams reginParams = getSelectedOrgInfo();
String compCode = getOrgCode(reginParams);
List<RiskSourceTreeResponse> riskSources = riskSourceService.findRiskSourceTrees(compCode);
List<RiskSourceTreeResponse> treeRiskSources = getRiskSourcesTree(riskSources);
return CommonResponseUtil.success(riskSourceStatistics(treeRiskSources));
}
@Permission
//@Authorization(ingore = true)
@ApiOperation(httpMethod = "GET", value = "统计级别为1的风险点下面设备统计", notes = "统计级别为1的风险点下面设备统计")
@RequestMapping(value = "/equipStatistics", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
public CommonResponse equipStatistics() throws Exception {
List<RiskSourceTreeResponse> riskSources = riskSourceService.findRiskSourceEquipStatistics();
List<RiskSourceTreeResponse> treeRiskSources = getRiskSourcesEquipTree(riskSources);
return CommonResponseUtil.success(riskSourceEquipStatistics(treeRiskSources, true, 0));
}
@Permission
//@Authorization(ingore = true)
@ApiOperation(httpMethod = "GET", value = "统计级别为1的巡检点统计", notes = "统计级别为1的巡检点统计")
@RequestMapping(value = "/checkPointStatistics", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
public CommonResponse riskStatistics() throws Exception {
List<RiskSourceTreeResponse> riskSources = riskSourceService.getCheckPointRiskSources();
List<RiskSourceTreeResponse> treeRiskSources = getRiskSourcesEquipTree(riskSources);
return CommonResponseUtil.success(checkPointEquipStatistics(treeRiskSources, false, 0));
}
private Object checkPointEquipStatistics(List<RiskSourceTreeResponse> list, boolean isLevel, int level) {
List<Map<String, Object>> treeList = new ArrayList<Map<String, Object>>();
if (!ObjectUtils.isEmpty(list)) {
Map<String, Object> map = new HashMap<>();
// List<RiskSourceTreeResponse> firstChildrens = list.get(0).getChildren();
list.forEach(item -> {
// if (!ObjectUtils.isEmpty(item.getPosition3d())) {
Map<String, Object> itemMap = (Map<String, Object>) map.get(item.getId());
if (ObjectUtils.isEmpty(itemMap)) {
itemMap = new HashMap<>();
itemMap.put("id", item.getId());
itemMap.put("key", "key" + item.getId());
itemMap.put("name", item.getName());
if (isLevel) {
itemMap.put("level", level);
} else {
itemMap.put("level", item.getLevel());
}
Map<String, Object> position = new HashMap<>();
if (!ObjectUtils.isEmpty(item.getPosition3d())) {
String[] pos = item.getPosition3d().split(",");
position.put("x", pos[0]);
position.put("y", pos[1]);
position.put("z", pos[2]);
}
Map<String, Object> rotation = new HashMap<>();
rotation.put("x", 0);
rotation.put("y", 0);
rotation.put("z", 0);
Map<String, Object> scale = new HashMap<>();
scale.put("x", 1);
scale.put("y", 1);
scale.put("z", 1);
itemMap.put("position", position);
itemMap.put("scale", scale);
itemMap.put("rotation", rotation);
}
List<Map> itemCountList = new ArrayList<>();
Map<String, Object> ItemCount = new HashMap<>();
ItemCount.put("name", "合格");
ItemCount.put("count", getPointChildrenCount(item, "Qualified"));
itemCountList.add(ItemCount);
Map<String, Object> ItemCount1 = new HashMap<>();
ItemCount1.put("name", "不合格");
ItemCount1.put("count", getPointChildrenCount(item, "Unqualified"));
itemCountList.add(ItemCount1);
Map<String, Object> ItemCount2 = new HashMap<>();
ItemCount2.put("name", "漏检");
ItemCount2.put("count", getPointChildrenCount(item, "Omission"));
itemCountList.add(ItemCount2);
// Map<String, Object> ItemCount3 = new HashMap<>();
// ItemCount.put("name", "合格");
// ItemCount3.put("count", getPointChildrenCount(item, "Unplan"));
// itemCountList.add(ItemCount3);
itemMap.put("statisticsData", itemCountList);
map.put(item.getId() + "", itemMap);
// }
});
for (String key : map.keySet()) {
treeList.add((Map<String, Object>) map.get(key));
}
}
return treeList;
}
private static int getPointChildrenCount(RiskSourceTreeResponse riskSource, String status) {
if (ObjectUtils.isEmpty(riskSource.getChildren())) {
return 0;
}
int count = 0;
if (status.equals("Qualified")) {
count += riskSource.getQualified();
} else if (status.equals("Unqualified")) {
count += riskSource.getUnqualified();
} else if (status.equals("Omission")) {
count += riskSource.getOmission();
} else if (status.equals("Unplan")) {
count += riskSource.getUnplan();
}
for (RiskSourceTreeResponse action : riskSource.getChildren()) {
if (ObjectUtils.isEmpty(action.getPosition3d())) {
continue;
}
count = count + getPointChildrenCount(action, status);
if (status.equals("Qualified")) {
count += action.getQualified();
} else if (status.equals("Unqualified")) {
count += action.getUnqualified();
} else if (status.equals("Omission")) {
count += action.getOmission();
} else if (status.equals("Unplan")) {
count += action.getUnplan();
}
}
return count;
}
@Permission
// @Authorization(ingore = true)
@ApiOperation(httpMethod = "GET", value = "统计级别为1的风险点下面设备统计", notes = "统计级别为1的风险点下面设备统计")
@RequestMapping(value = "/equipStatistics/{type}", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
public CommonResponse equipStatistics(@PathVariable(value = "type", required = true) String[] type) throws Exception {
List<RiskSourceTreeResponse> riskSources = riskSourceService.findRiskSourceEquipStatistics(type);
List<RiskSourceTreeResponse> treeRiskSources = getRiskSourcesEquipTree(riskSources);
return CommonResponseUtil.success(riskSourceEquipStatistics(treeRiskSources, true, 0));
}
private static List<RiskSourceTreeResponse> getRiskSourcesEquipTree(List<RiskSourceTreeResponse> list) {
List<RiskSourceTreeResponse> treeList = new ArrayList<RiskSourceTreeResponse>();
for (RiskSourceTreeResponse tree : list) {
if (tree.getParentId() != null && tree.getParentId() == 1) {
treeList.add(tree);
}
for (RiskSourceTreeResponse treeNode : list) {
if (treeNode.getParentId().longValue() == tree.getId()) {
if (tree.getChildren() == null) {
tree.setChildren(new ArrayList<RiskSourceTreeResponse>());
}
tree.getChildren().add(treeNode);
}
}
}
return treeList;
}
private Object riskSourceEquipStatistics(List<RiskSourceTreeResponse> list, Boolean isLevel, int level) {
List<Map<String, Object>> treeList = new ArrayList<Map<String, Object>>();
if (!ObjectUtils.isEmpty(list)) {
Map<String, Object> map = new HashMap<>();
// List<RiskSourceTreeResponse> firstChildrens = list.get(0).getChildren();
list.forEach(item -> {
// if (!ObjectUtils.isEmpty(item.getPosition3d())) {
Map<String, Object> itemMap = (Map<String, Object>) map.get(item.getId());
if (ObjectUtils.isEmpty(itemMap)) {
itemMap = new HashMap<>();
itemMap.put("id", item.getId());
itemMap.put("key", "key" + item.getId());
itemMap.put("name", item.getName());
if (isLevel) {
itemMap.put("level", level);
} else {
itemMap.put("level", item.getLevel());
}
Map<String, Object> position = new HashMap<>();
if (!ObjectUtils.isEmpty(item.getPosition3d())) {
String[] pos = item.getPosition3d().split(",");
position.put("x", pos[0]);
position.put("y", pos[1]);
position.put("z", pos[2]);
}
Map<String, Object> rotation = new HashMap<>();
rotation.put("x", 0);
rotation.put("y", 0);
rotation.put("z", 0);
Map<String, Object> scale = new HashMap<>();
scale.put("x", 1);
scale.put("y", 1);
scale.put("z", 1);
itemMap.put("position", position);
itemMap.put("scale", scale);
itemMap.put("rotation", rotation);
}
List<Map> itemCountList = new ArrayList<>();
Map<String, Object> ItemCount = new HashMap<>();
itemCountList.add(ItemCount);
ItemCount.put("count", getRiskSourceEquipChildrenCount(item));
itemMap.put("statisticsData", itemCountList);
map.put(item.getId() + "", itemMap);
// }
});
for (String key : map.keySet()) {
treeList.add((Map<String, Object>) map.get(key));
}
}
return treeList;
}
private static int getRiskSourceEquipChildrenCount(RiskSourceTreeResponse item) {
if (ObjectUtils.isEmpty(item.getChildren())) {
return item.getCount();
}
int count = item.getCount();
for (RiskSourceTreeResponse action : item.getChildren()) {
count = count + getRiskSourceChildrenCount(action, null);
count += action.getCount();
}
return count;
}
private static List<Map<String, Object>> riskSourceStatistics(List<RiskSourceTreeResponse> list) {
List<Map<String, Object>> treeList = new ArrayList<Map<String, Object>>();
if (!ObjectUtils.isEmpty(list)) {
Map<String, Object> map = new HashMap<>();
List<RiskSourceTreeResponse> firstChildrens = list.get(0).getChildren();
firstChildrens.forEach(item -> {
// if (!ObjectUtils.isEmpty(item.getPosition3d())) {
Map<String, Object> itemMap = (Map<String, Object>) map.get(item.getId());
if (ObjectUtils.isEmpty(itemMap)) {
itemMap = new HashMap<>();
itemMap.put("id", item.getId());
itemMap.put("key", "key" + item.getId());
itemMap.put("name", item.getName());
itemMap.put("level", item.getLevel());
Map<String, Object> position = new HashMap<>();
if (!ObjectUtils.isEmpty(item.getPosition3d())) {
String[] pos = item.getPosition3d().split(",");
position.put("x", pos[0]);
position.put("y", pos[1]);
position.put("z", pos[2]);
}
Map<String, Object> rotation = new HashMap<>();
rotation.put("x", 0);
rotation.put("y", 0);
rotation.put("z", 0);
Map<String, Object> scale = new HashMap<>();
scale.put("x", 1);
scale.put("y", 1);
scale.put("z", 1);
itemMap.put("position", position);
itemMap.put("scale", scale);
itemMap.put("rotation", rotation);
}
List<Map> itemCountList = new ArrayList<>();
Map<String, Object> ItemCount = new HashMap<>();
ItemCount.put("name", "告警");
ItemCount.put("count", getRiskSourceChildrenCount(item, "ANOMALY"));
itemCountList.add(ItemCount);
Map<String, Object> ItemCount1 = new HashMap<>();
ItemCount1.put("name", "风险点");
ItemCount1.put("count", getRiskSourceChildrenCount(item, null));
itemCountList.add(ItemCount1);
itemMap.put("statisticsData", itemCountList);
map.put(item.getId() + "", itemMap);
// }
});
for (String key : map.keySet()) {
treeList.add((Map<String, Object>) map.get(key));
}
}
return treeList;
}
private static int getRiskSourceChildrenCount(RiskSourceTreeResponse riskSource, String status) {
if (ObjectUtils.isEmpty(riskSource.getChildren())) {
return 0;
}
int count = 0;
if ("ANOMALY".equals(status)) {
count += (riskSource.getQualified() == null ? 0 : riskSource.getQualified());
} else {
count += (riskSource.getUnplan() == null ? 0 : riskSource.getUnplan());
}
for (RiskSourceTreeResponse action : riskSource.getChildren()) {
if (ObjectUtils.isEmpty(action.getPosition3d())) {
continue;
}
count = count + getRiskSourceChildrenCount(action, status);
if (status != null) {
if (status.equals(action.getStatus())) {
count++;
}
} else {
count++;
}
}
return count;
}
private static List<RiskSourceTreeResponse> getRiskSourcesTree(List<RiskSourceTreeResponse> list) {
List<RiskSourceTreeResponse> treeList = new ArrayList<RiskSourceTreeResponse>();
for (RiskSourceTreeResponse tree : list) {
if (tree.getParentId() != null && tree.getParentId() == 0) {
treeList.add(tree);
}
for (RiskSourceTreeResponse treeNode : list) {
if (treeNode.getParentId().longValue() == tree.getId()) {
if (tree.getChildren() == null) {
tree.setChildren(new ArrayList<>());
}
tree.getChildren().add(treeNode);
}
}
}
return treeList;
}
private static List<RiskSourceTreeResponse> getRegionTree(List<RiskSourceTreeResponse> list) {
List<RiskSourceTreeResponse> treeList = new ArrayList<RiskSourceTreeResponse>();
for (RiskSourceTreeResponse tree : list) {
if (tree.getParentId() != null && tree.getParentId() == 0) {
treeList.add(tree);
}
for (RiskSourceTreeResponse treeNode : list) {
if (treeNode.getParentId().longValue() == tree.getId() && "TRUE".equals(treeNode.getIsRegion())) {
if (tree.getChildren() == null) {
tree.setChildren(new ArrayList<>());
}
tree.getChildren().add(treeNode);
}
}
}
return treeList;
}
/**
* 根据风险点查询关联巡检点
*/
@Permission
@ApiOperation(value = "根据风险点查询关联巡检点", notes = "根据风险点查询关联巡检点")
@GetMapping(value = "/getBindPoints", produces = "application/json;charset=UTF-8")
public CommonResponse listFmeaPointInputitem(@ApiParam(value = "fmeaId", required = true) @RequestParam Long fmeaId,
@ApiParam(value = "分页参数", required = true) @RequestParam Integer pageNumber,
@ApiParam(value = "分页参数", required = true) @RequestParam Integer pageSize) {
try {
Page<Map<String, Object>> list = riskSourceService.listFmeaPointInputitem(getToken(), getProduct(), getAppKey(), fmeaId, pageNumber, pageSize);
return CommonResponseUtil.success(list);
} catch (Exception e) {
log.error(e.getMessage(), e);
return CommonResponseUtil.failure("查询巡检点信息失败");
}
}
@Permission
@ApiOperation(httpMethod = "GET", value = "查询指定风险点绑定关系", notes = "查询指定风险点绑定关系")
@RequestMapping(value = "/{fmeaId}/fireequiment/relations", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
public CommonResponse queryBoundRelation(@PathVariable Long fmeaId,
@RequestParam int pageNumber,
@RequestParam int pageSize) {
return CommonResponseUtil.success(riskSourceService.listFeamEquipmentPoint(fmeaId, pageNumber, pageSize));
}
@Permission
@ApiOperation(value = "绑定巡检点检查项", notes = "绑定巡检点检查项")
@PostMapping(value = "/bindFmea/pointInputitem")
public CommonResponse bindFmeaPointInputitem(@RequestBody FmeaBindParam pointInputitems) {
return CommonResponseUtil.success(riskSourceService.bindPointInputitem(pointInputitems));
}
@Permission
@ApiOperation(value = "绑定消防设备指标", notes = "绑定消防设备指标")
@PostMapping(value = "/bingFmea/equimentPoint")
public CommonResponse bindFmeaEquimentPoint(@RequestBody FmeaBindParam fmeaBindParam) {
return CommonResponseUtil.success(riskSourceService.bindFireEquiment(fmeaBindParam));
}
@Permission
@ApiOperation(httpMethod = "GET", value = "查询绑定关系设备", notes = "查询绑定关系包含已绑定和未绑定")
@RequestMapping(value = "/fireequiment/relation/all", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
public CommonResponse queryRelationWithNoBound(
@RequestParam String equimentId,
@RequestParam(value = "fname", required = false) String fname,
@RequestParam int pageNumber,
@RequestParam int pageSize) throws Exception {
CommonPageable commonPageable = new CommonPageable(pageNumber, pageSize);
fname = StringUtils.trimToNull(fname);
return CommonResponseUtil.success(riskSourceService.queryEquimentRelation(commonPageable, equimentId, fname));
}
@Permission
@ApiOperation(value = "查询设备指标", notes = "查询设备指标")
@GetMapping(value = "/listEquipmentPointById")
public CommonResponse listEquipmentPointById(@RequestParam Long fmeaId,
@RequestParam Long importantEquipId,
@RequestParam Long equimentId,
@RequestParam(required = false) String equipmentPointName) {
return CommonResponseUtil.success(riskSourceService.listEquipmentPointById(fmeaId, importantEquipId, equimentId, equipmentPointName));
}
@Permission
@ApiOperation(httpMethod = "PUT", value = "上传消防设备数据", notes = "上传消防设备数据")
@RequestMapping(value = "/data/fireqeuiment", produces = "application/json;charset=UTF-8", method = RequestMethod.PUT)
public CommonResponse postFireEqumentData(@RequestBody FireEquimentDataRo deviceData) throws Exception {
return CommonResponseUtil.success(riskSourceService.processFireEqumtData(deviceData));
}
@ApiOperation(httpMethod = "POST", value = "上传消防设备数据", notes = "上传消防设备数据")
@RequestMapping(value = "/data/fireqeuiment/soe", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
public CommonResponse postFireEqumentData(@RequestBody AlarmParam alarm) throws Exception {
log.debug("pointCode=soe=" + alarm.getPointCode() + " InformationAddress=soe=" + alarm.getInformationAddress());
riskSourceService.processFireEqumtData(alarm);
return CommonResponseUtil.success();
}
@ApiOperation(httpMethod = "POST", value = "上传消防设备数据", notes = "上传消防设备数据")
@RequestMapping(value = "/data/fireqeuiment/all", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
public CommonResponse postFireEqumentData(@RequestBody List<AlarmParam> deviceDatas) throws Exception {
riskSourceService.saveData(deviceDatas, "all");
return CommonResponseUtil.success();
}
// @Permission
// @Authorization(ingore = true)
@ApiOperation(httpMethod = "PUT", value = "上传巡检数据", notes = "上传巡检数据")
@RequestMapping(value = "/data/patroldata", produces = "application/json;charset=UTF-8", method = RequestMethod.PUT)
public CommonResponse postPatrolData(@RequestBody ProtalDataRo protalData) throws Exception {
log.info("上传巡检数据" + JSONObject.toJSONString(protalData));
ReginParams reginParams = getSelectedOrgInfo();
String compCode = getOrgCode(reginParams);
riskSourceService.processProtalData(getToken(), getProduct(), getAppKey(), protalData, compCode);
return CommonResponseUtil.success();
}
@Permission
@ApiOperation(httpMethod = "PUT", value = "上传巡检任务数据", notes = "上传巡检任务数据")
@RequestMapping(value = "/data/task", produces = "application/json;charset=UTF-8", method = RequestMethod.PUT)
public CommonResponse postTaskData(@RequestBody ProtalDataRo taskData) throws Exception {
return CommonResponseUtil.success(riskSourceService.processTaskData(taskData));
}
/**
* 查询风险点明细
*
* @param id
* @return
* @throws Exception
*/
@Permission
@ApiOperation(value = "查询风险点明细", notes = "查询风险点明细")
@GetMapping(value = "/detailById/{id}", produces = "application/json;charset=UTF-8")
public CommonResponse queryRiskSourceDetailById(@PathVariable Long id) {
RiskSourceTreeResponse det = riskSourceService.queryRiskSourceDetailById(id);
return CommonResponseUtil.success(det);
}
@Permission
@ApiOperation(value = "风险预警详情", notes = "风险预警详情")
@GetMapping(value = "/warning/detail", produces = "application/json;charset=UTF-8")
public CommonResponse earlyWarning(@RequestParam Long riskSourceId) {
Map map = riskSourceService.earlyWarning(riskSourceId);
return CommonResponseUtil.success(map);
}
/**
* 获取厂区下所有区域的风险点的rpn值
*/
@Permission
@ApiOperation(httpMethod = "GET", value = "获取厂区下所有区域的风险点的rpn值", notes = "获取厂区下所有区域的风险点的rpn值")
@RequestMapping(value = "/queryRiskAreaRpn", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
public CommonResponse queryRiskAreaRpn() {
return CommonResponseUtil.success(riskSourceService.queryRiskAreaRpn());
}
/**
* @return
*/
@Permission
@ApiOperation(httpMethod = "POST", value = "设置预案节点自动执行", notes = "设置预案节点自动执行")
@RequestMapping(value = "/contingency/setup", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
public CommonResponse queryRiskSourceSecondLevel(@RequestBody ContingencyDeviceStatus contingencyDeviceStatus) {
riskSourceService.queryContingencyDeviceStatus(contingencyDeviceStatus);
return CommonResponseUtil.success();
}
@Permission
@ApiOperation(httpMethod = "GET", value = "初始化預案水資源", notes = "初始化預案水資源")
@RequestMapping(value = "/contingency/water", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
public CommonResponse queryContingencyWater() {
return CommonResponseUtil.success(riskSourceService.queryContingencyWater());
}
/**
* 获取危险因素树二级节点
*
* @return
*/
@Permission
@ApiOperation(httpMethod = "GET", value = "获取危险因素树二级节点", notes = "获取危险因素树二级节点")
@RequestMapping(value = "/riskSourceSecondLevel", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
public CommonResponse queryRiskSourceSecondLevel() {
ReginParams reginParams = getSelectedOrgInfo();
String compCode = getOrgCode(reginParams);
return CommonResponseUtil.success(riskSourceService.queryRiskSourceSecondLevel(compCode));
}
/**
* 获取巡检点FMEA
*
* @return
*/
@Permission
@ApiOperation(httpMethod = "GET", value = "获取危险因素树二级节点", notes = "获取危险因素树二级节点")
@RequestMapping(value = "/queryFmea/point/{pointId}", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
public CommonResponse queryFmeaByPointId(@PathVariable Long pointId) {
return CommonResponseUtil.success(riskSourceService.queryFmeaByPointId(pointId));
}
}
package com.yeejoin.amos.fas.business.controller;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.alibaba.fastjson.JSONObject;
import com.yeejoin.amos.fas.business.action.model.FireEquimentDataRo;
import com.yeejoin.amos.fas.business.action.model.ProtalDataRo;
import com.yeejoin.amos.fas.business.param.AlarmParam;
import com.yeejoin.amos.fas.business.param.FmeaBindParam;
import com.yeejoin.amos.fas.business.service.intfc.IRiskFactorService;
import com.yeejoin.amos.fas.business.service.intfc.IRiskSourceService;
import com.yeejoin.amos.fas.business.service.model.ContingencyDeviceStatus;
import com.yeejoin.amos.fas.business.vo.ReginParams;
import com.yeejoin.amos.fas.config.Permission;
import com.yeejoin.amos.fas.core.common.request.CommonPageable;
import com.yeejoin.amos.fas.core.common.response.RiskSourceTreeResponse;
import com.yeejoin.amos.fas.core.util.CommonResponse;
import com.yeejoin.amos.fas.core.util.CommonResponseUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
@RestController
@RequestMapping("/api/risksource")
@Api(tags = "风险点API")
public class RiskSourceController extends BaseController {
private final Logger log = LoggerFactory.getLogger(RiskSourceController.class);
private final static String IS_RISK_AREA = "TRUE";
@Autowired
IRiskFactorService iRiskFactorService;
@Autowired
IRiskSourceService riskSourceService;
@Permission
//@Authorization(ingore = true)
@ApiOperation(httpMethod = "GET", value = "查询风险点子项", notes = "查询风险点子项")
@RequestMapping(value = "/children/list", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
public CommonResponse queryRiskSourceByPage() {
return CommonResponseUtil.success(riskSourceService.queryForRegion());
}
@Permission
//@Authorization(ingore = true)
@ApiOperation(httpMethod = "GET", value = "三维图统计", notes = "三维图统计")
@RequestMapping(value = "/collection3d", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
public CommonResponse collection3d() {
return CommonResponseUtil.success(riskSourceService.queryFor3DStatistics());
}
/**
* 查询风险点RPN统计
*
* @return
*/
@Permission
@ApiOperation(httpMethod = "GET", value = "查询风险点RPN统计", notes = "查询风险点RPN统计")
@RequestMapping(value = "/rpn/list", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
public CommonResponse queryRPNReport() {
return CommonResponseUtil.success(riskSourceService.queryRPNReport());
}
/**
* 风险上升率
*
* @return
*/
@Permission
@ApiOperation(httpMethod = "GET", value = "风险上升率", notes = "风险上升率")
@RequestMapping(value = "/riseuprate", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
public CommonResponse queryForRiseUp() throws Exception {
return CommonResponseUtil.success(riskSourceService.queryForRiseUp());
}
/**
* 发生率严重度矩阵
*
* @return
*/
@Permission
@ApiOperation(httpMethod = "GET", value = "发生率严重度矩阵", notes = "发生率严重度矩阵")
@RequestMapping(value = "/matrix", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
public CommonResponse queryForMatrix() throws Exception {
return CommonResponseUtil.success(riskSourceService.queryForMatrix());
}
/**
* 获取风险点树型结构
*
* @return
*/
@Permission
//@Authorization(ingore = true)
@ApiOperation(httpMethod = "GET", value = "获取风险点树型结构", notes = "获取风险点树型结构")
@RequestMapping(value = "/riskSourceTress", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
public CommonResponse getRiskSourceTress() {
ReginParams reginParams = getSelectedOrgInfo();
String compCode = getOrgCode(reginParams);
List<RiskSourceTreeResponse> riskSources = riskSourceService.findRiskSourceTrees(compCode);
return CommonResponseUtil.success(getRiskSourcesTree(riskSources));
}
@Permission
@ApiOperation(value = "远程同步", notes = "将本地 风险模型推送到远程同步")
@PutMapping(value = "/synToEquipManage")
public CommonResponse synToEquipManage() {
ReginParams reginParams = getSelectedOrgInfo();
String compCode = getOrgCode(reginParams);
if (!riskSourceService.isSynEquipManage()) {
return CommonResponseUtil.failure("同步功能未开启");
}
List<RiskSourceTreeResponse> riskSources = riskSourceService.findRiskSourceTrees(compCode).stream().filter(source -> IS_RISK_AREA.equalsIgnoreCase(source.getIsRegion())).collect(Collectors.toList());
String synMsg = riskSourceService.synToEquipManage(getAppKey(), getProduct(), getToken(), SUCCESS, getRiskSourcesTree(riskSources));
if (synMsg != null) {
return CommonResponseUtil.failure(synMsg);
}
return CommonResponseUtil.success();
}
/**
* 获取区域树型结构
*
* @return
*/
@Permission
//@Authorization(ingore = true)
@ApiOperation(httpMethod = "GET", value = "获取区域树型结构", notes = "获取区域树型结构")
@RequestMapping(value = "/regionTress", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
public CommonResponse getRegionTress() {
ReginParams reginParams = getSelectedOrgInfo();
String compCode = getOrgCode(reginParams);
List<RiskSourceTreeResponse> riskSources = riskSourceService.findRiskSourceTrees(compCode);
return CommonResponseUtil.success(getRegionTree(riskSources));
}
@Permission
//@Authorization(ingore = true)
@ApiOperation(httpMethod = "GET", value = "统计级别为1的风险点下面", notes = "获取风险点树型结构")
@RequestMapping(value = "/query3DStatistics/{markerType}", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
public CommonResponse query3DStatistics(@PathVariable(value = "markerType", required = true) String markerType) throws Exception {
if ("riskSource".equals(markerType)) {
return riskSourceStatistics();
} else if ("risk".equals(markerType)) {
return riskStatistics();
} else if ("impEquipment".equals(markerType)) {
return equipStatistics();
} else if ("fireResource".equals(markerType)) {
String[] type = {"4", "3"};
return equipStatistics(type);
} else if ("monitorEquipment".equals(markerType)) {
String[] type = {"0"};
return equipStatistics(type);
} else if ("video".equals(markerType)) {
String[] type = {"2"};
return equipStatistics(type);
}
return CommonResponseUtil.failure("未定义类型");
}
@Permission
//@Authorization(ingore = true)
@ApiOperation(httpMethod = "GET", value = "统计级别为1的风险点下面", notes = "获取风险点树型结构")
@RequestMapping(value = "/riskSourceStatistics", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
public CommonResponse riskSourceStatistics() throws Exception {
ReginParams reginParams = getSelectedOrgInfo();
String compCode = getOrgCode(reginParams);
List<RiskSourceTreeResponse> riskSources = riskSourceService.findRiskSourceTrees(compCode);
List<RiskSourceTreeResponse> treeRiskSources = getRiskSourcesTree(riskSources);
return CommonResponseUtil.success(riskSourceStatistics(treeRiskSources));
}
@Permission
//@Authorization(ingore = true)
@ApiOperation(httpMethod = "GET", value = "统计级别为1的风险点下面设备统计", notes = "统计级别为1的风险点下面设备统计")
@RequestMapping(value = "/equipStatistics", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
public CommonResponse equipStatistics() throws Exception {
List<RiskSourceTreeResponse> riskSources = riskSourceService.findRiskSourceEquipStatistics();
List<RiskSourceTreeResponse> treeRiskSources = getRiskSourcesEquipTree(riskSources);
return CommonResponseUtil.success(riskSourceEquipStatistics(treeRiskSources, true, 0));
}
@Permission
//@Authorization(ingore = true)
@ApiOperation(httpMethod = "GET", value = "统计级别为1的巡检点统计", notes = "统计级别为1的巡检点统计")
@RequestMapping(value = "/checkPointStatistics", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
public CommonResponse riskStatistics() throws Exception {
List<RiskSourceTreeResponse> riskSources = riskSourceService.getCheckPointRiskSources();
List<RiskSourceTreeResponse> treeRiskSources = getRiskSourcesEquipTree(riskSources);
return CommonResponseUtil.success(checkPointEquipStatistics(treeRiskSources, false, 0));
}
private Object checkPointEquipStatistics(List<RiskSourceTreeResponse> list, boolean isLevel, int level) {
List<Map<String, Object>> treeList = new ArrayList<Map<String, Object>>();
if (!ObjectUtils.isEmpty(list)) {
Map<String, Object> map = new HashMap<>();
// List<RiskSourceTreeResponse> firstChildrens = list.get(0).getChildren();
list.forEach(item -> {
// if (!ObjectUtils.isEmpty(item.getPosition3d())) {
Map<String, Object> itemMap = (Map<String, Object>) map.get(item.getId());
if (ObjectUtils.isEmpty(itemMap)) {
itemMap = new HashMap<>();
itemMap.put("id", item.getId());
itemMap.put("key", "key" + item.getId());
itemMap.put("name", item.getName());
if (isLevel) {
itemMap.put("level", level);
} else {
itemMap.put("level", item.getLevel());
}
Map<String, Object> position = new HashMap<>();
if (!ObjectUtils.isEmpty(item.getPosition3d())) {
String[] pos = item.getPosition3d().split(",");
position.put("x", pos[0]);
position.put("y", pos[1]);
position.put("z", pos[2]);
}
Map<String, Object> rotation = new HashMap<>();
rotation.put("x", 0);
rotation.put("y", 0);
rotation.put("z", 0);
Map<String, Object> scale = new HashMap<>();
scale.put("x", 1);
scale.put("y", 1);
scale.put("z", 1);
itemMap.put("position", position);
itemMap.put("scale", scale);
itemMap.put("rotation", rotation);
}
List<Map> itemCountList = new ArrayList<>();
Map<String, Object> ItemCount = new HashMap<>();
ItemCount.put("name", "合格");
ItemCount.put("count", getPointChildrenCount(item, "Qualified"));
itemCountList.add(ItemCount);
Map<String, Object> ItemCount1 = new HashMap<>();
ItemCount1.put("name", "不合格");
ItemCount1.put("count", getPointChildrenCount(item, "Unqualified"));
itemCountList.add(ItemCount1);
Map<String, Object> ItemCount2 = new HashMap<>();
ItemCount2.put("name", "漏检");
ItemCount2.put("count", getPointChildrenCount(item, "Omission"));
itemCountList.add(ItemCount2);
// Map<String, Object> ItemCount3 = new HashMap<>();
// ItemCount.put("name", "合格");
// ItemCount3.put("count", getPointChildrenCount(item, "Unplan"));
// itemCountList.add(ItemCount3);
itemMap.put("statisticsData", itemCountList);
map.put(item.getId() + "", itemMap);
// }
});
for (String key : map.keySet()) {
treeList.add((Map<String, Object>) map.get(key));
}
}
return treeList;
}
private static int getPointChildrenCount(RiskSourceTreeResponse riskSource, String status) {
if (ObjectUtils.isEmpty(riskSource.getChildren())) {
return 0;
}
int count = 0;
if (status.equals("Qualified")) {
count += riskSource.getQualified();
} else if (status.equals("Unqualified")) {
count += riskSource.getUnqualified();
} else if (status.equals("Omission")) {
count += riskSource.getOmission();
} else if (status.equals("Unplan")) {
count += riskSource.getUnplan();
}
for (RiskSourceTreeResponse action : riskSource.getChildren()) {
if (ObjectUtils.isEmpty(action.getPosition3d())) {
continue;
}
count = count + getPointChildrenCount(action, status);
if (status.equals("Qualified")) {
count += action.getQualified();
} else if (status.equals("Unqualified")) {
count += action.getUnqualified();
} else if (status.equals("Omission")) {
count += action.getOmission();
} else if (status.equals("Unplan")) {
count += action.getUnplan();
}
}
return count;
}
@Permission
// @Authorization(ingore = true)
@ApiOperation(httpMethod = "GET", value = "统计级别为1的风险点下面设备统计", notes = "统计级别为1的风险点下面设备统计")
@RequestMapping(value = "/equipStatistics/{type}", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
public CommonResponse equipStatistics(@PathVariable(value = "type", required = true) String[] type) throws Exception {
List<RiskSourceTreeResponse> riskSources = riskSourceService.findRiskSourceEquipStatistics(type);
List<RiskSourceTreeResponse> treeRiskSources = getRiskSourcesEquipTree(riskSources);
return CommonResponseUtil.success(riskSourceEquipStatistics(treeRiskSources, true, 0));
}
private static List<RiskSourceTreeResponse> getRiskSourcesEquipTree(List<RiskSourceTreeResponse> list) {
List<RiskSourceTreeResponse> treeList = new ArrayList<RiskSourceTreeResponse>();
for (RiskSourceTreeResponse tree : list) {
if (tree.getParentId() != null && tree.getParentId() == 1) {
treeList.add(tree);
}
for (RiskSourceTreeResponse treeNode : list) {
if (treeNode.getParentId().longValue() == tree.getId()) {
if (tree.getChildren() == null) {
tree.setChildren(new ArrayList<RiskSourceTreeResponse>());
}
tree.getChildren().add(treeNode);
}
}
}
return treeList;
}
private Object riskSourceEquipStatistics(List<RiskSourceTreeResponse> list, Boolean isLevel, int level) {
List<Map<String, Object>> treeList = new ArrayList<Map<String, Object>>();
if (!ObjectUtils.isEmpty(list)) {
Map<String, Object> map = new HashMap<>();
// List<RiskSourceTreeResponse> firstChildrens = list.get(0).getChildren();
list.forEach(item -> {
// if (!ObjectUtils.isEmpty(item.getPosition3d())) {
Map<String, Object> itemMap = (Map<String, Object>) map.get(item.getId());
if (ObjectUtils.isEmpty(itemMap)) {
itemMap = new HashMap<>();
itemMap.put("id", item.getId());
itemMap.put("key", "key" + item.getId());
itemMap.put("name", item.getName());
if (isLevel) {
itemMap.put("level", level);
} else {
itemMap.put("level", item.getLevel());
}
Map<String, Object> position = new HashMap<>();
if (!ObjectUtils.isEmpty(item.getPosition3d())) {
String[] pos = item.getPosition3d().split(",");
position.put("x", pos[0]);
position.put("y", pos[1]);
position.put("z", pos[2]);
}
Map<String, Object> rotation = new HashMap<>();
rotation.put("x", 0);
rotation.put("y", 0);
rotation.put("z", 0);
Map<String, Object> scale = new HashMap<>();
scale.put("x", 1);
scale.put("y", 1);
scale.put("z", 1);
itemMap.put("position", position);
itemMap.put("scale", scale);
itemMap.put("rotation", rotation);
}
List<Map> itemCountList = new ArrayList<>();
Map<String, Object> ItemCount = new HashMap<>();
itemCountList.add(ItemCount);
ItemCount.put("count", getRiskSourceEquipChildrenCount(item));
itemMap.put("statisticsData", itemCountList);
map.put(item.getId() + "", itemMap);
// }
});
for (String key : map.keySet()) {
treeList.add((Map<String, Object>) map.get(key));
}
}
return treeList;
}
private static int getRiskSourceEquipChildrenCount(RiskSourceTreeResponse item) {
if (ObjectUtils.isEmpty(item.getChildren())) {
return item.getCount();
}
int count = item.getCount();
for (RiskSourceTreeResponse action : item.getChildren()) {
count = count + getRiskSourceChildrenCount(action, null);
count += action.getCount();
}
return count;
}
private static List<Map<String, Object>> riskSourceStatistics(List<RiskSourceTreeResponse> list) {
List<Map<String, Object>> treeList = new ArrayList<Map<String, Object>>();
if (!ObjectUtils.isEmpty(list)) {
Map<String, Object> map = new HashMap<>();
List<RiskSourceTreeResponse> firstChildrens = list.get(0).getChildren();
firstChildrens.forEach(item -> {
// if (!ObjectUtils.isEmpty(item.getPosition3d())) {
Map<String, Object> itemMap = (Map<String, Object>) map.get(item.getId());
if (ObjectUtils.isEmpty(itemMap)) {
itemMap = new HashMap<>();
itemMap.put("id", item.getId());
itemMap.put("key", "key" + item.getId());
itemMap.put("name", item.getName());
itemMap.put("level", item.getLevel());
Map<String, Object> position = new HashMap<>();
if (!ObjectUtils.isEmpty(item.getPosition3d())) {
String[] pos = item.getPosition3d().split(",");
position.put("x", pos[0]);
position.put("y", pos[1]);
position.put("z", pos[2]);
}
Map<String, Object> rotation = new HashMap<>();
rotation.put("x", 0);
rotation.put("y", 0);
rotation.put("z", 0);
Map<String, Object> scale = new HashMap<>();
scale.put("x", 1);
scale.put("y", 1);
scale.put("z", 1);
itemMap.put("position", position);
itemMap.put("scale", scale);
itemMap.put("rotation", rotation);
}
List<Map> itemCountList = new ArrayList<>();
Map<String, Object> ItemCount = new HashMap<>();
ItemCount.put("name", "告警");
ItemCount.put("count", getRiskSourceChildrenCount(item, "ANOMALY"));
itemCountList.add(ItemCount);
Map<String, Object> ItemCount1 = new HashMap<>();
ItemCount1.put("name", "风险点");
ItemCount1.put("count", getRiskSourceChildrenCount(item, null));
itemCountList.add(ItemCount1);
itemMap.put("statisticsData", itemCountList);
map.put(item.getId() + "", itemMap);
// }
});
for (String key : map.keySet()) {
treeList.add((Map<String, Object>) map.get(key));
}
}
return treeList;
}
private static int getRiskSourceChildrenCount(RiskSourceTreeResponse riskSource, String status) {
if (ObjectUtils.isEmpty(riskSource.getChildren())) {
return 0;
}
int count = 0;
if ("ANOMALY".equals(status)) {
count += (riskSource.getQualified() == null ? 0 : riskSource.getQualified());
} else {
count += (riskSource.getUnplan() == null ? 0 : riskSource.getUnplan());
}
for (RiskSourceTreeResponse action : riskSource.getChildren()) {
if (ObjectUtils.isEmpty(action.getPosition3d())) {
continue;
}
count = count + getRiskSourceChildrenCount(action, status);
if (status != null) {
if (status.equals(action.getStatus())) {
count++;
}
} else {
count++;
}
}
return count;
}
private static List<RiskSourceTreeResponse> getRiskSourcesTree(List<RiskSourceTreeResponse> list) {
List<RiskSourceTreeResponse> treeList = new ArrayList<RiskSourceTreeResponse>();
for (RiskSourceTreeResponse tree : list) {
if (tree.getParentId() != null && tree.getParentId() == 0) {
treeList.add(tree);
}
for (RiskSourceTreeResponse treeNode : list) {
if (treeNode.getParentId().longValue() == tree.getId()) {
if (tree.getChildren() == null) {
tree.setChildren(new ArrayList<>());
}
tree.getChildren().add(treeNode);
}
}
}
return treeList;
}
private static List<RiskSourceTreeResponse> getRegionTree(List<RiskSourceTreeResponse> list) {
List<RiskSourceTreeResponse> treeList = new ArrayList<RiskSourceTreeResponse>();
for (RiskSourceTreeResponse tree : list) {
if (tree.getParentId() != null && tree.getParentId() == 0) {
treeList.add(tree);
}
for (RiskSourceTreeResponse treeNode : list) {
if (treeNode.getParentId().longValue() == tree.getId() && "TRUE".equals(treeNode.getIsRegion())) {
if (tree.getChildren() == null) {
tree.setChildren(new ArrayList<>());
}
tree.getChildren().add(treeNode);
}
}
}
return treeList;
}
/**
* 根据风险点查询关联巡检点
*/
@Permission
@ApiOperation(value = "根据风险点查询关联巡检点", notes = "根据风险点查询关联巡检点")
@GetMapping(value = "/getBindPoints", produces = "application/json;charset=UTF-8")
public CommonResponse listFmeaPointInputitem(@ApiParam(value = "fmeaId", required = true) @RequestParam Long fmeaId,
@ApiParam(value = "分页参数", required = true) @RequestParam Integer pageNumber,
@ApiParam(value = "分页参数", required = true) @RequestParam Integer pageSize) {
try {
Page<Map<String, Object>> list = riskSourceService.listFmeaPointInputitem(getToken(), getProduct(), getAppKey(), fmeaId, pageNumber, pageSize);
return CommonResponseUtil.success(list);
} catch (Exception e) {
log.error(e.getMessage(), e);
return CommonResponseUtil.failure("查询巡检点信息失败");
}
}
@Permission
@ApiOperation(httpMethod = "GET", value = "查询指定风险点绑定关系", notes = "查询指定风险点绑定关系")
@RequestMapping(value = "/{fmeaId}/fireequiment/relations", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
public CommonResponse queryBoundRelation(@PathVariable Long fmeaId,
@RequestParam int pageNumber,
@RequestParam int pageSize) {
return CommonResponseUtil.success(riskSourceService.listFeamEquipmentPoint(fmeaId, pageNumber, pageSize));
}
@Permission
@ApiOperation(value = "绑定巡检点检查项", notes = "绑定巡检点检查项")
@PostMapping(value = "/bindFmea/pointInputitem")
public CommonResponse bindFmeaPointInputitem(@RequestBody FmeaBindParam pointInputitems) {
return CommonResponseUtil.success(riskSourceService.bindPointInputitem(pointInputitems));
}
@Permission
@ApiOperation(value = "绑定消防设备指标", notes = "绑定消防设备指标")
@PostMapping(value = "/bingFmea/equimentPoint")
public CommonResponse bindFmeaEquimentPoint(@RequestBody FmeaBindParam fmeaBindParam) {
return CommonResponseUtil.success(riskSourceService.bindFireEquiment(fmeaBindParam));
}
@Permission
@ApiOperation(httpMethod = "GET", value = "查询绑定关系设备", notes = "查询绑定关系包含已绑定和未绑定")
@RequestMapping(value = "/fireequiment/relation/all", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
public CommonResponse queryRelationWithNoBound(
@RequestParam String equimentId,
@RequestParam(value = "fname", required = false) String fname,
@RequestParam int pageNumber,
@RequestParam int pageSize) throws Exception {
CommonPageable commonPageable = new CommonPageable(pageNumber, pageSize);
fname = StringUtils.trimToNull(fname);
return CommonResponseUtil.success(riskSourceService.queryEquimentRelation(commonPageable, equimentId, fname));
}
@Permission
@ApiOperation(value = "查询设备指标", notes = "查询设备指标")
@GetMapping(value = "/listEquipmentPointById")
public CommonResponse listEquipmentPointById(@RequestParam Long fmeaId,
@RequestParam Long importantEquipId,
@RequestParam Long equimentId,
@RequestParam(required = false) String equipmentPointName) {
return CommonResponseUtil.success(riskSourceService.listEquipmentPointById(fmeaId, importantEquipId, equimentId, equipmentPointName));
}
@Permission
@ApiOperation(httpMethod = "PUT", value = "上传消防设备数据", notes = "上传消防设备数据")
@RequestMapping(value = "/data/fireqeuiment", produces = "application/json;charset=UTF-8", method = RequestMethod.PUT)
public CommonResponse postFireEqumentData(@RequestBody FireEquimentDataRo deviceData) throws Exception {
return CommonResponseUtil.success(riskSourceService.processFireEqumtData(deviceData));
}
@ApiOperation(httpMethod = "POST", value = "上传消防设备数据", notes = "上传消防设备数据")
@RequestMapping(value = "/data/fireqeuiment/soe", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
public CommonResponse postFireEqumentData(@RequestBody AlarmParam alarm) throws Exception {
log.debug("pointCode=soe=" + alarm.getPointCode() + " InformationAddress=soe=" + alarm.getInformationAddress());
riskSourceService.processFireEqumtData(alarm);
return CommonResponseUtil.success();
}
@ApiOperation(httpMethod = "POST", value = "上传消防设备数据", notes = "上传消防设备数据")
@RequestMapping(value = "/data/fireqeuiment/all", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
public CommonResponse postFireEqumentData(@RequestBody List<AlarmParam> deviceDatas) throws Exception {
riskSourceService.saveData(deviceDatas, "all");
return CommonResponseUtil.success();
}
// @Permission
// @Authorization(ingore = true)
@ApiOperation(httpMethod = "PUT", value = "上传巡检数据", notes = "上传巡检数据")
@RequestMapping(value = "/data/patroldata", produces = "application/json;charset=UTF-8", method = RequestMethod.PUT)
public CommonResponse postPatrolData(@RequestBody ProtalDataRo protalData) throws Exception {
log.info("上传巡检数据" + JSONObject.toJSONString(protalData));
ReginParams reginParams = getSelectedOrgInfo();
String compCode = getOrgCode(reginParams);
riskSourceService.processProtalData(getToken(), getProduct(), getAppKey(), protalData, compCode);
return CommonResponseUtil.success();
}
@Permission
@ApiOperation(httpMethod = "PUT", value = "上传巡检任务数据", notes = "上传巡检任务数据")
@RequestMapping(value = "/data/task", produces = "application/json;charset=UTF-8", method = RequestMethod.PUT)
public CommonResponse postTaskData(@RequestBody ProtalDataRo taskData) throws Exception {
return CommonResponseUtil.success(riskSourceService.processTaskData(taskData));
}
/**
* 查询风险点明细
*
* @param id
* @return
* @throws Exception
*/
@Permission
@ApiOperation(value = "查询风险点明细", notes = "查询风险点明细")
@GetMapping(value = "/detailById/{id}", produces = "application/json;charset=UTF-8")
public CommonResponse queryRiskSourceDetailById(@PathVariable Long id) {
RiskSourceTreeResponse det = riskSourceService.queryRiskSourceDetailById(id);
return CommonResponseUtil.success(det);
}
@Permission
@ApiOperation(value = "风险预警详情", notes = "风险预警详情")
@GetMapping(value = "/warning/detail", produces = "application/json;charset=UTF-8")
public CommonResponse earlyWarning(@RequestParam Long riskSourceId) {
Map map = riskSourceService.earlyWarning(riskSourceId);
return CommonResponseUtil.success(map);
}
/**
* 获取厂区下所有区域的风险点的rpn值
*/
@Permission
@ApiOperation(httpMethod = "GET", value = "获取厂区下所有区域的风险点的rpn值", notes = "获取厂区下所有区域的风险点的rpn值")
@RequestMapping(value = "/queryRiskAreaRpn", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
public CommonResponse queryRiskAreaRpn() {
return CommonResponseUtil.success(riskSourceService.queryRiskAreaRpn());
}
/**
* @return
*/
@Permission
@ApiOperation(httpMethod = "POST", value = "设置预案节点自动执行", notes = "设置预案节点自动执行")
@RequestMapping(value = "/contingency/setup", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
public CommonResponse queryRiskSourceSecondLevel(@RequestBody ContingencyDeviceStatus contingencyDeviceStatus) {
riskSourceService.queryContingencyDeviceStatus(contingencyDeviceStatus);
return CommonResponseUtil.success();
}
@Permission
@ApiOperation(httpMethod = "GET", value = "初始化預案水資源", notes = "初始化預案水資源")
@RequestMapping(value = "/contingency/water", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
public CommonResponse queryContingencyWater() {
return CommonResponseUtil.success(riskSourceService.queryContingencyWater());
}
/**
* 获取危险因素树二级节点
*
* @return
*/
@Permission
@ApiOperation(httpMethod = "GET", value = "获取危险因素树二级节点", notes = "获取危险因素树二级节点")
@RequestMapping(value = "/riskSourceSecondLevel", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
public CommonResponse queryRiskSourceSecondLevel() {
ReginParams reginParams = getSelectedOrgInfo();
String compCode = getOrgCode(reginParams);
return CommonResponseUtil.success(riskSourceService.queryRiskSourceSecondLevel(compCode));
}
/**
* 获取巡检点FMEA
*
* @return
*/
@Permission
@ApiOperation(httpMethod = "GET", value = "获取危险因素树二级节点", notes = "获取危险因素树二级节点")
@RequestMapping(value = "/queryFmea/point/{pointId}", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
public CommonResponse queryFmeaByPointId(@PathVariable Long pointId) {
return CommonResponseUtil.success(riskSourceService.queryFmeaByPointId(pointId));
}
}
package com.yeejoin.amos.fas.business.controller;
import com.yeejoin.amos.fas.business.service.intfc.IStationMaintenService;
import com.yeejoin.amos.fas.config.Permission;
import com.yeejoin.amos.fas.core.util.CommonResponse;
import com.yeejoin.amos.fas.core.util.CommonResponseUtil;
import com.yeejoin.amos.fas.dao.entity.StationInfo;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Date;
@RestController
@RequestMapping(value = "/api/stationMainten")
@Api(tags="站端api")
public class StationMaintenController extends BaseController{
@Autowired
private IStationMaintenService stationMaintenService;
/**
* 保存站端信息
*/
@Permission
@ApiOperation(value = "保存录入站端信息", notes = "保存录入站端信息")
@PostMapping(value = "/save")
public CommonResponse saveStation(@RequestBody StationInfo stationParams) {
AgencyUserModel userModel = getUserInfo();
stationParams.setCreateBy(getUserId());
stationParams.setCreateDate(new Date());
stationParams.setCreateUserName(userModel.getUserName());
stationParams.setCreateUserPhoneNum(userModel.getMobile());
stationMaintenService.save(stationParams);
return CommonResponseUtil.success();
}
/**
* 获取站端信息
*/
@Permission
@ApiOperation(value = "获取站端信息", notes = "获取站端信息")
@PostMapping(value = "/detail")
public CommonResponse detail() {
StationInfo stationInfo = stationMaintenService.detail();
return CommonResponseUtil.success(stationInfo);
}
}
package com.yeejoin.amos.fas.business.controller;
import com.yeejoin.amos.fas.business.service.intfc.IStationMaintenService;
import com.yeejoin.amos.fas.config.Permission;
import com.yeejoin.amos.fas.core.util.CommonResponse;
import com.yeejoin.amos.fas.core.util.CommonResponseUtil;
import com.yeejoin.amos.fas.dao.entity.StationInfo;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Date;
@RestController
@RequestMapping(value = "/api/stationMainten")
@Api(tags="站端api")
public class StationMaintenController extends BaseController{
@Autowired
private IStationMaintenService stationMaintenService;
/**
* 保存站端信息
*/
@Permission
@ApiOperation(value = "保存录入站端信息", notes = "保存录入站端信息")
@PostMapping(value = "/save")
public CommonResponse saveStation(@RequestBody StationInfo stationParams) {
AgencyUserModel userModel = getUserInfo();
stationParams.setCreateBy(getUserId());
stationParams.setCreateDate(new Date());
stationParams.setCreateUserName(userModel.getUserName());
stationParams.setCreateUserPhoneNum(userModel.getMobile());
stationMaintenService.save(stationParams);
return CommonResponseUtil.success();
}
/**
* 获取站端信息
*/
@Permission
@ApiOperation(value = "获取站端信息", notes = "获取站端信息")
@PostMapping(value = "/detail")
public CommonResponse detail() {
StationInfo stationInfo = stationMaintenService.detail();
return CommonResponseUtil.success(stationInfo);
}
}
......@@ -57,8 +57,6 @@ public interface FireEquipMapper extends BaseMapper {
EquipDetailsResponse findEquipDetailsById(@Param("id") Long id);
List<EquipCommunicationData> findAllEquipPointInfo();
EquipCommunicationData findOneByPointCode(@Param("code") String code);
void saveBatch(List<FireEquipmentParam> list);
......
package com.yeejoin.amos.fas.business.service.impl;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.apache.commons.lang3.ArrayUtils;
import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.client.RestTemplate;
import com.alibaba.fastjson.JSONObject;
import com.yeejoin.amos.component.rule.RuleTrigger;
import com.yeejoin.amos.fas.business.action.ContingencyAction;
import com.yeejoin.amos.fas.business.action.model.ContingencyEvent;
import com.yeejoin.amos.fas.business.action.model.ContingencyRo;
import com.yeejoin.amos.fas.business.action.model.SetpEnum;
import com.yeejoin.amos.fas.business.action.util.ContingencyLogPublisher;
import com.yeejoin.amos.fas.business.dao.mapper.FireEquipPointMapper;
import com.yeejoin.amos.fas.business.dao.mapper.ImpAndFireEquipMapper;
import com.yeejoin.amos.fas.business.dao.repository.IContingencyOriginalDataDao;
import com.yeejoin.amos.fas.business.dao.repository.IContingencyPlanInstanceRepository;
import com.yeejoin.amos.fas.business.service.intfc.IContingencyInstance;
import com.yeejoin.amos.fas.business.service.model.Operate;
import com.yeejoin.amos.fas.business.service.model.OperateGroup;
import com.yeejoin.amos.fas.dao.entity.ContingencyOriginalData;
import com.yeejoin.amos.fas.dao.entity.ContingencyPlanInstance;
import com.yeejoin.amos.fas.dao.entity.Equipment;
@Service
public class ContingencyInstanceImpl /*extends GenericManagerImpl<ContingencyPlanInstance, String>*/ implements IContingencyInstance {
private static final Logger log = LoggerFactory.getLogger(ContingencyInstanceImpl.class);
@Autowired
private IContingencyPlanInstanceRepository repository;
@Autowired
IContingencyOriginalDataDao iContingencyOriginalDataDao;
@Autowired
private RestTemplate restTemplate;
@Autowired
private ImpAndFireEquipMapper impAndFireEquipMapper;
@Autowired
private RedisTemplate redisTemplate;
@Autowired
private FireEquipPointMapper fireEquipPointMapper;
@Value("${params.remoteRuleUrl}")
private String remoteRuleUrl;
@Autowired
private IContingencyInstance iContingencyInstance;
@Value("${station.name}")
private String stationName;
private static Map<String, String> stepMap = new HashMap<>();
@Autowired
private RuleTrigger ruleTrigger;
@Value("${spring.application.name}")
private String serviceName;
/* public ContingencyInstanceImpl(IContingencyPlanInstanceRepository repository) {
super(repository);
this.repository = repository;
}*/
@Autowired
ContingencyAction contingencyAction;
@Autowired
private ContingencyLogPublisher contingencyLogPublisher;
/**
* 创建预案执行记录
*
* @param category 一级分类
* @param subCategory 二级分类
* @param content 信息内容
* @param recordType 信息分类
* @param icon 信息显示图标
*/
public ContingencyPlanInstance createInstanceRecord(String instanceNo, String category, String subCategory, String content, String recordType, String icon) {
ContingencyPlanInstance planInstance = new ContingencyPlanInstance();
planInstance.setContent(content);
planInstance.setIcon(icon);
planInstance.setRecordType(recordType);
planInstance.setCategory(category);
planInstance.setBatchNo(instanceNo);
planInstance.setCreateDate(new Date());
//计算序号
int count = repository.countByBatchNo(instanceNo);
planInstance.setSort(++count);
return this.repository.save(planInstance);
}
/**
* 查询时间轴
*
* @param instanceNo
* @return
* @throws Exception
*/
public List<ContingencyPlanInstance> queryForTimeLine(String instanceNo, String recordType) throws Exception {
List<ContingencyPlanInstance> categorys = repository.queryForCategory(instanceNo, recordType);
return categorys;
}
public void fire(String batchNo, String stepCode, String contingencyPlanId, String buttonCode, String buttonState, String stepStateOnbutton) throws Exception {
//火灾误报
ContingencyOriginalData contingencyOriginalData = iContingencyOriginalDataDao.findByBatchNo(batchNo);
String stepKey = batchNo + "_" + stepCode;
if (stepMap.get(stepKey) == null)
stepMap.put(stepKey, "");
if (contingencyOriginalData != null) {
log.info("数据库中的stepcode:" + contingencyOriginalData.getStep());
contingencyOriginalData.setConfirm(buttonState);
contingencyOriginalData.setRunstep(false);
if (contingencyOriginalData.getStepState() == null)
contingencyOriginalData.setStepState("");
if ("CONFIRM".equals(buttonState)
&& !contingencyOriginalData.getStepState().contains(stepStateOnbutton)
&& stepCode.equals(contingencyOriginalData.getStep()))
contingencyOriginalData.setStepState(contingencyOriginalData.getStepState() + stepStateOnbutton);
//请求中的步骤小于以保存的步骤
if (Integer.parseInt(stepCode) < Integer.parseInt(contingencyOriginalData.getStep())) {
contingencyOriginalData.setRunstep(true);
}
if (Integer.parseInt(stepCode) > Integer.parseInt(contingencyOriginalData.getStep())) {
contingencyOriginalData.setStepState(stepStateOnbutton);
}
iContingencyOriginalDataDao.updateByButton(
contingencyOriginalData.getConfirm(),
contingencyOriginalData.getRunstep(),
contingencyOriginalData.getStepState(),
contingencyOriginalData.getBatchNo());
//使用原始数据触发规则
if ("CONFIRM".equals(buttonState)
&& !stepMap.get(stepKey).contains(stepStateOnbutton))
stepMap.put(stepKey, stepMap.get(stepKey) + stepStateOnbutton);
ContingencyRo contingencyRo = new ContingencyRo();
contingencyRo.setButtonCode(buttonCode);
contingencyRo.setButtonState(buttonState);
BeanUtils.copyProperties(contingencyOriginalData, contingencyRo);
SetpEnum step = SetpEnum.getStepByCode(stepCode);
contingencyRo.setStep(step.getValue());
contingencyRo.setStepState(stepMap.get(stepKey));
// contingencyRo.setStep(stepCode);
log.info("stepstate:" + contingencyRo.getStepState());
log.info("stepCode:" + stepCode);
Equipment equipment = impAndFireEquipMapper.queryImpEqumtByFireEquipmt(Long.parseLong(contingencyRo.getFireEquipmentId()));
// 获取重点设备胚胎指标
// 获取遥信指标
List<Map> points = fireEquipPointMapper.getPointsByEquipmentIdAndType(equipment.getId(), "SWITCH");
HashMap<String, Integer> telesignallingMap = new HashMap<>();
for (Map map : points) {
telesignallingMap.put(map.get("code") + "", (ObjectUtils.isEmpty(map.get("value")) || "false".equals(map.get("value").toString())) ? 0 : 1);
}
contingencyRo.setTelesignallingMap(telesignallingMap);
// 获取遥测指标
points = fireEquipPointMapper.getPointsByEquipmentIdAndType(equipment.getId(), "ANALOGUE");
HashMap<String, Double> telemetryMap = new HashMap<>();
for (Map map : points) {
telemetryMap.put(map.get("code") + "", Double.valueOf(ObjectUtils.isEmpty(map.get("value")) ? "0" : map.get("value").toString()));
}
contingencyRo.setTelemetryMap(telemetryMap);
contingencyRo.setEquipmentCode(equipment.getCode());
ruleTrigger.publish(contingencyRo, equipment.getReservePlan(), ArrayUtils.toArray(equipment.getName()));
publisherPlanLog(stepCode, buttonCode, batchNo);
} else {
throw new Exception("数据异常,请联系管理员.");
}
}
private void publisherPlanLog(String stepCode, String buttonCode, String batchNo) {
ContingencyEvent event = new ContingencyEvent(this);
JSONObject json = new JSONObject();
JSONObject msgContext = new JSONObject();
JSONObject content = new JSONObject();
content.put("stepCode", stepCode);
content.put("buttonCode", buttonCode);
msgContext.put("type", "clickEvent");
msgContext.put("content", content);
json.put("msgType", "message");
json.put("msgContext", msgContext);
event.setMsgBody(json.toJSONString());
String topic = String.format("/%s/%s/%s", serviceName, stationName,"plan");
event.setTopic(topic);
event.setMsgType("clickEvent");
event.setContingency(batchNo);
contingencyLogPublisher.publish(event);
}
public void setButtonExecuted(String batchNo, String contingencyPlanId, String code, String buttonState) throws Exception {
ObjectMapper objectMapper = new ObjectMapper();
Optional<ContingencyPlanInstance> contingencyPlanInstance1 = repository.findById(contingencyPlanId);
ContingencyPlanInstance contingencyPlanInstance=contingencyPlanInstance1.get();
if(contingencyPlanInstance1.isPresent()){
if (contingencyPlanInstance != null && "OPERATE".equals(contingencyPlanInstance.getRecordType())) {
String operateJson = contingencyPlanInstance.getContent();
OperateGroup operateGroup = objectMapper.readValue(operateJson, OperateGroup.class);
List<Operate> operates = operateGroup.getOperate();
if (!CollectionUtils.isEmpty(operates)) {
for (Operate operate : operates) {
if (code.equals(operate.getCode()) && ("executed".equals(operate.getState()) || "disable".equals(operate.getState()))){
if("FIRE_CANCEL".equals(code) || "END_EMERGENCY".equals(code)){
redisTemplate.delete(RiskSourceServiceImpl.cacheKeyForCanBeRunning());
}
throw new Exception("请勿重复操作.");
}
if ("CONFIRM".equals(buttonState)) {
if (code.equals(operate.getCode())) {
operate.setState("executed");
if("FIRE_CANCEL".equals(code) || "END_EMERGENCY".equals(code))
redisTemplate.delete(RiskSourceServiceImpl.cacheKeyForCanBeRunning());
} else {
operate.setState("disable");
}
}
}
}
if (buttonState.equals("CONFIRM"))
contingencyPlanInstance.setRunstate(true);
operateJson = objectMapper.writeValueAsString(operateGroup);
contingencyPlanInstance.setContent(operateJson);
repository.save(contingencyPlanInstance);
}
}
}
public void setButtonWait(String batchNo, String contingencyPlanId, String buttonState) throws Exception {
ObjectMapper objectMapper = new ObjectMapper();
Optional<ContingencyPlanInstance> contingencyPlanInstance1 = repository.findById(contingencyPlanId);
ContingencyPlanInstance contingencyPlanInstance=null;
if(contingencyPlanInstance1.isPresent()){
contingencyPlanInstance=contingencyPlanInstance1.get();
}
if (contingencyPlanInstance != null && "OPERATE".equals(contingencyPlanInstance.getRecordType())) {
String operateJson = contingencyPlanInstance.getContent();
OperateGroup operateGroup = objectMapper.readValue(operateJson, OperateGroup.class);
List<Operate> operates = operateGroup.getOperate();
if (!CollectionUtils.isEmpty(operates)) {
for (Operate operate : operates) {
if ("CONFIRM".equals(buttonState)) {
operate.setState("executed");
}
}
}
if (buttonState.equals("CONFIRM"))
contingencyPlanInstance.setRunstate(true);
operateJson = objectMapper.writeValueAsString(operateGroup);
contingencyPlanInstance.setContent(operateJson);
repository.save(contingencyPlanInstance);
}
}
@Override
public void updateStep(String step, String batchNo) {
iContingencyOriginalDataDao.updateByButtonStep(step,batchNo);
}
}
package com.yeejoin.amos.fas.business.service.impl;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.apache.commons.lang3.ArrayUtils;
import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.client.RestTemplate;
import com.alibaba.fastjson.JSONObject;
import com.yeejoin.amos.component.rule.RuleTrigger;
import com.yeejoin.amos.fas.business.action.ContingencyAction;
import com.yeejoin.amos.fas.business.action.model.ContingencyEvent;
import com.yeejoin.amos.fas.business.action.model.ContingencyRo;
import com.yeejoin.amos.fas.business.action.model.SetpEnum;
import com.yeejoin.amos.fas.business.action.util.ContingencyLogPublisher;
import com.yeejoin.amos.fas.business.dao.mapper.FireEquipPointMapper;
import com.yeejoin.amos.fas.business.dao.mapper.ImpAndFireEquipMapper;
import com.yeejoin.amos.fas.business.dao.repository.IContingencyOriginalDataDao;
import com.yeejoin.amos.fas.business.dao.repository.IContingencyPlanInstanceRepository;
import com.yeejoin.amos.fas.business.service.intfc.IContingencyInstance;
import com.yeejoin.amos.fas.business.service.model.Operate;
import com.yeejoin.amos.fas.business.service.model.OperateGroup;
import com.yeejoin.amos.fas.dao.entity.ContingencyOriginalData;
import com.yeejoin.amos.fas.dao.entity.ContingencyPlanInstance;
import com.yeejoin.amos.fas.dao.entity.Equipment;
@Service
public class ContingencyInstanceImpl /*extends GenericManagerImpl<ContingencyPlanInstance, String>*/ implements IContingencyInstance {
private static final Logger log = LoggerFactory.getLogger(ContingencyInstanceImpl.class);
@Autowired
private IContingencyPlanInstanceRepository repository;
@Autowired
IContingencyOriginalDataDao iContingencyOriginalDataDao;
@Autowired
private RestTemplate restTemplate;
@Autowired
private ImpAndFireEquipMapper impAndFireEquipMapper;
@Autowired
private RedisTemplate redisTemplate;
@Autowired
private FireEquipPointMapper fireEquipPointMapper;
@Value("${params.remoteRuleUrl}")
private String remoteRuleUrl;
@Autowired
private IContingencyInstance iContingencyInstance;
@Value("${station.name}")
private String stationName;
private static Map<String, String> stepMap = new HashMap<>();
@Autowired
private RuleTrigger ruleTrigger;
@Value("${spring.application.name}")
private String serviceName;
/* public ContingencyInstanceImpl(IContingencyPlanInstanceRepository repository) {
super(repository);
this.repository = repository;
}*/
@Autowired
ContingencyAction contingencyAction;
@Autowired
private ContingencyLogPublisher contingencyLogPublisher;
/**
* 创建预案执行记录
*
* @param category 一级分类
* @param subCategory 二级分类
* @param content 信息内容
* @param recordType 信息分类
* @param icon 信息显示图标
*/
public ContingencyPlanInstance createInstanceRecord(String instanceNo, String category, String subCategory, String content, String recordType, String icon) {
ContingencyPlanInstance planInstance = new ContingencyPlanInstance();
planInstance.setContent(content);
planInstance.setIcon(icon);
planInstance.setRecordType(recordType);
planInstance.setCategory(category);
planInstance.setBatchNo(instanceNo);
planInstance.setCreateDate(new Date());
//计算序号
int count = repository.countByBatchNo(instanceNo);
planInstance.setSort(++count);
return this.repository.save(planInstance);
}
/**
* 查询时间轴
*
* @param instanceNo
* @return
* @throws Exception
*/
public List<ContingencyPlanInstance> queryForTimeLine(String instanceNo, String recordType) throws Exception {
List<ContingencyPlanInstance> categorys = repository.queryForCategory(instanceNo, recordType);
return categorys;
}
public void fire(String batchNo, String stepCode, String contingencyPlanId, String buttonCode, String buttonState, String stepStateOnbutton) throws Exception {
//火灾误报
ContingencyOriginalData contingencyOriginalData = iContingencyOriginalDataDao.findByBatchNo(batchNo);
String stepKey = batchNo + "_" + stepCode;
if (stepMap.get(stepKey) == null)
stepMap.put(stepKey, "");
if (contingencyOriginalData != null) {
log.info("数据库中的stepcode:" + contingencyOriginalData.getStep());
contingencyOriginalData.setConfirm(buttonState);
contingencyOriginalData.setRunstep(false);
if (contingencyOriginalData.getStepState() == null)
contingencyOriginalData.setStepState("");
if ("CONFIRM".equals(buttonState)
&& !contingencyOriginalData.getStepState().contains(stepStateOnbutton)
&& stepCode.equals(contingencyOriginalData.getStep()))
contingencyOriginalData.setStepState(contingencyOriginalData.getStepState() + stepStateOnbutton);
//请求中的步骤小于以保存的步骤
if (Integer.parseInt(stepCode) < Integer.parseInt(contingencyOriginalData.getStep())) {
contingencyOriginalData.setRunstep(true);
}
if (Integer.parseInt(stepCode) > Integer.parseInt(contingencyOriginalData.getStep())) {
contingencyOriginalData.setStepState(stepStateOnbutton);
}
iContingencyOriginalDataDao.updateByButton(
contingencyOriginalData.getConfirm(),
contingencyOriginalData.getRunstep(),
contingencyOriginalData.getStepState(),
contingencyOriginalData.getBatchNo());
//使用原始数据触发规则
if ("CONFIRM".equals(buttonState)
&& !stepMap.get(stepKey).contains(stepStateOnbutton))
stepMap.put(stepKey, stepMap.get(stepKey) + stepStateOnbutton);
ContingencyRo contingencyRo = new ContingencyRo();
contingencyRo.setButtonCode(buttonCode);
contingencyRo.setButtonState(buttonState);
BeanUtils.copyProperties(contingencyOriginalData, contingencyRo);
SetpEnum step = SetpEnum.getStepByCode(stepCode);
contingencyRo.setStep(step.getValue());
contingencyRo.setStepState(stepMap.get(stepKey));
// contingencyRo.setStep(stepCode);
log.info("stepstate:" + contingencyRo.getStepState());
log.info("stepCode:" + stepCode);
Equipment equipment = impAndFireEquipMapper.queryImpEqumtByFireEquipmt(Long.parseLong(contingencyRo.getFireEquipmentId()));
// 获取重点设备胚胎指标
// 获取遥信指标
List<Map> points = fireEquipPointMapper.getPointsByEquipmentIdAndType(equipment.getId(), "SWITCH");
HashMap<String, Integer> telesignallingMap = new HashMap<>();
for (Map map : points) {
telesignallingMap.put(map.get("code") + "", (ObjectUtils.isEmpty(map.get("value")) || "false".equals(map.get("value").toString())) ? 0 : 1);
}
contingencyRo.setTelesignallingMap(telesignallingMap);
// 获取遥测指标
points = fireEquipPointMapper.getPointsByEquipmentIdAndType(equipment.getId(), "ANALOGUE");
HashMap<String, Double> telemetryMap = new HashMap<>();
for (Map map : points) {
telemetryMap.put(map.get("code") + "", Double.valueOf(ObjectUtils.isEmpty(map.get("value")) ? "0" : map.get("value").toString()));
}
contingencyRo.setTelemetryMap(telemetryMap);
contingencyRo.setEquipmentCode(equipment.getCode());
ruleTrigger.publish(contingencyRo, equipment.getReservePlan(), ArrayUtils.toArray(equipment.getName()));
publisherPlanLog(stepCode, buttonCode, batchNo);
} else {
throw new Exception("数据异常,请联系管理员.");
}
}
private void publisherPlanLog(String stepCode, String buttonCode, String batchNo) {
ContingencyEvent event = new ContingencyEvent(this);
JSONObject json = new JSONObject();
JSONObject msgContext = new JSONObject();
JSONObject content = new JSONObject();
content.put("stepCode", stepCode);
content.put("buttonCode", buttonCode);
msgContext.put("type", "clickEvent");
msgContext.put("content", content);
json.put("msgType", "message");
json.put("msgContext", msgContext);
event.setMsgBody(json.toJSONString());
String topic = String.format("/%s/%s/%s", serviceName, stationName,"plan");
event.setTopic(topic);
event.setMsgType("clickEvent");
event.setContingency(batchNo);
contingencyLogPublisher.publish(event);
}
public void setButtonExecuted(String batchNo, String contingencyPlanId, String code, String buttonState) throws Exception {
ObjectMapper objectMapper = new ObjectMapper();
Optional<ContingencyPlanInstance> contingencyPlanInstance1 = repository.findById(contingencyPlanId);
ContingencyPlanInstance contingencyPlanInstance=contingencyPlanInstance1.get();
if(contingencyPlanInstance1.isPresent()){
if (contingencyPlanInstance != null && "OPERATE".equals(contingencyPlanInstance.getRecordType())) {
String operateJson = contingencyPlanInstance.getContent();
OperateGroup operateGroup = objectMapper.readValue(operateJson, OperateGroup.class);
List<Operate> operates = operateGroup.getOperate();
if (!CollectionUtils.isEmpty(operates)) {
for (Operate operate : operates) {
if (code.equals(operate.getCode()) && ("executed".equals(operate.getState()) || "disable".equals(operate.getState()))){
if("FIRE_CANCEL".equals(code) || "END_EMERGENCY".equals(code)){
redisTemplate.delete(RiskSourceServiceImpl.cacheKeyForCanBeRunning());
}
throw new Exception("请勿重复操作.");
}
if ("CONFIRM".equals(buttonState)) {
if (code.equals(operate.getCode())) {
operate.setState("executed");
if("FIRE_CANCEL".equals(code) || "END_EMERGENCY".equals(code))
redisTemplate.delete(RiskSourceServiceImpl.cacheKeyForCanBeRunning());
} else {
operate.setState("disable");
}
}
}
}
if (buttonState.equals("CONFIRM"))
contingencyPlanInstance.setRunstate(true);
operateJson = objectMapper.writeValueAsString(operateGroup);
contingencyPlanInstance.setContent(operateJson);
repository.save(contingencyPlanInstance);
}
}
}
public void setButtonWait(String batchNo, String contingencyPlanId, String buttonState) throws Exception {
ObjectMapper objectMapper = new ObjectMapper();
Optional<ContingencyPlanInstance> contingencyPlanInstance1 = repository.findById(contingencyPlanId);
ContingencyPlanInstance contingencyPlanInstance=null;
if(contingencyPlanInstance1.isPresent()){
contingencyPlanInstance=contingencyPlanInstance1.get();
}
if (contingencyPlanInstance != null && "OPERATE".equals(contingencyPlanInstance.getRecordType())) {
String operateJson = contingencyPlanInstance.getContent();
OperateGroup operateGroup = objectMapper.readValue(operateJson, OperateGroup.class);
List<Operate> operates = operateGroup.getOperate();
if (!CollectionUtils.isEmpty(operates)) {
for (Operate operate : operates) {
if ("CONFIRM".equals(buttonState)) {
operate.setState("executed");
}
}
}
if (buttonState.equals("CONFIRM"))
contingencyPlanInstance.setRunstate(true);
operateJson = objectMapper.writeValueAsString(operateGroup);
contingencyPlanInstance.setContent(operateJson);
repository.save(contingencyPlanInstance);
}
}
@Override
public void updateStep(String step, String batchNo) {
iContingencyOriginalDataDao.updateByButtonStep(step,batchNo);
}
}
package com.yeejoin.amos.fas.business.service.impl;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import javax.annotation.PostConstruct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.domain.Sort.Order;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;
import com.yeejoin.amos.component.feign.model.FeignClientResult;
import com.yeejoin.amos.fas.business.constants.FasConstant;
import com.yeejoin.amos.fas.business.dao.mapper.FireEquipMapper;
import com.yeejoin.amos.fas.business.dao.mapper.ImpAndFireEquipMapper;
import com.yeejoin.amos.fas.business.dao.mapper.ImpEquipMapper;
import com.yeejoin.amos.fas.business.dao.mongo.EquipCommunicationDao;
import com.yeejoin.amos.fas.business.dao.repository.IEquipmentDao;
import com.yeejoin.amos.fas.business.dao.repository.IEquipmentFireEquipmentDao;
import com.yeejoin.amos.fas.business.dao.repository.IFireEquipmentDao;
import com.yeejoin.amos.fas.business.dao.repository.IFmeaEquipmentPointDao;
import com.yeejoin.amos.fas.business.dao.repository.IPreplanPictureDao;
import com.yeejoin.amos.fas.business.feign.RemoteSecurityService;
import com.yeejoin.amos.fas.business.param.ImgParam;
import com.yeejoin.amos.fas.business.service.intfc.IEquipmentService;
import com.yeejoin.amos.fas.business.vo.EquipCommunicationData;
import com.yeejoin.amos.fas.core.common.request.CommonPageable;
import com.yeejoin.amos.fas.core.common.response.EquipDetailsResponse;
import com.yeejoin.amos.fas.core.util.DaoCriteria;
import com.yeejoin.amos.fas.core.util.query.BaseQuerySpecification;
import com.yeejoin.amos.fas.dao.entity.Equipment;
import com.yeejoin.amos.fas.dao.entity.EquipmentFireEquipment;
import com.yeejoin.amos.fas.dao.entity.FireEquipment;
import com.yeejoin.amos.fas.dao.entity.PreplanPicture;
import com.yeejoin.amos.fas.exception.YeeException;
import com.yeejoin.amos.feign.privilege.Privilege;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import com.yeejoin.amos.feign.privilege.model.CompanyModel;
import com.yeejoin.amos.feign.privilege.model.DepartmentModel;
@Service("equipService")
public class EquipmentServiceImpl implements IEquipmentService {
private final Logger log = LoggerFactory.getLogger(EquipmentServiceImpl.class);
@Autowired
ImpEquipMapper impEquipMapper;
@Autowired
FireEquipMapper fireEquipMapper;
@Autowired
IEquipmentDao iEquipmentDao;
@Autowired
IPreplanPictureDao iPreplanPictureDao;
@Autowired
IEquipmentFireEquipmentDao equipmentFireEquipmentDao;
@Autowired
IFireEquipmentDao iFireEquipmentDao;
@Autowired
ImpAndFireEquipMapper impAndFireEquipMapper;
@Autowired
private IPreplanPictureDao preplanPictureDao;
@Autowired
private RedisTemplate redisTemplate;
@Autowired
private IFmeaEquipmentPointDao iFmeaEquipmentPointDao;
@Autowired
private MongoTemplate mongoTemplate;
@Autowired
private EquipCommunicationDao equipCommunicationDao;
@Value("${windows.img.path}")
private String winImgPath;
@Value("${linux.img.path}")
private String linuxImgPath;
@Autowired
private RemoteSecurityService remoteSecurityService;
public Equipment save(Equipment equipment) {
Long eqId = equipment.getId();
equipment = iEquipmentDao.saveAndFlush(equipment);
return equipment;
}
public Equipment queryOne(Long id) {
Optional<Equipment> dict1=iEquipmentDao.findById(id);
Equipment dict=null;
if(dict1.isPresent()){
dict=dict1.get();
}
return dict;
}
@Override
@Transactional
public String[] delete(String[] idArray) throws Exception {
for (String id : idArray) {
Optional<Equipment> equipment1 = iEquipmentDao.findById(Long.parseLong(id));
Equipment equipment=null;
if(equipment1.isPresent()){
equipment=equipment1.get();
}
if (equipment != null) {
List<EquipmentFireEquipment> eqFireEqs = equipmentFireEquipmentDao.findAllByEquipmentId(equipment.getId());
if(!eqFireEqs.isEmpty()){
equipmentFireEquipmentDao.deleteAll(eqFireEqs);
}
this.iEquipmentDao.deleteById(Long.parseLong(id));
} else {
throw new Exception("找不到指定的对象:" + id);
}
//删除重点设备关联关系
equipmentFireEquipmentDao.deleteByEquipmentId(Long.valueOf(id));
}
return idArray;
}
@Override
public List<PreplanPicture> queryImgByIdAndType(List<DaoCriteria> criterias) {
BaseQuerySpecification<PreplanPicture> spec = new BaseQuerySpecification<>(criterias);
return iPreplanPictureDao.findAll(spec);
}
@Override
public Page<Equipment> queryImpEquip(List<DaoCriteria> criterias, CommonPageable commonPageable) {
String name = "";
String id = "";
for (DaoCriteria criteria : criterias) {
if (criteria.getPropertyName().equals("name")) {
name = String.valueOf(criteria.getValue() != null ? criteria.getValue().toString() : "");
}
if (criteria.getPropertyName().equals("id")) {
id = String.valueOf(criteria.getValue() != null ? criteria.getValue().toString() : "");
}
}
Long total = impEquipMapper.getEquipPageCount(name, id);
List<Map> content = impEquipMapper.getEquipPage(name, id, commonPageable.getOffset(),
commonPageable.getPageSize());
Page result = new PageImpl(content, commonPageable, total);
return result;
}
@Override
public List<Equipment> queryEquipNoPage() {
return iEquipmentDao.findAll();
}
/**
* 绑定消防设备
*
* @param list
* @return
* @throws Exception
*/
@Transactional(rollbackFor = Exception.class)
public List<Map<String, Object>> bindFireEqumt(Long equipmentId, List<EquipmentFireEquipment> list) throws Exception {
List<Map<String, Object>> resultList = new ArrayList<>();
for (EquipmentFireEquipment equipmentFireEquipment : list) {
int count = equipmentFireEquipmentDao.findByEqmtIdAndFireEqmtId(equipmentId, equipmentFireEquipment.getFireEquipmentId());
if (count > 0) {
continue;
}
equipmentFireEquipment.setEquipmentId(equipmentId);
equipmentFireEquipment.setCreateDate(new Date());
Map<String, Object> result = new HashMap<>();
result.put("exits", false);
Equipment equipment = this.iEquipmentDao.getOne(equipmentFireEquipment.getEquipmentId().longValue());
FireEquipment fireEquipment = iFireEquipmentDao.getOne(equipmentFireEquipment.getFireEquipmentId().longValue());
if (equipment == null || fireEquipment == null)
throw new Exception("找不到数据");
this.equipmentFireEquipmentDao.save(equipmentFireEquipment);
//已存在的绑定关系
List<EquipmentFireEquipment> exits = impAndFireEquipMapper.queryForList(String.valueOf(equipmentFireEquipment.getFireEquipmentId()), null);
if (!CollectionUtils.isEmpty(exits))
result.put("exits", true);
result.put("newModel", equipmentFireEquipment);
resultList.add(result);
}
return resultList;
}
@Override
@Transactional(rollbackFor = Exception.class)
public List<Long> removeFireEqmtBind(Long equipmentId, String[] fireEquipmentIds) {
List<Long> ids = new ArrayList<>();
for (String id : fireEquipmentIds) {
long result = 0;
EquipmentFireEquipment equipmentFireEquipment = impAndFireEquipMapper.queryForOne(String.valueOf(id), String.valueOf(equipmentId));
if (equipmentFireEquipment != null) {
result = equipmentFireEquipment.getId();
this.equipmentFireEquipmentDao.deleteById(equipmentFireEquipment.getId());
fireEquipMapper.removeIfmeaPointByFireEquipIdAndEquipId(Long.valueOf(id), equipmentId);
//iFmeaEquipmentPointDao.removeByFireEquipIdAndEquipId(Long.valueOf(id), equipmentId);
}
ids.add(result);
}
return ids;
}
/**
* 查询指定重点设备已经绑定的消防设备
*
* @param equipmentId
* @return
*/
@Override
public Page queryBindFirEqumtList(CommonPageable commonPageable, Long equipmentId) {
long start = -1;
int length = -1;
if (null != commonPageable) {
start = commonPageable.getOffset();
length = commonPageable.getPageSize();
}
long total = this.impAndFireEquipMapper.queryBindFirEqumtPageCount(String.valueOf(equipmentId));
List<FireEquipment> list = this.impAndFireEquipMapper.queryBindFirEqumtPage(start, length, String.valueOf(equipmentId));
if(commonPageable==null)
{
commonPageable = new CommonPageable();
}
Page result = new PageImpl(list, commonPageable, total);
return result;
}
@Override
public Equipment saveImg(MultipartFile file, Equipment equipment, int type, Long userId) {
// TODO Auto-generated method stub
Long equipmentId = Long.valueOf(equipment.getId());
PreplanPicture pp = preplanPictureDao.selectOne(equipmentId, type);
if (pp == null) {
pp = new PreplanPicture();
pp.setEquipmentId(equipmentId);
pp.setType(type);
pp.setCreateDate(new Date());
pp.setCreateBy(userId.intValue()+"");
}
String path = FasConstant.UPLOAD_ROOT_PATH + File.separator + FasConstant.UPLOAD_EQUIPMENT_PATH + File.separator
+ equipment.getId();
String filePath = getRootPath() + path;
String fileType = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."),
file.getOriginalFilename().length());
String fileName = File.separator + type + fileType;
try {
File dest = new File(filePath + File.separator + fileName);
if (!dest.exists()) {
if (dest.getParentFile() != null && !dest.getParentFile().exists()) {
dest.getParentFile().mkdirs();
}
dest.createNewFile();
}
file.transferTo(dest);
} catch (IOException e) {
throw new YeeException("上传图片失败");
}
String picture = path + fileName;
pp.setCreateBy(userId.intValue()+"");
pp.setPicture(picture);
if (equipment.getCreateDate() == null) {
Optional<Equipment> date=iEquipmentDao.findById(equipment.getId());
Equipment equipment2=null;
if(date.isPresent()){
equipment2=date.get();
}
equipment.setCreateDate(equipment2.getCreateDate());
}
preplanPictureDao.saveAndFlush(pp);
equipment = iEquipmentDao.saveAndFlush(equipment);
return equipment;
}
private String getRootPath() {
String localPath = "";
if ("\\".equals(File.separator)) {
localPath += winImgPath;
} else if ("/".equals(File.separator)) {
localPath += linuxImgPath;
}
return localPath.trim();
}
@Override
public Equipment saveEquipmentAndImg(ImgParam[] imgs, Equipment equipment) {
// TODO Auto-generated method stub
if (imgs == null || imgs.length < 1) {
equipment = save(equipment);
if (equipment.getCreateDate() == null) {
Optional<Equipment> date=iEquipmentDao.findById(equipment.getId());
Equipment equipment2=null;
if(date.isPresent()){
equipment2=date.get();
}
equipment.setCreateDate(equipment2.getCreateDate() == null ? new Date() : equipment2.getCreateDate());
}
} else {
equipment = save(equipment);
if (equipment.getCreateDate() == null) {
Optional<Equipment> date=iEquipmentDao.findById(equipment.getId());
Equipment equipment2=null;
if(date.isPresent()){
equipment2=date.get();
}
equipment.setCreateDate(equipment2.getCreateDate() == null ? new Date() : equipment2.getCreateDate());
}
Long equipmentId = Long.valueOf(equipment.getId());
for (int i = 0; i < imgs.length; i++) {
MultipartFile file = imgs[i].getFile();
if (null != file) {
int type = imgs[i].getType();
PreplanPicture pp = preplanPictureDao.selectOne(equipmentId, type);
if (pp == null) {
pp = new PreplanPicture();
pp.setEquipmentId(equipmentId);
pp.setType(type);
pp.setCreateDate(new Date());
}
String path = FasConstant.UPLOAD_ROOT_PATH + File.separator + FasConstant.UPLOAD_EQUIPMENT_PATH
+ File.separator + equipment.getId();
String filePath = getRootPath() + path;
String fileType = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."),
file.getOriginalFilename().length());
String fileName = File.separator + type + fileType;
try {
File dest = new File(filePath + File.separator + fileName);
if (!dest.exists()) {
if (dest.getParentFile() != null && !dest.getParentFile().exists()) {
dest.getParentFile().mkdirs();
}
dest.createNewFile();
}
file.transferTo(dest);
} catch (IOException e) {
log.error(e.getMessage(), e);
throw new YeeException("上传图片失败");
}
String picture = path + fileName;
pp.setPicture(picture);
preplanPictureDao.saveAndFlush(pp);
}
}
equipment = iEquipmentDao.saveAndFlush(equipment);
}
return equipment;
}
@Override
public List<Map<String, Object>> findEquipVideoList() {
List<Map<String, Object>> list = impAndFireEquipMapper.findEquipVideo();
Map<String, Map<String, Object>> tempEquip = new HashMap<String, Map<String, Object>>();
List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
for (Map<String, Object> temp : list) {
Map<String, Object> equip = new HashMap<String, Object>();
Map<String, Object> video = new HashMap<String, Object>();
video.put("id", temp.get("id"));
video.put("code", temp.get("code"));
video.put("name", temp.get("name"));
video.put("videoUrl", temp.get("url"));
video.put("equipName", temp.get("equipName"));
video.put("monitorTime", new Date());
List<Map<String, Object>> videoList = new ArrayList<Map<String, Object>>();
if (tempEquip.containsKey(temp.get("equipId").toString())) {
equip = tempEquip.get(temp.get("equipId").toString());
videoList = (List<Map<String, Object>>) equip.get("children");
videoList.add(video);
} else {
equip.put("equipId", temp.get("equipId"));
equip.put("equipName", temp.get("equipName"));
equip.put("equipCode", temp.get("equipCode"));
videoList.add(video);
equip.put("children", videoList);
tempEquip.put(temp.get("equipId").toString(), equip);
result.add(equip);
}
}
return result;
}
@Override
public EquipDetailsResponse findEquipDetailsById(String toke,String product,String appKey,Long id) {
EquipDetailsResponse equipDetailsResponse = fireEquipMapper.findEquipDetailsById(id);
AgencyUserModel user = remoteSecurityService.getUserById(toke, product, appKey, equipDetailsResponse.getUserId());
equipDetailsResponse.setUsername(user.getRealName());
equipDetailsResponse.setTel(user.getMobile());
if(user.getCompanys().get(0)!=null)
{
CompanyModel companyModel = user.getCompanys().get(0);
if(user.getCompanyDepartments().get(companyModel.getSequenceNbr())!=null)
{
List<DepartmentModel> departList = user.getCompanyDepartments().get(companyModel.getSequenceNbr());
if(!departList.isEmpty())
{
equipDetailsResponse.setDepName(departList.get(0).getDepartmentName());
}
}
}
return equipDetailsResponse;
}
@Override
public List<Equipment> findAll() {
return iEquipmentDao.findAll();
}
@Override
@PostConstruct
public void findAllEquipPointInfo() {
List<EquipCommunicationData> list = fireEquipMapper.findAllEquipPointInfo();
if (!ObjectUtils.isEmpty(list)) {
HashMap<String, EquipCommunicationData> map = new HashMap<>();
list.forEach(data -> {
map.put(data.getPointCode(), data);
});
redisTemplate.opsForHash().putAll("fireEquipData", map);
}
}
@Override
public EquipCommunicationData findFireEquipmentByPointCode(String code) {
// EquipCommunicationData data = (EquipCommunicationData) redisTemplate.opsForHash().get("fireEquipData", code);
// if (ObjectUtils.isEmpty(data)) {
EquipCommunicationData data = fireEquipMapper.findOneByPointCode(code);
// }
return data;
}
@Override
public EquipCommunicationData findFireEquipDataByPointCode(String code) {
Query query = new Query();
query.addCriteria(Criteria.where("pointCode").is(code)).limit(1);
query.with(new Sort(new Order(Direction.DESC, "recDate")));
query.limit(1);
List<EquipCommunicationData> data = mongoTemplate.find(query, EquipCommunicationData.class);
if (data.isEmpty()) {
return null;
}
return data.get(0);
}
@Override
public int countImpEquipByIds(String[] idArray) {
return equipmentFireEquipmentDao.countImpEquipByIds(idArray);
}
@Override
public int countFemaRelation(String[] idArray) {
return iEquipmentDao.countFemaRelation(idArray);
}
}
package com.yeejoin.amos.fas.business.service.impl;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import javax.annotation.PostConstruct;
import com.yeejoin.amos.fas.business.dao.mapper.EquipmentSpecificMapper;
import com.yeejoin.amos.fas.business.vo.EquipmentSpecificVo;
import com.yeejoin.amos.fas.core.util.StringUtil;
import com.yeejoin.amos.fas.dao.entity.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.domain.Sort.Order;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import com.yeejoin.amos.component.feign.model.FeignClientResult;
import com.yeejoin.amos.fas.business.constants.FasConstant;
import com.yeejoin.amos.fas.business.dao.mapper.FireEquipMapper;
import com.yeejoin.amos.fas.business.dao.mapper.ImpAndFireEquipMapper;
import com.yeejoin.amos.fas.business.dao.mapper.ImpEquipMapper;
import com.yeejoin.amos.fas.business.dao.mongo.EquipCommunicationDao;
import com.yeejoin.amos.fas.business.dao.repository.IEquipmentDao;
import com.yeejoin.amos.fas.business.dao.repository.IEquipmentFireEquipmentDao;
import com.yeejoin.amos.fas.business.dao.repository.IFireEquipmentDao;
import com.yeejoin.amos.fas.business.dao.repository.IFmeaEquipmentPointDao;
import com.yeejoin.amos.fas.business.dao.repository.IPreplanPictureDao;
import com.yeejoin.amos.fas.business.feign.RemoteSecurityService;
import com.yeejoin.amos.fas.business.param.ImgParam;
import com.yeejoin.amos.fas.business.service.intfc.IEquipmentService;
import com.yeejoin.amos.fas.business.vo.EquipCommunicationData;
import com.yeejoin.amos.fas.core.common.request.CommonPageable;
import com.yeejoin.amos.fas.core.common.response.EquipDetailsResponse;
import com.yeejoin.amos.fas.core.util.DaoCriteria;
import com.yeejoin.amos.fas.core.util.query.BaseQuerySpecification;
import com.yeejoin.amos.fas.dao.entity.Equipment;
import com.yeejoin.amos.fas.dao.entity.EquipmentFireEquipment;
import com.yeejoin.amos.fas.dao.entity.FireEquipment;
import com.yeejoin.amos.fas.dao.entity.PreplanPicture;
import com.yeejoin.amos.fas.exception.YeeException;
import com.yeejoin.amos.feign.privilege.Privilege;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import com.yeejoin.amos.feign.privilege.model.CompanyModel;
import com.yeejoin.amos.feign.privilege.model.DepartmentModel;
@Service("equipService")
public class EquipmentServiceImpl implements IEquipmentService {
private final Logger log = LoggerFactory.getLogger(EquipmentServiceImpl.class);
@Autowired
ImpEquipMapper impEquipMapper;
@Autowired
FireEquipMapper fireEquipMapper;
@Autowired
EquipmentSpecificMapper equipmentSpecificMapper;
@Autowired
IEquipmentDao iEquipmentDao;
@Autowired
IPreplanPictureDao iPreplanPictureDao;
@Autowired
IEquipmentFireEquipmentDao equipmentFireEquipmentDao;
@Autowired
IFireEquipmentDao iFireEquipmentDao;
@Autowired
ImpAndFireEquipMapper impAndFireEquipMapper;
@Autowired
private IPreplanPictureDao preplanPictureDao;
@Autowired
private RedisTemplate redisTemplate;
@Autowired
private IFmeaEquipmentPointDao iFmeaEquipmentPointDao;
@Autowired
private MongoTemplate mongoTemplate;
@Autowired
private EquipCommunicationDao equipCommunicationDao;
@Value("${windows.img.path}")
private String winImgPath;
@Value("${linux.img.path}")
private String linuxImgPath;
@Autowired
private RemoteSecurityService remoteSecurityService;
public Equipment save(Equipment equipment) {
Long eqId = equipment.getId();
equipment = iEquipmentDao.saveAndFlush(equipment);
return equipment;
}
public Equipment queryOne(Long id) {
Optional<Equipment> dict1=iEquipmentDao.findById(id);
Equipment dict=null;
if(dict1.isPresent()){
dict=dict1.get();
}
return dict;
}
@Override
@Transactional
public String[] delete(String[] idArray) throws Exception {
for (String id : idArray) {
Optional<Equipment> equipment1 = iEquipmentDao.findById(Long.parseLong(id));
Equipment equipment=null;
if(equipment1.isPresent()){
equipment=equipment1.get();
}
if (equipment != null) {
List<EquipmentFireEquipment> eqFireEqs = equipmentFireEquipmentDao.findAllByEquipmentId(equipment.getId());
if(!eqFireEqs.isEmpty()){
equipmentFireEquipmentDao.deleteAll(eqFireEqs);
}
this.iEquipmentDao.deleteById(Long.parseLong(id));
} else {
throw new Exception("找不到指定的对象:" + id);
}
//删除重点设备关联关系
equipmentFireEquipmentDao.deleteByEquipmentId(Long.valueOf(id));
}
return idArray;
}
@Override
public List<PreplanPicture> queryImgByIdAndType(List<DaoCriteria> criterias) {
BaseQuerySpecification<PreplanPicture> spec = new BaseQuerySpecification<>(criterias);
return iPreplanPictureDao.findAll(spec);
}
@Override
public Page<Equipment> queryImpEquip(List<DaoCriteria> criterias, CommonPageable commonPageable) {
String name = "";
String id = "";
for (DaoCriteria criteria : criterias) {
if (criteria.getPropertyName().equals("name")) {
name = String.valueOf(criteria.getValue() != null ? criteria.getValue().toString() : "");
}
if (criteria.getPropertyName().equals("id")) {
id = String.valueOf(criteria.getValue() != null ? criteria.getValue().toString() : "");
}
}
Long total = impEquipMapper.getEquipPageCount(name, id);
List<Map> content = impEquipMapper.getEquipPage(name, id, commonPageable.getOffset(),
commonPageable.getPageSize());
Page result = new PageImpl(content, commonPageable, total);
return result;
}
@Override
public List<Equipment> queryEquipNoPage() {
return iEquipmentDao.findAll();
}
/**
* 绑定消防设备
*
* @param list
* @return
* @throws Exception
*/
@Transactional(rollbackFor = Exception.class)
public List<Map<String, Object>> bindFireEqumt(Long equipmentId, List<EquipmentFireEquipment> list) throws Exception {
List<Map<String, Object>> resultList = new ArrayList<>();
for (EquipmentFireEquipment equipmentFireEquipment : list) {
int count = equipmentFireEquipmentDao.findByEqmtIdAndFireEqmtId(equipmentId, equipmentFireEquipment.getFireEquipmentId());
if (count > 0) {
continue;
}
equipmentFireEquipment.setEquipmentId(equipmentId);
equipmentFireEquipment.setCreateDate(new Date());
Map<String, Object> result = new HashMap<>();
result.put("exits", false);
Equipment equipment = this.iEquipmentDao.getOne(equipmentFireEquipment.getEquipmentId().longValue());
String equipmentSpecific = equipmentSpecificMapper.findEquipNameById(equipmentFireEquipment.getFireEquipmentId());
if (equipment == null || StringUtils.isEmpty(equipmentSpecific))
throw new RuntimeException("找不到数据");
this.equipmentFireEquipmentDao.save(equipmentFireEquipment);
//已存在的绑定关系
List<EquipmentFireEquipment> exits = impAndFireEquipMapper.queryForList(String.valueOf(equipmentFireEquipment.getFireEquipmentId()), null);
if (!CollectionUtils.isEmpty(exits))
result.put("exits", true);
result.put("newModel", equipmentFireEquipment);
resultList.add(result);
}
return resultList;
}
@Override
@Transactional(rollbackFor = Exception.class)
public List<Long> removeFireEqmtBind(Long equipmentId, String[] fireEquipmentIds) {
List<Long> ids = new ArrayList<>();
for (String id : fireEquipmentIds) {
long result = 0;
EquipmentFireEquipment equipmentFireEquipment = impAndFireEquipMapper.queryForOne(String.valueOf(id), String.valueOf(equipmentId));
if (equipmentFireEquipment != null) {
result = equipmentFireEquipment.getId();
this.equipmentFireEquipmentDao.deleteById(equipmentFireEquipment.getId());
fireEquipMapper.removeIfmeaPointByFireEquipIdAndEquipId(Long.valueOf(id), equipmentId);
//iFmeaEquipmentPointDao.removeByFireEquipIdAndEquipId(Long.valueOf(id), equipmentId);
}
ids.add(result);
}
return ids;
}
/**
* 查询指定重点设备已经绑定的消防设备
*
* @param equipmentId
* @return
*/
@Override
public Page queryBindFirEqumtList(CommonPageable commonPageable, Long equipmentId) {
long start = -1;
int length = -1;
if (null != commonPageable) {
start = commonPageable.getOffset();
length = commonPageable.getPageSize();
}
long total = this.impAndFireEquipMapper.queryBindFirEqumtPageCount(String.valueOf(equipmentId));
List<FireEquipment> list = this.impAndFireEquipMapper.queryBindFirEqumtPage(start, length, String.valueOf(equipmentId));
if(commonPageable==null)
{
commonPageable = new CommonPageable();
}
Page result = new PageImpl(list, commonPageable, total);
return result;
}
@Override
public Equipment saveImg(MultipartFile file, Equipment equipment, int type, Long userId) {
// TODO Auto-generated method stub
Long equipmentId = Long.valueOf(equipment.getId());
PreplanPicture pp = preplanPictureDao.selectOne(equipmentId, type);
if (pp == null) {
pp = new PreplanPicture();
pp.setEquipmentId(equipmentId);
pp.setType(type);
pp.setCreateDate(new Date());
pp.setCreateBy(userId.intValue()+"");
}
String path = FasConstant.UPLOAD_ROOT_PATH + File.separator + FasConstant.UPLOAD_EQUIPMENT_PATH + File.separator
+ equipment.getId();
String filePath = getRootPath() + path;
String fileType = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."),
file.getOriginalFilename().length());
String fileName = File.separator + type + fileType;
try {
File dest = new File(filePath + File.separator + fileName);
if (!dest.exists()) {
if (dest.getParentFile() != null && !dest.getParentFile().exists()) {
dest.getParentFile().mkdirs();
}
dest.createNewFile();
}
file.transferTo(dest);
} catch (IOException e) {
throw new YeeException("上传图片失败");
}
String picture = path + fileName;
pp.setCreateBy(userId.intValue()+"");
pp.setPicture(picture);
if (equipment.getCreateDate() == null) {
Optional<Equipment> date=iEquipmentDao.findById(equipment.getId());
Equipment equipment2=null;
if(date.isPresent()){
equipment2=date.get();
}
equipment.setCreateDate(equipment2.getCreateDate());
}
preplanPictureDao.saveAndFlush(pp);
equipment = iEquipmentDao.saveAndFlush(equipment);
return equipment;
}
private String getRootPath() {
String localPath = "";
if ("\\".equals(File.separator)) {
localPath += winImgPath;
} else if ("/".equals(File.separator)) {
localPath += linuxImgPath;
}
return localPath.trim();
}
@Override
public Equipment saveEquipmentAndImg(ImgParam[] imgs, Equipment equipment) {
// TODO Auto-generated method stub
if (imgs == null || imgs.length < 1) {
equipment = save(equipment);
if (equipment.getCreateDate() == null) {
Optional<Equipment> date=iEquipmentDao.findById(equipment.getId());
Equipment equipment2=null;
if(date.isPresent()){
equipment2=date.get();
}
equipment.setCreateDate(equipment2.getCreateDate() == null ? new Date() : equipment2.getCreateDate());
}
} else {
equipment = save(equipment);
if (equipment.getCreateDate() == null) {
Optional<Equipment> date=iEquipmentDao.findById(equipment.getId());
Equipment equipment2=null;
if(date.isPresent()){
equipment2=date.get();
}
equipment.setCreateDate(equipment2.getCreateDate() == null ? new Date() : equipment2.getCreateDate());
}
Long equipmentId = Long.valueOf(equipment.getId());
for (int i = 0; i < imgs.length; i++) {
MultipartFile file = imgs[i].getFile();
if (null != file) {
int type = imgs[i].getType();
PreplanPicture pp = preplanPictureDao.selectOne(equipmentId, type);
if (pp == null) {
pp = new PreplanPicture();
pp.setEquipmentId(equipmentId);
pp.setType(type);
pp.setCreateDate(new Date());
}
String path = FasConstant.UPLOAD_ROOT_PATH + File.separator + FasConstant.UPLOAD_EQUIPMENT_PATH
+ File.separator + equipment.getId();
String filePath = getRootPath() + path;
String fileType = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."),
file.getOriginalFilename().length());
String fileName = File.separator + type + fileType;
try {
File dest = new File(filePath + File.separator + fileName);
if (!dest.exists()) {
if (dest.getParentFile() != null && !dest.getParentFile().exists()) {
dest.getParentFile().mkdirs();
}
dest.createNewFile();
}
file.transferTo(dest);
} catch (IOException e) {
log.error(e.getMessage(), e);
throw new YeeException("上传图片失败");
}
String picture = path + fileName;
pp.setPicture(picture);
preplanPictureDao.saveAndFlush(pp);
}
}
equipment = iEquipmentDao.saveAndFlush(equipment);
}
return equipment;
}
@Override
public List<Map<String, Object>> findEquipVideoList() {
List<Map<String, Object>> list = impAndFireEquipMapper.findEquipVideo();
Map<String, Map<String, Object>> tempEquip = new HashMap<String, Map<String, Object>>();
List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
for (Map<String, Object> temp : list) {
Map<String, Object> equip = new HashMap<String, Object>();
Map<String, Object> video = new HashMap<String, Object>();
video.put("id", temp.get("id"));
video.put("code", temp.get("code"));
video.put("name", temp.get("name"));
video.put("videoUrl", temp.get("url"));
video.put("equipName", temp.get("equipName"));
video.put("monitorTime", new Date());
List<Map<String, Object>> videoList = new ArrayList<Map<String, Object>>();
if (tempEquip.containsKey(temp.get("equipId").toString())) {
equip = tempEquip.get(temp.get("equipId").toString());
videoList = (List<Map<String, Object>>) equip.get("children");
videoList.add(video);
} else {
equip.put("equipId", temp.get("equipId"));
equip.put("equipName", temp.get("equipName"));
equip.put("equipCode", temp.get("equipCode"));
videoList.add(video);
equip.put("children", videoList);
tempEquip.put(temp.get("equipId").toString(), equip);
result.add(equip);
}
}
return result;
}
@Override
public EquipDetailsResponse findEquipDetailsById(String toke,String product,String appKey,Long id) {
EquipDetailsResponse equipDetailsResponse = fireEquipMapper.findEquipDetailsById(id);
AgencyUserModel user = remoteSecurityService.getUserById(toke, product, appKey, equipDetailsResponse.getUserId());
equipDetailsResponse.setUsername(user.getRealName());
equipDetailsResponse.setTel(user.getMobile());
if(user.getCompanys().get(0)!=null)
{
CompanyModel companyModel = user.getCompanys().get(0);
if(user.getCompanyDepartments().get(companyModel.getSequenceNbr())!=null)
{
List<DepartmentModel> departList = user.getCompanyDepartments().get(companyModel.getSequenceNbr());
if(!departList.isEmpty())
{
equipDetailsResponse.setDepName(departList.get(0).getDepartmentName());
}
}
}
return equipDetailsResponse;
}
@Override
public List<Equipment> findAll() {
return iEquipmentDao.findAll();
}
@Override
public EquipCommunicationData findFireEquipmentByPointCode(String code) {
// EquipCommunicationData data = (EquipCommunicationData) redisTemplate.opsForHash().get("fireEquipData", code);
// if (ObjectUtils.isEmpty(data)) {
EquipCommunicationData data = fireEquipMapper.findOneByPointCode(code);
// }
return data;
}
@Override
public EquipCommunicationData findFireEquipDataByPointCode(String code) {
Query query = new Query();
query.addCriteria(Criteria.where("pointCode").is(code)).limit(1);
query.with(new Sort(new Order(Direction.DESC, "recDate")));
query.limit(1);
List<EquipCommunicationData> data = mongoTemplate.find(query, EquipCommunicationData.class);
if (data.isEmpty()) {
return null;
}
return data.get(0);
}
@Override
public int countImpEquipByIds(String[] idArray) {
return equipmentFireEquipmentDao.countImpEquipByIds(idArray);
}
@Override
public int countFemaRelation(String[] idArray) {
return iEquipmentDao.countFemaRelation(idArray);
}
}
......@@ -139,7 +139,7 @@ public class HandlerMqttMessageImpl implements IEquipmentHandlerService {
@Value("${station.name}")
private String stationName;
@Value("${spring.application.name}")
private String serviceName;
......@@ -186,6 +186,8 @@ public class HandlerMqttMessageImpl implements IEquipmentHandlerService {
} else { // 向三维推送实时值修改
log.info("(监测)Message type is: " + equipmentSpecificIndex.getType());
// 是否关联风险点
notifyAlarm(equipmentSpecificIndex, 0);
Map<String, Object> content = new HashMap<>();
content.put("id", "id");
content.put("label", "eqPointName");
......
package com.yeejoin.amos.fas.business.service.intfc;
import com.yeejoin.amos.fas.business.vo.ReginParams;
/**
* @author keyong
* @title: IEquipmentHandler
* <pre>
* @description: 站端接受装备信息系统数据处理流程
* </pre>
* @date 2020/11/10 18:01
*/
public interface IEquipmentHandlerService {
void handlerMqttMessage(String topic, String message);
// void subscribeTopic(ReginParams reginParams);
void subscribeTopic();
}
package com.yeejoin.amos.fas.business.service.intfc;
import com.yeejoin.amos.fas.business.vo.ReginParams;
/**
* @author keyong
* @title: IEquipmentHandler
* <pre>
* @description: 站端接受装备信息系统数据处理流程
* </pre>
* @date 2020/11/10 18:01
*/
public interface IEquipmentHandlerService {
void handlerMqttMessage(String topic, String message);
// void subscribeTopic(ReginParams reginParams);
void subscribeTopic();
}
......@@ -97,8 +97,6 @@ public interface IEquipmentService {
*/
List<Equipment> findAll();
void findAllEquipPointInfo();
EquipCommunicationData findFireEquipmentByPointCode(String code);
EquipCommunicationData findFireEquipDataByPointCode(String code);
......
package com.yeejoin.amos.fas.business.vo;
import lombok.Data;
@Data
public class EquipmentSpecificVo {
private String id;
//装备码
private String code;
//装备名称
private String name;
//装备分类
private String type;
//是否绑定
private String isbind;
//地址
private String address;
//库存
private Integer amount;
//是否单件管理(1是多件)
private Integer single;
}
package com.yeejoin.amos.fas.business.vo;
import lombok.Data;
@Data
public class EquipmentSpecificVo {
private String id;
//装备码
private String code;
//装备名称
private String name;
//装备分类
private String type;
//是否绑定
private String isbind;
//地址
private String address;
//库存
private Integer amount;
//是否单件管理(1是多件)
private Integer single;
//IOT编码
private String iotCode;
//装备编码
private String specificCode;
//系统名称
private String systemName;
}
package com.yeejoin.amos.fas.config;
import javax.servlet.http.HttpServletRequest;
import com.yeejoin.amos.component.feign.config.InnerInvokException;
import com.yeejoin.amos.fas.business.action.mq.WebMqttSubscribe;
import com.yeejoin.amos.fas.business.feign.RemoteSecurityService;
import com.yeejoin.amos.fas.business.vo.DepartmentBo;
import com.yeejoin.amos.fas.business.vo.RoleBo;
import com.yeejoin.amos.feign.privilege.model.DepartmentModel;
import com.yeejoin.amos.feign.privilege.model.RoleModel;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.typroject.tyboot.core.foundation.context.RequestContext;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yeejoin.amos.component.feign.config.TokenOperation;
import com.yeejoin.amos.component.feign.model.FeignClientResult;
import com.yeejoin.amos.fas.business.vo.CompanyBo;
import com.yeejoin.amos.fas.business.vo.ReginParams;
import com.yeejoin.amos.fas.exception.PermissionException;
import com.yeejoin.amos.feign.privilege.Privilege;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import com.yeejoin.amos.feign.privilege.model.CompanyModel;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
@Aspect
@Component
@ResponseBody
public class PermissionAspect {
private static final Logger logger = LoggerFactory.getLogger(PermissionAspect.class);
@Autowired
private RedisTemplate<String, String> redisTemplate;
@Autowired
private RemoteSecurityService remoteSecurityService;
// 前置通知,在方法执行之前
@Before(value = "@annotation(Permission)")
public void PermissionCheck(JoinPoint joinPoint) throws PermissionException {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
.getRequestAttributes()).getRequest();
logger.info("======开始权限校验======");
// 用户token
String token = (String) request.getHeader("token");
token = ObjectUtils.isEmpty(token) ? (String) request.getHeader("X-Access-Token") : token;
String product = (String) request.getHeader("product");
String appKey = (String) request.getHeader("appKey");
logger.info("用户token:" + token);
RequestContext.setToken(token);
RequestContext.setProduct(product);
RequestContext.setAppKey(appKey);
if (!TokenOperation.refresh(token)) {
throw new PermissionException("登录信息失效,请重新登录");
}
if (joinPoint.getSignature().getName().equals("saveCurCompany")) {
return;
}
FeignClientResult feignClientResult;
AgencyUserModel userModel=null;
try {
feignClientResult = Privilege.agencyUserClient.getme();
userModel = (AgencyUserModel) feignClientResult.getResult();
} catch (InnerInvokException e) {
e.printStackTrace();
}
String userId = null;
ReginParams regionParam = new ReginParams();
if(userModel != null){
userId = userModel.getUserId();
ReginParams reginParams = JSON.parseObject(redisTemplate.opsForValue().get(buildKey(userModel.getUserId(), token)), ReginParams.class);
if(reginParams == null && userModel.getCompanys().size() > 0){
CompanyModel companyModel = userModel.getCompanys().get(0);
List<DepartmentModel> deptList = remoteSecurityService.getDepartmentTreeByCompanyId(token, product, appKey, companyModel.getSequenceNbr().toString());
if(deptList.size() > 0){
CompanyBo companyBo = convertCompanyModelToBo(companyModel);
DepartmentBo departmentBo = convertDepartmentModelToBo(deptList.get(0));
regionParam.setCompany(companyBo);
regionParam.setDepartment(departmentBo);
}
Map<Long, List<RoleModel>> orgRoles = userModel.getOrgRoles();
List<RoleModel> roleModels = null;
if(!ObjectUtils.isEmpty(orgRoles)) {
for (Map.Entry<Long, List<RoleModel>> entry : orgRoles.entrySet()) {
roleModels = entry.getValue();
break;
}
}
if(!ObjectUtils.isEmpty(roleModels)){
regionParam.setRole(convertRoleModelToBo(roleModels.get(0)));
}
redisTemplate.opsForValue().set(buildKey(userId, token), JSONObject.toJSONString(regionParam));
}
}
}
private DepartmentBo convertDepartmentModelToBo(DepartmentModel departmentModel){
DepartmentBo departmentBo = new DepartmentBo();
if(departmentModel != null) {
departmentBo.setCompanySeq(departmentModel.getCompanySeq().toString());
departmentBo.setDepartmentDesc(departmentModel.getDepartmentDesc());
departmentBo.setDepartmentName(departmentModel.getDepartmentName());
departmentBo.setLevel(departmentModel.getLevel());
departmentBo.setOrgCode(departmentModel.getOrgCode());
departmentBo.setParentId(departmentModel.getParentId().toString());
departmentBo.setDeptOrgCode(departmentModel.getDeptOrgCode().toString());
departmentBo.setSequenceNbr(departmentModel.getSequenceNbr().toString());
}
return departmentBo;
}
/**
* Model 转 Bo
*/
private CompanyBo convertCompanyModelToBo(CompanyModel companyModel){
CompanyBo companyBo = new CompanyBo();
if(companyModel != null) {
companyBo.setAddress(companyModel.getAddress());
companyBo.setCompanyName(companyModel.getCompanyName());
companyBo.setCompanyOrgCode(Long.parseLong(companyModel.getCompanyOrgCode().toString()));
companyBo.setEmail(companyModel.getEmail());
companyBo.setLandlinePhone(companyModel.getLandlinePhone());
companyBo.setLongitude(companyModel.getLongitude());
companyBo.setLatitude(companyModel.getLatitude());
companyBo.setLevel(companyModel.getLevel());
companyBo.setOrgCode(companyModel.getOrgCode());
companyBo.setSequenceNbr(companyModel.getSequenceNbr().toString());
companyBo.setParentId(companyModel.getParentId().toString());
}
return companyBo;
}
private RoleBo convertRoleModelToBo(RoleModel roleModel) {
RoleBo roleBo = new RoleBo();
if(roleModel != null){
roleBo.setRoleName(roleModel.getRoleName());
roleBo.setRoleType(roleModel.getRoleType());
roleBo.setSequenceNbr(roleModel.getSequenceNbr().toString());
}
return roleBo;
}
//redi缓存选择的用户信息
private String buildKey(String userId, String token) {
return "region_" + userId + "_" + token;
}
}
package com.yeejoin.amos.fas.config;
import javax.servlet.http.HttpServletRequest;
import com.yeejoin.amos.component.feign.config.InnerInvokException;
import com.yeejoin.amos.fas.business.action.mq.WebMqttSubscribe;
import com.yeejoin.amos.fas.business.feign.RemoteSecurityService;
import com.yeejoin.amos.fas.business.vo.DepartmentBo;
import com.yeejoin.amos.fas.business.vo.RoleBo;
import com.yeejoin.amos.feign.privilege.model.DepartmentModel;
import com.yeejoin.amos.feign.privilege.model.RoleModel;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.typroject.tyboot.core.foundation.context.RequestContext;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yeejoin.amos.component.feign.config.TokenOperation;
import com.yeejoin.amos.component.feign.model.FeignClientResult;
import com.yeejoin.amos.fas.business.vo.CompanyBo;
import com.yeejoin.amos.fas.business.vo.ReginParams;
import com.yeejoin.amos.fas.exception.PermissionException;
import com.yeejoin.amos.feign.privilege.Privilege;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import com.yeejoin.amos.feign.privilege.model.CompanyModel;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
@Aspect
@Component
@ResponseBody
public class PermissionAspect {
private static final Logger logger = LoggerFactory.getLogger(PermissionAspect.class);
@Autowired
private RedisTemplate<String, String> redisTemplate;
@Autowired
private RemoteSecurityService remoteSecurityService;
// 前置通知,在方法执行之前
@Before(value = "@annotation(Permission)")
public void PermissionCheck(JoinPoint joinPoint) throws PermissionException {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
.getRequestAttributes()).getRequest();
logger.info("======开始权限校验======");
// 用户token
String token = (String) request.getHeader("token");
token = ObjectUtils.isEmpty(token) ? (String) request.getHeader("X-Access-Token") : token;
String product = (String) request.getHeader("product");
String appKey = (String) request.getHeader("appKey");
logger.info("用户token:" + token);
RequestContext.setToken(token);
RequestContext.setProduct(product);
RequestContext.setAppKey(appKey);
if (!TokenOperation.refresh(token)) {
throw new PermissionException("登录信息失效,请重新登录");
}
if (joinPoint.getSignature().getName().equals("saveCurCompany")) {
return;
}
FeignClientResult feignClientResult;
AgencyUserModel userModel=null;
try {
feignClientResult = Privilege.agencyUserClient.getme();
userModel = (AgencyUserModel) feignClientResult.getResult();
} catch (InnerInvokException e) {
e.printStackTrace();
}
String userId = null;
ReginParams regionParam = new ReginParams();
if(userModel != null){
userId = userModel.getUserId();
ReginParams reginParams = JSON.parseObject(redisTemplate.opsForValue().get(buildKey(userModel.getUserId(), token)), ReginParams.class);
if(reginParams == null && userModel.getCompanys().size() > 0){
CompanyModel companyModel = userModel.getCompanys().get(0);
List<DepartmentModel> deptList = remoteSecurityService.getDepartmentTreeByCompanyId(token, product, appKey, companyModel.getSequenceNbr().toString());
if(deptList.size() > 0){
CompanyBo companyBo = convertCompanyModelToBo(companyModel);
DepartmentBo departmentBo = convertDepartmentModelToBo(deptList.get(0));
regionParam.setCompany(companyBo);
regionParam.setDepartment(departmentBo);
}
Map<Long, List<RoleModel>> orgRoles = userModel.getOrgRoles();
List<RoleModel> roleModels = null;
if(!ObjectUtils.isEmpty(orgRoles)) {
for (Map.Entry<Long, List<RoleModel>> entry : orgRoles.entrySet()) {
roleModels = entry.getValue();
break;
}
}
if(!ObjectUtils.isEmpty(roleModels)){
regionParam.setRole(convertRoleModelToBo(roleModels.get(0)));
}
redisTemplate.opsForValue().set(buildKey(userId, token), JSONObject.toJSONString(regionParam));
}
}
}
private DepartmentBo convertDepartmentModelToBo(DepartmentModel departmentModel){
DepartmentBo departmentBo = new DepartmentBo();
if(departmentModel != null) {
departmentBo.setCompanySeq(departmentModel.getCompanySeq().toString());
departmentBo.setDepartmentDesc(departmentModel.getDepartmentDesc());
departmentBo.setDepartmentName(departmentModel.getDepartmentName());
departmentBo.setLevel(departmentModel.getLevel());
departmentBo.setOrgCode(departmentModel.getOrgCode());
departmentBo.setParentId(departmentModel.getParentId().toString());
departmentBo.setDeptOrgCode(departmentModel.getDeptOrgCode().toString());
departmentBo.setSequenceNbr(departmentModel.getSequenceNbr().toString());
}
return departmentBo;
}
/**
* Model 转 Bo
*/
private CompanyBo convertCompanyModelToBo(CompanyModel companyModel){
CompanyBo companyBo = new CompanyBo();
if(companyModel != null) {
companyBo.setAddress(companyModel.getAddress());
companyBo.setCompanyName(companyModel.getCompanyName());
companyBo.setCompanyOrgCode(Long.parseLong(companyModel.getCompanyOrgCode().toString()));
companyBo.setEmail(companyModel.getEmail());
companyBo.setLandlinePhone(companyModel.getLandlinePhone());
companyBo.setLongitude(companyModel.getLongitude());
companyBo.setLatitude(companyModel.getLatitude());
companyBo.setLevel(companyModel.getLevel());
companyBo.setOrgCode(companyModel.getOrgCode());
companyBo.setSequenceNbr(companyModel.getSequenceNbr().toString());
companyBo.setParentId(companyModel.getParentId().toString());
}
return companyBo;
}
private RoleBo convertRoleModelToBo(RoleModel roleModel) {
RoleBo roleBo = new RoleBo();
if(roleModel != null){
roleBo.setRoleName(roleModel.getRoleName());
roleBo.setRoleType(roleModel.getRoleType());
roleBo.setSequenceNbr(roleModel.getSequenceNbr().toString());
}
return roleBo;
}
//redi缓存选择的用户信息
private String buildKey(String userId, String token) {
return "region_" + userId + "_" + token;
}
}
security.password=a1234560
security.loginId=fas_autosys
security.productWeb=CONVERTER_STATION_WEB
security.appKeyWeb=CONVERTER_STATION
#environment
#spring.profiles.active = dev
eureka.client.serviceUrl.defaultZone=http://172.16.10.72:10001/eureka/
eureka.client.register-with-eureka = true
eureka.client.fetch-registry = true
eureka.client.healthcheck.enabled = true
eureka.client.fetchRegistry = true
eureka.instance.prefer-ip-address=true
#DB properties:
spring.datasource.url=jdbc:mysql://172.16.11.33:3306/safety-business-2.0-36?allowMultiQueries=true&serverTimezone=GMT%2B8&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=admin_1234
spring.datasource.driver-class-name = com.mysql.jdbc.Driver
spring.datasource.hikari.maxLifetime = 1765000
spring.datasource.hikari.maximum-pool-size = 10
spring.datasource.testWhileIdle = true
spring.datasource.validationQuery = SELECT 1
#mongodb
spring.data.mongodb.uri = mongodb://172.16.11.33:27017/iecmonitor
#rule
#params.remoteRuleUrl=http://172.16.3.3:8080/
params.remoteRuleUrl=http://magintursh.xicp.net:18080/
params.remoteWebsocketUrl=http://172.16.11.36:10600/
spring.redis.database=0
spring.redis.host=172.16.10.85
spring.redis.port=6379
spring.redis.password=amos2019Redis
spring.redis.jedis.pool.max-active=200
spring.redis.jedis.pool.max-wait=-1
spring.redis.jedis.pool.max-idle=10
spring.redis.jedis.pool.min-idle=0
spring.redis.timeout=1000
#picture upload
file.uploadUrl=F:\\upload\\files\\
#picture read
file.readUrl=http://172.16.3.89:8083/file/getFile?in=
params.isPush=true
## emqx
emqx.clean-session=true
emqx.client-id=${spring.application.name}-${random.int[1024,65536]}
emqx.broker=tcp://172.16.10.85:1883
emqx.user-name=super
emqx.password=a123456
# 只用于初始化
emqx.defaultTopic=mqtt_topic
Push.fegin.name=APPMESSAGEPUSHSERVICE-36
dutyMode.fegin.name=AMOSDUTYMODE
##\u89C4\u5219\u5BF9\u8C61\u81EA\u52A8\u626B\u63CF
rule.definition.load=true
rule.definition.model-package=com.yeejoin.amos.fas.business.action.model
rule.definition.default-agency=STATE_GRID
#Fegin service config
amos.feign.gennerator.use-gateway=true
autoSys.push.type=mqtt
#�����
file.downLoad.url=http://39.98.246.31:8888/
#站端名称使用全拼
station.name = yinan
security.password=a1234560
security.loginId=fas_autosys
security.productWeb=CONVERTER_STATION_WEB
security.appKeyWeb=CONVERTER_STATION
#environment
#spring.profiles.active = dev
eureka.client.serviceUrl.defaultZone=http://172.16.10.72:10001/eureka/
eureka.client.register-with-eureka = true
eureka.client.fetch-registry = true
eureka.client.healthcheck.enabled = true
eureka.client.fetchRegistry = true
eureka.instance.prefer-ip-address=true
#DB properties:
spring.datasource.url=jdbc:mysql://172.16.11.33:3306/safety-business-2.0-36?allowMultiQueries=true&serverTimezone=GMT%2B8&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=admin_1234
spring.datasource.driver-class-name = com.mysql.jdbc.Driver
spring.datasource.hikari.maxLifetime = 1765000
spring.datasource.hikari.maximum-pool-size = 10
spring.datasource.testWhileIdle = true
spring.datasource.validationQuery = SELECT 1
#mongodb
spring.data.mongodb.uri = mongodb://172.16.11.33:27017/iecmonitor
#rule
#params.remoteRuleUrl=http://172.16.3.3:8080/
params.remoteRuleUrl=http://magintursh.xicp.net:18080/
params.remoteWebsocketUrl=http://172.16.11.36:10600/
spring.redis.database=0
spring.redis.host=172.16.10.85
spring.redis.port=6379
spring.redis.password=amos2019Redis
spring.redis.jedis.pool.max-active=200
spring.redis.jedis.pool.max-wait=-1
spring.redis.jedis.pool.max-idle=10
spring.redis.jedis.pool.min-idle=0
spring.redis.timeout=1000
#picture upload
file.uploadUrl=F:\\upload\\files\\
#picture read
file.readUrl=http://172.16.3.89:8083/file/getFile?in=
params.isPush=true
## emqx
emqx.clean-session=true
emqx.client-id=${spring.application.name}-${random.int[1024,65536]}
emqx.broker=tcp://172.16.10.85:1883
emqx.user-name=super
emqx.password=a123456
# 只用于初始化
emqx.defaultTopic=mqtt_topic
Push.fegin.name=APPMESSAGEPUSHSERVICE-36
dutyMode.fegin.name=AMOSDUTYMODE
##\u89C4\u5219\u5BF9\u8C61\u81EA\u52A8\u626B\u63CF
rule.definition.load=true
rule.definition.model-package=com.yeejoin.amos.fas.business.action.model
rule.definition.default-agency=STATE_GRID
#Fegin service config
amos.feign.gennerator.use-gateway=true
autoSys.push.type=mqtt
#�����
file.downLoad.url=http://39.98.246.31:8888/
#站端名称使用全拼
station.name = yinan
<?xml version="1.0" encoding="utf-8"?>
<databaseChangeLog
xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog
http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.4.xsd">
<changeSet author="suhuiguang" id="1587349916716-1">
<preConditions onFail="MARK_RAN">
<not>
<columnExists tableName="f_risk_source" columnName="ue4_location"/>
</not>
</preConditions>
<comment>f_risk_source add column ue4_location</comment>
<sql>
alter table `f_risk_source` add column `ue4_location` text default null comment 'ue4位置' after `position3d`;
</sql>
</changeSet>
<changeSet author="suhuiguang" id="1587349916716-2">
<preConditions onFail="MARK_RAN">
<not>
<columnExists tableName="f_risk_source" columnName="ue4_rotation"/>
</not>
</preConditions>
<comment>f_risk_source add column ue4_rotation</comment>
<sql>
alter table `f_risk_source` add column `ue4_rotation` text default null comment 'ue4旋转' after `position3d`;
</sql>
</changeSet>
<changeSet author="suhuiguang" id="1587349916716-3">
<preConditions onFail="MARK_RAN">
<not>
<columnExists tableName="f_risk_source" columnName="ue4_extent"/>
</not>
</preConditions>
<comment>f_risk_source add column ue4_extent</comment>
<sql>
alter table `f_risk_source` add column `ue4_extent` text default null comment 'ue4缩放' after `position3d`;
</sql>
</changeSet>
<changeSet author="suhuiguang" id="1587351415717-1">
<preConditions onFail="MARK_RAN">
<not>
<columnExists tableName="f_equipment" columnName="ue4_location"/>
</not>
</preConditions>
<comment>f_equipment add column ue4_location</comment>
<sql>
alter table `f_equipment` add column `ue4_location` text default null comment 'ue4位置' after `position3d`;
</sql>
</changeSet>
<changeSet author="suhuiguang" id="1587351415717-2">
<preConditions onFail="MARK_RAN">
<not>
<columnExists tableName="f_equipment" columnName="ue4_rotation"/>
</not>
</preConditions>
<comment>f_equipment add column ue4_rotation</comment>
<sql>
alter table `f_equipment` add column `ue4_rotation` text default null comment 'ue4旋转' after `position3d`;
</sql>
</changeSet>
<changeSet author="suhuiguang" id="1587350445716-1">
<preConditions onFail="MARK_RAN">
<not>
<columnExists tableName="f_fire_car" columnName="ue4_location"/>
</not>
</preConditions>
<comment>f_fire_car add column ue4_location</comment>
<sql>
alter table `f_fire_car` add column `ue4_location` text default null comment 'ue4位置' after `position3d`;
</sql>
</changeSet>
<changeSet author="suhuiguang" id="1587350445716-2">
<preConditions onFail="MARK_RAN">
<not>
<columnExists tableName="f_fire_car" columnName="ue4_rotation"/>
</not>
</preConditions>
<comment>f_fire_car add column ue4_rotation</comment>
<sql>
alter table `f_fire_car` add column `ue4_rotation` text default null comment 'ue4旋转' after `position3d`;
</sql>
</changeSet>
<changeSet author="suhuiguang" id="1587350552716-1">
<preConditions onFail="MARK_RAN">
<not>
<columnExists tableName="f_fire_equipment" columnName="ue4_location"/>
</not>
</preConditions>
<comment>f_fire_equipment add column ue4_location</comment>
<sql>
alter table `f_fire_equipment` add column `ue4_location` text default null comment 'ue4位置' after `position3d`;
</sql>
</changeSet>
<changeSet author="suhuiguang" id="1587350552716-2">
<preConditions onFail="MARK_RAN">
<not>
<columnExists tableName="f_fire_equipment" columnName="ue4_rotation"/>
</not>
</preConditions>
<comment>f_fire_equipment add column ue4_rotation</comment>
<sql>
alter table `f_fire_equipment` add column `ue4_rotation` text default null comment 'ue4旋转' after `position3d`;
</sql>
</changeSet>
<changeSet author="suhuiguang" id="1587350593716-1">
<preConditions onFail="MARK_RAN">
<not>
<columnExists tableName="f_fire_station" columnName="ue4_location"/>
</not>
</preConditions>
<comment>f_fire_station add column ue4_location</comment>
<sql>
alter table `f_fire_station` add column `ue4_location` text default null comment 'ue4位置' after `position3d`;
</sql>
</changeSet>
<changeSet author="suhuiguang" id="1587350593716-2">
<preConditions onFail="MARK_RAN">
<not>
<columnExists tableName="f_fire_station" columnName="ue4_rotation"/>
</not>
</preConditions>
<comment>f_fire_station add column ue4_rotation</comment>
<sql>
alter table `f_fire_station` add column `ue4_rotation` text default null comment 'ue4旋转' after `position3d`;
</sql>
</changeSet>
<changeSet author="suhuiguang" id="1587350759717-1">
<preConditions onFail="MARK_RAN">
<not>
<columnExists tableName="f_water_resource" columnName="ue4_location"/>
</not>
</preConditions>
<comment>f_water_resource add column ue4_location</comment>
<sql>
alter table `f_water_resource` add column `ue4_location` text default null comment 'ue4位置' after `position3d`;
</sql>
</changeSet>
<changeSet author="suhuiguang" id="1587350759717-2">
<preConditions onFail="MARK_RAN">
<not>
<columnExists tableName="f_water_resource" columnName="ue4_rotation"/>
</not>
</preConditions>
<comment>f_water_resource add column ue4_rotation</comment>
<sql>
alter table `f_water_resource` add column `ue4_rotation` text default null comment 'ue4旋转' after `position3d`;
</sql>
</changeSet>
<changeSet author="suhuiguang" id="1587350860716-1">
<preConditions onFail="MARK_RAN">
<not>
<tableExists tableName="f_safety_index_change_log"/>
</not>
</preConditions>
<comment>create f_safety_index_change_log</comment>
<sql>
create table f_safety_index_change_log
(
id bigint(20) not null auto_increment comment '物理主键',
safety_index decimal(4,1) comment '安全指数',
collect_date date comment '统计日期',
org_code varchar(100) comment '机构',
remark varchar(255) comment '备注',
primary key (id)
);
alter table f_safety_index_change_log comment '安全指数日流水';
create index Index_org_code on f_safety_index_change_log
(
org_code
);
</sql>
</changeSet>
<changeSet id="1587882668719-1" author="suhuiguang">
<preConditions onFail="MARK_RAN">
<not>
<indexExists indexName="idx_type"/>
</not>
</preConditions>
<createIndex
indexName="idx_type"
tableName="f_fire_station"
tablespace="A String"
unique="false">
<column name="type"/>
</createIndex>
</changeSet>
<changeSet author="shanqiyun" id="1588067351000-1">
<preConditions onFail="MARK_RAN">
<not>
<columnExists tableName="f_risk_source" columnName="route_path"/>
</not>
</preConditions>
<comment>f_risk_source add column route_path </comment>
<sql>
alter table f_risk_source add column `route_path` varchar(2000) DEFAULT NULL COMMENT '路径坐标' after `position3d`;
</sql>
</changeSet>
<changeSet author="suhuiguang" id="1588140925893-1">
<preConditions onFail="MARK_RAN">
<not>
<columnExists tableName="f_safety_index_change_log" columnName="create_date"/>
</not>
</preConditions>
<comment>f_safety_index_change_log add column create_date</comment>
<sql>
alter table `f_safety_index_change_log` add column `create_date` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '创建时间';
</sql>
</changeSet>
<changeSet author="suhuiguang" id="1588990926789-1">
<preConditions onFail="MARK_RAN">
<not>
<columnExists tableName="f_risk_level " columnName="manage_level"/>
</not>
</preConditions>
<comment>f_risk_level add column manage_level 管控级别</comment>
<sql>
ALTER TABLE `f_risk_level`
add COLUMN `manage_level` tinyint(4) DEFAULT NULL COMMENT '管控级别';
</sql>
</changeSet>
<changeSet author="suhuiguang" id="1589165258908-1">
<preConditions onFail="MARK_RAN">
<not>
<columnExists tableName="f_rpn_change_log " columnName="trigger_type"/>
</not>
</preConditions>
<comment>f_rpn_change_log add column trigger_type 触发类型</comment>
<sql>
ALTER TABLE `f_rpn_change_log`
add COLUMN `trigger_type` varchar(20) DEFAULT NULL COMMENT '触发类型:巡检、告警、评价、删除' after `trigger_by`;
</sql>
</changeSet>
<changeSet author="suhuiguang" id="1589165258908-2">
<preConditions onFail="MARK_RAN">
<not>
<columnExists tableName="f_risk_source " columnName="flicker_frequency"/>
</not>
</preConditions>
<comment>f_risk_source add column flicker_frequency 闪烁频率</comment>
<sql>
ALTER TABLE `f_risk_source`
add COLUMN `flicker_frequency` int(11) DEFAULT 0 COMMENT '闪烁频率' after `status`;
</sql>
</changeSet>
<changeSet author="maoying" id="1589444792914-1">
<preConditions onFail="MARK_RAN">
<tableExists tableName="f_alarm"/>
</preConditions>
<comment>create table f_alarm</comment>
<sql>
DROP TABLE IF EXISTS f_alarm;
CREATE TABLE `f_alarm` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键',
`org_code` varchar(100) NOT NULL COMMENT '机构编号',
`fire_equipment_id` bigint(20) NOT NULL DEFAULT '0' COMMENT '消防设备id',
`fire_equipment_code` varchar(255) NOT NULL COMMENT '设备编码',
`fire_equipment_name` varchar(255) NOT NULL COMMENT '设备名称',
`fire_equipment_point_id` bigint(20) NOT NULL COMMENT '消防点位id',
`fire_equipment_point_code` varchar(255) NOT NULL COMMENT '消防点位名称',
`fire_equipment_point_name` varchar(255) NOT NULL,
`fire_equipment_point_value` varchar(500) DEFAULT NULL COMMENT '报警值',
`frequency` int(10) NOT NULL DEFAULT '1' COMMENT '发生频次',
`status` bit(1) DEFAULT b'1' COMMENT '报警状态:1报警0恢复',
`type` varchar(50) NOT NULL COMMENT '报警类型:alarm_type_fire(火灾报警)/alarm_type_trouble(故障告警)',
`create_date` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_date` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
`recovery_date` datetime DEFAULT NULL COMMENT '告警恢复时间',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='报警信息表';
</sql>
</changeSet>
<changeSet author="zhouyi" id="1589444792916-1">
<preConditions onFail="MARK_RAN">
<tableExists tableName="f_station_info"/>
</preConditions>
<comment>create table f_station_info</comment>
<sql>
DROP TABLE IF EXISTS f_station_info;
CREATE TABLE `f_station_info` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键',
`name` varchar(20) DEFAULT NULL COMMENT '名称',
`station_code` varchar(32) NOT NULL COMMENT '环流站编码',
`code` varchar(10) DEFAULT NULL COMMENT '后三位编码',
`elec_type` tinyint(4) DEFAULT NULL COMMENT '换流站类型:1-发电类型;2-收电类型',
`use_type` tinyint(4) NOT NULL COMMENT '用途类型:1-电厂升压变电站;2-公用普通变电站;3-公用换流变电站;4-企业自备变电站;5-其他',
`province_code` varchar(32) DEFAULT NULL COMMENT '省份编码',
`city_code` varchar(32) DEFAULT NULL COMMENT '市区编码',
`district_code` varchar(32) DEFAULT NULL COMMENT '区县编码',
`address` varchar(255) DEFAULT NULL COMMENT '详细地址',
`status` bit(1) NOT NULL DEFAULT b'0' COMMENT '0-启用;1-停用',
`longitude` double DEFAULT NULL COMMENT '经度',
`latitude` double DEFAULT NULL COMMENT '纬度',
`station_charge_user_id` varchar(50) DEFAULT NULL COMMENT '换流站负责人',
`safety_charge_user_id` varchar(50) DEFAULT NULL COMMENT '安全负责人',
`create_date` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '创建日期',
`create_by` varchar(255) DEFAULT NULL COMMENT '创建人',
`remark` varchar(255) DEFAULT NULL COMMENT '备注',
PRIMARY KEY (`id`),
UNIQUE KEY `f_station_info_uniq` (`station_code`)
) ENGINE=InnoDB AUTO_INCREMENT=18 DEFAULT CHARSET=utf8mb4 COMMENT='站端信息表';
</sql>
</changeSet>
<changeSet author="suhuiguang" id="1589769364577-1">
<preConditions onFail="MARK_RAN">
<columnExists tableName="f_risk_level " columnName="manage_level"/>
</preConditions>
<comment>f_risk_level 增加管控级别 初始化数据</comment>
<sql>
update f_risk_level set manage_level = 1 where level = '1';
update f_risk_level set manage_level = 2 where level = '2';
update f_risk_level set manage_level = 3 where level = '3';
update f_risk_level set manage_level = 4 where level = '4';
</sql>
</changeSet>
<changeSet author="maoying" id="11590390304001-1">
<preConditions onFail="MARK_RAN">
<columnExists tableName="f_fire_equipment_point " columnName="fire_equipment_id"/>
</preConditions>
<comment>修改fire_equipment_id可为空</comment>
<sql>
ALTER TABLE `f_fire_equipment_point`
MODIFY COLUMN `fire_equipment_id` bigint(20) NULL COMMENT '消防装备id' AFTER `code`;
</sql>
</changeSet>
<changeSet author="shanqiyun" id="1591672147780-1">
<preConditions onFail="MARK_RAN">
<viewExists viewName="toip_biz_message"/>
</preConditions>
<comment>create view toip_biz_message</comment>
<sql>
DROP VIEW IF EXISTS toip_biz_message;
CREATE ALGORITHM = UNDEFINED DEFINER = `root` @`%` SQL SECURITY DEFINER VIEW `toip_biz_message` AS SELECT
`m`.`id` AS `id`,
`m`.`time` AS `time`,
`m`.`content` AS `content`,
`m`.`title` AS `title`,
`m`.`type` AS `type`,
`m`.`sender` AS `sender`,
`m`.`receiver` AS `receiver`,
`m`.`reader` AS `reader`,
`m`.`biz_id` AS `biz_id`,
`m`.`bizclass_name` AS `bizclass_name`,
`n`.`org_code` AS `org_code`
FROM
( `toip_sys_message` `m` JOIN `f_equipment` `n` )
WHERE
( ( `n`.`id` = `m`.`biz_id` ) AND ( `m`.`bizclass_name` = 'class com.yeejoin.amos.fas.business.service.model.FireEquimentDataRo' ) ) UNION ALL
SELECT
`m`.`id` AS `id`,
`m`.`time` AS `time`,
`m`.`content` AS `content`,
`m`.`title` AS `title`,
`m`.`type` AS `type`,
`m`.`sender` AS `sender`,
`m`.`receiver` AS `receiver`,
`m`.`reader` AS `reader`,
`m`.`biz_id` AS `biz_id`,
`m`.`bizclass_name` AS `bizclass_name`,
`n`.`org_code` AS `org_code`
FROM
( `toip_sys_message` `m` JOIN `p_point` `n` )
WHERE
( ( `n`.`id` = `m`.`biz_id` ) AND ( `m`.`bizclass_name` = 'class com.yeejoin.amos.fas.business.service.model.ProtalDataRo' ) ) UNION ALL
SELECT
`m`.`id` AS `id`,
`m`.`time` AS `time`,
`m`.`content` AS `content`,
`m`.`title` AS `title`,
`m`.`type` AS `type`,
`m`.`sender` AS `sender`,
`m`.`receiver` AS `receiver`,
`m`.`reader` AS `reader`,
`m`.`biz_id` AS `biz_id`,
`m`.`bizclass_name` AS `bizclass_name`,
`n`.`org_code` AS `org_code`
FROM
( `toip_sys_message` `m` JOIN `f_risk_source` `n` )
WHERE
( ( `n`.`id` = `m`.`biz_id` ) AND ( `m`.`bizclass_name` = 'class com.yeejoin.amos.fas.business.service.model.RiskSourceRuleRo' ) );
</sql>
</changeSet>
<changeSet author="shanqiyun" id="1593309428780-1">
<preConditions onFail="MARK_RAN">
<not>
<tableExists tableName="contingency_original_data" />
</not>
</preConditions>
<comment>create table contingency_original_data</comment>
<sql>
DROP TABLE IF EXISTS contingency_original_data;
CREATE TABLE `contingency_original_data` (
`id` varchar(36) NOT NULL COMMENT 'rule',
`fire_Equipment_Name` varchar(32) NOT NULL COMMENT '记录类型:消息MESSAGE,操作OPERATE',
`fire_Equipment_Id` varchar(500) NOT NULL COMMENT '记录内容:文本信息或者json数据',
`layer` int(11) NOT NULL COMMENT '一级分类',
`fire_Equipment_Layer` int(11) NOT NULL COMMENT '二级分类',
`fire_Equipment_Position` varchar(255) DEFAULT NULL COMMENT '图标,url,或者文件名',
`equipment_Id` int(11) NOT NULL COMMENT '排序',
`equipment_Name` varchar(255) DEFAULT NULL,
`mobile` varchar(255) DEFAULT NULL,
`admin_Name` varchar(255) DEFAULT NULL,
`camera_Codes` varchar(255) DEFAULT NULL,
`camera_Ids` varchar(255) DEFAULT NULL,
`fire_Count` int(11) DEFAULT NULL,
`confirm` varchar(255) DEFAULT NULL,
`create_date` datetime DEFAULT NULL,
`create_user` varchar(50) DEFAULT NULL,
`update_date` datetime DEFAULT NULL,
`update_user` varchar(50) DEFAULT NULL,
`is_delete` bit(1) DEFAULT NULL,
`batch_No` varchar(36) NOT NULL,
`picture1` varchar(255) DEFAULT NULL,
`picture2` varchar(255) DEFAULT NULL,
`picture4` varchar(255) DEFAULT NULL,
`picture3` varchar(255) DEFAULT NULL,
`fire_Truck_Route` varchar(2000) DEFAULT NULL,
`runstep` bit(1) DEFAULT NULL,
`step_state` varchar(255) DEFAULT NULL,
`step` varchar(255) DEFAULT NULL,
`equipment_position3d` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `INDEX_BATCH_NO` (`batch_No`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='应急预案信息节点定义';
</sql>
</changeSet>
<changeSet author="shanqiyun" id="1593309428780-2">
<preConditions onFail="MARK_RAN">
<not>
<tableExists tableName="contingency_plan" />
</not>
</preConditions>
<comment>create table contingency_plan</comment>
<sql>
DROP TABLE IF EXISTS contingency_plan;
CREATE TABLE `contingency_plan` (
`id` varchar(36) NOT NULL COMMENT 'rule',
`record_type` varchar(32) NOT NULL COMMENT '记录类型:消息MESSAGE,操作OPERATE',
`content` varchar(500) NOT NULL COMMENT '记录内容:文本信息或者json数据',
`category` varchar(36) NOT NULL COMMENT '一级分类',
`sub_category` varchar(36) NOT NULL COMMENT '二级分类',
`icon` varchar(255) DEFAULT NULL COMMENT '图标,url,或者文件名',
`sort` int(11) NOT NULL COMMENT '排序',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='应急预案信息节点定义';
</sql>
</changeSet>
<changeSet author="shanqiyun" id="1593309428780-3">
<preConditions onFail="MARK_RAN">
<not>
<tableExists tableName="contingency_plan_instance" />
</not>
</preConditions>
<comment>create table contingency_plan_instance</comment>
<sql>
DROP TABLE IF EXISTS contingency_plan_instance;
CREATE TABLE `contingency_plan_instance` (
`id` varchar(36) NOT NULL COMMENT 'rule',
`record_type` varchar(32) NOT NULL COMMENT '记录类型:消息MESSAGE,操作OPERATE',
`category` varchar(36) DEFAULT NULL COMMENT '一级分类',
`content` varchar(2000) NOT NULL COMMENT '记录内容:文本信息或者json数据',
`icon` varchar(255) DEFAULT NULL COMMENT '图标,url,或者文件名',
`sort` int(11) DEFAULT NULL COMMENT '所有节点一起的排序号',
`sequence_num` int(11) DEFAULT NULL COMMENT '用于显示的序号',
`batch_no` varchar(36) NOT NULL COMMENT '预案实例编号,暂时无法区分多个火灾,暂时存储报警设备id',
`create_date` datetime DEFAULT NULL,
`create_user` varchar(50) DEFAULT NULL,
`update_date` datetime DEFAULT NULL,
`update_user` varchar(50) DEFAULT NULL,
`is_delete` bit(1) DEFAULT NULL,
`tips` varchar(255) DEFAULT NULL,
`runstate` bit(1) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='应急预案执行记录实例';
</sql>
</changeSet>
<changeSet author="keyong" id="1605924681-1">
<preConditions onFail="MARK_RAN">
<not>
<columnExists tableName="f_station_info" columnName="station_charge_user_name" />
</not>
</preConditions>
<comment>修改f_station_info表结构</comment>
<sql>
ALTER TABLE `f_station_info` ADD COLUMN `station_charge_user_name` varchar(20) NULL COMMENT '换流站负责人姓名';
</sql>
</changeSet>
<changeSet author="keyong" id="1605924681-2">
<preConditions onFail="MARK_RAN">
<not>
<columnExists tableName="f_station_info" columnName="safety_charge_user_name" />
</not>
</preConditions>
<comment>修改f_station_info表结构</comment>
<sql>
ALTER TABLE `f_station_info` ADD COLUMN `safety_charge_user_name` varchar(20) NULL COMMENT '安全负责人姓名';
</sql>
</changeSet>
<changeSet author="keyong" id="1605924681-3">
<preConditions onFail="MARK_RAN">
<not>
<columnExists tableName="f_station_info" columnName="create_user_name" />
</not>
</preConditions>
<comment>修改f_station_info表结构</comment>
<sql>
ALTER TABLE `f_station_info` ADD COLUMN `create_user_name` varchar(20) NULL COMMENT '创建人姓名';
</sql>
</changeSet>
<changeSet author="keyong" id="1606290088-1">
<preConditions onFail="MARK_RAN">
<not>
<columnExists tableName="f_station_info" columnName="create_user_phone_num" />
</not>
</preConditions>
<comment>修改f_station_info表结构</comment>
<sql>
ALTER TABLE `f_station_info` ADD COLUMN `create_user_phone_num` varchar(20) NULL COMMENT '创建人联系方式';
</sql>
</changeSet>
<changeSet author="keyong" id="1606290088-2">
<preConditions onFail="MARK_RAN">
<not>
<columnExists tableName="f_station_info" columnName="station_user_phone_num" />
</not>
</preConditions>
<comment>修改f_station_info表结构</comment>
<sql>
ALTER TABLE `f_station_info` ADD COLUMN `station_user_phone_num` varchar(20) NULL COMMENT '换流站负责人联系方式';
</sql>
</changeSet>
<changeSet author="keyong" id="1606290088-3">
<preConditions onFail="MARK_RAN">
<not>
<columnExists tableName="f_station_info" columnName="safety_user_phone_num" />
</not>
</preConditions>
<comment>修改f_station_info表结构</comment>
<sql>
ALTER TABLE `f_station_info` ADD COLUMN `safety_user_phone_num` varchar(20) NULL COMMENT '安全负责人联系方式';
</sql>
</changeSet>
<?xml version="1.0" encoding="utf-8"?>
<databaseChangeLog
xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog
http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.4.xsd">
<changeSet author="suhuiguang" id="1587349916716-1">
<preConditions onFail="MARK_RAN">
<not>
<columnExists tableName="f_risk_source" columnName="ue4_location"/>
</not>
</preConditions>
<comment>f_risk_source add column ue4_location</comment>
<sql>
alter table `f_risk_source` add column `ue4_location` text default null comment 'ue4位置' after `position3d`;
</sql>
</changeSet>
<changeSet author="suhuiguang" id="1587349916716-2">
<preConditions onFail="MARK_RAN">
<not>
<columnExists tableName="f_risk_source" columnName="ue4_rotation"/>
</not>
</preConditions>
<comment>f_risk_source add column ue4_rotation</comment>
<sql>
alter table `f_risk_source` add column `ue4_rotation` text default null comment 'ue4旋转' after `position3d`;
</sql>
</changeSet>
<changeSet author="suhuiguang" id="1587349916716-3">
<preConditions onFail="MARK_RAN">
<not>
<columnExists tableName="f_risk_source" columnName="ue4_extent"/>
</not>
</preConditions>
<comment>f_risk_source add column ue4_extent</comment>
<sql>
alter table `f_risk_source` add column `ue4_extent` text default null comment 'ue4缩放' after `position3d`;
</sql>
</changeSet>
<changeSet author="suhuiguang" id="1587351415717-1">
<preConditions onFail="MARK_RAN">
<not>
<columnExists tableName="f_equipment" columnName="ue4_location"/>
</not>
</preConditions>
<comment>f_equipment add column ue4_location</comment>
<sql>
alter table `f_equipment` add column `ue4_location` text default null comment 'ue4位置' after `position3d`;
</sql>
</changeSet>
<changeSet author="suhuiguang" id="1587351415717-2">
<preConditions onFail="MARK_RAN">
<not>
<columnExists tableName="f_equipment" columnName="ue4_rotation"/>
</not>
</preConditions>
<comment>f_equipment add column ue4_rotation</comment>
<sql>
alter table `f_equipment` add column `ue4_rotation` text default null comment 'ue4旋转' after `position3d`;
</sql>
</changeSet>
<changeSet author="suhuiguang" id="1587350445716-1">
<preConditions onFail="MARK_RAN">
<not>
<columnExists tableName="f_fire_car" columnName="ue4_location"/>
</not>
</preConditions>
<comment>f_fire_car add column ue4_location</comment>
<sql>
alter table `f_fire_car` add column `ue4_location` text default null comment 'ue4位置' after `position3d`;
</sql>
</changeSet>
<changeSet author="suhuiguang" id="1587350445716-2">
<preConditions onFail="MARK_RAN">
<not>
<columnExists tableName="f_fire_car" columnName="ue4_rotation"/>
</not>
</preConditions>
<comment>f_fire_car add column ue4_rotation</comment>
<sql>
alter table `f_fire_car` add column `ue4_rotation` text default null comment 'ue4旋转' after `position3d`;
</sql>
</changeSet>
<changeSet author="suhuiguang" id="1587350552716-1">
<preConditions onFail="MARK_RAN">
<not>
<columnExists tableName="f_fire_equipment" columnName="ue4_location"/>
</not>
</preConditions>
<comment>f_fire_equipment add column ue4_location</comment>
<sql>
alter table `f_fire_equipment` add column `ue4_location` text default null comment 'ue4位置' after `position3d`;
</sql>
</changeSet>
<changeSet author="suhuiguang" id="1587350552716-2">
<preConditions onFail="MARK_RAN">
<not>
<columnExists tableName="f_fire_equipment" columnName="ue4_rotation"/>
</not>
</preConditions>
<comment>f_fire_equipment add column ue4_rotation</comment>
<sql>
alter table `f_fire_equipment` add column `ue4_rotation` text default null comment 'ue4旋转' after `position3d`;
</sql>
</changeSet>
<changeSet author="suhuiguang" id="1587350593716-1">
<preConditions onFail="MARK_RAN">
<not>
<columnExists tableName="f_fire_station" columnName="ue4_location"/>
</not>
</preConditions>
<comment>f_fire_station add column ue4_location</comment>
<sql>
alter table `f_fire_station` add column `ue4_location` text default null comment 'ue4位置' after `position3d`;
</sql>
</changeSet>
<changeSet author="suhuiguang" id="1587350593716-2">
<preConditions onFail="MARK_RAN">
<not>
<columnExists tableName="f_fire_station" columnName="ue4_rotation"/>
</not>
</preConditions>
<comment>f_fire_station add column ue4_rotation</comment>
<sql>
alter table `f_fire_station` add column `ue4_rotation` text default null comment 'ue4旋转' after `position3d`;
</sql>
</changeSet>
<changeSet author="suhuiguang" id="1587350759717-1">
<preConditions onFail="MARK_RAN">
<not>
<columnExists tableName="f_water_resource" columnName="ue4_location"/>
</not>
</preConditions>
<comment>f_water_resource add column ue4_location</comment>
<sql>
alter table `f_water_resource` add column `ue4_location` text default null comment 'ue4位置' after `position3d`;
</sql>
</changeSet>
<changeSet author="suhuiguang" id="1587350759717-2">
<preConditions onFail="MARK_RAN">
<not>
<columnExists tableName="f_water_resource" columnName="ue4_rotation"/>
</not>
</preConditions>
<comment>f_water_resource add column ue4_rotation</comment>
<sql>
alter table `f_water_resource` add column `ue4_rotation` text default null comment 'ue4旋转' after `position3d`;
</sql>
</changeSet>
<changeSet author="suhuiguang" id="1587350860716-1">
<preConditions onFail="MARK_RAN">
<not>
<tableExists tableName="f_safety_index_change_log"/>
</not>
</preConditions>
<comment>create f_safety_index_change_log</comment>
<sql>
create table f_safety_index_change_log
(
id bigint(20) not null auto_increment comment '物理主键',
safety_index decimal(4,1) comment '安全指数',
collect_date date comment '统计日期',
org_code varchar(100) comment '机构',
remark varchar(255) comment '备注',
primary key (id)
);
alter table f_safety_index_change_log comment '安全指数日流水';
create index Index_org_code on f_safety_index_change_log
(
org_code
);
</sql>
</changeSet>
<changeSet id="1587882668719-1" author="suhuiguang">
<preConditions onFail="MARK_RAN">
<not>
<indexExists indexName="idx_type"/>
</not>
</preConditions>
<createIndex
indexName="idx_type"
tableName="f_fire_station"
tablespace="A String"
unique="false">
<column name="type"/>
</createIndex>
</changeSet>
<changeSet author="shanqiyun" id="1588067351000-1">
<preConditions onFail="MARK_RAN">
<not>
<columnExists tableName="f_risk_source" columnName="route_path"/>
</not>
</preConditions>
<comment>f_risk_source add column route_path </comment>
<sql>
alter table f_risk_source add column `route_path` varchar(2000) DEFAULT NULL COMMENT '路径坐标' after `position3d`;
</sql>
</changeSet>
<changeSet author="suhuiguang" id="1588140925893-1">
<preConditions onFail="MARK_RAN">
<not>
<columnExists tableName="f_safety_index_change_log" columnName="create_date"/>
</not>
</preConditions>
<comment>f_safety_index_change_log add column create_date</comment>
<sql>
alter table `f_safety_index_change_log` add column `create_date` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '创建时间';
</sql>
</changeSet>
<changeSet author="suhuiguang" id="1588990926789-1">
<preConditions onFail="MARK_RAN">
<not>
<columnExists tableName="f_risk_level " columnName="manage_level"/>
</not>
</preConditions>
<comment>f_risk_level add column manage_level 管控级别</comment>
<sql>
ALTER TABLE `f_risk_level`
add COLUMN `manage_level` tinyint(4) DEFAULT NULL COMMENT '管控级别';
</sql>
</changeSet>
<changeSet author="suhuiguang" id="1589165258908-1">
<preConditions onFail="MARK_RAN">
<not>
<columnExists tableName="f_rpn_change_log " columnName="trigger_type"/>
</not>
</preConditions>
<comment>f_rpn_change_log add column trigger_type 触发类型</comment>
<sql>
ALTER TABLE `f_rpn_change_log`
add COLUMN `trigger_type` varchar(20) DEFAULT NULL COMMENT '触发类型:巡检、告警、评价、删除' after `trigger_by`;
</sql>
</changeSet>
<changeSet author="suhuiguang" id="1589165258908-2">
<preConditions onFail="MARK_RAN">
<not>
<columnExists tableName="f_risk_source " columnName="flicker_frequency"/>
</not>
</preConditions>
<comment>f_risk_source add column flicker_frequency 闪烁频率</comment>
<sql>
ALTER TABLE `f_risk_source`
add COLUMN `flicker_frequency` int(11) DEFAULT 0 COMMENT '闪烁频率' after `status`;
</sql>
</changeSet>
<changeSet author="maoying" id="1589444792914-1">
<preConditions onFail="MARK_RAN">
<tableExists tableName="f_alarm"/>
</preConditions>
<comment>create table f_alarm</comment>
<sql>
DROP TABLE IF EXISTS f_alarm;
CREATE TABLE `f_alarm` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键',
`org_code` varchar(100) NOT NULL COMMENT '机构编号',
`fire_equipment_id` bigint(20) NOT NULL DEFAULT '0' COMMENT '消防设备id',
`fire_equipment_code` varchar(255) NOT NULL COMMENT '设备编码',
`fire_equipment_name` varchar(255) NOT NULL COMMENT '设备名称',
`fire_equipment_point_id` bigint(20) NOT NULL COMMENT '消防点位id',
`fire_equipment_point_code` varchar(255) NOT NULL COMMENT '消防点位名称',
`fire_equipment_point_name` varchar(255) NOT NULL,
`fire_equipment_point_value` varchar(500) DEFAULT NULL COMMENT '报警值',
`frequency` int(10) NOT NULL DEFAULT '1' COMMENT '发生频次',
`status` bit(1) DEFAULT b'1' COMMENT '报警状态:1报警0恢复',
`type` varchar(50) NOT NULL COMMENT '报警类型:alarm_type_fire(火灾报警)/alarm_type_trouble(故障告警)',
`create_date` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_date` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
`recovery_date` datetime DEFAULT NULL COMMENT '告警恢复时间',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='报警信息表';
</sql>
</changeSet>
<changeSet author="zhouyi" id="1589444792916-1">
<preConditions onFail="MARK_RAN">
<tableExists tableName="f_station_info"/>
</preConditions>
<comment>create table f_station_info</comment>
<sql>
DROP TABLE IF EXISTS f_station_info;
CREATE TABLE `f_station_info` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键',
`name` varchar(20) DEFAULT NULL COMMENT '名称',
`station_code` varchar(32) NOT NULL COMMENT '环流站编码',
`code` varchar(10) DEFAULT NULL COMMENT '后三位编码',
`elec_type` tinyint(4) DEFAULT NULL COMMENT '换流站类型:1-发电类型;2-收电类型',
`use_type` tinyint(4) NOT NULL COMMENT '用途类型:1-电厂升压变电站;2-公用普通变电站;3-公用换流变电站;4-企业自备变电站;5-其他',
`province_code` varchar(32) DEFAULT NULL COMMENT '省份编码',
`city_code` varchar(32) DEFAULT NULL COMMENT '市区编码',
`district_code` varchar(32) DEFAULT NULL COMMENT '区县编码',
`address` varchar(255) DEFAULT NULL COMMENT '详细地址',
`status` bit(1) NOT NULL DEFAULT b'0' COMMENT '0-启用;1-停用',
`longitude` double DEFAULT NULL COMMENT '经度',
`latitude` double DEFAULT NULL COMMENT '纬度',
`station_charge_user_id` varchar(50) DEFAULT NULL COMMENT '换流站负责人',
`safety_charge_user_id` varchar(50) DEFAULT NULL COMMENT '安全负责人',
`create_date` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '创建日期',
`create_by` varchar(255) DEFAULT NULL COMMENT '创建人',
`remark` varchar(255) DEFAULT NULL COMMENT '备注',
PRIMARY KEY (`id`),
UNIQUE KEY `f_station_info_uniq` (`station_code`)
) ENGINE=InnoDB AUTO_INCREMENT=18 DEFAULT CHARSET=utf8mb4 COMMENT='站端信息表';
</sql>
</changeSet>
<changeSet author="suhuiguang" id="1589769364577-1">
<preConditions onFail="MARK_RAN">
<columnExists tableName="f_risk_level " columnName="manage_level"/>
</preConditions>
<comment>f_risk_level 增加管控级别 初始化数据</comment>
<sql>
update f_risk_level set manage_level = 1 where level = '1';
update f_risk_level set manage_level = 2 where level = '2';
update f_risk_level set manage_level = 3 where level = '3';
update f_risk_level set manage_level = 4 where level = '4';
</sql>
</changeSet>
<changeSet author="maoying" id="11590390304001-1">
<preConditions onFail="MARK_RAN">
<columnExists tableName="f_fire_equipment_point " columnName="fire_equipment_id"/>
</preConditions>
<comment>修改fire_equipment_id可为空</comment>
<sql>
ALTER TABLE `f_fire_equipment_point`
MODIFY COLUMN `fire_equipment_id` bigint(20) NULL COMMENT '消防装备id' AFTER `code`;
</sql>
</changeSet>
<changeSet author="shanqiyun" id="1591672147780-1">
<preConditions onFail="MARK_RAN">
<viewExists viewName="toip_biz_message"/>
</preConditions>
<comment>create view toip_biz_message</comment>
<sql>
DROP VIEW IF EXISTS toip_biz_message;
CREATE ALGORITHM = UNDEFINED DEFINER = `root` @`%` SQL SECURITY DEFINER VIEW `toip_biz_message` AS SELECT
`m`.`id` AS `id`,
`m`.`time` AS `time`,
`m`.`content` AS `content`,
`m`.`title` AS `title`,
`m`.`type` AS `type`,
`m`.`sender` AS `sender`,
`m`.`receiver` AS `receiver`,
`m`.`reader` AS `reader`,
`m`.`biz_id` AS `biz_id`,
`m`.`bizclass_name` AS `bizclass_name`,
`n`.`org_code` AS `org_code`
FROM
( `toip_sys_message` `m` JOIN `f_equipment` `n` )
WHERE
( ( `n`.`id` = `m`.`biz_id` ) AND ( `m`.`bizclass_name` = 'class com.yeejoin.amos.fas.business.service.model.FireEquimentDataRo' ) ) UNION ALL
SELECT
`m`.`id` AS `id`,
`m`.`time` AS `time`,
`m`.`content` AS `content`,
`m`.`title` AS `title`,
`m`.`type` AS `type`,
`m`.`sender` AS `sender`,
`m`.`receiver` AS `receiver`,
`m`.`reader` AS `reader`,
`m`.`biz_id` AS `biz_id`,
`m`.`bizclass_name` AS `bizclass_name`,
`n`.`org_code` AS `org_code`
FROM
( `toip_sys_message` `m` JOIN `p_point` `n` )
WHERE
( ( `n`.`id` = `m`.`biz_id` ) AND ( `m`.`bizclass_name` = 'class com.yeejoin.amos.fas.business.service.model.ProtalDataRo' ) ) UNION ALL
SELECT
`m`.`id` AS `id`,
`m`.`time` AS `time`,
`m`.`content` AS `content`,
`m`.`title` AS `title`,
`m`.`type` AS `type`,
`m`.`sender` AS `sender`,
`m`.`receiver` AS `receiver`,
`m`.`reader` AS `reader`,
`m`.`biz_id` AS `biz_id`,
`m`.`bizclass_name` AS `bizclass_name`,
`n`.`org_code` AS `org_code`
FROM
( `toip_sys_message` `m` JOIN `f_risk_source` `n` )
WHERE
( ( `n`.`id` = `m`.`biz_id` ) AND ( `m`.`bizclass_name` = 'class com.yeejoin.amos.fas.business.service.model.RiskSourceRuleRo' ) );
</sql>
</changeSet>
<changeSet author="shanqiyun" id="1593309428780-1">
<preConditions onFail="MARK_RAN">
<not>
<tableExists tableName="contingency_original_data" />
</not>
</preConditions>
<comment>create table contingency_original_data</comment>
<sql>
DROP TABLE IF EXISTS contingency_original_data;
CREATE TABLE `contingency_original_data` (
`id` varchar(36) NOT NULL COMMENT 'rule',
`fire_Equipment_Name` varchar(32) NOT NULL COMMENT '记录类型:消息MESSAGE,操作OPERATE',
`fire_Equipment_Id` varchar(500) NOT NULL COMMENT '记录内容:文本信息或者json数据',
`layer` int(11) NOT NULL COMMENT '一级分类',
`fire_Equipment_Layer` int(11) NOT NULL COMMENT '二级分类',
`fire_Equipment_Position` varchar(255) DEFAULT NULL COMMENT '图标,url,或者文件名',
`equipment_Id` int(11) NOT NULL COMMENT '排序',
`equipment_Name` varchar(255) DEFAULT NULL,
`mobile` varchar(255) DEFAULT NULL,
`admin_Name` varchar(255) DEFAULT NULL,
`camera_Codes` varchar(255) DEFAULT NULL,
`camera_Ids` varchar(255) DEFAULT NULL,
`fire_Count` int(11) DEFAULT NULL,
`confirm` varchar(255) DEFAULT NULL,
`create_date` datetime DEFAULT NULL,
`create_user` varchar(50) DEFAULT NULL,
`update_date` datetime DEFAULT NULL,
`update_user` varchar(50) DEFAULT NULL,
`is_delete` bit(1) DEFAULT NULL,
`batch_No` varchar(36) NOT NULL,
`picture1` varchar(255) DEFAULT NULL,
`picture2` varchar(255) DEFAULT NULL,
`picture4` varchar(255) DEFAULT NULL,
`picture3` varchar(255) DEFAULT NULL,
`fire_Truck_Route` varchar(2000) DEFAULT NULL,
`runstep` bit(1) DEFAULT NULL,
`step_state` varchar(255) DEFAULT NULL,
`step` varchar(255) DEFAULT NULL,
`equipment_position3d` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `INDEX_BATCH_NO` (`batch_No`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='应急预案信息节点定义';
</sql>
</changeSet>
<changeSet author="shanqiyun" id="1593309428780-2">
<preConditions onFail="MARK_RAN">
<not>
<tableExists tableName="contingency_plan" />
</not>
</preConditions>
<comment>create table contingency_plan</comment>
<sql>
DROP TABLE IF EXISTS contingency_plan;
CREATE TABLE `contingency_plan` (
`id` varchar(36) NOT NULL COMMENT 'rule',
`record_type` varchar(32) NOT NULL COMMENT '记录类型:消息MESSAGE,操作OPERATE',
`content` varchar(500) NOT NULL COMMENT '记录内容:文本信息或者json数据',
`category` varchar(36) NOT NULL COMMENT '一级分类',
`sub_category` varchar(36) NOT NULL COMMENT '二级分类',
`icon` varchar(255) DEFAULT NULL COMMENT '图标,url,或者文件名',
`sort` int(11) NOT NULL COMMENT '排序',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='应急预案信息节点定义';
</sql>
</changeSet>
<changeSet author="shanqiyun" id="1593309428780-3">
<preConditions onFail="MARK_RAN">
<not>
<tableExists tableName="contingency_plan_instance" />
</not>
</preConditions>
<comment>create table contingency_plan_instance</comment>
<sql>
DROP TABLE IF EXISTS contingency_plan_instance;
CREATE TABLE `contingency_plan_instance` (
`id` varchar(36) NOT NULL COMMENT 'rule',
`record_type` varchar(32) NOT NULL COMMENT '记录类型:消息MESSAGE,操作OPERATE',
`category` varchar(36) DEFAULT NULL COMMENT '一级分类',
`content` varchar(2000) NOT NULL COMMENT '记录内容:文本信息或者json数据',
`icon` varchar(255) DEFAULT NULL COMMENT '图标,url,或者文件名',
`sort` int(11) DEFAULT NULL COMMENT '所有节点一起的排序号',
`sequence_num` int(11) DEFAULT NULL COMMENT '用于显示的序号',
`batch_no` varchar(36) NOT NULL COMMENT '预案实例编号,暂时无法区分多个火灾,暂时存储报警设备id',
`create_date` datetime DEFAULT NULL,
`create_user` varchar(50) DEFAULT NULL,
`update_date` datetime DEFAULT NULL,
`update_user` varchar(50) DEFAULT NULL,
`is_delete` bit(1) DEFAULT NULL,
`tips` varchar(255) DEFAULT NULL,
`runstate` bit(1) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='应急预案执行记录实例';
</sql>
</changeSet>
<changeSet author="keyong" id="1605924681-1">
<preConditions onFail="MARK_RAN">
<not>
<columnExists tableName="f_station_info" columnName="station_charge_user_name" />
</not>
</preConditions>
<comment>修改f_station_info表结构</comment>
<sql>
ALTER TABLE `f_station_info` ADD COLUMN `station_charge_user_name` varchar(20) NULL COMMENT '换流站负责人姓名';
</sql>
</changeSet>
<changeSet author="keyong" id="1605924681-2">
<preConditions onFail="MARK_RAN">
<not>
<columnExists tableName="f_station_info" columnName="safety_charge_user_name" />
</not>
</preConditions>
<comment>修改f_station_info表结构</comment>
<sql>
ALTER TABLE `f_station_info` ADD COLUMN `safety_charge_user_name` varchar(20) NULL COMMENT '安全负责人姓名';
</sql>
</changeSet>
<changeSet author="keyong" id="1605924681-3">
<preConditions onFail="MARK_RAN">
<not>
<columnExists tableName="f_station_info" columnName="create_user_name" />
</not>
</preConditions>
<comment>修改f_station_info表结构</comment>
<sql>
ALTER TABLE `f_station_info` ADD COLUMN `create_user_name` varchar(20) NULL COMMENT '创建人姓名';
</sql>
</changeSet>
<changeSet author="keyong" id="1606290088-1">
<preConditions onFail="MARK_RAN">
<not>
<columnExists tableName="f_station_info" columnName="create_user_phone_num" />
</not>
</preConditions>
<comment>修改f_station_info表结构</comment>
<sql>
ALTER TABLE `f_station_info` ADD COLUMN `create_user_phone_num` varchar(20) NULL COMMENT '创建人联系方式';
</sql>
</changeSet>
<changeSet author="keyong" id="1606290088-2">
<preConditions onFail="MARK_RAN">
<not>
<columnExists tableName="f_station_info" columnName="station_user_phone_num" />
</not>
</preConditions>
<comment>修改f_station_info表结构</comment>
<sql>
ALTER TABLE `f_station_info` ADD COLUMN `station_user_phone_num` varchar(20) NULL COMMENT '换流站负责人联系方式';
</sql>
</changeSet>
<changeSet author="keyong" id="1606290088-3">
<preConditions onFail="MARK_RAN">
<not>
<columnExists tableName="f_station_info" columnName="safety_user_phone_num" />
</not>
</preConditions>
<comment>修改f_station_info表结构</comment>
<sql>
ALTER TABLE `f_station_info` ADD COLUMN `safety_user_phone_num` varchar(20) NULL COMMENT '安全负责人联系方式';
</sql>
</changeSet>
</databaseChangeLog>
\ No newline at end of file
......@@ -28,33 +28,38 @@
</delete>
<select id="getEquipmentBySpe" resultType="com.yeejoin.amos.fas.business.vo.EquipmentSpecificVo">
select
sto.id as id ,
equ.code as code,
det.name as name,
cate.name as type,
if(fire.fire_equipment_id is null ,'NO','YES') as isbind,
ware.full_name as address,
spe.single as single,
sto.amount as amount
from
wl_stock_detail as sto
left join wl_equipment_specific as spe on sto.qr_code = spe.qr_code
left join wl_warehouse_structure as ware on sto.warehouse_structure_id = ware .id
left join wl_equipment_detail as det on sto.equipment_detail_id = det.id
left join wl_equipment as equ on det.equipment_id = equ.id
left join wl_equipment_category as cate on equ.category_id = cate.id
left join f_equipment_fire_equipment as fire on sto.id = fire.fire_equipment_id
where sto.amount <![CDATA[>]]> 0
<if test="name != null and name!='null' ">
and det.name like CONCAT('%',#{name},'%' )
</if>
<if test="code != null and code!='null' ">
and cate.code like CONCAT('%',#{code},'%' )
</if>
<if test="equipmentId != null and equipmentId!='null' ">
and fire.equipment_id = #{equipmentId}
</if>
limit #{pageNumber},#{pageSize}
spe.id as id ,
equ.code as code,
det.name as name,
cate.name as type,
if(fire.fire_equipment_id is null ,'NO','YES') as isbind,
ware.full_name as address,
spe.single as single,
sto.amount as amount,
spe.iot_code,
spe.code as specific_code,
spe.system_id,
manage.name as system_name
from
wl_stock_detail as sto
left join wl_equipment_specific as spe on sto.qr_code = spe.qr_code
left join wl_warehouse_structure as ware on sto.warehouse_structure_id = ware .id
left join wl_equipment_detail as det on sto.equipment_detail_id = det.id
left join wl_equipment as equ on det.equipment_id = equ.id
left join wl_equipment_category as cate on equ.category_id = cate.id
left join f_equipment_fire_equipment as fire on spe.id = fire.fire_equipment_id
left join f_equipment_manage as manage on spe.system_id = manage.SEQUENCE_NBR
where sto.amount <![CDATA[>]]> 0
<if test="name != null and name!='null' ">
and det.name like CONCAT('%',#{name},'%' )
</if>
<if test="code != null and code!='null' ">
and cate.code like CONCAT('%',#{code},'%' )
</if>
<if test="equipmentId != null and equipmentId!='null' ">
and fire.equipment_id = #{equipmentId}
</if>
limit #{pageNumber},#{pageSize}
</select>
<select id="getEquipmentBySpeCount" resultType="int">
......@@ -80,54 +85,54 @@
</if>
</select>
<select id="getFireEquiments" resultType="com.yeejoin.amos.fas.business.vo.EquipmentSpeVo">
select
sto.equipment_specific_id as id ,
equ.code as f_code,
det.name as f_name
from
wl_stock_detail as sto
left join wl_equipment_detail as det on sto.equipment_detail_id = det.id
left join wl_equipment as equ on det.equipment_id = equ.id
left join f_equipment_fire_equipment as fire on sto.equipment_specific_id = fire.fire_equipment_id
where sto.amount <![CDATA[>]]> 0
<if test="fname != null and fname!='null' ">
and det.name like CONCAT('%',#{fname},'%' )
</if>
<if test="equipmentId != null and equipmentId!='null' ">
and fire.equipment_id = #{equipmentId}
</if>
</select>
<select id="getBindEquipment" resultType="com.yeejoin.amos.fas.business.vo.EquipmentPointVo">
select
speind.id,
equindex.name,
(
select
sto.id as id ,
equ.code as f_code,
det.name as f_name
case when count(1) > 0 then 'bound' else 'noBound' end
from
f_fmea_equipment_point as d
where
d.equipment_point_id = speind.id
and
d.fmea_id = #{fmeaId}
and
d.important_equipment_id = #{importantEquipId} ) isBound
from
wl_stock_detail as sto
left join wl_equipment_detail as det on sto.equipment_detail_id = det.id
left join wl_equipment as equ on det.equipment_id = equ.id
left join f_equipment_fire_equipment as fire on sto.id = fire.fire_equipment_id
where sto.amount <![CDATA[>]]> 0
<if test="fname != null and fname!='null' ">
and det.name like CONCAT('%',#{fname},'%' )
f_equipment_fire_equipment as fire
left join wl_stock_detail as sto on fire.fire_equipment_id = sto.equipment_specific_id
left join wl_equipment_specific as spe on sto.qr_code = spe.qr_code
left join wl_equipment_specific_index as speind on sto.equipment_specific_id = speind.equipment_specific_id
left join wl_equipment_index as equindex on speind.equipment_index_id = equindex.id
where equindex.type_code ='BREAKDOWN'
<if test="importantEquipId != null ">
and fire.equipment_id = #{importantEquipId}
</if>
<if test="equipmentId != null and equipmentId!='null' ">
and fire.equipment_id = #{equipmentId}
<if test="equimentId != null ">
and fire.fire_equipment_id =#{equimentId}
</if>
<if test="equipmentPointName != null and equipmentPointName!='null' ">
and equindex.name like CONCAT('%',#{equipmentPointName},'%' )
</if>
</select>
<select id="getBindEquipment" resultType="com.yeejoin.amos.fas.business.vo.EquipmentPointVo">
select
speind.id,
equindex.name,
(
select
case when count(1) > 0 then 'bound' else 'noBound' end
from
f_fmea_equipment_point as d
where
d.equipment_point_id = speind.id
and
d.fmea_id = #{fmeaId}
and
d.important_equipment_id = #{importantEquipId} ) isBound
from
f_equipment_fire_equipment as fire
left join wl_stock_detail as sto on fire.fire_equipment_id = sto.id
left join wl_equipment_specific as spe on sto.qr_code = spe.qr_code
left join wl_equipment_specific_index as speind on spe.id = speind.equipment_specific_id
left join wl_equipment_index as equindex on speind.equipment_index_id = equindex.id
where equindex.type_code ='BREAKDOWN'
<if test="importantEquipId != null ">
and fire.equipment_id = #{importantEquipId}
</if>
<if test="equimentId != null ">
and fire.fire_equipment_id =#{equimentId}
</if>
<if test="equipmentPointName != null and equipmentPointName!='null' ">
and equindex.name like CONCAT('%',#{equipmentPointName},'%' )
</if>
</select>
<select id="getAssoEquips" resultType="com.yeejoin.amos.fas.business.vo.AssoEquipsVo">
select
......
......@@ -324,25 +324,6 @@
</where>
</select>
<select id="findAllEquipPointInfo" resultType="com.yeejoin.amos.fas.business.vo.EquipCommunicationData">
SELECT
p.`code` pointCode,
p.`name` pointName,
f.`name` equimentName,
f.id equimentId,
e.id fireEquipmentId,
e.`name` fireEquipmentName,
e.code fireEquipmentCode,
p.type,
d.dict_value alarmType,
p.unit
FROM
f_fire_equipment_point p
LEFT JOIN f_fire_equipment e ON e.id = p.fire_equipment_id
LEFT JOIN f_equipment_fire_equipment fe ON fe.fire_equipment_id = e.id
LEFT JOIN f_equipment f ON f.id = fe.equipment_id
LEFT JOIN f_dict d on d.id = p.alarm_type
</select>
<select id="findOneByPointCode" resultType="com.yeejoin.amos.fas.business.vo.EquipCommunicationData">
SELECT
......
......@@ -438,12 +438,12 @@
</delete>
<select id="getPointsByEquipmentIdAndType" resultType="Map">
<!-- SELECT p.* from
SELECT p.* from
f_fire_equipment_point p
LEFT JOIN f_fire_equipment fe on p.fire_equipment_id = fe.id
LEFT JOIN f_equipment_fire_equipment e on fe.id = e.fire_equipment_id
where e.equipment_id = #{id}
and p.type = #{type} -->
and p.type = #{type}
</select>
</mapper>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.yeejoin.amos.fas.business.dao.mapper.RiskSourceMapper">
<!--统计-->
<select id="countPageData" resultType="long">
SELECT
COUNT(1) AS total_num
FROM
f_risk_source rs
LEFT JOIN f_risk_level rl ON rl.id = rs.risk_level_id
<trim prefix="WHERE" prefixOverrides="AND ">
<if test="name!=null"> and rs.name like concat(concat("%",#{name}),"%")</if>
</trim>
</select>
<!--分页查询 -->
<select id="queryRiskSourceByPage" resultType="java.util.HashMap">
SELECT
rs.*, rl.`name` riskLevelName
FROM
f_risk_source rs
LEFT JOIN f_risk_level rl ON rl.id = rs.risk_level_id
<trim prefix="WHERE" prefixOverrides="AND ">
<if test="name!=null"> and rs.name like concat(concat("%",#{name}),"%")</if>
</trim>
order by rs.id desc
<choose>
<when test="pageSize==-1"></when>
<when test="pageSize!=-1">limit #{offset},#{pageSize}</when>
</choose>
</select>
<select id="queryForRegion" resultType="java.util.Map">
SELECT
rs.id,
rs.`code`,
rs.`name`,
(select rl.color from f_risk_level rl where rl.id = rs.risk_level_id) color,
(select rl.`level` from f_risk_level rl where rl.id = rs.risk_level_id) level,
rs.parent_id parentId
FROM
f_risk_source rs
where rs.is_region = 'TRUE';
</select>
<select id="queryRPNReport" resultType="java.util.Map">
<!-- SELECT
rs.`code`,
rs.id,
rs.`name`,
IFNULL(rs.rpn, 0) rpn,
IFNULL(
(
SELECT
sum(ff.rpni)
FROM
f_fmea ff
WHERE
ff.risk_source_id = rs.id
GROUP BY
ff.risk_source_id
),
0
) rpni
FROM
f_risk_source rs
WHERE
rs.parent_id &gt; 0
ORDER BY rpni DESC
LIMIT 10 -->
SELECT
rs.`code`,
rs.id,
rs.`name`,
IFNULL(rs.rpn, 0) rpn,
IFNULL(rs.rpni, 0) rpni
FROM
f_risk_source rs
WHERE
rs.parent_id &gt; 0
ORDER BY
rpni DESC, rpn DESC
LIMIT 10
</select>
<select id="queryForRiseUp" resultType="java.util.Map">
select
d.countOfType0,
d.countOfSource,
CONCAT(ROUND(IFNULL(d.countOfType0/d.countOfSource,0)*100,2),'%')type0Rate
from
(SELECT
count(DISTINCT cl.risk_source_id) countOfType0,
(select count(1) from f_risk_source rs )countOfSource
FROM
f_rpn_change_log cl
WHERE
cl.type = 0
and cl.create_date BETWEEN '${startTime}' and '${endTime}'
)d
</select>
<select id="queryForMatrix" resultType="java.util.Map">
<!-- SELECT
ff1.risk_source_id riskSourceId,
ff1.evaluation_oid evaluationOid,
ff1.evaluation_sid evaluationSid,
d.mutiby,
rs.`name`
FROM
f_fmea ff1
JOIN (
SELECT
ff.risk_source_id sourceId,
MAX(
ff.evaluation_oid * ff.evaluation_sid
) mutiby
FROM
f_fmea ff
GROUP BY
ff.risk_source_id
LIMIT 20
) d ON (
ff1.risk_source_id = d.sourceId
AND ff1.evaluation_oid * ff1.evaluation_sid
)
LEFT JOIN f_risk_source rs ON rs.id = ff1.risk_source_id
GROUP BY ff1.risk_source_id -->
SELECT
ff1.risk_source_id riskSourceId,
d.ovalue evaluationOid,
d.svalue evaluationSid,
d.mutiby,
rs.`name`
FROM
f_fmea ff1
JOIN (
SELECT
o.risk_source_id sourceId,
o.ovalue,
s.svalue,
MAX(o.ovalue * s.svalue) mutiby
FROM
(
SELECT
ff.risk_source_id,
fem.coefficient ovalue
FROM
f_fmea ff
LEFT JOIN f_evaluation_model fem ON fem.id = ff.evaluation_oid
) o
LEFT JOIN (
SELECT
ff.risk_source_id,
fem.coefficient svalue
FROM
f_fmea ff
LEFT JOIN f_evaluation_model fem ON fem.id = ff.evaluation_sid
) s ON s.risk_source_id = o.risk_source_id
GROUP BY
o.risk_source_id
LIMIT 20
) d ON (
ff1.risk_source_id = d.sourceId
)
LEFT JOIN f_risk_source rs ON rs.id = ff1.risk_source_id
GROUP BY
ff1.risk_source_id;
</select>
<resultMap id="riskSourceMap" type="com.yeejoin.amos.fas.core.common.response.RiskSourceTreeResponse">
<result property="id" column="id" />
<result property="parentId" column="parent_id" />
<result property="code" column="code" />
<result property="name" column="name" />
<result property="level" column="level" />
<result property="riskLevelId" column="risk_level_id" />
<result property="rpn" column="rpn" />
<result property="rpni" column="rpni" />
<result property="isRegion" column="is_region" />
<result property="isIndoor" column="is_indoor" />
<result property="status" column="status" />
<result property="count" column="ccount" />
<result property="qualified" column="qualified" />
<result property="unqualified" column="unqualified" />
<result property="omission" column="omission" />
<result property="unplan" column="unplan" />
</resultMap>
<select id="getRiskSources" resultMap="riskSourceMap">
SELECT
rs.id,
rs.`code`,
rs.parent_id,
rs.`name`,
rl.`level`,
rs.risk_level_id,
rs.rpn,
rs.rpni,
rs.is_region,
rs.position3d,
rs.floor3d,
rs.status,
rs.is_indoor
FROM
`f_risk_source` rs
LEFT JOIN f_risk_level rl ON rl.id = rs.risk_level_id
where rs.org_code = #{compCode}
ORDER BY rs.sort_num,rs.id ASC
</select>
<select id="getRiskSourcesEquipment" resultMap="riskSourceMap">
SELECT
sum(a.cc) ccount,
a.`name`,
a.position3d,
a.parent_id,
min(a.level) level,
a.id
FROM
(
SELECT
IF (E.ID, 1, 0) cc,
s.`name`,
s.position3d,
s.parent_id,
s.risk_level_id level,
s.id
FROM
f_equipment e
RIGHT JOIN f_risk_source s ON s.id = e.risk_source_id
) a
GROUP BY
a.`name`,
a.position3d,
a.parent_id,
a.id
</select>
<select id="getCheckPointRiskSource" resultMap="riskSourceMap">
SELECT
sum(a.cc) ccount,
a.`name`,
a.position3d,
a.parent_id,
min(a.level) level,
sum(a.qualified) qualified,
sum(a.unqualified) unqualified,
sum(a.omission) omission,
sum(a.unplan) unplan,
a.id
FROM
(
SELECT
IF (E.ID, 1, 0) cc,
s.`name`,
s.position3d,
s.parent_id,
IFNULL(e.`level`,0) level,
IF (E.`status` = '1', 1, 0) qualified,
IF (E.`status` = '2', 1, 0) unqualified,
IF (E.`status` = '3', 1, 0) omission,
IF (E.`status` = '0', 1, 0) unplan,
e.`status`,
s.id
FROM
p_point e
RIGHT JOIN f_risk_source s ON s.id = e.risk_source_id and e.is_delete = 0
) a
GROUP BY
a.`name`,
a.position3d,
a.parent_id,
a.id
</select>
<select id="getRiskSourcesFireEquipmentByType" resultMap="riskSourceMap">
SELECT
sum(a.cc) ccount,
a.`name`,
a.position3d,
a.parent_id,
min(a.level) level,
a.id
FROM
(
SELECT
IF (E.ID, 1, 0) cc,
s.`name`,
s.position3d,
s.parent_id,
s.risk_level_id level,
s.id
FROM
f_fire_equipment e
RIGHT JOIN f_risk_source s ON s.id = e.risk_source_id
where e.equip_classify in
<foreach collection="type" open="(" separator="," close=")" item="classify">
#{classify}
</foreach>
) a
GROUP BY
a.`name`,
a.position3d,
a.parent_id,
a.id
</select>
<select id="getRiskSourcePointCount" resultType="long">
SELECT
count(DISTINCT(pp.id))
FROM
`f_risk_source_point_inputitem` rspi
LEFT JOIN p_point pp ON pp.id = rspi.point_id
WHERE
1 = 1
AND rspi.risk_source_id = #{riskSourceId}
</select>
<select id="getRiskSourcePoints" resultType="java.util.HashMap">
SELECT
rspi.risk_source_id riskId,
pp.id pointId,
pp.point_no pointNo,
pp.`name` pointName,
pp.charge_person_id userId,
pp.charge_dept_id deptId,
GROUP_CONCAT(pii.`name`) inputItems
FROM
`f_risk_source_point_inputitem` rspi
LEFT JOIN p_point pp ON pp.id = rspi.point_id
LEFT JOIN p_input_item pii ON pii.id = rspi.point_inputitem_id
WHERE pii.`name` is not NULL
AND rspi.risk_source_id = #{riskSourceId}
GROUP BY riskId,pointId,pointNo,pointName,depName,username,telephone
<choose>
<when test="pageSize==-1"></when>
<when test="pageSize!=-1">limit #{offset},#{pageSize}</when>
</choose>
</select>
<select id="queryByFireEqument" resultType="com.yeejoin.amos.fas.dao.entity.RiskSource">
SELECT
*
FROM
f_risk_source rs
WHERE
EXISTS (
SELECT
1
FROM
f_risk_source_equipment se
WHERE
se.fire_equipment_id = ${fireEquipmentId}
AND se.risk_source_id = rs.id
)
</select>
<select id="queryByPoint" resultType="com.yeejoin.amos.fas.dao.entity.RiskSource">
SELECT
*
FROM
f_risk_source rs
WHERE
id in (
SELECT
pi.risk_source_id
FROM
f_risk_source_point_inputitem pi
WHERE
pi.point_id = ${pointId}
AND rs.id = pi.risk_source_id
)
</select>
<select id="findRiskSourceDetatil" resultMap="riskSourceMap">
SELECT
rs.id,
rs.`code`,
rs.parent_id,
rs.`name`,
rl.`name` as level,
rs.risk_level_id,
rs.rpni,
rs.rpn,
rs.is_region,
rs.floor3d,
rs.is_indoor,
rs.position3d
FROM
`f_risk_source` rs
LEFT JOIN f_risk_level rl ON rl.id = rs.risk_level_id
where rs.id = #{id}
</select>
<select id="statistics3dCount" resultType="map">
SELECT
(
SELECT
f.rpn
FROM
f_risk_source f
WHERE
f.parent_id = 0
) factoryRpn,
(
SELECT
CASE
WHEN f.increment &gt; 0 THEN
'UP'
WHEN f.increment = 0 THEN
'NOCHANGE'
WHEN f.increment &lt; 0 THEN
'DOWN'
END
FROM
f_risk_source f
WHERE
f.parent_id = 0
) rpnUpOrDown,
(
SELECT
count(1)
FROM
f_equipment
) equipmentCount,
(
SELECT
count(1)
FROM
f_risk_source
) riskSourceCount,
(SELECT count(1) FROM p_point p) pointCount;
SELECT
f.rpn
FROM
f_risk_source f
WHERE
f.parent_id = 0;
</select>
<select id="statisticsEquipClassify" resultType="map">
SELECT
fe.equip_classify,
count(1) classifyCount
FROM
f_fire_equipment fe
GROUP BY
fe.equip_classify
</select>
<select id="statisticsRiskLevel" resultType="map">
SELECT
IFNULL(d.riskLevel,'') riskLevel,
IFNULL(count(1),0) levelRiskCount
FROM
(
SELECT
rs.id,
(
SELECT
fl.`level`
FROM
f_risk_level fl
WHERE
fl.id = rs.risk_level_id
) riskLevel
FROM
f_risk_source rs
) d
GROUP BY
d.riskLevel;
</select>
<select id="statisticsPointStatus" resultType="map">
SELECT
sum(
CASE
WHEN p.`status` = 1 THEN
1
ELSE
0
END
) qualifiedCount,
sum(
CASE
WHEN p.`status` = 2 THEN
1
ELSE
0
END
) unqualifiedCount,
sum(
CASE
WHEN p.`status` = 3 THEN
1
ELSE
0
END
) omitCount
FROM
p_point p;
</select>
<select id="queryForRiskSourceLevel" resultType="map">
SELECT
rs.`code`,
rs.`name`,
(select rl.`name` from f_risk_level rl where rl.id = rs.risk_level_id)level
FROM
f_risk_source rs
WHERE
rs.id = ${riskSourceId};
</select>
<select id="queryForRiskSourceRpni" resultType="map">
SELECT
rs.`rpni` rpni
FROM
f_risk_source rs
WHERE
rs.parent_id = ${parentId};
</select>
<select id="queryForUnqualified" resultType="map">
SELECT
(
SELECT
i.`name`
FROM
p_input_item i
WHERE
i.id = ppi.input_item_id
) inputItemName,
(
SELECT
p.`name`
FROM
p_point p
WHERE
p.id = ppi.point_id
) pointName
FROM
f_fmea_point_inputitem pi
LEFT JOIN p_point_inputitem ppi ON ppi.id = pi.point_inputitem_id
LEFT JOIN f_fmea fm ON fm.id = pi.fmea_id
WHERE
pi.`state` = 1
AND fm.risk_source_id = #{riskSourceId};
</select>
<select id="queryForFmeaEquipAlarm" resultType="map">
SELECT
ed.`name` as 'fireEquipmentName',
ei.`name` as 'name'
FROM
`f_fmea_equipment_point` AS fmep
LEFT JOIN wl_equipment_specific_index fep ON fep.id = fmep.equipment_point_id
LEFT JOIN wl_equipment_index ei ON ei.id = fep.equipment_index_id
LEFT JOIN wl_equipment_specific fe ON fe.id = fep.equipment_specific_id
LEFT JOIN wl_equipment_detail ed ON ed.id = fe.equipment_detail_id
LEFT JOIN f_fmea fm ON fm.id = fmep.fmea_id
WHERE
fmep.state = 1
AND fm.risk_source_id = #{riskSourceId}
GROUP BY fireEquipmentName,name
</select>
<select id="queryRiskAreaRpn" resultType="java.util.HashMap">
SELECT
rs.id,
rs.name,
rs.rpn,
rs.rpni,
rs.risk_level_id as riskLevelId,
rl.`name` as riskLevelName,
rl.level,
rl.color
FROM
f_risk_source rs
LEFT JOIN f_risk_level rl ON rl.id = rs.risk_level_id
WHERE rs.parent_id &gt; 0
order by rs.sort_num,rs.id
</select>
<select id="queryByFactor" resultType="com.yeejoin.amos.fas.dao.entity.RiskSource">
SELECT
*
FROM
f_risk_source rs
WHERE
rs.id IN (
SELECT
ff.risk_source_id
FROM
f_fmea ff
JOIN f_risk_factor rf ON ff.risk_factors_id = rf.id
WHERE
rf.id = ${factorId}
)
</select>
<select id="queryRiskSourceSecondLevel" resultType="java.util.HashMap">
SELECT
rs.id,
rs.`code`,
rs.`name`,
rl.`level`,
rs.rpn
FROM
`f_risk_source` rs
LEFT JOIN f_risk_level rl ON rl.id = rs.risk_level_id
WHERE
rs.parent_id = (
SELECT
id
FROM
f_risk_source
WHERE
parent_id = 0 and org_code = #{compCode}
)
ORDER BY sort_num,id
</select>
<select id="queryContingencyWater" resultType="java.util.HashMap">
<!-- SELECT
wr.alarm_level,
wr.max_level,
wr.area,
ep.CODE,
wr.`name`,
ep.value
FROM
f_fire_equipment_point ep
INNER JOIN f_water_resource_equipment wre ON wre.fire_equipment_id = ep.fire_equipment_id AND ep.type = 'ANALOGUE'
RIGHT JOIN f_water_resource wr ON wr.id = wre.water_resource_id
LEFT JOIN f_dict d ON d.id = ep.alarm_type AND d.dict_value = 'analogue_water_level'
WHERE wr.type = 2
GROUP BY
wr.alarm_level,
wr.max_level,
wr.area,
wr.`name` -->
</select>
<select id="queryFmeaByPointId" resultType="java.util.HashMap">
SELECT
frf.`name` riskFactors,
fem1.influence level,
fem2.influence faultFrequency,
fem3.influence detectivity,
ff.engineering,
ff.management,
ff.train,
ff.protection,
ff.disposal
FROM
f_fmea ff
LEFT JOIN f_risk_source frs ON frs.id = ff.risk_source_id
LEFT JOIN f_risk_factor frf ON frf.id = ff.risk_factors_id
LEFT JOIN f_evaluation_model fem1 ON fem1.id = ff.evaluation_sid
LEFT JOIN f_evaluation_model fem2 ON fem2.id = ff.evaluation_oid
LEFT JOIN f_evaluation_model fem3 ON fem3.id = ff.evaluation_did
WHERE
EXISTS ( SELECT 1 FROM f_risk_source_point_inputitem frspi WHERE frspi.risk_source_id = frs.id AND frspi.point_id = ${pointId} )
</select>
<select id="countByParentIdAndIsRegion" resultType="long">
select
count(1)
from
f_risk_source
where
is_region = #{isRegion}
and
parent_id = #{riskSourceId}
</select>
<update id="updateRpn">
update f_risk_source
<set>
<if test="rpn != null">
rpn = #{rpn},
</if>
<if test="rpni != null">
rpni = #{rpni},
</if>
<if test="riskLevelId != null">
risk_level_id = #{riskLevelId},
</if>
<if test="flickerFrequency != null">
flicker_frequency = #{flickerFrequency}
</if>
</set>
where id = #{id}
</update>
<select id="getRegionList" parameterType="string" resultType="com.yeejoin.amos.fas.core.common.response.RegionTreeResponse">
select
rs.id,rs.name,rs.code,rs.parent_id,rs.ue4_location,rs.ue4_rotation,rs.ue4_extent,
<choose>
<when test="channelType == '3dpage'">
IF(ISNULL(rs.route_path) || LENGTH(trim(rs.route_path)) <![CDATA[ <]]> 1,0,1) as is_bind,
</when>
<otherwise>
IF(ISNULL(IF(replace(trim(rs.ue4_rotation),'[]','')='',NULL,rs.ue4_rotation))
AND ISNULL(IF(replace(trim(rs.ue4_location),'[]','')='',NULL,rs.ue4_location)),0,1) as is_bind,
</otherwise>
</choose>
IF(rs.is_region = 'TRUE',1,0) as is_region,
rs.route_path,
rl.level,
CONCAT('level_',rl.level) as level_str,
'riskSource' as type
from f_risk_source rs
left join f_risk_level rl ON rs.risk_level_id = rl.id
where is_region = 'TRUE' AND (rs.org_code = #{orgCode} OR rs.org_code like CONCAT(#{orgCode},'-%'))
</select>
<select id="findRegionById" resultType="java.util.HashMap">
select
id,name,code,parent_id as parentId,ue4_location as ue4Location,ue4_rotation as ue4Rotation,ue4_extent as ue4Extent,route_path as routePath,
<choose>
<when test="channelType == '3dpage'">
IF(ISNULL(route_path) || LENGTH(trim(route_path)) <![CDATA[ <]]> 1,0,1) as isBind,
</when>
<otherwise>
IF(ISNULL(IF(replace(trim(ue4_rotation),'[]','')='',NULL,ue4_rotation))
AND ISNULL(IF(replace(trim(ue4_location),'[]','')='',NULL,ue4_location)),0,1) as isBind,
</otherwise>
</choose>
IF(is_region = 'TRUE',1,0) as isRegion,
(select name from f_risk_level where level = r.risk_level_id) as riskLevel
from f_risk_source r
where id=#{id} AND (org_code = #{orgCode} OR org_code like CONCAT(#{orgCode},'-%'))
</select>
<update id="batchSaveRegionUe4" parameterType="java.util.List">
<foreach collection="list" item="item" index="index" open="" close="" separator=";">
update f_risk_source
<set >
<if test="item.ue4Location != null" >
ue4_location = #{item.ue4Location,jdbcType=VARCHAR},
</if>
<if test="item.ue4Rotation != null" >
ue4_rotation = #{item.ue4Rotation,jdbcType=VARCHAR},
</if>
<if test="item.ue4Extent != null" >
ue4_extent = #{item.ue4Extent,jdbcType=VARCHAR},
</if>
<if test="item.routePath != null" >
route_path = #{item.routePath,jdbcType=VARCHAR},
</if>
</set>
where id = #{item.riskSourceId,jdbcType=BIGINT}
</foreach>
</update>
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.yeejoin.amos.fas.business.dao.mapper.RiskSourceMapper">
<!--统计-->
<select id="countPageData" resultType="long">
SELECT
COUNT(1) AS total_num
FROM
f_risk_source rs
LEFT JOIN f_risk_level rl ON rl.id = rs.risk_level_id
<trim prefix="WHERE" prefixOverrides="AND ">
<if test="name!=null"> and rs.name like concat(concat("%",#{name}),"%")</if>
</trim>
</select>
<!--分页查询 -->
<select id="queryRiskSourceByPage" resultType="java.util.HashMap">
SELECT
rs.*, rl.`name` riskLevelName
FROM
f_risk_source rs
LEFT JOIN f_risk_level rl ON rl.id = rs.risk_level_id
<trim prefix="WHERE" prefixOverrides="AND ">
<if test="name!=null"> and rs.name like concat(concat("%",#{name}),"%")</if>
</trim>
order by rs.id desc
<choose>
<when test="pageSize==-1"></when>
<when test="pageSize!=-1">limit #{offset},#{pageSize}</when>
</choose>
</select>
<select id="queryForRegion" resultType="java.util.Map">
SELECT
rs.id,
rs.`code`,
rs.`name`,
(select rl.color from f_risk_level rl where rl.id = rs.risk_level_id) color,
(select rl.`level` from f_risk_level rl where rl.id = rs.risk_level_id) level,
rs.parent_id parentId
FROM
f_risk_source rs
where rs.is_region = 'TRUE';
</select>
<select id="queryRPNReport" resultType="java.util.Map">
<!-- SELECT
rs.`code`,
rs.id,
rs.`name`,
IFNULL(rs.rpn, 0) rpn,
IFNULL(
(
SELECT
sum(ff.rpni)
FROM
f_fmea ff
WHERE
ff.risk_source_id = rs.id
GROUP BY
ff.risk_source_id
),
0
) rpni
FROM
f_risk_source rs
WHERE
rs.parent_id &gt; 0
ORDER BY rpni DESC
LIMIT 10 -->
SELECT
rs.`code`,
rs.id,
rs.`name`,
IFNULL(rs.rpn, 0) rpn,
IFNULL(rs.rpni, 0) rpni
FROM
f_risk_source rs
WHERE
rs.parent_id &gt; 0
ORDER BY
rpni DESC, rpn DESC
LIMIT 10
</select>
<select id="queryForRiseUp" resultType="java.util.Map">
select
d.countOfType0,
d.countOfSource,
CONCAT(ROUND(IFNULL(d.countOfType0/d.countOfSource,0)*100,2),'%')type0Rate
from
(SELECT
count(DISTINCT cl.risk_source_id) countOfType0,
(select count(1) from f_risk_source rs )countOfSource
FROM
f_rpn_change_log cl
WHERE
cl.type = 0
and cl.create_date BETWEEN '${startTime}' and '${endTime}'
)d
</select>
<select id="queryForMatrix" resultType="java.util.Map">
<!-- SELECT
ff1.risk_source_id riskSourceId,
ff1.evaluation_oid evaluationOid,
ff1.evaluation_sid evaluationSid,
d.mutiby,
rs.`name`
FROM
f_fmea ff1
JOIN (
SELECT
ff.risk_source_id sourceId,
MAX(
ff.evaluation_oid * ff.evaluation_sid
) mutiby
FROM
f_fmea ff
GROUP BY
ff.risk_source_id
LIMIT 20
) d ON (
ff1.risk_source_id = d.sourceId
AND ff1.evaluation_oid * ff1.evaluation_sid
)
LEFT JOIN f_risk_source rs ON rs.id = ff1.risk_source_id
GROUP BY ff1.risk_source_id -->
SELECT
ff1.risk_source_id riskSourceId,
d.ovalue evaluationOid,
d.svalue evaluationSid,
d.mutiby,
rs.`name`
FROM
f_fmea ff1
JOIN (
SELECT
o.risk_source_id sourceId,
o.ovalue,
s.svalue,
MAX(o.ovalue * s.svalue) mutiby
FROM
(
SELECT
ff.risk_source_id,
fem.coefficient ovalue
FROM
f_fmea ff
LEFT JOIN f_evaluation_model fem ON fem.id = ff.evaluation_oid
) o
LEFT JOIN (
SELECT
ff.risk_source_id,
fem.coefficient svalue
FROM
f_fmea ff
LEFT JOIN f_evaluation_model fem ON fem.id = ff.evaluation_sid
) s ON s.risk_source_id = o.risk_source_id
GROUP BY
o.risk_source_id
LIMIT 20
) d ON (
ff1.risk_source_id = d.sourceId
)
LEFT JOIN f_risk_source rs ON rs.id = ff1.risk_source_id
GROUP BY
ff1.risk_source_id;
</select>
<resultMap id="riskSourceMap" type="com.yeejoin.amos.fas.core.common.response.RiskSourceTreeResponse">
<result property="id" column="id" />
<result property="parentId" column="parent_id" />
<result property="code" column="code" />
<result property="name" column="name" />
<result property="level" column="level" />
<result property="riskLevelId" column="risk_level_id" />
<result property="rpn" column="rpn" />
<result property="rpni" column="rpni" />
<result property="isRegion" column="is_region" />
<result property="isIndoor" column="is_indoor" />
<result property="status" column="status" />
<result property="count" column="ccount" />
<result property="qualified" column="qualified" />
<result property="unqualified" column="unqualified" />
<result property="omission" column="omission" />
<result property="unplan" column="unplan" />
</resultMap>
<select id="getRiskSources" resultMap="riskSourceMap">
SELECT
rs.id,
rs.`code`,
rs.parent_id,
rs.`name`,
rl.`level`,
rs.risk_level_id,
rs.rpn,
rs.rpni,
rs.is_region,
rs.position3d,
rs.floor3d,
rs.status,
rs.is_indoor
FROM
`f_risk_source` rs
LEFT JOIN f_risk_level rl ON rl.id = rs.risk_level_id
where rs.org_code = #{compCode}
ORDER BY rs.sort_num,rs.id ASC
</select>
<select id="getRiskSourcesEquipment" resultMap="riskSourceMap">
SELECT
sum(a.cc) ccount,
a.`name`,
a.position3d,
a.parent_id,
min(a.level) level,
a.id
FROM
(
SELECT
IF (E.ID, 1, 0) cc,
s.`name`,
s.position3d,
s.parent_id,
s.risk_level_id level,
s.id
FROM
f_equipment e
RIGHT JOIN f_risk_source s ON s.id = e.risk_source_id
) a
GROUP BY
a.`name`,
a.position3d,
a.parent_id,
a.id
</select>
<select id="getCheckPointRiskSource" resultMap="riskSourceMap">
SELECT
sum(a.cc) ccount,
a.`name`,
a.position3d,
a.parent_id,
min(a.level) level,
sum(a.qualified) qualified,
sum(a.unqualified) unqualified,
sum(a.omission) omission,
sum(a.unplan) unplan,
a.id
FROM
(
SELECT
IF (E.ID, 1, 0) cc,
s.`name`,
s.position3d,
s.parent_id,
IFNULL(e.`level`,0) level,
IF (E.`status` = '1', 1, 0) qualified,
IF (E.`status` = '2', 1, 0) unqualified,
IF (E.`status` = '3', 1, 0) omission,
IF (E.`status` = '0', 1, 0) unplan,
e.`status`,
s.id
FROM
p_point e
RIGHT JOIN f_risk_source s ON s.id = e.risk_source_id and e.is_delete = 0
) a
GROUP BY
a.`name`,
a.position3d,
a.parent_id,
a.id
</select>
<select id="getRiskSourcesFireEquipmentByType" resultMap="riskSourceMap">
SELECT
sum(a.cc) ccount,
a.`name`,
a.position3d,
a.parent_id,
min(a.level) level,
a.id
FROM
(
SELECT
IF (E.ID, 1, 0) cc,
s.`name`,
s.position3d,
s.parent_id,
s.risk_level_id level,
s.id
FROM
f_fire_equipment e
RIGHT JOIN f_risk_source s ON s.id = e.risk_source_id
where e.equip_classify in
<foreach collection="type" open="(" separator="," close=")" item="classify">
#{classify}
</foreach>
) a
GROUP BY
a.`name`,
a.position3d,
a.parent_id,
a.id
</select>
<select id="getRiskSourcePointCount" resultType="long">
SELECT
count(DISTINCT(pp.id))
FROM
`f_risk_source_point_inputitem` rspi
LEFT JOIN p_point pp ON pp.id = rspi.point_id
WHERE
1 = 1
AND rspi.risk_source_id = #{riskSourceId}
</select>
<select id="getRiskSourcePoints" resultType="java.util.HashMap">
SELECT
rspi.risk_source_id riskId,
pp.id pointId,
pp.point_no pointNo,
pp.`name` pointName,
pp.charge_person_id userId,
pp.charge_dept_id deptId,
GROUP_CONCAT(pii.`name`) inputItems
FROM
`f_risk_source_point_inputitem` rspi
LEFT JOIN p_point pp ON pp.id = rspi.point_id
LEFT JOIN p_input_item pii ON pii.id = rspi.point_inputitem_id
WHERE pii.`name` is not NULL
AND rspi.risk_source_id = #{riskSourceId}
GROUP BY riskId,pointId,pointNo,pointName,depName,username,telephone
<choose>
<when test="pageSize==-1"></when>
<when test="pageSize!=-1">limit #{offset},#{pageSize}</when>
</choose>
</select>
<select id="queryByFireEqument" resultType="com.yeejoin.amos.fas.dao.entity.RiskSource">
SELECT
*
FROM
f_risk_source rs
WHERE
EXISTS (
SELECT
1
FROM
f_risk_source_equipment se
WHERE
se.fire_equipment_id = ${fireEquipmentId}
AND se.risk_source_id = rs.id
)
</select>
<select id="queryByPoint" resultType="com.yeejoin.amos.fas.dao.entity.RiskSource">
SELECT
*
FROM
f_risk_source rs
WHERE
id in (
SELECT
pi.risk_source_id
FROM
f_risk_source_point_inputitem pi
WHERE
pi.point_id = ${pointId}
AND rs.id = pi.risk_source_id
)
</select>
<select id="findRiskSourceDetatil" resultMap="riskSourceMap">
SELECT
rs.id,
rs.`code`,
rs.parent_id,
rs.`name`,
rl.`name` as level,
rs.risk_level_id,
rs.rpni,
rs.rpn,
rs.is_region,
rs.floor3d,
rs.is_indoor,
rs.position3d
FROM
`f_risk_source` rs
LEFT JOIN f_risk_level rl ON rl.id = rs.risk_level_id
where rs.id = #{id}
</select>
<select id="statistics3dCount" resultType="map">
SELECT
(
SELECT
f.rpn
FROM
f_risk_source f
WHERE
f.parent_id = 0
) factoryRpn,
(
SELECT
CASE
WHEN f.increment &gt; 0 THEN
'UP'
WHEN f.increment = 0 THEN
'NOCHANGE'
WHEN f.increment &lt; 0 THEN
'DOWN'
END
FROM
f_risk_source f
WHERE
f.parent_id = 0
) rpnUpOrDown,
(
SELECT
count(1)
FROM
f_equipment
) equipmentCount,
(
SELECT
count(1)
FROM
f_risk_source
) riskSourceCount,
(SELECT count(1) FROM p_point p) pointCount;
SELECT
f.rpn
FROM
f_risk_source f
WHERE
f.parent_id = 0;
</select>
<select id="statisticsEquipClassify" resultType="map">
SELECT
fe.equip_classify,
count(1) classifyCount
FROM
f_fire_equipment fe
GROUP BY
fe.equip_classify
</select>
<select id="statisticsRiskLevel" resultType="map">
SELECT
IFNULL(d.riskLevel,'') riskLevel,
IFNULL(count(1),0) levelRiskCount
FROM
(
SELECT
rs.id,
(
SELECT
fl.`level`
FROM
f_risk_level fl
WHERE
fl.id = rs.risk_level_id
) riskLevel
FROM
f_risk_source rs
) d
GROUP BY
d.riskLevel;
</select>
<select id="statisticsPointStatus" resultType="map">
SELECT
sum(
CASE
WHEN p.`status` = 1 THEN
1
ELSE
0
END
) qualifiedCount,
sum(
CASE
WHEN p.`status` = 2 THEN
1
ELSE
0
END
) unqualifiedCount,
sum(
CASE
WHEN p.`status` = 3 THEN
1
ELSE
0
END
) omitCount
FROM
p_point p;
</select>
<select id="queryForRiskSourceLevel" resultType="map">
SELECT
rs.`code`,
rs.`name`,
(select rl.`name` from f_risk_level rl where rl.id = rs.risk_level_id)level
FROM
f_risk_source rs
WHERE
rs.id = ${riskSourceId};
</select>
<select id="queryForRiskSourceRpni" resultType="map">
SELECT
rs.`rpni` rpni
FROM
f_risk_source rs
WHERE
rs.parent_id = ${parentId};
</select>
<select id="queryForUnqualified" resultType="map">
SELECT
(
SELECT
i.`name`
FROM
p_input_item i
WHERE
i.id = ppi.input_item_id
) inputItemName,
(
SELECT
p.`name`
FROM
p_point p
WHERE
p.id = ppi.point_id
) pointName
FROM
f_fmea_point_inputitem pi
LEFT JOIN p_point_inputitem ppi ON ppi.id = pi.point_inputitem_id
LEFT JOIN f_fmea fm ON fm.id = pi.fmea_id
WHERE
pi.`state` = 1
AND fm.risk_source_id = #{riskSourceId};
</select>
<select id="queryForFmeaEquipAlarm" resultType="map">
SELECT
ed.`name` as 'fireEquipmentName',
ei.`name` as 'name'
FROM
`f_fmea_equipment_point` AS fmep
LEFT JOIN wl_equipment_specific_index fep ON fep.id = fmep.equipment_point_id
LEFT JOIN wl_equipment_index ei ON ei.id = fep.equipment_index_id
LEFT JOIN wl_equipment_specific fe ON fe.id = fep.equipment_specific_id
LEFT JOIN wl_equipment_detail ed ON ed.id = fe.equipment_detail_id
LEFT JOIN f_fmea fm ON fm.id = fmep.fmea_id
WHERE
fmep.state = 1
AND fm.risk_source_id = #{riskSourceId}
GROUP BY fireEquipmentName,name
</select>
<select id="queryRiskAreaRpn" resultType="java.util.HashMap">
SELECT
rs.id,
rs.name,
rs.rpn,
rs.rpni,
rs.risk_level_id as riskLevelId,
rl.`name` as riskLevelName,
rl.level,
rl.color
FROM
f_risk_source rs
LEFT JOIN f_risk_level rl ON rl.id = rs.risk_level_id
WHERE rs.parent_id &gt; 0
order by rs.sort_num,rs.id
</select>
<select id="queryByFactor" resultType="com.yeejoin.amos.fas.dao.entity.RiskSource">
SELECT
*
FROM
f_risk_source rs
WHERE
rs.id IN (
SELECT
ff.risk_source_id
FROM
f_fmea ff
JOIN f_risk_factor rf ON ff.risk_factors_id = rf.id
WHERE
rf.id = ${factorId}
)
</select>
<select id="queryRiskSourceSecondLevel" resultType="java.util.HashMap">
SELECT
rs.id,
rs.`code`,
rs.`name`,
rl.`level`,
rs.rpn
FROM
`f_risk_source` rs
LEFT JOIN f_risk_level rl ON rl.id = rs.risk_level_id
WHERE
rs.parent_id = (
SELECT
id
FROM
f_risk_source
WHERE
parent_id = 0 and org_code = #{compCode}
)
ORDER BY sort_num,id
</select>
<select id="queryContingencyWater" resultType="java.util.HashMap">
<!-- SELECT
wr.alarm_level,
wr.max_level,
wr.area,
ep.CODE,
wr.`name`,
ep.value
FROM
f_fire_equipment_point ep
INNER JOIN f_water_resource_equipment wre ON wre.fire_equipment_id = ep.fire_equipment_id AND ep.type = 'ANALOGUE'
RIGHT JOIN f_water_resource wr ON wr.id = wre.water_resource_id
LEFT JOIN f_dict d ON d.id = ep.alarm_type AND d.dict_value = 'analogue_water_level'
WHERE wr.type = 2
GROUP BY
wr.alarm_level,
wr.max_level,
wr.area,
wr.`name` -->
</select>
<select id="queryFmeaByPointId" resultType="java.util.HashMap">
SELECT
frf.`name` riskFactors,
fem1.influence level,
fem2.influence faultFrequency,
fem3.influence detectivity,
ff.engineering,
ff.management,
ff.train,
ff.protection,
ff.disposal
FROM
f_fmea ff
LEFT JOIN f_risk_source frs ON frs.id = ff.risk_source_id
LEFT JOIN f_risk_factor frf ON frf.id = ff.risk_factors_id
LEFT JOIN f_evaluation_model fem1 ON fem1.id = ff.evaluation_sid
LEFT JOIN f_evaluation_model fem2 ON fem2.id = ff.evaluation_oid
LEFT JOIN f_evaluation_model fem3 ON fem3.id = ff.evaluation_did
WHERE
EXISTS ( SELECT 1 FROM f_risk_source_point_inputitem frspi WHERE frspi.risk_source_id = frs.id AND frspi.point_id = ${pointId} )
</select>
<select id="countByParentIdAndIsRegion" resultType="long">
select
count(1)
from
f_risk_source
where
is_region = #{isRegion}
and
parent_id = #{riskSourceId}
</select>
<update id="updateRpn">
update f_risk_source
<set>
<if test="rpn != null">
rpn = #{rpn},
</if>
<if test="rpni != null">
rpni = #{rpni},
</if>
<if test="riskLevelId != null">
risk_level_id = #{riskLevelId},
</if>
<if test="flickerFrequency != null">
flicker_frequency = #{flickerFrequency}
</if>
</set>
where id = #{id}
</update>
<select id="getRegionList" parameterType="string" resultType="com.yeejoin.amos.fas.core.common.response.RegionTreeResponse">
select
rs.id,rs.name,rs.code,rs.parent_id,rs.ue4_location,rs.ue4_rotation,rs.ue4_extent,
<choose>
<when test="channelType == '3dpage'">
IF(ISNULL(rs.route_path) || LENGTH(trim(rs.route_path)) <![CDATA[ <]]> 1,0,1) as is_bind,
</when>
<otherwise>
IF(ISNULL(IF(replace(trim(rs.ue4_rotation),'[]','')='',NULL,rs.ue4_rotation))
AND ISNULL(IF(replace(trim(rs.ue4_location),'[]','')='',NULL,rs.ue4_location)),0,1) as is_bind,
</otherwise>
</choose>
IF(rs.is_region = 'TRUE',1,0) as is_region,
rs.route_path,
rl.level,
CONCAT('level_',rl.level) as level_str,
'riskSource' as type
from f_risk_source rs
left join f_risk_level rl ON rs.risk_level_id = rl.id
where is_region = 'TRUE' AND (rs.org_code = #{orgCode} OR rs.org_code like CONCAT(#{orgCode},'-%'))
</select>
<select id="findRegionById" resultType="java.util.HashMap">
select
id,name,code,parent_id as parentId,ue4_location as ue4Location,ue4_rotation as ue4Rotation,ue4_extent as ue4Extent,route_path as routePath,
<choose>
<when test="channelType == '3dpage'">
IF(ISNULL(route_path) || LENGTH(trim(route_path)) <![CDATA[ <]]> 1,0,1) as isBind,
</when>
<otherwise>
IF(ISNULL(IF(replace(trim(ue4_rotation),'[]','')='',NULL,ue4_rotation))
AND ISNULL(IF(replace(trim(ue4_location),'[]','')='',NULL,ue4_location)),0,1) as isBind,
</otherwise>
</choose>
IF(is_region = 'TRUE',1,0) as isRegion,
(select name from f_risk_level where level = r.risk_level_id) as riskLevel
from f_risk_source r
where id=#{id} AND (org_code = #{orgCode} OR org_code like CONCAT(#{orgCode},'-%'))
</select>
<update id="batchSaveRegionUe4" parameterType="java.util.List">
<foreach collection="list" item="item" index="index" open="" close="" separator=";">
update f_risk_source
<set >
<if test="item.ue4Location != null" >
ue4_location = #{item.ue4Location,jdbcType=VARCHAR},
</if>
<if test="item.ue4Rotation != null" >
ue4_rotation = #{item.ue4Rotation,jdbcType=VARCHAR},
</if>
<if test="item.ue4Extent != null" >
ue4_extent = #{item.ue4Extent,jdbcType=VARCHAR},
</if>
<if test="item.routePath != null" >
route_path = #{item.routePath,jdbcType=VARCHAR},
</if>
</set>
where id = #{item.riskSourceId,jdbcType=BIGINT}
</foreach>
</update>
</mapper>
\ No newline at end of file
......@@ -974,7 +974,6 @@
fe.is_indoor as inDoor,
case
when fe.equip_classify = 0 then CONCAT('monitorEquipment',fe.id)
when fe.equip_classify = 2 then CONCAT('video',fe.id)
when fe.equip_classify = 3 then CONCAT('fireEquipment',fe.id)
end as `key`,
fe.name,
......@@ -1007,7 +1006,6 @@
fe.name as title,
case
when fe.equip_classify = 0 then 'monitorEquipment'
when fe.equip_classify = 2 then 'video'
when fe.equip_classify = 3 then 'fireEquipment'
end as type,
fe.org_code as orgCode,
......@@ -1117,6 +1115,40 @@
where rs.id is not null
AND s.position3d != '' AND s.position3d is not null
UNION ALL
SELECT
wlv.CODE,
wlv.id,
'' AS inDoor,
CONCAT( 'video', wlv.id ) AS `key`,
wlv.NAME,
'' AS LEVEL,
'' AS levelStr,
'' AS objKey,
CONCAT(
'{"x":',
substring_index( wlv.position3d, ',', 1 ),
',"y":',
substring_index( substring_index( wlv.position3d, ',', - 2 ), ',', 1 ),
',"z":',
substring_index( wlv.position3d, ',', - 1 ),
'}'
)
as positionDTO,
'{ "x": 0, "y": 0, "z": 0 }' rotationDTO,
'{ "x": 1, "y": 1, "z": 1 }' scaleDTO,
FALSE AS `showInfo`,
wlv.NAME AS title,
'video' AS type,
wlv.org_code AS orgCode,
'' AS riskSourceId,
0 AS frequency,
FALSE AS twinkle
FROM
wl_video wlv
WHERE
wlv.position3d != ''
AND wlv.position3d IS NOT NULL
union all
select
w.code,
w.id,
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment