AuthServiceImpl.java 45 KB

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