AuthServiceImpl.java 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809
  1. package com.caimei.service.impl;
  2. import com.caimei.config.FastDfsClient;
  3. import com.caimei.mapper.AuthMapper;
  4. import com.caimei.mapper.AuthProductMapper;
  5. import com.caimei.model.ResponseJson;
  6. import com.caimei.model.dto.ProductSaveDto;
  7. import com.caimei.model.po.AuthImportPo;
  8. import com.caimei.model.po.CmBrandAuthPo;
  9. import com.caimei.model.po.ProductParamPo;
  10. import com.caimei.model.vo.AuthFormVo;
  11. import com.caimei.model.vo.AuthVo;
  12. import com.caimei.model.vo.ProductFormVo;
  13. import com.caimei.service.AuthProductService;
  14. import com.caimei.service.AuthService;
  15. import com.caimei.service.ShopService;
  16. import com.caimei.utils.ExcelOperateUtil;
  17. import com.github.pagehelper.PageHelper;
  18. import com.github.pagehelper.PageInfo;
  19. import lombok.extern.slf4j.Slf4j;
  20. import org.apache.commons.lang3.StringUtils;
  21. import org.apache.poi.hssf.usermodel.*;
  22. import org.apache.poi.ss.usermodel.*;
  23. import org.apache.poi.xssf.usermodel.*;
  24. import org.springframework.beans.BeanUtils;
  25. import org.springframework.beans.factory.annotation.Autowired;
  26. import org.springframework.beans.factory.annotation.Value;
  27. import org.springframework.stereotype.Service;
  28. import org.springframework.web.multipart.MultipartFile;
  29. import javax.annotation.Resource;
  30. import javax.imageio.ImageIO;
  31. import javax.servlet.http.HttpServletResponse;
  32. import java.awt.image.BufferedImage;
  33. import java.io.*;
  34. import java.net.HttpURLConnection;
  35. import java.net.URL;
  36. import java.util.*;
  37. import java.util.concurrent.atomic.AtomicInteger;
  38. /**
  39. * Description
  40. *
  41. * @author : Aslee
  42. * @date : 2021/5/11
  43. */
  44. @Slf4j
  45. @Service
  46. public class AuthServiceImpl implements AuthService {
  47. @Resource
  48. private AuthMapper authMapper;
  49. @Resource
  50. private AuthProductMapper authProductMapper;
  51. private AuthProductService authProductService;
  52. @Autowired
  53. public void setAuthProductService(AuthProductService authProductService) {
  54. this.authProductService = authProductService;
  55. }
  56. private ShopService shopService;
  57. @Autowired
  58. public void setShopService(ShopService shopService) {
  59. this.shopService = shopService;
  60. }
  61. @Value("${spring.profiles.active}")
  62. private String active;
  63. @Autowired
  64. private FastDfsClient client;
  65. @Value("${caimei.imageDomain}")
  66. private String imageDomain;
  67. @Override
  68. public ResponseJson<PageInfo<AuthVo>> getAuthList(Integer listType, Integer authUserId, String authParty, Integer status, Integer auditStatus, Integer lowerAuditStatus, Integer pageNum, Integer pageSize) {
  69. if (null == authUserId) {
  70. return ResponseJson.error("参数异常,请输入供应商用户id", null);
  71. }
  72. listType = null == listType ? 1 : listType;
  73. PageHelper.startPage(pageNum, pageSize);
  74. List<AuthVo> authList = authMapper.getAuthList(listType, authUserId, authParty, status, auditStatus);
  75. ListIterator<AuthVo> iterator = authList.listIterator();
  76. while (iterator.hasNext()) {
  77. // 根据是否完成商品信息审核筛选项,进行筛选
  78. AuthVo auth = iterator.next();
  79. Integer waitAuditNum = auth.getWaitAuditNum();
  80. if (waitAuditNum > 0) {
  81. auth.setLowerAuditStatus(0);
  82. if (null != lowerAuditStatus && 1 == lowerAuditStatus) {
  83. iterator.remove();
  84. }
  85. } else {
  86. auth.setLowerAuditStatus(1);
  87. if (null != lowerAuditStatus && 0 == lowerAuditStatus) {
  88. iterator.remove();
  89. }
  90. }
  91. }
  92. PageInfo<AuthVo> pageData = new PageInfo<>(authList);
  93. return ResponseJson.success(pageData);
  94. }
  95. @Override
  96. public ResponseJson updateAuthStatus(Integer authId, Integer status) {
  97. if (null == authId) {
  98. return ResponseJson.error("请输入授权id");
  99. }
  100. if (null == status) {
  101. return ResponseJson.error("请输入要更新的状态值");
  102. }
  103. authMapper.updateAuthStatusByAuthId(authId, status);
  104. if (0 == status) {
  105. return ResponseJson.success("下线品牌授权成功");
  106. } else {
  107. return ResponseJson.success("上线品牌授权成功");
  108. }
  109. }
  110. @Override
  111. public ResponseJson deleteAuth(Integer authId) {
  112. if (null == authId) {
  113. return ResponseJson.error("参数异常,请输入授权id");
  114. }
  115. // 删除品牌授权
  116. authMapper.deleteAuthByAuthId(authId);
  117. // 删除商品及商品参数
  118. List<Integer> productIdList = authProductService.getProductIdsByAuthId(authId);
  119. productIdList.forEach(productId->{
  120. if (null != productId) {
  121. authProductService.deleteProduct(productId);
  122. }
  123. });
  124. return ResponseJson.success("删除品牌授权成功");
  125. }
  126. @Override
  127. public ResponseJson<AuthFormVo> getAuthFormData(Integer authId) {
  128. if (null == authId) {
  129. return ResponseJson.error("参数异常,机构id不能为空", null);
  130. }
  131. CmBrandAuthPo auth = authMapper.getAuthById(authId);
  132. AuthFormVo authFormVo = new AuthFormVo();
  133. authFormVo.setAuthId(auth.getId());
  134. BeanUtils.copyProperties(auth, authFormVo);
  135. List<String> bannerList = authMapper.getBannerList(authId);
  136. authFormVo.setBannerList(bannerList);
  137. return ResponseJson.success(authFormVo);
  138. }
  139. @Override
  140. public ResponseJson saveAuth(CmBrandAuthPo auth, List<String> bannerList, boolean importFlag) {
  141. Integer authId = auth.getId();
  142. Integer authUserId = auth.getAuthUserId();
  143. String authParty = auth.getAuthParty();
  144. if (null == authUserId) {
  145. return ResponseJson.error("参数异常,请输入供应商用户id");
  146. }
  147. if (StringUtils.isBlank(authParty)) {
  148. return ResponseJson.error("参数异常,请输入授权机构名称");
  149. }
  150. Integer authIdByAuthParty = authMapper.getAuthIdByAuthParty(authParty, authUserId);
  151. if (null != authIdByAuthParty && !authIdByAuthParty.equals(authId)) {
  152. return ResponseJson.error("参数异常,该授权机构已存在,请重新输入", null);
  153. }
  154. if (null == auth.getCreateBy()) {
  155. return ResponseJson.error("参数异常,请输入创建人id");
  156. }
  157. if (!importFlag) {
  158. if (null == auth.getProvinceId() || null == auth.getCityId() || null == auth.getTownId() || StringUtils.isEmpty(auth.getAddress()) || StringUtils.isEmpty(auth.getLonAndLat())) {
  159. return ResponseJson.error("参数异常,地址信息异常");
  160. }
  161. if (StringUtils.isEmpty(auth.getLogo())) {
  162. return ResponseJson.error("参数异常,请上传机构logo");
  163. }
  164. if (null == bannerList || bannerList.size() <= 0) {
  165. return ResponseJson.error("参数异常,请上传轮播图");
  166. }
  167. }
  168. // 保存品牌授权信息,上线状态默认为“待上线”,审核状态为“待审核”
  169. auth.setStatus(2);
  170. auth.setAuditStatus(2);
  171. /*
  172. 保存授权
  173. */
  174. if (null == authId) {
  175. authMapper.insertAuth(auth);
  176. } else {
  177. authMapper.updateAuthByAuthId(auth);
  178. // 删除原有的轮播图
  179. authMapper.deleteBanner(auth.getId());
  180. }
  181. // 保存轮播图
  182. bannerList.forEach(banner-> authMapper.insertBanner(auth.getId(), banner));
  183. return ResponseJson.success("保存品牌授权成功", auth);
  184. }
  185. @Override
  186. public ResponseJson auditAuth(Integer authId, Integer auditStatus, String invalidReason, Integer auditBy) {
  187. if (authId == null) {
  188. return ResponseJson.error("请输入授权id");
  189. }
  190. if (auditStatus == null) {
  191. return ResponseJson.error("请输入审核结果");
  192. }
  193. if (auditStatus == 0 && StringUtils.isEmpty(invalidReason)) {
  194. return ResponseJson.error("请输入审核不通过的原因");
  195. }
  196. if (auditBy == null) {
  197. return ResponseJson.error("请输入审核人用户id");
  198. }
  199. Date auditTime = new Date();
  200. // 授权状态更新
  201. Integer status = null;
  202. if (auditStatus == 0) {
  203. // 审核不通过,下线授权
  204. status = 0;
  205. } else {
  206. // 审核通过,上线授权
  207. status = 1;
  208. }
  209. authMapper.updateAuthAuditStatus(authId, status, auditStatus, invalidReason, auditBy, auditTime);
  210. return ResponseJson.success("审核品牌授权成功");
  211. }
  212. @Override
  213. public ResponseJson importDataByExcel(MultipartFile file, Integer authUserId, Integer createBy) {
  214. String originalFilename = file.getOriginalFilename();
  215. String randomStr = UUID.randomUUID().toString();
  216. assert originalFilename != null;
  217. int index = originalFilename.lastIndexOf(".");
  218. String extName = originalFilename.substring(index);
  219. String filePath = "/mnt/newdatadrive/data/runtime/jar-instance/zplma/tempFile/";
  220. if ("dev".equals(active)) {
  221. filePath = "D:\\WorkSpace\\file\\tempImport\\";
  222. }
  223. filePath += randomStr + extName;
  224. try {
  225. File tempFile = new File(filePath);
  226. if (!tempFile.exists()) {
  227. tempFile.mkdirs();
  228. }
  229. file.transferTo(tempFile);
  230. return saveExcelData(filePath, authUserId, createBy);
  231. } catch (IOException e) {
  232. e.printStackTrace();
  233. }
  234. log.info(">>>>>>>>>>>>>>>>文件临时路径:" + filePath);
  235. return null;
  236. }
  237. @Override
  238. public ResponseJson exportDataByExcel(Integer authUserId, HttpServletResponse response) {
  239. try {
  240. // 导出表格名
  241. String fileName = new String("机构商品数据.xlsx".getBytes("UTF-8"),"iso-8859-1");
  242. // 机构数据
  243. List<CmBrandAuthPo> authPartyList = authMapper.getAuthPartyList(authUserId);
  244. authPartyList.forEach(authParty->{
  245. // 商品参数数量最大值
  246. final Integer[] maxParamNum = {0};
  247. Integer authId = authParty.getId();
  248. List<ProductFormVo> productList = authProductMapper.getAuthProductList(authId);
  249. productList.forEach(product->{
  250. // 参数列表
  251. List<ProductParamPo> paramList = authProductMapper.getParamsByProductId(product.getProductId());
  252. product.setParamList(paramList);
  253. if (paramList.size() > maxParamNum[0]) {
  254. maxParamNum[0] = paramList.size();
  255. }
  256. });
  257. authParty.setMaxParamNum(maxParamNum[0]);
  258. authParty.setProductList(productList);
  259. });
  260. OutputStream outputStream = response.getOutputStream();
  261. response.reset();
  262. response.setHeader("Content-disposition",
  263. "attachment; filename="+fileName);
  264. response.setContentType("application/msexcel");
  265. return exportData(authPartyList, outputStream);
  266. } catch (Exception e) {
  267. e.printStackTrace();
  268. return ResponseJson.error("导出失败");
  269. }
  270. }
  271. private ResponseJson saveExcelData(String filePath, Integer authUserId, Integer createBy) {
  272. //判断是否为excel类型文件
  273. if (!filePath.endsWith(".xls") && !filePath.endsWith(".xlsx")) {
  274. System.out.println("文件不是excel类型");
  275. }
  276. // 获取供应商品牌
  277. List<String> shopBrands = shopService.getShopBrands(authUserId);
  278. // 授权列表
  279. List<AuthImportPo> authImportList = new ArrayList<>();
  280. List<String> tempImageList = new ArrayList<>();
  281. try {
  282. FileInputStream fis = new FileInputStream(filePath);
  283. // 得到表格数据
  284. XSSFWorkbook workbook = new XSSFWorkbook(fis);
  285. // 获取工作表数量
  286. int sheetsNum = workbook.getNumberOfSheets();
  287. //得到第一个工作表(机构表)
  288. XSSFSheet authPartySheet = workbook.getSheetAt(0);
  289. //获得表头
  290. Row rowHead = authPartySheet.getRow(0);
  291. //判断表头是否正确
  292. if (1 != rowHead.getLastCellNum() || !"授权机构".equals(rowHead.getCell(0).getStringCellValue())) {
  293. return ResponseJson.error("授权机构表格式错误");
  294. }
  295. // 获得数据的总行数
  296. int authPartyRowNum = authPartySheet.getLastRowNum();
  297. // 商品sn码列表
  298. List<String> snCodeList = new ArrayList<>();
  299. //获得所有数据
  300. for (int i = 1; i <= authPartyRowNum; i++) {
  301. //获得第i行对象
  302. Row row = authPartySheet.getRow(i);
  303. //获得获得第i行第0列的机构名称
  304. Cell cell = row.getCell(0);
  305. // 机构名称
  306. String authParty = cell.getStringCellValue();
  307. if (StringUtils.isNotEmpty(authParty)) {
  308. /*
  309. * 授权数据
  310. */
  311. AuthImportPo authImportPo = new AuthImportPo();
  312. // 商品列表
  313. List<ProductSaveDto> productList = new ArrayList<>();
  314. // 得到机构对应的商品工作表
  315. XSSFSheet productSheet = i < sheetsNum ? workbook.getSheetAt(i) : null;
  316. String sheetName = null != productSheet ? productSheet.getSheetName() : null;
  317. if (null == productSheet || !authParty.equals(sheetName)) {
  318. // 遍历所有工作表,找到表名与授权机构名称相同的商品工作表
  319. for (int j = 1; j < sheetsNum; j++) {
  320. productSheet = workbook.getSheetAt(j);
  321. sheetName = productSheet.getSheetName();
  322. if (!authParty.equals(sheetName)) {
  323. // 没有该机构对应的商品表
  324. productSheet = null;
  325. }
  326. }
  327. }
  328. if (null != productSheet) {
  329. //获得表头
  330. Row productRowHead = productSheet.getRow(0);
  331. //判断表头是否正确
  332. short cellTotalNum = productRowHead.getLastCellNum();
  333. if (cellTotalNum < 13) {
  334. return ResponseJson.error(authParty + "机构商品表格式错误");
  335. }
  336. // 获取表格图片
  337. Map<String, XSSFPictureData> pictures = ExcelOperateUtil.getPictures(productSheet);
  338. Map<String, String> imageMap = ExcelOperateUtil.printImg(pictures);
  339. // 校验商品数据是否符合规范
  340. int productRowNum = productSheet.getLastRowNum();
  341. for (int k = 1; k <= productRowNum; k++) {
  342. XSSFRow productRow = productSheet.getRow(k);
  343. if (null != productRow && productRow.getCell(0) != null) {
  344. String errorReason = "";
  345. // 校验商品名称
  346. String productName = productRow.getCell(0).getStringCellValue();
  347. if (StringUtils.isEmpty(productName)) {
  348. errorReason = authParty + "机构商品表第" + (k + 1) + "行商品名称不能为空";
  349. }
  350. // 校验商品sn码
  351. String snCode = productRow.getCell(1).getStringCellValue();
  352. if (StringUtils.isEmpty(snCode)) {
  353. errorReason = authParty + "机构商品表第" + (k + 1) + "行商品名称不能为空";
  354. } else {
  355. Integer productIdBySnCode = authProductMapper.getProductIdBySnCode(snCode);
  356. if (null != productIdBySnCode || snCodeList.contains(snCode)) {
  357. errorReason = authParty + "机构商品表第" + (k + 1) + "行商品sn码已存在,请重新输入";
  358. } else {
  359. snCodeList.add(snCode);
  360. }
  361. }
  362. // 校验品牌名称
  363. String brand = productRow.getCell(2).getStringCellValue();
  364. Integer brandId = null;
  365. if (StringUtils.isEmpty(brand)) {
  366. errorReason = authParty + "机构商品表第" + (k + 1) + "行商品品牌不能为空";
  367. } else {
  368. if (!shopBrands.contains(brand)) {
  369. errorReason = authParty + "机构商品表第" + (k + 1) + "行商品品牌不存在";
  370. } else {
  371. brandId = authProductMapper.getBrandIdByBrandName(brand);
  372. }
  373. }
  374. // 校验商品图片
  375. String productImage = imageMap.get(k + "-3");
  376. if (StringUtils.isEmpty(productImage)) {
  377. errorReason = authParty + "机构商品表第" + (k + 1) + "行商品图片不能为空";
  378. }
  379. // 校验授权牌照
  380. String certificateImage = imageMap.get(k + "-4");
  381. if (StringUtils.isEmpty(certificateImage)) {
  382. errorReason = authParty + "机构商品表第" + (k + 1) + "行授权牌照不能为空";
  383. }
  384. List<ProductParamPo> paramList = new ArrayList<>();
  385. // 校验参数列表
  386. for (int a = 5; a + 1 < cellTotalNum; a += 2) {
  387. XSSFCell paramNameCell = productRow.getCell(a);
  388. XSSFCell paramContentCell = productRow.getCell(a + 1);
  389. boolean validName = null != paramNameCell;
  390. boolean validContent = null != paramContentCell;
  391. if (validName && validContent) {
  392. String paramName = paramNameCell.getStringCellValue();
  393. String paramContent = paramContentCell.getStringCellValue();
  394. validName = StringUtils.isNotEmpty(paramName);
  395. validContent = StringUtils.isNotEmpty(paramContent);
  396. if (validName && validContent) {
  397. ProductParamPo productParamPo = new ProductParamPo();
  398. productParamPo.setParamName(paramName);
  399. productParamPo.setParamContent(paramContent);
  400. paramList.add(productParamPo);
  401. } else if ((validName || validContent)) {
  402. errorReason = authParty + "机构商品表第" + (k + 1) + "行参数数据异常";
  403. }
  404. } else if (validName || validContent) {
  405. errorReason = authParty + "机构商品表第" + (k + 1) + "行参数数据异常";
  406. }
  407. }
  408. if (paramList.size() < 4) {
  409. errorReason = authParty + "机构商品表第" + (k + 1) + "行参数数量不足";
  410. }
  411. if (StringUtils.isNotEmpty(errorReason)) {
  412. // 删除临时图片文件
  413. for (String image : imageMap.values()) {
  414. if (StringUtils.isNotEmpty(image)) {
  415. File tempFile = new File(image);
  416. tempFile.delete();
  417. }
  418. }
  419. return ResponseJson.error(errorReason);
  420. }
  421. /*
  422. 组装商品数据
  423. */
  424. ProductSaveDto product = new ProductSaveDto();
  425. // 品牌id
  426. product.setBrandId(brandId);
  427. // 商品名称
  428. product.setProductName(productName);
  429. // sn码
  430. product.setSnCode(snCode);
  431. // 商品图片
  432. product.setProductImage(uploadImage(productImage));
  433. // 授权牌照
  434. product.setCertificateImage(uploadImage(certificateImage));
  435. // 参数列表
  436. product.setParamList(paramList);
  437. // 创建人
  438. product.setCreateBy(createBy);
  439. productList.add(product);
  440. tempImageList.add(productImage);
  441. tempImageList.add(certificateImage);
  442. }
  443. }
  444. }
  445. // 授权机构
  446. authImportPo.setAuthParty(authParty);
  447. // 商品列表
  448. authImportPo.setProductList(productList);
  449. // 添加数据
  450. authImportList.add(authImportPo);
  451. }
  452. }
  453. } catch (Exception e) {
  454. e.printStackTrace();
  455. return ResponseJson.error("导入失败,请检查表格数据");
  456. } finally {
  457. // 删除临时数据
  458. File tempFile = new File(filePath);
  459. boolean delete = tempFile.delete();
  460. log.info("【图片上传】>>>>>>>>>>>>>>>>删除临时表格:" + delete);
  461. tempImageList.forEach(tempImagePath->{
  462. File tempImage = new File(tempImagePath);
  463. boolean del = tempImage.delete();
  464. log.info("【图片上传】>>>>>>>>>>>>>>>>删除临时商品图片:" + del);
  465. });
  466. }
  467. // 保存授权数据
  468. authImportList.forEach(authImportPo -> {
  469. String authParty = authImportPo.getAuthParty();
  470. List<ProductSaveDto> productList = authImportPo.getProductList();
  471. Integer authId = authMapper.getAuthIdByAuthParty(authParty, authUserId);
  472. // 保存授权机构
  473. if (null == authId) {
  474. CmBrandAuthPo auth = new CmBrandAuthPo();
  475. auth.setAuthUserId(authUserId);
  476. auth.setAuthParty(authParty);
  477. auth.setCreateBy(createBy);
  478. ResponseJson responseJson = saveAuth(auth, null, true);
  479. CmBrandAuthPo authPo = (CmBrandAuthPo) responseJson.getData();
  480. authId = authPo.getId();
  481. }
  482. Integer finalAuthId = authId;
  483. // 保存商品列表
  484. productList.forEach(productDto -> {
  485. try {
  486. productDto.setAuthId(finalAuthId);
  487. // 上传商品图片和授权牌照
  488. String productImage = productDto.getProductImage();
  489. String certificateImage = productDto.getCertificateImage();
  490. productDto.setProductImage(productImage);
  491. productDto.setCertificateImage(certificateImage);
  492. authProductService.saveProduct(productDto);
  493. } catch (IOException e) {
  494. e.printStackTrace();
  495. }
  496. });
  497. });
  498. return ResponseJson.success("导入成功");
  499. }
  500. private ResponseJson exportData(List<CmBrandAuthPo> authPartyList, OutputStream outputStream) {
  501. try {
  502. HSSFWorkbook workbook = new HSSFWorkbook();
  503. // 创建机构工作表
  504. HSSFSheet authPartySheet = workbook.createSheet("授权机构");
  505. // sheet样式定义
  506. HSSFCellStyle topCellStyle = this.getTopCellStyle(workbook);
  507. HSSFCellStyle customCellStyle = this.getCustomCellStyle(workbook);
  508. // 创建列头行
  509. HSSFRow topRow = authPartySheet.createRow(0);
  510. HSSFCell topRowCell = topRow.createCell(0);
  511. topRowCell.setCellType(CellType.valueOf("STRING"));
  512. HSSFRichTextString text = new HSSFRichTextString("授权机构");
  513. topRowCell.setCellValue(text);
  514. topRowCell.setCellStyle(topCellStyle);
  515. // 行索引
  516. AtomicInteger authPartyRowNum = new AtomicInteger(1);
  517. // 每个机构创建一行数据
  518. authPartyList.forEach(authParty -> {
  519. HSSFRow authPartyRow = authPartySheet.createRow(authPartyRowNum.get());
  520. HSSFCell authPartyCell = authPartyRow.createCell(0);
  521. authPartyCell.setCellType(CellType.valueOf("STRING"));
  522. HSSFRichTextString authPartyName = new HSSFRichTextString(authParty.getAuthParty().trim());
  523. authPartyCell.setCellValue(authPartyName);
  524. authPartyCell.setCellStyle(customCellStyle);
  525. authPartyRowNum.getAndIncrement();
  526. });
  527. // 让列宽随着导出的列长自动适应
  528. int columnWidth = authPartySheet.getColumnWidth(0) / 256;
  529. for (int rowNum = 0; rowNum < authPartySheet.getLastRowNum(); rowNum++) {
  530. HSSFRow currentRow;
  531. // 当前行未被使用过
  532. if (authPartySheet.getRow(rowNum) == null) {
  533. currentRow = authPartySheet.createRow(rowNum);
  534. } else {
  535. currentRow = authPartySheet.getRow(rowNum);
  536. }
  537. if (currentRow.getCell(0) != null) {
  538. HSSFCell currentCell = currentRow.getCell(0);
  539. if (currentCell.getCellTypeEnum().equals(CellType.valueOf("STRING"))) {
  540. int length = currentCell.getStringCellValue()
  541. .getBytes().length;
  542. if (columnWidth < length) {
  543. columnWidth = length;
  544. }
  545. }
  546. }
  547. }
  548. authPartySheet.setColumnWidth(0, (columnWidth + 4) * 256);
  549. // 创建每个机构对应的商品表
  550. authPartyList.forEach(authParty -> {
  551. // 授权机构名称作为表名
  552. String productSheetName = authParty.getAuthParty();
  553. // 商品列表
  554. List<ProductFormVo> productList = authParty.getProductList();
  555. // 创建商品工作表
  556. HSSFSheet productSheet = workbook.createSheet(productSheetName);
  557. // 创建列头行
  558. HSSFRow productTopRow = productSheet.createRow(0);
  559. // 添加列头单元格(5个固定列+参数列表)
  560. String[] rowName = {"商品名称", "商品SN码", "所属品牌", "商品图片(尺寸:128px×88px)",
  561. "授权牌(尺寸:128px×88px)", "参数名称1", "参数值1", "参数名称2", "参数值2", "参数名称3",
  562. "参数值3", "参数名称4", "参数值4", "参数名称5", "参数值5", "参数名称6", "参数值6", "参数名称7",
  563. "参数值7", "参数名称8", "参数值8", "参数名称9", "参数值9", "参数名称10", "参数值10", "参数名称11",
  564. "参数值11", "参数名称12", "参数值12"};
  565. for (int i = 0; i < 5 + (0 == authParty.getMaxParamNum() ? 4 : authParty.getMaxParamNum()) * 2; i++) {
  566. HSSFCell productTopRowCell = productTopRow.createCell(i);
  567. productTopRowCell.setCellType(CellType.valueOf("STRING"));
  568. HSSFRichTextString columnText = new HSSFRichTextString(rowName[i]);
  569. productTopRowCell.setCellValue(columnText);
  570. productTopRowCell.setCellStyle(topCellStyle);
  571. }
  572. // 添加商品数据到单元格中
  573. // 行索引
  574. AtomicInteger productRowNum = new AtomicInteger(1);
  575. productList.forEach(product -> {
  576. // 创建商品行
  577. HSSFRow productRow = productSheet.createRow(productRowNum.get());
  578. // 设置行高度
  579. productRow.setHeight((short) 2200);
  580. // 参数列表
  581. List<ProductParamPo> paramList = product.getParamList();
  582. // 组装商品数据
  583. List<String> productData = new ArrayList<>();
  584. productData.add(product.getProductName());
  585. productData.add(product.getSnCode());
  586. productData.add(product.getBrandName());
  587. productData.add(product.getProductImage());
  588. productData.add(product.getCertificateImage());
  589. paramList.forEach(param -> {
  590. productData.add(param.getParamName());
  591. productData.add(param.getParamContent());
  592. });
  593. for (int j = 0; j < 5 + paramList.size() * 2; j++) {
  594. HSSFCell productCell = productRow.createCell(j);
  595. if (j == 3 || j == 4) {
  596. // productSheet.addMergedRegion(new CellRangeAddress(j + 1,j + 1,j + 1,j + 1)) ;
  597. // 头像
  598. String imageUrl = productData.get(j);
  599. String fileType = imageUrl.substring(imageUrl.lastIndexOf(".") + 1);
  600. InputStream imageStream = getImageStream(imageUrl);
  601. if (null != imageStream) {
  602. try {
  603. BufferedImage bufferedImage = ImageIO.read(imageStream);
  604. ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
  605. ImageIO.write(bufferedImage, fileType, byteArrayOut);
  606. byte[] data = byteArrayOut.toByteArray();
  607. HSSFPatriarch drawingPatriarch = productSheet.createDrawingPatriarch();
  608. // 设置图片位置
  609. HSSFClientAnchor anchor = new HSSFClientAnchor(30, 30, 700, 200, (short) j, productRowNum.get(), (short) j, productRowNum.get());
  610. drawingPatriarch.createPicture(anchor, workbook.addPicture(data, HSSFWorkbook.PICTURE_TYPE_JPEG));
  611. } catch (Exception e) {
  612. e.printStackTrace();
  613. }
  614. } else {
  615. productCell.setCellType(CellType.valueOf("STRING"));
  616. productCell.setCellValue("");
  617. }
  618. } else {
  619. productCell.setCellType(CellType.valueOf("STRING"));
  620. HSSFRichTextString productCellValue = new HSSFRichTextString(productData.get(j));
  621. productCell.setCellValue(productCellValue);
  622. productCell.setCellStyle(customCellStyle);
  623. }
  624. }
  625. productRowNum.getAndIncrement();
  626. });
  627. // 让列宽随着导出的列长自动适应
  628. for (int colNum = 0; (colNum < 5 + authParty.getMaxParamNum() * 2); colNum++) {
  629. if (colNum == 3 || colNum == 4) {
  630. productSheet.setColumnWidth(colNum, 8200);
  631. } else {
  632. int productColumnWidth = productSheet.getColumnWidth(colNum) / 256;
  633. for (int rowNum = 0; rowNum < productSheet.getLastRowNum(); rowNum++) {
  634. HSSFRow currentRow;
  635. // 当前行未被使用过
  636. if (productSheet.getRow(rowNum) == null) {
  637. currentRow = productSheet.createRow(rowNum);
  638. } else {
  639. currentRow = productSheet.getRow(rowNum);
  640. }
  641. if (currentRow.getCell(colNum) != null) {
  642. HSSFCell currentCell = currentRow.getCell(colNum);
  643. if (currentCell.getCellTypeEnum().equals(CellType.valueOf("STRING"))) {
  644. int length = currentCell.getStringCellValue()
  645. .getBytes().length;
  646. if (productColumnWidth < length) {
  647. productColumnWidth = length;
  648. }
  649. }
  650. }
  651. }
  652. productSheet.setColumnWidth(colNum, (productColumnWidth + 4) * 256);
  653. }
  654. }
  655. });
  656. outputStream.flush();
  657. workbook.write(outputStream);
  658. outputStream.close();
  659. } catch (Exception e) {
  660. e.printStackTrace();
  661. return ResponseJson.error("导出失败");
  662. }
  663. return ResponseJson.success("导出成功");
  664. }
  665. private String uploadImage(String filePath) throws IOException {
  666. // 临时图片
  667. File tempFile = new File(filePath);
  668. log.info("【图片上传】>>>>>>>>>>>>>>>>图片临时路径:" + filePath);
  669. String imageUrl = imageDomain + "/" + client.uploadFile(filePath);
  670. return imageUrl;
  671. }
  672. /**
  673. * 列头单元格样式
  674. */
  675. private HSSFCellStyle getTopCellStyle(HSSFWorkbook workbook) {
  676. // 设置字体
  677. HSSFFont font = workbook.createFont();
  678. // 设置字体大小
  679. font.setFontHeightInPoints((short) 11);
  680. // 字体加粗
  681. font.setBold(true);
  682. // 设置字体名字
  683. font.setFontName("Courier New");
  684. // 设置样式;
  685. HSSFCellStyle style = workbook.createCellStyle();
  686. // 设置底边框;
  687. style.setBorderBottom(BorderStyle.THIN);
  688. // 设置底边框颜色;
  689. style.setBottomBorderColor(IndexedColors.BLACK.index);
  690. // 设置左边框;
  691. style.setBorderLeft(BorderStyle.THIN);
  692. // 设置左边框颜色;
  693. style.setLeftBorderColor(IndexedColors.BLACK.index);
  694. // 设置右边框;
  695. style.setBorderRight(BorderStyle.THIN);
  696. // 设置右边框颜色;
  697. style.setRightBorderColor(IndexedColors.BLACK.index);
  698. // 设置顶边框;
  699. style.setBorderTop(BorderStyle.THIN);
  700. // 设置顶边框颜色;
  701. style.setTopBorderColor(IndexedColors.BLACK.index);
  702. // 在样式用应用设置的字体;
  703. style.setFont(font);
  704. // 设置自动换行;
  705. style.setWrapText(false);
  706. // 设置水平对齐的样式为居中对齐;
  707. style.setAlignment(HorizontalAlignment.CENTER);
  708. // 设置垂直对齐的样式为居中对齐;
  709. style.setVerticalAlignment(VerticalAlignment.CENTER);
  710. return style;
  711. }
  712. /**
  713. * 列数据信息单元格样式
  714. */
  715. private HSSFCellStyle getCustomCellStyle(HSSFWorkbook workbook) {
  716. // 设置字体
  717. HSSFFont font = workbook.createFont();
  718. // 设置字体大小
  719. // font.setFontHeightInPoints((short)10);
  720. // 字体加粗
  721. // font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
  722. // 设置字体名字
  723. font.setFontName("Courier New");
  724. // 设置样式;
  725. HSSFCellStyle style = workbook.createCellStyle();
  726. // 设置底边框;
  727. style.setBorderBottom(BorderStyle.THIN);
  728. // 设置底边框颜色;
  729. style.setBottomBorderColor(IndexedColors.BLACK.index);
  730. // 设置左边框;
  731. style.setBorderLeft(BorderStyle.THIN);
  732. // 设置左边框颜色;
  733. style.setLeftBorderColor(IndexedColors.BLACK.index);
  734. // 设置右边框;
  735. style.setBorderRight(BorderStyle.THIN);
  736. // 设置右边框颜色;
  737. style.setRightBorderColor(IndexedColors.BLACK.index);
  738. // 设置顶边框;
  739. style.setBorderTop(BorderStyle.THIN);
  740. // 设置顶边框颜色;
  741. style.setTopBorderColor(IndexedColors.BLACK.index);
  742. // 在样式用应用设置的字体;
  743. style.setFont(font);
  744. // 设置自动换行;
  745. style.setWrapText(false);
  746. // 设置水平对齐的样式为居中对齐;
  747. style.setAlignment(HorizontalAlignment.CENTER);
  748. // 设置垂直对齐的样式为居中对齐;
  749. style.setVerticalAlignment(VerticalAlignment.CENTER);
  750. return style;
  751. }
  752. public InputStream getImageStream(String url) {
  753. try {
  754. HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
  755. connection.setReadTimeout(5000);
  756. connection.setConnectTimeout(5000);
  757. connection.setRequestMethod("GET");
  758. if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
  759. InputStream inputStream = connection.getInputStream();
  760. return inputStream;
  761. }
  762. } catch (IOException e) {
  763. System.out.println("获取网络图片出现异常,图片路径为:" + url);
  764. e.printStackTrace();
  765. }
  766. return null;
  767. }
  768. }