LocalSysFileServiceImpl.java 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553
  1. package com.boman.file.service;
  2. import com.alibaba.fastjson.JSON;
  3. import com.alibaba.fastjson.JSONObject;
  4. import com.alibaba.fastjson.TypeReference;
  5. import com.boman.common.core.utils.SecurityUtils;
  6. import com.boman.common.core.utils.ServletUtils;
  7. import com.boman.common.core.utils.obj.ObjectUtils;
  8. import com.boman.common.core.utils.poi.ExcelUtil;
  9. import com.boman.common.redis.RedisKey;
  10. import com.boman.common.redis.service.RedisService;
  11. import com.boman.domain.*;
  12. import com.boman.domain.constant.CacheConstants;
  13. import com.boman.domain.constant.MaskConstant;
  14. import com.boman.domain.dto.AjaxResult;
  15. import com.boman.domain.dto.ExportExcelDto;
  16. import com.boman.domain.dto.FormDataDto;
  17. import com.boman.domain.dto.ImportExcelDto;
  18. import com.boman.domain.utils.CamelLowerUnderScore;
  19. import com.boman.domain.utils.ThreadPoolService;
  20. import com.boman.file.utils.FileUploadUtils;
  21. import com.boman.system.api.RemoteDeptService;
  22. import com.boman.system.api.model.LoginUser;
  23. import com.boman.web.core.api.RemoteAttendanceService;
  24. import com.boman.web.core.api.RemoteObjService;
  25. import com.boman.web.core.api.RemoteVaccineInfoService;
  26. import com.google.common.base.CaseFormat;
  27. import org.apache.commons.beanutils.BeanUtils;
  28. import org.apache.commons.lang3.BooleanUtils;
  29. import org.apache.http.impl.client.HttpClients;
  30. import org.slf4j.Logger;
  31. import org.slf4j.LoggerFactory;
  32. import org.springframework.beans.factory.annotation.Value;
  33. import org.springframework.cloud.context.config.annotation.RefreshScope;
  34. import org.springframework.context.annotation.Primary;
  35. import org.springframework.stereotype.Service;
  36. import org.springframework.web.client.RestTemplate;
  37. import org.springframework.web.multipart.MultipartFile;
  38. import javax.annotation.Resource;
  39. import javax.servlet.http.HttpServletRequest;
  40. import javax.servlet.http.HttpServletResponse;
  41. import java.io.File;
  42. import java.io.FileOutputStream;
  43. import java.io.IOException;
  44. import java.lang.reflect.InvocationTargetException;
  45. import java.util.*;
  46. import java.util.concurrent.TimeUnit;
  47. import static com.boman.common.core.utils.obj.ObjectUtils.*;
  48. /**
  49. * 本地文件存储
  50. *
  51. * @author ruoyi
  52. */
  53. @Primary
  54. @Service
  55. @RefreshScope
  56. public class LocalSysFileServiceImpl implements ISysFileService
  57. {
  58. private static final Logger LOGGER = LoggerFactory.getLogger(LocalSysFileServiceImpl.class);
  59. public static final String DOWNLOADING = "downloading";
  60. @Resource
  61. private RemoteObjService remoteObjService;
  62. @Resource
  63. private RedisService redisService;
  64. @Resource
  65. private RemoteAttendanceService remoteAttendanceService;
  66. @Resource
  67. private RemoteVaccineInfoService remoteVaccineInfoService;
  68. @Resource
  69. private RemoteDeptService remoteDeptService;
  70. /**
  71. * 资源映射路径 前缀
  72. */
  73. @Value("${file.prefix}")
  74. public String localFilePrefix;
  75. /**
  76. * 域名或本机访问地址
  77. */
  78. @Value("${file.domain}")
  79. public String domain;
  80. /**
  81. * 上传文件存储在本地的根路径
  82. */
  83. @Value("${file.path}")
  84. private String localFilePath;
  85. /******************************* 考勤表中的常量 *******************************/
  86. public static final String USERNAME= "userName";
  87. public static final String DEPT_NAME= "deptName";
  88. public static final String ATTENDANCE_TABLE_LEAVE_OR_SUM= "attendanceTableLeaveOrSum";
  89. public static final String ATTENDANCE_TABLE_LATE_SUM= "attendanceTableLateSum";
  90. public static final String ATTENDANCE_TABLE_LEAVE_SUM= "attendanceTableLeaveSum";
  91. public static final String DATE= "date";
  92. /**
  93. * 本地文件上传接口
  94. *
  95. * @param file 上传的文件
  96. * @return 访问地址
  97. * @throws Exception
  98. */
  99. @Override
  100. public String uploadFile(MultipartFile file) throws Exception
  101. {
  102. String name = FileUploadUtils.upload(localFilePath, file);
  103. String url = domain + localFilePrefix + name;
  104. LOGGER.info("上传的路径为: {}", url);
  105. return url;
  106. }
  107. /**
  108. * 功能描述: 上传base64
  109. *
  110. * @param base64 base64
  111. * @return java.lang.String
  112. */
  113. @Override
  114. public String uploadFileBase64(String base64) throws IOException {
  115. MultipartFile multipartFile = FileUploadUtils.base64ToMultipart(base64);
  116. String name = FileUploadUtils.upload(localFilePath, multipartFile);
  117. String path = domain + localFilePrefix + name;
  118. LOGGER.info("上传的路径为: {}", path);
  119. return path;
  120. }
  121. /**
  122. * 功能描述: 通用的导入接口
  123. *
  124. * @param multipartFile multipartFile
  125. * @param tableName tableName
  126. * @return java.util.List<com.alibaba.fastjson.JSONObject>
  127. */
  128. @Override
  129. public AjaxResult importExcelCommon(MultipartFile multipartFile, String tableName) throws Exception {
  130. Objects.requireNonNull(multipartFile, "multipartFile is empty");
  131. ObjectUtils.requireNonNull(tableName, "tableName is empty");
  132. GenTable genTable = redisService.getCacheObject(RedisKey.TABLE_INFO + tableName);
  133. List<GenTableColumn> columns = genTable.getColumns();
  134. ExcelUtil<JSONObject> util = new ExcelUtil<>(JSONObject.class);
  135. List<JSONObject> list = util.importCommonExcel("", multipartFile.getInputStream(), columns);
  136. ImportExcelDto dto = new ImportExcelDto();
  137. dto.setDataList(list);
  138. dto.setTableName(tableName);
  139. return remoteObjService.importCommonData(dto);
  140. }
  141. /**
  142. * 功能描述: 通用的导出接口
  143. *
  144. * @param response response
  145. * @param dto tableName
  146. * empty(true=>只带表头的excel,不含数据, false=>带数据的excel)
  147. * condition 查询条件
  148. * @return com.boman.domain.dto.AjaxResult
  149. */
  150. @Override
  151. public AjaxResult exportExcelCommon(HttpServletResponse response, ExportExcelDto dto) {
  152. String tableName = dto.getTableName();
  153. Boolean empty = dto.getEmpty();
  154. ObjectUtils.requireNonNull(tableName, "exportExcelCommon tableName is empty");
  155. ObjectUtils.requireNonNull(empty, "exportExcelCommon empty is empty");
  156. GenTable genTable = redisService.getCacheObject(RedisKey.TABLE_INFO + tableName);
  157. List<GenTableColumn> columns = genTable.getColumns();
  158. columns = ExcelUtil.filterData(columns, 4, MaskConstant.LIST_VISIBLE::equals);
  159. ExcelUtil<JSONObject> util = new ExcelUtil<>(JSONObject.class);
  160. List<Map<String, Object>> list;
  161. if (BooleanUtils.isTrue(empty)) {
  162. list = new ArrayList<>(0);
  163. } else {
  164. list = getData(dto, tableName, columns);
  165. }
  166. try {
  167. util.exportExcelCommon(response, list, "sheet1", columns, empty, false);
  168. } catch (IOException e) {
  169. e.printStackTrace();
  170. }
  171. return null;
  172. }
  173. /**
  174. * 功能描述: 通用的导出接口
  175. *
  176. * @param response response
  177. * @param dto tableName
  178. * empty(true=>只带表头的excel,不含数据, false=>带数据的excel)
  179. * condition 查询条件
  180. * @return com.boman.domain.dto.AjaxResult
  181. */
  182. @Override
  183. public AjaxResult asyncExportExcelCommon(HttpServletRequest request, HttpServletResponse response, ExportExcelDto dto) {
  184. String tableName = dto.getTableName();
  185. Boolean empty = dto.getEmpty();
  186. ObjectUtils.requireNonNull(tableName, "exportExcelCommon tableName is empty");
  187. ObjectUtils.requireNonNull(empty, "exportExcelCommon empty is empty");
  188. GenTable genTable = redisService.getCacheObject(RedisKey.TABLE_INFO + tableName);
  189. List<GenTableColumn> allColumn = genTable.getColumns();
  190. List<GenTableColumn> columns = ExcelUtil.filterData(allColumn, 4, MaskConstant.LIST_VISIBLE::equals);
  191. String filename = UUID.randomUUID() + ".xlsx";
  192. String fileAbsPath = localFilePath + "/" + filename;
  193. String fileStaticPath = domain + localFilePrefix + "/" + filename;
  194. File file = new File(fileAbsPath);
  195. ExcelUtil<JSONObject> util = new ExcelUtil<>(JSONObject.class);
  196. String username = SecurityUtils.getUsername();
  197. String token = SecurityUtils.getToken(request);
  198. LoginUser loginUser = redisService.getCacheObject(CacheConstants.LOGIN_TOKEN_KEY + token);
  199. Long deptId = loginUser.getSysUser().getDeptId();
  200. List<SysDept> sysDepts = remoteDeptService.listChildrenDepts(deptId);
  201. List<Long> deptIdList = new ArrayList<>();
  202. if (sysDepts != null && sysDepts.size() > 0) {
  203. for (SysDept sysDept : sysDepts) {
  204. Long id = sysDept.getId();
  205. deptIdList.add(id);
  206. }
  207. }
  208. ThreadPoolService.execute(() -> {
  209. List<Map<String, Object>> list;
  210. int size = 0;
  211. Boolean emptyIn = empty;
  212. if (BooleanUtils.isTrue(emptyIn)) {
  213. list = new ArrayList<>(0);
  214. } else {
  215. LOGGER.info("开始查询, 线程名称: {}", Thread.currentThread().getName());
  216. long currentTimeMillis = System.currentTimeMillis();
  217. list = getData1(dto, tableName, columns, token);
  218. if (isEmpty(list)) {
  219. size = 0;
  220. emptyIn = true;
  221. } else {
  222. size = list.size();
  223. }
  224. LOGGER.info("查询到的数据长度为: {}, 查询耗时:{}秒, 文件:{}", size, (System.currentTimeMillis() - currentTimeMillis) / 1000, filename);
  225. }
  226. try {
  227. util.asyncExportExcelCommon(new FileOutputStream(file), list, "sheet1", columns, emptyIn, false);
  228. // long timeout = 2L;
  229. // if (size > 100000 && size < 500000) {
  230. // timeout = 5L;
  231. // } else if(size > 500000){
  232. // timeout = 10L;
  233. // }
  234. String key = RedisKey.ASYNC_DOWNLOAD_YMJZ + username;
  235. JSONObject jsonObject = new JSONObject();
  236. jsonObject.put("fileStaticPath", fileStaticPath);
  237. jsonObject.put("fileAbsPath", fileAbsPath);
  238. redisService.setCacheObject(key, jsonObject);
  239. } catch (IOException e) {
  240. LOGGER.error("导出失败", e);
  241. e.printStackTrace();
  242. }
  243. });
  244. return AjaxResult.success("成功", fileStaticPath);
  245. }
  246. /**
  247. * 功能描述: 通用的导出接口
  248. *
  249. * @param response response
  250. * @param info 查询条件
  251. * @return com.boman.domain.dto.AjaxResult
  252. */
  253. @Override
  254. public AjaxResult asyncExportYmjzExcel(HttpServletResponse response, VaccineInfoOperation info) throws IOException {
  255. GenTable genTable = redisService.getCacheObject(RedisKey.TABLE_INFO + "vaccine_info");
  256. List<GenTableColumn> allColumn = genTable.getColumns();
  257. List<GenTableColumn> columns = ExcelUtil.filterData(allColumn, 4, MaskConstant.LIST_VISIBLE::equals);
  258. String filename = UUID.randomUUID() + ".xlsx";
  259. String fileAbsPath = localFilePath + "/" + filename;
  260. String fileStaticPath = domain + localFilePrefix + "/" + filename;
  261. File file = new File(fileAbsPath);
  262. ExcelUtil<JSONObject> util = new ExcelUtil<>(JSONObject.class);
  263. String username = SecurityUtils.getUsername();
  264. ThreadPoolService.execute(() -> {
  265. List<Map<String, Object>> list;
  266. LOGGER.info("开始查询, 线程名称: {}", Thread.currentThread().getName());
  267. long currentTimeMillis = System.currentTimeMillis();
  268. String key = RedisKey.ASYNC_DOWNLOAD_YMJZ + username;
  269. JSONObject jsonObject = new JSONObject();
  270. jsonObject.put("fileStaticPath", fileStaticPath);
  271. jsonObject.put("fileAbsPath", fileAbsPath);
  272. redisService.setCacheObject(key, jsonObject);
  273. list = listYmjz(info, columns);
  274. boolean empty = isEmpty(list);
  275. int size = BooleanUtils.isFalse(empty) ? 0 : list.size();
  276. LOGGER.info("查询到的数据长度为: {}, 查询耗时:{}秒", size, (System.currentTimeMillis() - currentTimeMillis) / 1000);
  277. try {
  278. util.asyncExportExcelCommon(new FileOutputStream(file), list, "sheet1", columns, empty, false);
  279. long timeout = 2L;
  280. if (size > 100000 && size < 500000) {
  281. timeout = 5L;
  282. } else if (size > 500000) {
  283. timeout = 10L;
  284. }
  285. } catch (IOException e) {
  286. LOGGER.error("导出失败", e);
  287. e.printStackTrace();
  288. }
  289. });
  290. return AjaxResult.success("成功", fileStaticPath);
  291. }
  292. private List<Map<String, Object>> getData(ExportExcelDto dto, String tableName, List<GenTableColumn> columns) {
  293. List<Map<String, Object>> list = null;
  294. FormDataDto condition = new FormDataDto();
  295. condition.setTable(tableName);
  296. condition.setFixedData(new JSONObject(dto.getCondition()));
  297. condition.setPageSize(Integer.MAX_VALUE);
  298. condition.setPageNo(1);
  299. AjaxResult ajaxResult = remoteObjService.getByMap(condition);
  300. if (AjaxResult.checkSuccess(ajaxResult)) {
  301. list = ((List<Map<String, Object>>) ajaxResult.get(AjaxResult.DATA_TAG));
  302. handleNullColumnValue(list, map(columns, GenTableColumn::getColumnName));
  303. }
  304. return list;
  305. }
  306. private List<Map<String, Object>> getData1(ExportExcelDto dto, String tableName, List<GenTableColumn> columns, String token) {
  307. List<Map<String, Object>> list = null;
  308. Map<String, Object> formData = dto.getCondition();
  309. String idCard = (String) formData.get("idCard");
  310. String userName = (String) formData.get("userName");
  311. String phoneNum = (String) formData.get("phoneNum");
  312. String jici = (String) formData.get("jici");
  313. String keyIndustries = (String) formData.get("keyIndustries");
  314. String vaccineName = (String) formData.get("vaccineName");
  315. String vaccinationPlace = (String) formData.get("vaccinationPlace");
  316. String isVaccination = (String) formData.get("isVaccination");
  317. String shouldBe = (String) formData.get("shouldBe");
  318. String shouldSlow = (String) formData.get("shouldSlow");
  319. Integer deptIdTemp = (Integer) formData.get("deptId");
  320. Long deptId;
  321. if (deptIdTemp == null) {
  322. LoginUser loginUser = redisService.getCacheObject(CacheConstants.LOGIN_TOKEN_KEY + token);
  323. deptId = loginUser.getSysUser().getDeptId();
  324. } else {
  325. deptId = deptIdTemp.longValue();
  326. }
  327. List<SysDept> sysDepts = remoteDeptService.listChildrenDepts(deptId);
  328. List<Long> deptIdList = new ArrayList<>();
  329. if (sysDepts != null && sysDepts.size() > 0) {
  330. for (SysDept sysDept : sysDepts) {
  331. Long id = sysDept.getId();
  332. deptIdList.add(id);
  333. }
  334. }
  335. FormDataDto condition = new FormDataDto();
  336. condition.setTable(tableName);
  337. JSONObject jsonObject = new JSONObject();
  338. jsonObject.put("dept_id", deptIdList);
  339. jsonObject.put("is_del", 'N');
  340. if (isNotEmpty(idCard)) {
  341. jsonObject.put("id_card", idCard);
  342. }
  343. if (isNotEmpty(phoneNum)) {
  344. jsonObject.put("phone_num", phoneNum);
  345. }
  346. if (isNotEmpty(userName)) {
  347. jsonObject.put("user_name", userName);
  348. }
  349. if (isNotEmpty(jici)) {
  350. jsonObject.put("jici", jici);
  351. }
  352. if (isNotEmpty(keyIndustries)) {
  353. jsonObject.put("key_industries", keyIndustries);
  354. }
  355. if (isNotEmpty(vaccineName)) {
  356. jsonObject.put("vaccine_name", vaccineName);
  357. }
  358. if (isNotEmpty(vaccinationPlace)) {
  359. jsonObject.put("vaccination_place", vaccinationPlace);
  360. }
  361. if (isNotEmpty(isVaccination)) {
  362. jsonObject.put("is_vaccination", isVaccination);
  363. }
  364. if (isNotEmpty(shouldBe)) {
  365. jsonObject.put("should_be", shouldBe);
  366. }
  367. if (isNotEmpty(shouldSlow)) {
  368. jsonObject.put("should_slow", shouldSlow);
  369. }
  370. condition.setFixedData(jsonObject);
  371. condition.setPageSize(Integer.MAX_VALUE);
  372. condition.setPageNo(1);
  373. AjaxResult ajaxResult = remoteObjService.getByMap(condition);
  374. if (AjaxResult.checkSuccess(ajaxResult)) {
  375. list = ((List<Map<String, Object>>) ajaxResult.get(AjaxResult.DATA_TAG));
  376. handleNullColumnValue(list, map(columns, GenTableColumn::getColumnName));
  377. }
  378. return list;
  379. }
  380. /**
  381. * 功能描述: 单独去查疫苗接种信息的
  382. *
  383. * @param info info
  384. * @return java.util.List<java.util.Map < java.lang.String, java.lang.Object>>
  385. */
  386. private List<Map<String, Object>> listYmjz(VaccineInfoOperation info, List<GenTableColumn> columns) {
  387. // TableDataInfo list = remoteObjService.list(info);
  388. // LOGGER.info("查询结果:{}", JSON.toJSONString(list));
  389. // List<?> rows = list.getRows();
  390. // return JSON.parseObject(JSON.toJSONString(rows), new TypeReference<List<Map<String, Object>>>() {
  391. // }.getType());
  392. List<Map<String, Object>> list = null;
  393. FormDataDto condition = new FormDataDto();
  394. condition.setTable("vaccine_info");
  395. condition.setFixedData(new JSONObject());
  396. condition.setPageSize(Integer.MAX_VALUE);
  397. condition.setPageNo(1);
  398. AjaxResult ajaxResult = remoteObjService.getByMap(condition);
  399. if (AjaxResult.checkSuccess(ajaxResult)) {
  400. list = ((List<Map<String, Object>>) ajaxResult.get(AjaxResult.DATA_TAG));
  401. handleNullColumnValue(list, map(columns, GenTableColumn::getColumnName));
  402. }
  403. return list;
  404. }
  405. /**
  406. * 功能描述: 导出数据,只是sql不一样,其余的都是通用接口的内容
  407. *
  408. * @param response response
  409. * @param dto tableName
  410. * empty(true=>只带表头的excel,不含数据, false=>带数据的excel)
  411. * condition 查询条件
  412. * @return com.boman.domain.dto.AjaxResult
  413. */
  414. @Override
  415. public AjaxResult statisticsByMonth(HttpServletResponse response, ExportExcelDto dto) {
  416. String tableName = dto.getTableName();
  417. Boolean empty = dto.getEmpty();
  418. ObjectUtils.requireNonNull(tableName, "exportExcelCommon tableName is empty");
  419. ObjectUtils.requireNonNull(empty, "exportExcelCommon empty is empty");
  420. ExcelUtil<JSONObject> util = new ExcelUtil<>(JSONObject.class);
  421. List<Map<String, Object>> list = null;
  422. if (BooleanUtils.isTrue(empty)) {
  423. list = new ArrayList<>(0);
  424. } else {
  425. AjaxResult ajaxResult = remoteAttendanceService.statisticsByMonth(dto.getCondition());
  426. if (AjaxResult.checkSuccess(ajaxResult)) {
  427. list = ((List<Map<String, Object>>) ajaxResult.get(AjaxResult.DATA_TAG));
  428. // 导出不需要user_id, 同时把map中的value换成int
  429. List<Map<String, Object>> newList = new ArrayList<>(list.size());
  430. for (Map<String, Object> map : list) {
  431. map.remove("user_id");
  432. for (Map.Entry<String, Object> entry : map.entrySet()) {
  433. Object value = entry.getValue();
  434. if (value instanceof Double) {
  435. Double value1 = (Double) value;
  436. entry.setValue(value1.intValue());
  437. }
  438. }
  439. Map<String, Object> newMap = new LinkedHashMap<>(map.size());
  440. newMap.put(USERNAME, map.get(USERNAME));
  441. newMap.put(DEPT_NAME, map.get(DEPT_NAME));
  442. newMap.put(ATTENDANCE_TABLE_LATE_SUM, map.get(ATTENDANCE_TABLE_LATE_SUM));
  443. newMap.put(ATTENDANCE_TABLE_LEAVE_SUM, map.get(ATTENDANCE_TABLE_LEAVE_SUM));
  444. newMap.put(ATTENDANCE_TABLE_LEAVE_OR_SUM, map.get(ATTENDANCE_TABLE_LEAVE_OR_SUM));
  445. newMap.put(DATE, map.get(DATE));
  446. newList.add(newMap);
  447. }
  448. list = newList;
  449. }
  450. }
  451. try {
  452. util.exportExcelCommon(response, list, "sheet1", null, empty, true);
  453. } catch (IOException e) {
  454. LOGGER.error("考勤统计导出失败,导出数据为:{}", list);
  455. e.printStackTrace();
  456. }
  457. return null;
  458. }
  459. /**
  460. * 功能描述: 通用的导入接口
  461. *
  462. * @param dto@return java.util.List<com.alibaba.fastjson.JSONObject>
  463. */
  464. @Override
  465. public List<JSONObject> importExcelCommon(ImportExcelDto dto) throws Exception {
  466. return null;
  467. }
  468. public void handleNullColumnValue(List<Map<String, Object>> result, List<String> showData) {
  469. for (Map<String, Object> map : result) {
  470. Set<String> resultKeySet = map.keySet();
  471. for (String columnName : showData) {
  472. if (!resultKeySet.contains(columnName)) {
  473. map.put(columnName, "");
  474. }
  475. }
  476. }
  477. }
  478. /**
  479. * 功能描述: 获取系统配置
  480. *
  481. * @return java.lang.String
  482. */
  483. @Override
  484. public String getConfigPath() {
  485. return localFilePrefix + "_._" + domain + "_._" + localFilePath;
  486. }
  487. }