package com.caimei.service.auth.impl; import com.aliyuncs.utils.StringUtils; import com.caimei.mapper.cmMapper.AuthMapper; import com.caimei.mapper.cmMapper.AuthProductMapper; import com.caimei.mapper.cmMapper.FileMapper; import com.caimei.model.ResponseJson; import com.caimei.model.po.ProductImagePo; import com.caimei.model.po.ProductParamPo; import com.caimei.model.po.UploadFilePo; import com.caimei.model.vo.AuthFormVo; import com.caimei.model.vo.AuthVo; import com.caimei.model.vo.ClubUserVo; import com.caimei.model.vo.ProductFormVo; import com.caimei.service.auth.DownloadService; import com.caimei.service.auth.UploadService; import com.caimei.utils.FileIOUtils; import com.caimei.utils.OSSUtils; import com.caimei.utils.PoiUtils; import lombok.extern.slf4j.Slf4j; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFRichTextString; import org.apache.poi.ss.usermodel.CellType; import org.apache.poi.xssf.usermodel.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.*; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.text.SimpleDateFormat; import java.util.*; import java.util.concurrent.atomic.AtomicInteger; /** * Description * * @author : Aslee * @date : 2021/7/9 */ @Slf4j @Service public class DownloadServiceImpl implements DownloadService { @Resource private FileMapper fileMapper; @Resource private AuthMapper authMapper; @Resource private AuthProductMapper authProductMapper; private UploadService uploadService; @Value("${caimei.oldapi}") private String wwwServer; @Value("${caimei.zpapi}") private String zpServer; @Value("${spring.profiles.active}") private String active; @Autowired public void setUploadService(UploadService uploadService) { this.uploadService = uploadService; } @Override public void downloadFile(String ossName, String fileName, HttpServletRequest request, HttpServletResponse response) throws IOException { OSSUtils.downFile("authFile/", ossName, fileName); download(request, response, "./" + fileName, fileName); } @Override public void downloadShopImage(String authIds, Integer type, HttpServletRequest request, HttpServletResponse response) throws Exception { ArrayList fileList = new ArrayList<>(); HashMap> fileMap = new HashMap<>(); List authImageList = fileMapper.getAuthImageList(authIds); if (1 == type) { // 机构授权牌 List fileNameList = new ArrayList<>(); authImageList.forEach(authImage ->{ if (StringUtils.isNotEmpty(authImage.getAuthImage())) { UploadFilePo file = new UploadFilePo(); String fileName = authImage.getAuthParty(); int k = 1; while (fileNameList.contains(fileName)) { fileName = fileName.replace("(" + (k-1) + ")", "") + "(" + k + ")"; k++; } fileNameList.add(fileName); file.setFileUrl(authImage.getAuthImage()); file.setFileName(fileName); fileList.add(file); } }); if (fileList.size() > 0) { fileMap.put("机构授权牌", fileList); } } else if (2 == type) { // 设备授权牌 authImageList.forEach(authImage->{ List productList = fileMapper.getProductImageList(authImage.getAuthId()); ArrayList list = new ArrayList<>(); productList.forEach(product->{ if (StringUtils.isNotEmpty(product.getCertificateImage())) { UploadFilePo file = new UploadFilePo(); file.setFileUrl(product.getCertificateImage()); file.setFileName(product.getProductName() + "-" + product.getSnCode()); list.add(file); } }); if (list.size() > 0) { fileMap.put(authImage.getAuthParty(), list); } }); } else if (3 == type) { // 机构二维码 List fileNameList = new ArrayList<>(); authImageList.forEach(authImage -> { String qrCodeLink = zpServer + "/" + authImage.getAuthUserId() + "/app/approve/club/detail?id=" + authImage.getAuthId(); String fileName = authImage.getAuthParty(); int k = 1; while (fileNameList.contains(fileName)) { fileName = fileName.replace("(" + (k-1) + ")", "") + "(" + k + ")"; k++; } fileNameList.add(fileName); UploadFilePo file = new UploadFilePo(); file.setFileUrl(qrCodeLink); file.setFileName(authImage.getAuthParty()); file.setAuthName(authImage.getName()); fileList.add(file); // String imagePath = createBufferedImageFile(qrCodeImage, fileName, "png"); }); if (fileList.size() > 0) { fileMap.put("机构二维码", fileList); } } else { // 设备二维码 authImageList.forEach(authImage->{ List productList = fileMapper.getProductImageList(authImage.getAuthId()); ArrayList list = new ArrayList<>(); productList.forEach(product->{ String qrCodeLink = wwwServer + "/product/auth/product-" + product.getProductId() + ".html"; UploadFilePo file = new UploadFilePo(); file.setFileUrl(qrCodeLink); file.setFileName(product.getProductName() + "-" + product.getSnCode()); list.add(file); }); if (list.size() > 0) { fileMap.put(authImage.getAuthParty(), list); } }); } String fileName = 1 == type ? "机构授权牌" : 2 == type ? "设备授权牌" : 3 == type ? "机构二维码" : "设备二维码"; // 将授权牌压缩成zip文件 String imageZipPath = uploadService.createImageZip(fileMap, type); download(request, response, imageZipPath, fileName + ".zip"); // 删除临时文件夹 String tempPath = imageZipPath.substring(0, imageZipPath.lastIndexOf("/")); File tempFile = new File(tempPath); boolean delete = tempFile.delete(); log.info("【图片压缩包】,删除图片压缩包文件夹:" + delete); } @Override public ResponseJson downloadAuthData(String authIds, HttpServletResponse response) { try { // 导出表格名 String fileName = new String("机构信息.xlsx".getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1); // 机构数据 List authPartyList = authMapper.getAuthPartyList(authIds); OutputStream outputStream = response.getOutputStream(); response.reset(); response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Credentials", "true"); response.setHeader("Content-disposition", "attachment; filename="+fileName); // response.setContentType("application/vnd.ms-excel"); -- xls response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); return generateAuthExcel(authPartyList, outputStream); } catch (Exception e) { e.printStackTrace(); return ResponseJson.error("导出失败"); } } @Override public ResponseJson downloadProductData(String authIds, HttpServletRequest request, HttpServletResponse response) throws IOException { HashMap> fileMap = new HashMap<>(); // 机构列表 List authImageList = fileMapper.getAuthImageList(authIds); // 设备列表 authImageList.forEach(authImage->{ final Integer[] maxParamNum = {0}; List productList = authProductMapper.getAuthProductList(authImage.getAuthId()); productList.forEach(product->{ // 参数列表 List paramList = new ArrayList<>(); if (null == product.getProductTypeId()) { paramList = authProductMapper.getParamsByProductId(product.getProductId()); } else { paramList = authProductMapper.getProductTypeParamList(product.getProductTypeId()); } product.setParamList(paramList); if (paramList.size() > maxParamNum[0]) { maxParamNum[0] = paramList.size(); } }); authImage.setMaxParamNum(maxParamNum[0]); if (productList.size() > 0) { fileMap.put(authImage, productList); } }); // 将授权牌压缩成zip文件 String imageZipPath = createExcelZip(fileMap); download(request, response, imageZipPath, "设备信息.zip"); // 删除临时文件夹 String tempPath = imageZipPath.substring(0, imageZipPath.lastIndexOf("/")); File tempFile = new File(tempPath); boolean delete = tempFile.delete(); log.info("【图片压缩包】,删除图片压缩包文件夹:" + delete); return null; } @Override public void downloadAuthTemplate(HttpServletRequest request, HttpServletResponse response) throws IOException { String ossName = "认证通机构导入模板.xlsx"; OSSUtils.downFile("authFile/", ossName, ossName); download(request, response, "./" + ossName, ossName); } private String createExcelZip(HashMap> authMap) throws FileNotFoundException { String randomStr = UUID.randomUUID().toString(); String filePath = "/mnt/newdatadrive/data/runtime/jar-instance/zplma/tempImage/"; if ("dev".equals(active)){ filePath = "D:\\uploadZip\\"; } // 压缩文件夹上层临时文件夹路径 String tempPath = filePath + randomStr; // 压缩文件夹路径 String basePath = ""; // 生成唯一临时文件夹 filePath += randomStr + "/"; // 在临时文件夹中生成要压缩的基础文件夹 String baseDirName = "设备信息"; filePath += baseDirName; basePath = filePath; File fileDir = new File(filePath); if (!fileDir.exists()) { fileDir.mkdirs(); } // 往基础文件夹中填充相应数据 for (Map.Entry> entry : authMap.entrySet()) { AuthVo auth = entry.getKey(); List productList = entry.getValue(); generateProductExcel(filePath, auth, productList); } // 将文件夹转为压缩文件 String zipPath = tempPath + "/" + baseDirName + ".zip"; FileOutputStream zipOut = new FileOutputStream(zipPath); FileIOUtils.zipFolder(basePath, zipOut, true); return zipPath; } private void generateProductExcel(String tempFilePath, AuthVo authParty, List productList) { String fileName = authParty.getAuthParty(); String filePath = tempFilePath + "/" + fileName + ".xlsx"; try { FileOutputStream outputStream = new FileOutputStream(filePath); XSSFWorkbook workbook = new XSSFWorkbook(); // 创建设备工作表 XSSFSheet productSheet = workbook.createSheet("设备信息"); // sheet样式定义 XSSFCellStyle topCellStyle = PoiUtils.getXSSFTopCellStyle(workbook); XSSFCellStyle customCellStyle = PoiUtils.getXSSFCustomCellStyle(workbook); // 创建列头行 XSSFRow authTopRow = productSheet.createRow(0); // 添加列头单元格(4个固定列+参数列表) String[] rowName = {"设备名称", "设备SN码", "所属品牌", "购买渠道", "参数名1", "参数值1", "参数名2", "参数值2", "参数名3", "参数值3", "参数名4", "参数值4", "参数名5", "参数值5", "参数名6", "参数值6", "参数名7", "参数值7", "参数名8", "参数值8", "参数名9", "参数值9", "参数名10", "参数值10", "参数名11", "参数值11", "参数名12", "参数值12"}; for (int i = 0; i < 4 + (0 == authParty.getMaxParamNum() ? 4 : authParty.getMaxParamNum()) * 2; i++) { XSSFCell authTopRowCell = authTopRow.createCell(i); authTopRowCell.setCellType(CellType.valueOf("STRING")); XSSFRichTextString columnText = new XSSFRichTextString(rowName[i]); authTopRowCell.setCellValue(columnText); authTopRowCell.setCellStyle(topCellStyle); } // 行索引 AtomicInteger productRowNum = new AtomicInteger(1); productList.forEach(product->{ // 创建设备行 XSSFRow productRow = productSheet.createRow(productRowNum.get()); // 参数列表 List paramList = product.getParamList(); // 组装设备数据 List productData = new ArrayList<>(); productData.add(product.getProductName()); productData.add(product.getSnCode()); productData.add(product.getBrandName()); productData.add(product.getPurchaseWay()); paramList.forEach(param -> { productData.add(param.getParamName()); productData.add(param.getParamContent()); }); for (int j = 0; j < 4 + paramList.size() * 2; j++) { XSSFCell productCell = productRow.createCell(j); productCell.setCellType(CellType.valueOf("STRING")); XSSFRichTextString productCellValue = new XSSFRichTextString(productData.get(j)); productCell.setCellValue(productCellValue); productCell.setCellStyle(customCellStyle); } productRowNum.getAndIncrement(); }); // 让列宽随着导出的列长自动适应 for (int colNum = 0; colNum < rowName.length; colNum++) { int productColumnWidth = productSheet.getColumnWidth(colNum) / 256; for (int rowNum = 0; rowNum < productSheet.getLastRowNum(); rowNum++) { XSSFRow currentRow; // 当前行未被使用过 if (productSheet.getRow(rowNum) == null) { currentRow = productSheet.createRow(rowNum); } else { currentRow = productSheet.getRow(rowNum); } if (currentRow.getCell(colNum) != null) { XSSFCell currentCell = currentRow.getCell(colNum); if (currentCell.getCellTypeEnum().equals(CellType.valueOf("STRING"))) { int length = currentCell.getStringCellValue() .getBytes().length; if (productColumnWidth < length) { productColumnWidth = length; } } } } productSheet.setColumnWidth(colNum, (productColumnWidth + 4) * 256); } workbook.write(outputStream); } catch (Exception e) { e.printStackTrace(); } } private ResponseJson generateAuthExcel(List authPartyList, OutputStream outputStream) { try { XSSFWorkbook workbook = new XSSFWorkbook(); // 创建机构工作表 XSSFSheet authPartySheet = workbook.createSheet("授权机构"); // sheet样式定义 XSSFCellStyle topCellStyle = PoiUtils.getXSSFTopCellStyle(workbook); XSSFCellStyle customCellStyle = PoiUtils.getXSSFCustomCellStyle(workbook); // 创建列头行 XSSFRow authTopRow = authPartySheet.createRow(0); // 添加列头单元格 String[] rowName = {"机构名称(必填)", "所在地区(必填)", "详细地址(必填)", "经纬度(选填)", "联系电话(必填)", "认证编号(选填)", "认证日期(选填)", "员工人数(必填)", "店铺备注(选填)"}; for (int i = 0; i < rowName.length; i++) { XSSFCell authTopRowCell = authTopRow.createCell(i); authTopRowCell.setCellType(CellType.valueOf("STRING")); XSSFRichTextString columnText = new XSSFRichTextString(rowName[i]); authTopRowCell.setCellValue(columnText); authTopRowCell.setCellStyle(topCellStyle); } // 行索引 AtomicInteger authPartyRowNum = new AtomicInteger(1); authPartyList.forEach(authParty -> { // 创建机构行 XSSFRow authRow = authPartySheet.createRow(authPartyRowNum.get()); // 组装机构数据 List authData = new ArrayList<>(); authData.add(authParty.getAuthParty()); authData.add(authParty.getArea()); authData.add(authParty.getAddress()); authData.add(authParty.getLngAndLat()); authData.add(authParty.getMobile()); authData.add(authParty.getAuthCode()); SimpleDateFormat format = new SimpleDateFormat("yyyy.MM.dd"); Date authDate = authParty.getAuthDate(); if (null != authDate) { authData.add(format.format(authDate)); } else { authData.add(""); } authData.add(authParty.getEmpNum().toString()); authData.add(authParty.getRemarks()); for (int j = 0; j < authData.size(); j++) { XSSFCell authCell = authRow.createCell(j); authCell.setCellStyle(customCellStyle); if (j == 7) { authCell.setCellType(CellType.NUMERIC); authCell.setCellValue(Integer.parseInt(authData.get(j))); } else { authCell.setCellType(CellType.valueOf("STRING")); XSSFRichTextString authCellValue = new XSSFRichTextString(authData.get(j)); authCell.setCellValue(authCellValue); } } authPartyRowNum.getAndIncrement(); }); // 让列宽随着导出的列长自动适应 for (int colNum = 0; colNum < rowName.length; colNum++) { int productColumnWidth = authPartySheet.getColumnWidth(colNum) / 256; for (int rowNum = 0; rowNum < authPartySheet.getLastRowNum(); rowNum++) { XSSFRow currentRow; // 当前行未被使用过 if (authPartySheet.getRow(rowNum) == null) { currentRow = authPartySheet.createRow(rowNum); } else { currentRow = authPartySheet.getRow(rowNum); } if (currentRow.getCell(colNum) != null) { XSSFCell currentCell = currentRow.getCell(colNum); if (currentCell.getCellTypeEnum().equals(CellType.valueOf("STRING"))) { int length = currentCell.getStringCellValue() .getBytes().length; if (productColumnWidth < length) { productColumnWidth = length; } } } } authPartySheet.setColumnWidth(colNum, (productColumnWidth + 4) * 256); } outputStream.flush(); workbook.write(outputStream); outputStream.close(); } catch (Exception e) { e.printStackTrace(); return ResponseJson.error("导出失败"); } return null; } public void download(HttpServletRequest request, HttpServletResponse response, String filePath, String fileName) throws IOException { File file = new File(filePath); // 文件存在才下载 if (file.exists()) { OutputStream out = null; FileInputStream in = null; try { // 1.读取要下载的内容 in = new FileInputStream(file); // 2. 告诉浏览器下载的方式以及一些设置 // 解决文件名乱码问题,获取浏览器类型,转换对应文件名编码格式,IE要求文件名必须是utf-8, firefo要求是iso-8859-1编码 String agent = request.getHeader("user-agent"); if (agent.contains("FireFox")) { fileName = new String(fileName.getBytes("UTF-8"), "iso-8859-1"); } else { fileName = URLEncoder.encode(fileName, "UTF-8"); } // 设置下载文件的mineType,告诉浏览器下载文件类型 String mineType = request.getServletContext().getMimeType(fileName); response.setContentType(mineType); // 设置一个响应头,无论是否被浏览器解析,都下载 response.setHeader("Content-disposition", "attachment; filename=" + fileName); // 将要下载的文件内容通过输出流写到浏览器 out = response.getOutputStream(); int len = 0; byte[] buffer = new byte[1024]; while ((len = in.read(buffer)) > 0) { out.write(buffer, 0, len); } } catch (IOException e) { e.printStackTrace(); } finally { if (out != null) { out.close(); } if (in != null) { in.close(); } file.delete(); } } } /** * 下载用户信息 * @param clubUserIds * @param response * @return */ @Override public ResponseJson downloadClubuserlistInfo(Integer authUserId,String clubUserIds, HttpServletResponse response) { //导出的用户表名 String fileName=new String("用户信息.xlsx".getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1); //获取用户信息 List clubUserVosList = authMapper.getclubuserInfo(authUserId,clubUserIds); try { OutputStream outputStream = response.getOutputStream(); response.reset(); response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Credentials", "true"); response.setHeader("Content-disposition", "attachment; filename="+fileName); // response.setContentType("application/vnd.ms-excel"); -- xls response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); return generateClubUserExcel(clubUserVosList,outputStream); } catch (IOException e) { e.printStackTrace(); return ResponseJson.error("导出失败"); } } private ResponseJson generateClubUserExcel(List clubUserVosList, OutputStream outputStream) { try { XSSFWorkbook workbook = new XSSFWorkbook(); // 创建机构工作表 XSSFSheet authPartySheet = workbook.createSheet("用户信息"); // sheet样式定义 XSSFCellStyle topCellStyle = PoiUtils.getXSSFTopCellStyle(workbook); XSSFCellStyle customCellStyle = PoiUtils.getXSSFCustomCellStyle(workbook); // 创建列头行 XSSFRow authTopRow = authPartySheet.createRow(0); // 添加列头单元格 String[] rowName = {"序号", "机构名称", "手机号", "注册时间", "认证状态", "用户状态"}; for (int i = 0; i < rowName.length; i++) { XSSFCell authTopRowCell = authTopRow.createCell(i); authTopRowCell.setCellType(CellType.valueOf("STRING")); XSSFRichTextString columnText = new XSSFRichTextString(rowName[i]); authTopRowCell.setCellValue(columnText); authTopRowCell.setCellStyle(topCellStyle); } // 行索引 AtomicInteger authPartyRowNum = new AtomicInteger(1); int serialNum=1; // clubUserVosList.forEach(club -> { for (ClubUserVo club:clubUserVosList) { // 创建机构行 XSSFRow authRow = authPartySheet.createRow(authPartyRowNum.get()); // 组装机构数据 List authData = new ArrayList<>(); authData.add(serialNum + ""); authData.add(club.getName()); authData.add(club.getMobile()); SimpleDateFormat format = new SimpleDateFormat("yyyy.MM.dd HH:mm"); Date authDate = club.getAddTime(); if (null != authDate) { authData.add(format.format(authDate)); } else { authData.add(""); } authData.add(club.getAuthenticationStatus()); if(null!=club.getStatus()&&club.getStatus()==1){ authData.add("启用"); }else if(null!=club.getStatus()&&club.getStatus()==0){ authData.add("停用"); } for (int j = 0; j < authData.size(); j++) { XSSFCell authCell = authRow.createCell(j); authCell.setCellStyle(customCellStyle); // if (j == 7) { // authCell.setCellType(CellType.NUMERIC); // authCell.setCellValue(Integer.parseInt(authData.get(j))); // } else { authCell.setCellType(CellType.valueOf("STRING")); XSSFRichTextString authCellValue = new XSSFRichTextString(authData.get(j)); authCell.setCellValue(authCellValue); // } } authPartyRowNum.getAndIncrement(); serialNum++; } // }); // 让列宽随着导出的列长自动适应 for (int colNum = 0; colNum < rowName.length; colNum++) { int productColumnWidth = authPartySheet.getColumnWidth(colNum) / 256; for (int rowNum = 0; rowNum < authPartySheet.getLastRowNum(); rowNum++) { XSSFRow currentRow; // 当前行未被使用过 if (authPartySheet.getRow(rowNum) == null) { currentRow = authPartySheet.createRow(rowNum); } else { currentRow = authPartySheet.getRow(rowNum); } if (currentRow.getCell(colNum) != null) { XSSFCell currentCell = currentRow.getCell(colNum); if (currentCell.getCellTypeEnum().equals(CellType.valueOf("STRING"))) { int length = currentCell.getStringCellValue() .getBytes().length; if (productColumnWidth < length) { productColumnWidth = length; } } } } authPartySheet.setColumnWidth(colNum, (productColumnWidth + 4) * 256); } outputStream.flush(); workbook.write(outputStream); outputStream.close(); } catch (Exception e) { e.printStackTrace(); return ResponseJson.error("导出失败"); } return null; } }