AuthServiceImpl.java 42 KB

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