package com.product.administration.service; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.beust.jcommander.internal.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.product.admin.service.PublicService; import com.product.administration.config.CmnConst; import com.product.administration.config.SystemCode; import com.product.administration.service.ide.IEarlyWarningManager; import com.product.common.collect.SetUtils; import com.product.common.exception.job.TaskException; import com.product.common.lang.StringUtils; import com.product.core.dao.BaseDao; import com.product.core.entity.DataTableEntity; import com.product.core.entity.FieldSetEntity; import com.product.core.exception.BaseException; import com.product.core.service.support.AbstractBaseService; import com.product.core.service.support.QueryFilterService; import com.product.core.spring.context.SpringMVCContextHolder; import com.product.core.transfer.Transactional; import com.product.core.websocket.service.WebsocketMesssageServiceThread; import com.product.file.service.FileManagerService; import com.product.module.sys.entity.SystemUser; import com.product.org.admin.service.StaffManagerService; import com.product.quartz.service.impl.SysJobService; import com.product.util.BaseUtil; import com.product.util.SystemParamReplace; import org.apache.commons.codec.binary.Base64; import org.quartz.SchedulerException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.*; @Component public class EarlyWarningManagerService extends AbstractBaseService implements IEarlyWarningManager { @Autowired BaseDao baseDao; @Autowired PublicService publicService; @Autowired SysJobService sysJobService; @Autowired EarlyWarningServer earlyWarningServer; @Autowired QueryFilterService queryFilterService; /** * 预警配置列表 * * @param pageSize * @param cpage * @param fse * @return */ public DataTableEntity listWarning(Integer pageSize, Integer cpage, FieldSetEntity fse) { String queryFilter = queryFilterService.getQueryFilter(fse); if (!StringUtils.isEmpty(fse.getString("filter"))) { String filter = fse.getString("filter"); if (!StringUtils.isEmpty(queryFilter)) { queryFilter += " and "; } queryFilter += " (" + filter + " ) "; } DataTableEntity dt = baseDao.listTable(CmnConst.PRODUCT_SYS_EARLY_WARNING, queryFilter, new Object[]{}, null, null, pageSize, cpage); baseDao.loadPromptData(dt); return dt; } /** * 预警配置详情 * * @param uuid * @return */ public String findWarning(String uuid) { FieldSetEntity fs = baseDao.getFieldSetEntity(CmnConst.PRODUCT_SYS_EARLY_WARNING, uuid, true); JSONObject result = new JSONObject(); Map values = (Map) fs.getValues(); result.putAll(values); //预警方式转换为String[] if (result.get(CmnConst.WARNING_METHOD) != null) { result.put(CmnConst.WARNING_METHOD, result.getString(CmnConst.WARNING_METHOD).split(",")); } String conditon_config = result.getString(CmnConst.CONDITON_CONFIG); if (!JSON.isValidArray(conditon_config)) { conditon_config = null; } result.put(CmnConst.CONDITON_CONFIG, configDataTransition(conditon_config)); String warning_content_config = result.getString(CmnConst.WARNING_CONTENT_CONFIG); if (!JSON.isValidArray(warning_content_config)) { warning_content_config = null; } result.put(CmnConst.WARNING_CONTENT_CONFIG, configDataTransition(warning_content_config)); return BaseUtil.success(result, null); } /** * 预警配置数据装换 */ List> configDataTransition(String arratStr) { List> list = Lists.newArrayList(); if (!StringUtils.isEmpty(arratStr)) { JSONArray array = JSON.parseArray(arratStr); if (array.size() == 0) { return configDataTransition(null); } List row = Lists.newArrayList(); for (int i = 0; i < array.size(); i++) { if (i != 0 && i % 6 == 0) { list.add(row); row = Lists.newArrayList(); } row.add(array.getJSONObject(i)); } if (row.size() > 0) { if (row.size() < 6) { Map template = null; while (row.size() < 6) { template = Maps.newHashMap(); template.put("label", ""); template.put("val", ""); row.add(new JSONObject(template)); } } list.add(row); } if (!StringUtils.isEmpty(list.get(list.size() - 1).get(5).getString("label"))) { List templates = Lists.newArrayList(); JSONObject template = null; row = Lists.newArrayList(); while (row.size() == 6) { template = new JSONObject(); template.put("label", ""); template.put("val", ""); row.add(template); } list.add(templates); } } else { JSONObject template = null; List row = Lists.newArrayList(); while (row.size() < 6) { template = new JSONObject(); template.put("label", ""); template.put("val", ""); row.add(template); } list.add(row); } return list; } /** * 预警配置新增 * * @param fse * @return * @throws TaskException * @throws SchedulerException * @throws BaseException */ @Transactional public String addWarning(FieldSetEntity fse) throws BaseException, SchedulerException, TaskException { fse.setValue(CmnConst.CREATED_BY, SpringMVCContextHolder.getCurrentUser().getUser_id()); fse.setValue(CmnConst.CREATED_UTC_DATETIME, new Date()); if (fse.getString("type").equals("0")){ FieldSetEntity fseJob = new FieldSetEntity(); fseJob.setTableName("product_sys_timed_task"); fseJob.setValue("concurrent", 1); fseJob.setValue("job_name", fse.getString("config_name")); fseJob.setValue("cron_expression", fse.getString("execution_frequency")); fseJob.setValue("invoke_target", "warnTask.triggerSingleWarningTask('null')"); fseJob.setValue("job_group", "system"); fseJob.setValue("misfire_policy", 2); fseJob.setValue("remark", ""); if (fse.getInteger("config_status") == 0) { fseJob.setValue("status", 0); } else { fseJob.setValue("status", 1); } fseJob.setValue("is_conceal", 1); sysJobService.insertJob(fseJob); fse.setValue("time_task_uuid", fseJob.getUUID()); String uuid = baseDao.add(fse); fseJob.setValue("invoke_target", "warnTask.triggerSingleWarningTask('" + fse.getUUID() + "')"); sysJobService.updateJob(fseJob); return uuid; }else { return baseDao.add(fse); } } /** * 预警配置修改 * * @param fse * @return * @throws TaskException * @throws SchedulerException * @throws BaseException */ @Transactional public boolean updateWarning(FieldSetEntity fse) throws BaseException, SchedulerException, TaskException { if (fse.getString("type").equals("0")) { FieldSetEntity fseJob = new FieldSetEntity(); fseJob.setTableName("product_sys_timed_task"); fseJob.setValue("concurrent", 1); fseJob.setValue("job_name", fse.getString("config_name")); fseJob.setValue("cron_expression", fse.getString("execution_frequency")); fseJob.setValue("invoke_target", "warnTask.triggerSingleWarningTask('" + fse.getUUID() + "')"); fseJob.setValue("job_group", "system"); fseJob.setValue("misfire_policy", 2); fseJob.setValue("remark", ""); if (fse.getInteger("config_status") == 0) { fseJob.setValue("status", 0); sysJobService.pauseJob(fse.getString("time_task_uuid")); } else { fseJob.setValue("status", 1); sysJobService.resumeJob(fse.getString("time_task_uuid")); } fseJob.setValue("is_conceal", 1); fseJob.setValue("uuid", fse.getString("time_task_uuid")); sysJobService.updateJob(fseJob); } fse.setValue(CmnConst.UPDATED_BY, SpringMVCContextHolder.getCurrentUser().getUser_id()); fse.setValue(CmnConst.UPDATED_UTC_DATETIME, new Date()); return baseDao.update(fse); } /** * 预警配置删除 * * @param uuid * @return * @throws SchedulerException * @throws BaseException */ @Transactional public boolean deleteWarning(String uuid) throws BaseException, SchedulerException { FieldSetEntity fseWarnInfo = baseDao.getFieldSetEntity(CmnConst.PRODUCT_SYS_EARLY_WARNING, uuid, false); sysJobService.deleteJobByIds(fseWarnInfo.getString("time_task_uuid").split(",")); return baseDao.delete(CmnConst.PRODUCT_SYS_EARLY_WARNING, "uuid=?", new Object[]{uuid}); } /** * 批量修改预警时间 * @param fse * @return * @throws SchedulerException * @throws BaseException */ @Override public boolean updateEarlyWarningTime(FieldSetEntity fse) throws BaseException, SchedulerException, TaskException { String cronExpression = fse.getString("cronExpression"); if(!sysJobService.checkCronExpressionIsValid(cronExpression)){ throw new BaseException (com.product.quartz.config.SystemCode.SYSTEM_QUARTZ_CRON_FAIL.getValue(), com.product.quartz.config.SystemCode.SYSTEM_QUARTZ_CRON_FAIL.getText()); } String uuids = fse.getString("uuids"); String[] uuid = uuids.split(","); DataTableEntity data = baseDao.listTable(fse.getTableName(), BaseUtil.buildQuestionMarkFilter("uuid", uuid,true), new String[]{}); StringBuffer sql = new StringBuffer(); sql.append("SELECT a.* FROM product_sys_timed_task a JOIN " + fse.getTableName() + " b on a.invoke_target like CONCAT('%',b.uuid,'%') WHERE "+ BaseUtil.buildQuestionMarkFilter("b.uuid", uuid,true)); DataTableEntity jobData = baseDao.listTable(sql.toString(), new String[]{}); for (int i = 0; i < data.getRows(); i++) { FieldSetEntity fieldSetEntity = data.getFieldSetEntity(i); fieldSetEntity.setValue("execution_frequency", cronExpression); } baseDao.update(data); for (int i = 0; i < jobData.getRows(); i++) { FieldSetEntity jobFse = jobData.getFieldSetEntity(i); jobFse.setValue("cron_expression",cronExpression); sysJobService.updateJob(jobFse); } return true; } public String getFieldByFlowCode(String type_code) { //获取流程信息 FieldSetEntity fseFlow = baseDao.getFieldSetEntityByFilter(CmnConst.PRODUCT_SYS_FLOW_MODEL, "type_code=?", new Object[]{type_code}, false); if (fseFlow == null) { throw new BaseException(SystemCode.SYS_GET_FLOW_INFO_FAIL.getValue(), SystemCode.SYS_GET_FLOW_INFO_FAIL.getText(), this.getClass(), "getFieldByFlowCode"); } String table_uuid = fseFlow.getString(CmnConst.TABLE_UUID); return publicService.getFields(table_uuid, false); } /** * 预警配置条件检测 * * @return */ public boolean conditionCheck(String mainTableName, String warnCondition) { Map tableNameAndAlias = new HashMap<>();//相关表名-->表别名,tableName-->tableName1 Map fieldAndAlias = new HashMap<>(); //相关字段-->字段别名,tableName.fieldName-->tableName1fieldName Map fieldReference = new HashMap<>(); //组合相关字段的参照,tableName1fieldName-->referenceName StringBuilder concatField = new StringBuilder(); //组合相关字段,tableName1.fieldName tableName1fieldName earlyWarningServer.parseWarningContent(warnCondition, concatField, tableNameAndAlias, fieldAndAlias, fieldReference); // 替换系统参数 warnCondition = SystemParamReplace.systemParamsReplace(warnCondition); //生成主子表关联SQL String relationSQL = earlyWarningServer.createTableRelation(tableNameAndAlias, mainTableName); StringBuilder serviceSQL = new StringBuilder(); serviceSQL.append("\nSELECT \n"); serviceSQL.append(StringUtils.isEmpty(concatField) ? "*" : concatField.subSequence(1, concatField.length())); serviceSQL.append("\nFROM \n"); serviceSQL.append(relationSQL); serviceSQL.append("\nWHERE \n"); serviceSQL.append(earlyWarningServer.parseWarnCondition(warnCondition, tableNameAndAlias)); try { baseDao.listTable(serviceSQL.toString(), new Object[]{}); return true; } catch (Exception e) { SpringMVCContextHolder.getSystemLogger().error(e.getMessage()); return false; } } @Autowired StaffManagerService staffManagerService; public void sendWarnFeedBackMessage(FieldSetEntity fse) throws BaseException { String userId = String.valueOf(SpringMVCContextHolder.getCurrentUser().getUser_id()); fse.setValue( CmnConst.USER_ID,userId);//当前人作为消息发送人,其它预警接收人作为收消息人 String parent_uuid = fse.getString("puuid"); Set receiverSet = this.getReceiver(fse.getString("parent_uuid")); if (StringUtils.isEmpty(parent_uuid)) { //发送给直属领导 String leaderUserId = staffManagerService.getLeaderUserId(); if (!StringUtils.isEmpty(leaderUserId)) { receiverSet.add(leaderUserId); } receiverSet.remove(userId); if(receiverSet.isEmpty()){ logger.error("发送消息,失败"); return; } WebsocketMesssageServiceThread.getInstance().appendMessage( SetUtils.set2String(receiverSet), "您有一条新的预警反馈,请及时查看", "预警反馈", fse.getInteger(CmnConst.USER_ID), String.valueOf(31), CmnConst.BUTTON_URL_WARN_MESSAGE_INFO + "?uuid=" + fse.getString("parent_uuid"), CmnConst.PRODUCT_SYS_EARLY_WARNING_INFO, fse.getString("parent_uuid"), fse.getInteger(CmnConst.USER_ID), 1, 1); } else { FieldSetEntity fs = baseDao.getFieldSetEntity(CmnConst.PRODUCT_SYS_EARLY_WARNING_INFO_FEEDBACK, parent_uuid, false); if (fs != null) { //发送给被回复人 String user_id = fs.getString(CmnConst.USER_ID); if (user_id == null || user_id.equals(fse.getString(CmnConst.USER_ID))) { // logger.error("预警反馈回复消息发送失败," + fse.getUUID()); return; } WebsocketMesssageServiceThread.getInstance().appendMessage( user_id, "您有一条新的预警反馈回复,请及时查看", "预警反馈回复", fse.getInteger(CmnConst.USER_ID), String.valueOf(31), CmnConst.BUTTON_URL_WARN_MESSAGE_INFO + "?uuid=" + fse.getString("parent_uuid"), CmnConst.PRODUCT_SYS_EARLY_WARNING_INFO, fse.getString("parent_uuid"), fse.getInteger(CmnConst.USER_ID), 1, 1); } } } /** * 获取消息接收人 * @param parent_uuid * @return */ public Set getReceiver(String parent_uuid){ Set receiverSet = Sets.newHashSet(); FieldSetEntity fieldSetEntity = baseDao.getFieldSet("product_sys_early_warning_info", parent_uuid, false); String receiver = fieldSetEntity.getString("receiver"); Collections.addAll(receiverSet, receiver.split(",")); return receiverSet; } @Autowired FileManagerService fileManagerService; public DataTableEntity getWarnFeedBack(String parent_uuid) { DataTableEntity dt = baseDao.listTable("select a.*,b.thumbnail_img,b.user_name FROM product_sys_early_warning_info_feedback a\n" + "join product_sys_users b on a.created_by=b.user_id where a.parent_uuid=? order by createDate", new Object[]{parent_uuid}); if (!BaseUtil.dataTableIsEmpty(dt)) { Map> usersMap = Maps.newHashMap(); for (int i = 0; i < dt.getRows(); i++) { String thumbnail_img = dt.getString(i, "thumbnail_img"); String user_id = dt.getString(i, CmnConst.USER_ID); String user_name = dt.getString(i, CmnConst.USER_NAME); String puuid = dt.getString(i, "puuid"); Map commentUser = Maps.newHashMap(); dt.setFieldValue(i, "commentUser", commentUser); if (!StringUtils.isEmpty(puuid)) { dt.setFieldValue(i, "targetUser", new JSONObject(usersMap.get(puuid))); } usersMap.put(dt.getString(i, CmnConst.UUID), commentUser); commentUser.put("user_id", user_id); commentUser.put("id", user_id); commentUser.put("nickName", user_name); if (!StringUtils.isEmpty(thumbnail_img)) { // 获取员工头像 try { byte[] fileContent = fileManagerService.getFileContent(thumbnail_img); if (fileContent == null) { continue; } String bytes = Base64.encodeBase64String(fileContent); commentUser.put("avatar", "data:image/*;base64," + bytes); } catch (Exception e) { // e.printStackTrace(); } } } } return dt; } public FieldSetEntity findWarnInfo(FieldSetEntity fse) throws BaseException { FieldSetEntity fs = publicService.getFieldSetEntity(fse, false); if (fs != null) { // 已查看人 String preReadedUsers = fs.getString(CmnConst.KNOWN_USER); String curUserID = SpringMVCContextHolder.getCurrentUserId(); if (StringUtils.isEmpty(preReadedUsers)) { fs.setValue(CmnConst.KNOWN_USER, curUserID); } else { if (!("," + preReadedUsers + ",").contains("," + curUserID + ",")) { fs.setValue(CmnConst.KNOWN_USER, preReadedUsers + "," + curUserID); } } if (preReadedUsers == null || !preReadedUsers.equals(fs.getString(CmnConst.KNOWN_USER))) { baseDao.update(fs); } String uuid = fs.getUUID(); DataTableEntity warnFeedBack = getWarnFeedBack(uuid); fs.addSubDataTable(warnFeedBack); } return fs; } /** * 预警反馈-列表 * @param fse * @return */ public DataTableEntity listWarnInfo(FieldSetEntity fse) { StringBuilder sql = new StringBuilder(128); sql.append("\nselect distinct i.*"); sql.append("\nfrom product_sys_early_warning_info i"); sql.append("\ninner join ("); sql.append("\n select user_id"); sql.append("\n from product_sys_staffs s"); sql.append("\n inner join ("); sql.append("\n select org_level_code from product_sys_staffs sc inner join product_sys_org_levels c on sc.org_level_uuid=c.uuid and sc.is_org_manager=1 and user_id=?"); sql.append("\n union all"); sql.append("\n select org_level_code from product_sys_staffs sc inner join product_sys_org_levels d on sc.dept_uuid=d.uuid and sc.is_dept_manage=1 and user_id=?"); sql.append("\n ) o on s.tricode like concat(o.org_level_code,'%')"); sql.append("\n union all"); sql.append("\n select ? from dual"); sql.append("\n) u on concat(',',i.receiver,',') like concat('%,',u.user_id,',%')"); sql.append("\nwhere early_warning_uuid is not null"); SystemUser sysUser = SpringMVCContextHolder.getCurrentUser(); int userID = sysUser.getUser_id(); if (!BaseUtil.dataTableIsEmpty(fse.getSubDataTable("systemSeniorQueryString"))) { sql.append("\nand (").append(queryFilterService.getQueryFilter(fse)).append(")"); } sql.append("\norder by id desc"); Integer cpage = fse.getInteger("cpage"); Integer pageSize = fse.getInteger("pagesize"); DataTableEntity dte = baseDao.listTable(sql.toString(), new Object[]{userID, userID, userID}, pageSize, cpage); if (!DataTableEntity.isEmpty(dte)) { baseDao.loadPromptData(dte); } return dte; } /** * 转发 * @param fse */ @Override public void transmit(FieldSetEntity fse) { String uuid = fse.getUUID(); String messageAccepter = fse.getString("user"); FieldSetEntity warnMsgFse = baseDao.getFieldSetEntity(CmnConst.PRODUCT_SYS_EARLY_WARNING_INFO, uuid, false); String preReceiver = warnMsgFse.getString(CmnConst.RECEIVER); Set preReceiverSet = Sets.newHashSet(preReceiver.split(",")); if (StringUtils.isEmpty(messageAccepter)) { throw new BaseException(SystemCode.WARN_TRANSMIT_USER_IS_NULL); } Set transmitUserSet = Sets.newHashSet(messageAccepter.split(",")); transmitUserSet.forEach(transmitUser -> { if (preReceiverSet.contains(transmitUser)) { FieldSetEntity transmitUserFse = baseDao.getFieldSetByFilter(CmnConst.PRODUCT_SYS_USERS, "user_id=?", new Object[]{transmitUser}, false); throw new BaseException(SystemCode.WARN_TRANSMIT_USER_REPEAT.getValue(), String.format("%s:%s", SystemCode.WARN_TRANSMIT_USER_REPEAT.getText(), transmitUserFse.getString(CmnConst.USER_NAME))); } }); // 更新预警信息表 warnMsgFse.setValue(CmnConst.RECEIVER, preReceiver + "," + messageAccepter); baseDao.saveFieldSetEntity(warnMsgFse); // 发送消息给转发人 SystemUser curUser = SpringMVCContextHolder.getCurrentUser(); FieldSetEntity msgFse = baseDao.getFieldSetByFilter(CmnConst.PRODUCT_SYS_MESSAGE, "source_table=? and source_uuid=?", new Object[]{CmnConst.PRODUCT_SYS_EARLY_WARNING_INFO, uuid}, false); String title = String.format("%s向您转发了预警消息《%s》", curUser.getUser_name(), msgFse.getString(CmnConst.TITLE)); String content = msgFse.getString("content"); WebsocketMesssageServiceThread.getInstance().appendMessage(messageAccepter, content, title, curUser.getUser_id(), "31", CmnConst.BUTTON_URL_WARN_MESSAGE_INFO + "?uuid=" + fse.getUUID(), CmnConst.PRODUCT_SYS_EARLY_WARNING_INFO, fse.getUUID(), curUser.getUser_id(), 0, 0, null); } }