RelationReportController.java 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724
  1. package com.persagy.proxy.adm.controller;
  2. import java.io.File;
  3. import java.io.FileNotFoundException;
  4. import java.io.FileOutputStream;
  5. import java.io.IOException;
  6. import java.net.URLEncoder;
  7. import java.nio.charset.StandardCharsets;
  8. import java.util.ArrayList;
  9. import java.util.HashSet;
  10. import java.util.List;
  11. import java.util.Set;
  12. import javax.servlet.http.HttpServletRequest;
  13. import javax.servlet.http.HttpServletResponse;
  14. import org.apache.poi.xssf.usermodel.XSSFCell;
  15. import org.apache.poi.xssf.usermodel.XSSFRow;
  16. import org.apache.poi.xssf.usermodel.XSSFSheet;
  17. import org.apache.poi.xssf.usermodel.XSSFWorkbook;
  18. import org.springframework.beans.factory.annotation.Value;
  19. import org.springframework.util.ResourceUtils;
  20. import org.springframework.web.bind.annotation.RequestBody;
  21. import org.springframework.web.bind.annotation.RequestMapping;
  22. import org.springframework.web.bind.annotation.RequestParam;
  23. import org.springframework.web.bind.annotation.RestController;
  24. import org.springframework.web.multipart.MultipartFile;
  25. import com.alibaba.excel.EasyExcel;
  26. import com.alibaba.excel.ExcelWriter;
  27. import com.alibaba.fastjson.JSONObject;
  28. import com.fasterxml.jackson.core.JsonProcessingException;
  29. import com.fasterxml.jackson.databind.ObjectMapper;
  30. import com.fasterxml.jackson.databind.node.ObjectNode;
  31. import com.google.common.collect.Lists;
  32. import com.persagy.dmp.basic.model.QueryCriteria;
  33. import com.persagy.dmp.common.helper.SpringHelper;
  34. import com.persagy.proxy.adm.constant.AdmCommonConstant;
  35. import com.persagy.proxy.adm.constant.AdmRelationTypeEnum;
  36. import com.persagy.proxy.adm.handler.RelationReportHandler;
  37. import com.persagy.proxy.adm.model.AdmRelationObject;
  38. import com.persagy.proxy.adm.model.EquipmentBindPointExcel;
  39. import com.persagy.proxy.adm.model.EquipmentCountExcel;
  40. import com.persagy.proxy.adm.model.EquipmentExcel;
  41. import com.persagy.proxy.adm.request.AdmQueryCriteria;
  42. import com.persagy.proxy.adm.request.AdmResponse;
  43. import com.persagy.proxy.adm.service.IRelationReportService;
  44. import com.persagy.proxy.adm.strategy.RelationObjectContext;
  45. import com.persagy.proxy.adm.utils.AdmQueryCriteriaHelper;
  46. import cn.hutool.core.collection.CollectionUtil;
  47. import cn.hutool.core.util.StrUtil;
  48. import lombok.RequiredArgsConstructor;
  49. import lombok.extern.slf4j.Slf4j;
  50. /**
  51. * 报表/模板下载
  52. *
  53. * @version 1.0.0
  54. * @company persagy
  55. * @author zhangqiankun
  56. * @date 2021年8月30日 下午7:41:56
  57. */
  58. @Slf4j
  59. @RestController
  60. @RequiredArgsConstructor
  61. public class RelationReportController {
  62. public static final String EXPORT_SHEET_NAME = "关系维护";
  63. @Value("${middleware.group.code}")
  64. private String defaultCode;
  65. private final RelationReportHandler relationReportHandler;
  66. private final RelationObjectContext relationObjectContext;
  67. private final IRelationReportService relationReportService;
  68. /**
  69. * 查询总数量
  70. *
  71. * @param queryCriteria
  72. * @param request
  73. * @return
  74. */
  75. @RequestMapping("/graphic/query-count")
  76. public AdmResponse queryCount(HttpServletRequest request) {
  77. String groupCode = request.getHeader(AdmCommonConstant.GROUP_CODE_HEADER);
  78. String projectId = request.getHeader(AdmCommonConstant.PROJECT_ID_HEADER);
  79. List<JSONObject> relationProjectCal = this.relationReportService.getAllRelationProjectCalTree(groupCode, projectId);
  80. return AdmResponse.success(relationProjectCal);
  81. }
  82. /**
  83. * 查询总览数量-根据类型查询关系数量
  84. *
  85. * @param type relationType
  86. */
  87. @RequestMapping("/graphic/type/query-count")
  88. public AdmResponse countRelationObjects(@RequestParam String type, HttpServletRequest request) {
  89. String groupCode = request.getHeader(AdmCommonConstant.GROUP_CODE_HEADER);
  90. String projectId = request.getHeader(AdmCommonConstant.PROJECT_ID_HEADER);
  91. JSONObject objectNode = this.relationReportService.getRelationProjectCal(groupCode, projectId, type);
  92. return AdmResponse.success(Lists.newArrayList(objectNode));
  93. }
  94. /**
  95. * 查询关系总览(空表,先插入)
  96. *
  97. * @param content:模糊查询卡片名称关键字
  98. * @return
  99. */
  100. @RequestMapping("/graphic/overview")
  101. public JSONObject overview(@RequestParam(required = false) String content) throws JsonProcessingException {
  102. JSONObject overview = this.relationReportService.overview(content);
  103. return overview;
  104. }
  105. /**
  106. * 项目关系类型查询
  107. * {"filters":"relationType in [\"bd2sp\",\"fl2sp\"];computationalState>1"}
  108. *
  109. * @param queryCriteria
  110. * @param request
  111. * @return
  112. */
  113. @RequestMapping("/graphic/relation_type_project")
  114. public AdmResponse queryRelationObjects(@RequestBody AdmQueryCriteria requestCriteria, HttpServletRequest request) {
  115. String groupCode = request.getHeader(AdmCommonConstant.GROUP_CODE_HEADER);
  116. String projectId = request.getHeader(AdmCommonConstant.PROJECT_ID_HEADER);
  117. String filters = requestCriteria.getFilters();
  118. QueryCriteria queryCriteria = new QueryCriteria();
  119. ObjectMapper objectMapper = SpringHelper.getBean(ObjectMapper.class);
  120. ObjectNode criteria = objectMapper.createObjectNode();
  121. criteria.put("projectId", projectId);
  122. Set<String> graphs = new HashSet<String>();
  123. Set<String> relCodes = new HashSet<String>();
  124. if (StrUtil.isNotBlank(filters)) {
  125. if (filters.contains("relationType")) {
  126. String condition = filters.substring(filters.indexOf("in [") + 4, filters.lastIndexOf("]"));
  127. String[] split = condition.split(",");
  128. for (String relType : split) {
  129. relType = relType.replaceAll("\"", "");
  130. AdmRelationTypeEnum typeEnum = AdmCommonConstant.RELATION_TYPE_MAP.get(relType);
  131. if (typeEnum != null) {
  132. graphs.add(typeEnum.getGraphCode());
  133. relCodes.add(typeEnum.getRelCode());
  134. }
  135. }
  136. }
  137. String[] split = filters.split(";");
  138. for (int i = 0; i < split.length; i++) {
  139. if (i == 0) {
  140. continue;
  141. }
  142. String express = split[i];
  143. String cond = StrUtil.getContainsStr(express, AdmQueryCriteriaHelper.COND_STR);
  144. cond = StrUtil.isBlank(cond) ? StrUtil.getContainsStr(express, AdmQueryCriteriaHelper.COND_STR_TRIM) : cond;
  145. if(StrUtil.isBlank(cond)) {
  146. continue;
  147. }
  148. int condIndex = StrUtil.indexOfIgnoreCase(express, cond, 0);
  149. String condLeft = StrUtil.subPre(express, condIndex).trim();
  150. String condRight = StrUtil.subSuf(express, condIndex+cond.length()).trim();
  151. // condLeft 替换为中台的字段名称
  152. condLeft = this.convert2BDTPField(condLeft);
  153. if ("=".equals(cond)) {
  154. criteria.put(condLeft, condRight);
  155. } else {
  156. JSONObject condition = new JSONObject();
  157. condition.put(AdmQueryCriteriaHelper.OPERATOR_MAP.get(cond), condRight);
  158. criteria.putPOJO(condLeft, condition);
  159. }
  160. }
  161. }
  162. if (CollectionUtil.isNotEmpty(graphs)) {
  163. JSONObject graphObject = new JSONObject();
  164. graphObject.put("$in", graphs);
  165. criteria.putPOJO("graphCode", graphObject);
  166. }
  167. if (CollectionUtil.isNotEmpty(relCodes)) {
  168. JSONObject relObject = new JSONObject();
  169. relObject.put("$in", relCodes);
  170. criteria.putPOJO("relCode", relObject);
  171. }
  172. queryCriteria.setCriteria(criteria);
  173. List<JSONObject> relationProjectCal = this.relationReportService.getAllRelationProjectCal(queryCriteria, groupCode, projectId);
  174. return AdmResponse.success(relationProjectCal);
  175. }
  176. /**
  177. * 下载报告-查询key值
  178. *
  179. * @param queryCriteria
  180. * @param request
  181. * @return
  182. */
  183. @RequestMapping("/graphic/downloads/point/key")
  184. public AdmResponse downloadsPointKey(@RequestBody AdmQueryCriteria queryCriteria, HttpServletRequest request) {
  185. //String groupCode = request.getHeader(AdmCommonConstant.GROUP_CODE_HEADER);
  186. //String projectId = request.getHeader(AdmCommonConstant.PROJECT_ID_HEADER);
  187. //List<ObjectNode> relationProjectCal = this.relationReportService.getAllRelationProjectCal(groupCode, projectId);
  188. return AdmResponse.success(null);
  189. }
  190. /**
  191. * 下载报告-设备-未关联空间的设备
  192. * 设备.xlsx 是个空模板,所以这里未使用
  193. *
  194. * @param projectId
  195. * @param request
  196. * @param response
  197. * @return
  198. */
  199. @RequestMapping("/graphic/downloads/eq/not/sp")
  200. public void downloadsEqNotSp(@RequestParam(required = false) String projectId, HttpServletRequest request, HttpServletResponse response) {
  201. String groupCode = request.getHeader(AdmCommonConstant.GROUP_CODE_HEADER);
  202. if (StrUtil.isBlank(projectId)) {
  203. projectId = request.getHeader(AdmCommonConstant.PROJECT_ID_HEADER);
  204. }
  205. try {
  206. response.setContentType("application/vnd.ms-excel");
  207. String encode = StandardCharsets.UTF_8.name();
  208. response.setCharacterEncoding(encode);
  209. // 防止中文乱码
  210. String fileName = URLEncoder.encode("equipment", encode);
  211. response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
  212. List<EquipmentExcel> equipByNotSpace = this.relationReportHandler.findEquipByNotSpace(groupCode, projectId);
  213. EasyExcel.write(response.getOutputStream(), EquipmentExcel.class).sheet("设备").doWrite(equipByNotSpace);
  214. } catch(Exception e) {
  215. log.error("设备数据导出异常", e);
  216. }
  217. }
  218. /**
  219. * 下载报告-统计项目下已有的设备,信息点,每个设备
  220. * 设备.xlsx 是个空模板,所以这里未使用
  221. *
  222. * @param projectId
  223. * @param request
  224. * @param response
  225. * @return
  226. */
  227. @RequestMapping("/graphic/downloads/project/binding/point")
  228. public void downloadsProjectBindingPoint(@RequestParam(required = false) String projectId, HttpServletRequest request, HttpServletResponse response) {
  229. String groupCode = request.getHeader(AdmCommonConstant.GROUP_CODE_HEADER);
  230. if (StrUtil.isBlank(projectId)) {
  231. projectId = request.getHeader(AdmCommonConstant.PROJECT_ID_HEADER);
  232. }
  233. try {
  234. response.setContentType("application/vnd.ms-excel");
  235. String encode = StandardCharsets.UTF_8.name();
  236. response.setCharacterEncoding(encode);
  237. // 防止中文乱码
  238. String fileName = URLEncoder.encode("设备实例交付", encode);
  239. response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
  240. List<EquipmentBindPointExcel> equipmentBindPointExcel = this.relationReportHandler.queryProjectBindPoint(groupCode, projectId);
  241. EasyExcel.write(response.getOutputStream(), EquipmentBindPointExcel.class).sheet(0).doWrite(equipmentBindPointExcel);
  242. } catch(Exception e) {
  243. log.error("设备数据导出异常", e);
  244. }
  245. }
  246. /**
  247. * 下载报告-统计项目下已有的设备,以及静态和iot 信息点使用情况
  248. * 设备.xlsx 是个空模板,所以这里未使用
  249. *
  250. * @param projectId
  251. * @param request
  252. * @param response
  253. * @return
  254. */
  255. @RequestMapping("/graphic/downloads/project/equip/count")
  256. public void downloadsProjectEquipPoint(@RequestParam(required = false) String projectId, HttpServletRequest request, HttpServletResponse response) {
  257. String groupCode = request.getHeader(AdmCommonConstant.GROUP_CODE_HEADER);
  258. if (StrUtil.isBlank(projectId)) {
  259. projectId = request.getHeader(AdmCommonConstant.PROJECT_ID_HEADER);
  260. }
  261. try {
  262. response.setContentType("application/vnd.ms-excel");
  263. String encode = StandardCharsets.UTF_8.name();
  264. response.setCharacterEncoding(encode);
  265. // 防止中文乱码
  266. String fileName = URLEncoder.encode("equipment", encode);
  267. response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
  268. List<EquipmentCountExcel> equipmentCountExcel = this.relationReportHandler.countClassCodeEquip(groupCode, projectId);
  269. EasyExcel.write(response.getOutputStream(), EquipmentCountExcel.class).sheet(0).doWrite(equipmentCountExcel);
  270. } catch(Exception e) {
  271. log.error("设备数据导出异常", e);
  272. }
  273. }
  274. /**
  275. * 下载报告-设备静态信息维护模板
  276. *
  277. * @param request
  278. * @param response
  279. */
  280. @RequestMapping("/graphic/downloads/equip/template")
  281. public void downloadEquipTemplate(HttpServletRequest request, HttpServletResponse response) {
  282. ExcelWriter excelWriter = null;
  283. try {
  284. response.setContentType("application/vnd.ms-excel");
  285. String encode = StandardCharsets.UTF_8.name();
  286. response.setCharacterEncoding(encode);
  287. // 防止中文乱码
  288. String fileName = URLEncoder.encode("台账信息导入模板", encode);
  289. response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
  290. File templateFile = this.getTemplateFile("equip_template.xlsx");
  291. excelWriter = EasyExcel.write(response.getOutputStream()).withTemplate(templateFile).build();
  292. } catch (Exception e) {
  293. log.error("设备静态信息维护模板下载失败", e);
  294. } finally {
  295. if (excelWriter != null) {
  296. excelWriter.finish();
  297. }
  298. }
  299. }
  300. /**
  301. * 下载报告-点表
  302. *
  303. * @param request
  304. * @param response
  305. */
  306. @RequestMapping("/graphic/downloads/point")
  307. public void downloadPoint(@RequestParam(required = false) String key, HttpServletRequest request, HttpServletResponse response) {
  308. ExcelWriter excelWriter = null;
  309. try {
  310. response.setContentType("application/vnd.ms-excel");
  311. String encode = StandardCharsets.UTF_8.name();
  312. response.setCharacterEncoding(encode);
  313. response.setHeader("Content-disposition", "attachment;filename=" + key);
  314. File file = null;
  315. try {
  316. file = ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX + "template/upload/" + key);
  317. } catch (FileNotFoundException e) {
  318. file = ResourceUtils.getFile(AdmCommonConstant.SERVER_ROOT_PATH + "template/upload/" + key);
  319. }
  320. if (file == null || !file.exists()) {
  321. try {
  322. file = ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX + "/template/relation-template.xlsx");
  323. } catch (FileNotFoundException e) {
  324. file = ResourceUtils.getFile(AdmCommonConstant.SERVER_ROOT_PATH + "/template/relation-template.xlsx");
  325. }
  326. }
  327. excelWriter = EasyExcel.write(response.getOutputStream()).withTemplate(file).build();
  328. } catch (Exception e) {
  329. log.error("下载报告-点表失败", e);
  330. } finally {
  331. if (excelWriter != null) {
  332. excelWriter.finish();
  333. }
  334. }
  335. }
  336. /**
  337. * 下载模板
  338. *
  339. * @param request
  340. * @param response
  341. */
  342. @RequestMapping("/graphic/template-downloads")
  343. public void templateDownloads(HttpServletRequest request, HttpServletResponse response) {
  344. ExcelWriter excelWriter = null;
  345. try {
  346. response.setContentType("application/vnd.ms-excel");
  347. String encode = StandardCharsets.UTF_8.name();
  348. response.setCharacterEncoding(encode);
  349. response.setHeader("Content-disposition", "attachment;filename=relation-template.xlsx");
  350. File templateFile = this.getTemplateFile("relation-template.xlsx");
  351. excelWriter = EasyExcel.write(response.getOutputStream()).withTemplate(templateFile).build();
  352. } catch (Exception e) {
  353. log.error("模板下载失败", e);
  354. } finally {
  355. if (excelWriter != null) {
  356. excelWriter.finish();
  357. }
  358. }
  359. }
  360. /**
  361. * 下载报告
  362. *
  363. * @param request
  364. * @param response
  365. */
  366. @RequestMapping("/graphic/report-downloads")
  367. public void reportDownloads(@RequestParam String projectId, @RequestParam String relType, @RequestParam(required = false) String zoneType,
  368. HttpServletRequest request, HttpServletResponse response) {
  369. ExcelWriter excelWriter = null;
  370. try {
  371. response.setContentType("application/vnd.ms-excel");
  372. String encode = StandardCharsets.UTF_8.name();
  373. response.setCharacterEncoding(encode);
  374. String templateFile = projectId + AdmCommonConstant.LINE_THROUGH + relType + AdmCommonConstant.EXCEL_SUFFIX_XLSX;
  375. response.setHeader("Content-disposition", "attachment;filename=" + templateFile);
  376. File file = this.getTemplateOrDefaultFile(templateFile);
  377. excelWriter = EasyExcel.write(response.getOutputStream()).withTemplate(file).build();
  378. } catch (Exception e) {
  379. log.error("下载报告失败", e);
  380. } finally {
  381. if (excelWriter != null) {
  382. excelWriter.finish();
  383. }
  384. }
  385. }
  386. /**
  387. * 导出-点位模板
  388. *
  389. * @param request
  390. * @param response
  391. */
  392. @RequestMapping("/graphic/export/point")
  393. public void exportPoint(@RequestParam String buildingId, @RequestParam String floorId, @RequestParam String category,
  394. HttpServletRequest request, HttpServletResponse response) {
  395. ExcelWriter excelWriter = null;
  396. try {
  397. response.setContentType("application/vnd.ms-excel");
  398. String encode = StandardCharsets.UTF_8.name();
  399. response.setCharacterEncoding(encode);
  400. //excelWriter = EasyExcel.write(response.getOutputStream()).withTemplate(file).build();
  401. } catch (Exception e) {
  402. log.error("导出-点位模板失败", e);
  403. } finally {
  404. if (excelWriter != null) {
  405. excelWriter.finish();
  406. }
  407. }
  408. }
  409. /**
  410. * 导出关系
  411. *
  412. * @param request
  413. * @param response
  414. */
  415. @RequestMapping("/graphic/export")
  416. public void export(@RequestParam String projectId, @RequestParam String relType, @RequestParam(required = false) String code,
  417. @RequestParam(required = false) String zoneType, HttpServletRequest request, HttpServletResponse response) {
  418. ExcelWriter excelWriter = null;
  419. try {
  420. String groupCode = request.getHeader(AdmCommonConstant.GROUP_CODE_HEADER);
  421. groupCode = StrUtil.isBlank(groupCode) ? defaultCode : groupCode;
  422. code = StrUtil.isBlank(code) ? "对象ID" : code;
  423. response.setContentType("application/vnd.ms-excel");
  424. String encode = StandardCharsets.UTF_8.name();
  425. response.setCharacterEncoding(encode);
  426. response.setHeader("Content-disposition", "attachment;filename=relation-template.xlsx");
  427. log.info("下载报表: groupCode[{}], projectId[{}], relType[{}], code[{}]", groupCode, projectId, relType, code);
  428. AdmRelationTypeEnum typeEnum = AdmCommonConstant.RELATION_TYPE_MAP.get(relType);
  429. List<AdmRelationObject> relationObjects = null;
  430. if (typeEnum != null) {
  431. String graphAndRelKey = typeEnum.getGraphCode() + AdmCommonConstant.UNDERLINE + typeEnum.getRelCode();
  432. relationObjects = this.relationObjectContext.exportRelationObject(groupCode, projectId, graphAndRelKey);
  433. }
  434. File templateFile = this.getTemplateFile("relation-template.xlsx");
  435. EasyExcel.write(response.getOutputStream()).withTemplate(templateFile).sheet(EXPORT_SHEET_NAME).needHead(false).doWrite(relationObjects);
  436. } catch (Exception e) {
  437. log.error("导出关系失败", e);
  438. } finally {
  439. if (excelWriter != null) {
  440. excelWriter.finish();
  441. }
  442. }
  443. }
  444. /************************************************** 文件上传 ***********************************************/
  445. /**
  446. * 文件导入,这里由于需要回写文件,且存储到本地,采用原始POI文件解析、上传、回写、存储
  447. *
  448. * @param relType
  449. * @param code
  450. * @param zoneType
  451. * @param request
  452. * @param response
  453. */
  454. @SuppressWarnings("resource")
  455. @RequestMapping("/graphic/import")
  456. public AdmResponse importFile(@RequestParam("file") MultipartFile file, @RequestParam String relType, @RequestParam(required = false) String zoneType,
  457. HttpServletRequest request, HttpServletResponse response) {
  458. String failure = null;
  459. FileOutputStream fileOutputStream = null;
  460. try {
  461. if (file == null) {
  462. return AdmResponse.failure("未选择文件");
  463. }
  464. AdmRelationTypeEnum typeEnum = AdmCommonConstant.RELATION_TYPE_MAP.get(relType);
  465. if (typeEnum == null) {
  466. return AdmResponse.failure("不支持的关系类型");
  467. }
  468. String graphAndRelKey = typeEnum.getGraphCode() + AdmCommonConstant.UNDERLINE + typeEnum.getRelCode();
  469. int failurNum = 0;
  470. int successNum = 0;
  471. String graphId = null;
  472. // 临时存储行号
  473. Set<Integer> rowNums = new HashSet<Integer>();
  474. // 批量更新数据
  475. List<ObjectNode> relationObjects = new ArrayList<ObjectNode>();
  476. String groupCode = request.getHeader(AdmCommonConstant.GROUP_CODE_HEADER);
  477. String projectId = request.getHeader(AdmCommonConstant.PROJECT_ID_HEADER);
  478. XSSFWorkbook workbook = new XSSFWorkbook(file.getInputStream());
  479. XSSFSheet sheet = workbook.getSheet("关系维护");
  480. // 获取识别码的属性
  481. String code = sheet.getRow(2).getCell(1).toString();
  482. int lastRowNum = sheet.getLastRowNum();
  483. for (int i = 5; i <= lastRowNum; i++) {
  484. XSSFRow xssfRow = sheet.getRow(i);
  485. if (xssfRow == null) {
  486. continue;
  487. }
  488. // 封装cell数据
  489. XSSFCell masterCodeCell = xssfRow.getCell(0);
  490. XSSFCell slaveCodeCell = xssfRow.getCell(8);
  491. XSSFCell masterIdCell = xssfRow.getCell(3);
  492. XSSFCell slaveIdCell = xssfRow.getCell(11);
  493. AdmRelationObject relationObject = new AdmRelationObject();
  494. relationObject.setMasterCode(masterCodeCell == null ? null : masterCodeCell.getStringCellValue());
  495. relationObject.setSlaveCode(slaveCodeCell == null ? null : slaveCodeCell.getStringCellValue());
  496. relationObject.setMasterId(masterIdCell == null ? null : masterIdCell.getStringCellValue());
  497. relationObject.setSlaveId(slaveIdCell == null ? null : slaveIdCell.getStringCellValue());
  498. // 校验数据
  499. Object result = this.relationObjectContext.checkRelationObject(relationObject, groupCode, projectId, graphAndRelKey, code);
  500. if (result instanceof String) {
  501. failurNum++;
  502. xssfRow.createCell(16).setCellValue((String)result);
  503. continue;
  504. }
  505. ObjectNode relation = (ObjectNode) result;
  506. graphId = relation.get("graphId") == null ? graphId : relation.get("graphId").asText();
  507. // 每一千条数据,批量新增一次
  508. rowNums.add(i);
  509. relationObjects.add(relation);
  510. if (relationObjects.size() >= 1000) {
  511. boolean objects = this.relationObjectContext.saveRelationObjects(relationObjects, groupCode, projectId, graphAndRelKey);
  512. if (objects) {
  513. successNum += relationObjects.size();
  514. } else {
  515. failurNum += relationObjects.size();
  516. for (int rowNum : rowNums) {
  517. sheet.getRow(rowNum).createCell(16).setCellValue("调用中台,存储失败");
  518. }
  519. }
  520. rowNums.clear();
  521. relationObjects.clear();
  522. }
  523. }
  524. // 最后一次遗留数据录入
  525. if (CollectionUtil.isNotEmpty(relationObjects)) {
  526. boolean objects = this.relationObjectContext.saveRelationObjects(relationObjects, groupCode, projectId, graphAndRelKey);
  527. if (objects) {
  528. successNum += relationObjects.size();
  529. } else {
  530. failurNum += relationObjects.size();
  531. for (int rowNum : rowNums) {
  532. sheet.getRow(rowNum).createCell(16).setCellValue("调用中台,存储失败");
  533. }
  534. }
  535. }
  536. try {
  537. // 调用中台存储完成之后,此文件存储至本地
  538. String uploadFile = projectId + AdmCommonConstant.LINE_THROUGH + relType + AdmCommonConstant.EXCEL_SUFFIX_XLSX;
  539. File templateFile = this.createTemplateFile(uploadFile);
  540. fileOutputStream = new FileOutputStream(templateFile);
  541. workbook.write(fileOutputStream);
  542. } catch (Exception e) {
  543. log.error("文件存储失败", e);
  544. }
  545. return AdmResponse.success(Lists.newArrayList(this.getImportResult(graphId, successNum, failurNum)));
  546. } catch (Exception e) {
  547. log.error("文件导入失败", e);
  548. failure = e.getMessage();
  549. } finally {
  550. if (fileOutputStream != null) {
  551. try {
  552. fileOutputStream.flush();
  553. fileOutputStream.close();
  554. } catch (IOException e) {}
  555. }
  556. }
  557. return AdmResponse.failure(failure);
  558. }
  559. /************************************************** 本地文件获取、创建 ***********************************************/
  560. /**
  561. * 获取对应的文件,或者默认文件
  562. * 不同路径,防止镜像部署时获取不到
  563. *
  564. * @param templateName 带后缀的文件名
  565. * @return
  566. * @throws FileNotFoundException
  567. */
  568. private File getTemplateOrDefaultFile(String templateName) throws FileNotFoundException {
  569. File file = null;
  570. try {
  571. file = ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX + "template/" + templateName);
  572. } catch (FileNotFoundException e) {
  573. file = ResourceUtils.getFile(AdmCommonConstant.SERVER_ROOT_PATH + "template/" + templateName);
  574. }
  575. if (file == null || !file.exists()) {
  576. try {
  577. file = ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX + "template/relation-template.xlsx");
  578. } catch (FileNotFoundException e) {
  579. file = ResourceUtils.getFile(AdmCommonConstant.SERVER_ROOT_PATH + "/template/relation-template.xlsx");
  580. }
  581. }
  582. return file;
  583. }
  584. /**
  585. * 获取对应的模板文件,不同路径,防止镜像内获取不到
  586. *
  587. * @param templateName 带后缀的文件名
  588. * @return
  589. * @throws FileNotFoundException
  590. */
  591. private File getTemplateFile(String templateName) throws FileNotFoundException {
  592. File file = null;
  593. try {
  594. file = ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX + "template/" + templateName);
  595. } catch (FileNotFoundException e) {}
  596. if (file == null || !file.exists()) {
  597. file = ResourceUtils.getFile(AdmCommonConstant.SERVER_ROOT_PATH + "/template/" + templateName);
  598. }
  599. return file;
  600. }
  601. /**
  602. * 创建本地文件,这里不再在classpath下创建
  603. *
  604. * @param uploadFile 文件名称,带后缀
  605. * @throws IOException
  606. */
  607. private File createTemplateFile(String uploadFile) throws IOException {
  608. String path = AdmCommonConstant.SERVER_ROOT_PATH + "/template";
  609. File file = new File(path);
  610. if (!file.exists()) {
  611. file.mkdirs();
  612. }
  613. file = new File(path + "/" + uploadFile);
  614. if (!file.exists()) {
  615. file.createNewFile();
  616. }
  617. return file;
  618. }
  619. /**
  620. * 获取导入结果
  621. *
  622. * @return
  623. */
  624. private JSONObject getImportResult(String graphId, int successNum, int failureNum) {
  625. JSONObject result = new JSONObject();
  626. result.put("relationType", graphId);
  627. result.put("successCount", successNum);
  628. result.put("failCount", failureNum);
  629. String state = null;
  630. if (successNum > 0 && failureNum > 0) {
  631. state = "1";
  632. } else if (successNum > 0 && failureNum == 0) {
  633. state = "0";
  634. } else {
  635. state = "2";
  636. }
  637. result.put("state", state);
  638. return result;
  639. }
  640. /**
  641. * 将前端所传的字段,转为BDTP中台所需要的字段
  642. *
  643. * @param condLeft
  644. * @return 转换后的,或原字段
  645. */
  646. private String convert2BDTPField(String condLeft) {
  647. if ("automatic".equals(condLeft)) {
  648. return "automaticFlag";
  649. }
  650. if ("source".equals(condLeft)) {
  651. return "sourceFlag";
  652. }
  653. /*if ("graphicId".equals(condLeft)) {
  654. return "graphCode";
  655. }*/
  656. return condLeft;
  657. }
  658. }