123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893 |
- package com.caimei.service.auth.impl;
- import com.caimei.config.FastDfsClient;
- import com.caimei.mapper.cmMapper.AuthMapper;
- import com.caimei.mapper.cmMapper.AuthProductMapper;
- import com.caimei.model.ResponseJson;
- import com.caimei.model.dto.ProductSaveDto;
- import com.caimei.model.po.AuthImportPo;
- import com.caimei.model.po.CmBrandAuthPo;
- import com.caimei.model.po.LdmDataPo;
- import com.caimei.model.po.ProductParamPo;
- import com.caimei.model.vo.AuthFormVo;
- import com.caimei.model.vo.AuthVo;
- import com.caimei.model.vo.ProductFormVo;
- import com.caimei.service.auth.AuthProductService;
- import com.caimei.service.auth.AuthService;
- import com.caimei.service.auth.ShopService;
- import com.caimei.service.auth.UploadService;
- import com.caimei.utils.ExcelOperateUtil;
- import com.github.pagehelper.PageHelper;
- import com.github.pagehelper.PageInfo;
- import com.github.tobato.fastdfs.service.FastFileStorageClient;
- import lombok.extern.slf4j.Slf4j;
- import org.apache.commons.lang3.StringUtils;
- import org.apache.poi.hssf.usermodel.*;
- import org.apache.poi.ss.usermodel.*;
- import org.apache.poi.xssf.usermodel.*;
- import org.springframework.beans.BeanUtils;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.beans.factory.annotation.Value;
- import org.springframework.stereotype.Service;
- import org.springframework.web.multipart.MultipartFile;
- import javax.annotation.Resource;
- import javax.imageio.ImageIO;
- import javax.servlet.http.HttpServletResponse;
- import java.awt.image.BufferedImage;
- import java.io.*;
- import java.math.BigDecimal;
- import java.net.HttpURLConnection;
- import java.net.URL;
- import java.util.*;
- import java.util.concurrent.atomic.AtomicInteger;
- /**
- * Description
- *
- * @author : Aslee
- * @date : 2021/5/11
- */
- @Slf4j
- @Service
- public class AuthServiceImpl implements AuthService {
- @Resource
- private AuthMapper authMapper;
- @Resource
- private AuthProductMapper authProductMapper;
- private AuthProductService authProductService;
- @Autowired
- public void setAuthProductService(AuthProductService authProductService) {
- this.authProductService = authProductService;
- }
- private ShopService shopService;
- @Autowired
- public void setShopService(ShopService shopService) {
- this.shopService = shopService;
- }
- private UploadService uploadService;
- @Autowired
- public void setUploadService(UploadService uploadService) {
- this.uploadService = uploadService;
- }
- @Value("${spring.profiles.active}")
- private String active;
- @Autowired
- private FastDfsClient client;
- @Value("${caimei.imageDomain}")
- private String imageDomain;
- @Autowired
- private FastFileStorageClient storageClient;
- @Override
- public ResponseJson<PageInfo<AuthVo>> getAuthList(Integer listType, Integer authUserId, String authParty, Integer status, Integer auditStatus, Integer lowerAuditStatus, Integer pageNum, Integer pageSize) {
- if (null == authUserId) {
- return ResponseJson.error("参数异常,请输入供应商用户id", null);
- }
- listType = null == listType ? 1 : listType;
- PageHelper.startPage(pageNum, pageSize);
- List<AuthVo> authList = authMapper.getAuthList(listType, authUserId, authParty, status, auditStatus, lowerAuditStatus);
- ListIterator<AuthVo> iterator = authList.listIterator();
- while (iterator.hasNext()) {
- // 根据是否完成商品信息审核筛选项,进行筛选
- AuthVo auth = iterator.next();
- Integer waitAuditNum = auth.getWaitAuditNum();
- if (waitAuditNum > 0) {
- auth.setLowerAuditStatus(0);
- } else {
- auth.setLowerAuditStatus(1);
- }
- }
- PageInfo<AuthVo> pageData = new PageInfo<>(authList);
- return ResponseJson.success(pageData);
- }
- @Override
- public ResponseJson updateAuthStatus(Integer authId, Integer status) {
- if (null == authId) {
- return ResponseJson.error("请输入授权id");
- }
- if (null == status) {
- return ResponseJson.error("请输入要更新的状态值");
- }
- authMapper.updateAuthStatusByAuthId(authId, status);
- if (0 == status) {
- return ResponseJson.success("下线品牌授权成功");
- } else {
- return ResponseJson.success("上线品牌授权成功");
- }
- }
- @Override
- public ResponseJson deleteAuth(Integer authId) {
- if (null == authId) {
- return ResponseJson.error("参数异常,请输入授权id");
- }
- // 删除品牌授权
- authMapper.deleteAuthByAuthId(authId);
- // 删除轮播图
- authMapper.deleteBanner(authId);
- // 删除商品及商品参数
- List<Integer> productIdList = authProductService.getProductIdsByAuthId(authId);
- productIdList.forEach(productId->{
- if (null != productId) {
- authProductService.deleteProduct(productId);
- }
- });
- return ResponseJson.success("删除品牌授权成功");
- }
- @Override
- public ResponseJson<AuthFormVo> getAuthFormData(Integer authId) {
- if (null == authId) {
- return ResponseJson.error("参数异常,机构id不能为空", null);
- }
- CmBrandAuthPo auth = authMapper.getAuthById(authId);
- AuthFormVo authFormVo = new AuthFormVo();
- authFormVo.setAuthId(auth.getId());
- BeanUtils.copyProperties(auth, authFormVo);
- if (null != auth.getLng()) {
- authFormVo.setLngAndLat(auth.getLng() + "," + auth.getLat());
- }
- List<String> bannerList = authMapper.getBannerList(authId);
- authFormVo.setBannerList(bannerList);
- return ResponseJson.success(authFormVo);
- }
- @Override
- public ResponseJson saveAuth(CmBrandAuthPo auth, List<String> bannerList, boolean importFlag) {
- Integer authId = auth.getId();
- Integer authUserId = auth.getAuthUserId();
- String authParty = auth.getAuthParty();
- if (null == authUserId) {
- return ResponseJson.error("参数异常,请输入供应商用户id");
- }
- if (StringUtils.isBlank(authParty)) {
- return ResponseJson.error("参数异常,请输入授权机构名称");
- }
- Integer authIdByAuthParty = authMapper.getAuthIdByAuthParty(authParty, authUserId);
- if (null != authIdByAuthParty && !authIdByAuthParty.equals(authId)) {
- return ResponseJson.error("参数异常,该授权机构已存在,请重新输入", null);
- }
- if (null == auth.getCreateBy()) {
- return ResponseJson.error("参数异常,请输入创建人id");
- }
- if (!importFlag) {
- if (null == auth.getProvinceId() || null == auth.getCityId() || null == auth.getTownId() || StringUtils.isEmpty(auth.getAddress()) || null == auth.getLng() || null == auth.getLat()) {
- return ResponseJson.error("参数异常,地址信息异常");
- }
- if (StringUtils.isEmpty(auth.getLogo())) {
- return ResponseJson.error("参数异常,请上传机构logo");
- }
- if (null == bannerList || bannerList.size() <= 0) {
- return ResponseJson.error("参数异常,请上传轮播图");
- }
- }
- // 保存品牌授权信息,上线状态默认为“待上线”,审核状态为“待审核”
- auth.setStatus(2);
- auth.setAuditStatus(2);
- auth.setDelFlag(0);
- /*
- 保存授权
- */
- if (null == authId) {
- authMapper.insertAuth(auth);
- } else {
- authMapper.updateAuthByAuthId(auth);
- // 删除原有的轮播图
- authMapper.deleteBanner(auth.getId());
- }
- // 保存轮播图
- if (null != bannerList) {
- bannerList.forEach(banner-> authMapper.insertBanner(auth.getId(), banner));
- }
- return ResponseJson.success("保存品牌授权成功", auth);
- }
- @Override
- public ResponseJson auditAuth(Integer authId, Integer auditStatus, String invalidReason, Integer auditBy) {
- if (authId == null) {
- return ResponseJson.error("请输入授权id");
- }
- if (auditStatus == null) {
- return ResponseJson.error("请输入审核结果");
- }
- if (auditStatus == 0 && StringUtils.isEmpty(invalidReason)) {
- return ResponseJson.error("请输入审核不通过的原因");
- }
- if (auditBy == null) {
- return ResponseJson.error("请输入审核人用户id");
- }
- Date auditTime = new Date();
- // 授权状态更新
- Integer status = null;
- if (auditStatus == 0) {
- // 审核不通过,下线授权
- status = 0;
- } else {
- // 审核通过,上线授权
- status = 1;
- }
- authMapper.updateAuthAuditStatus(authId, status, auditStatus, invalidReason, auditBy, auditTime);
- return ResponseJson.success("审核品牌授权成功");
- }
- @Override
- public ResponseJson importDataByExcel(MultipartFile file, Integer authUserId, Integer createBy) {
- String originalFilename = file.getOriginalFilename();
- String randomStr = UUID.randomUUID().toString();
- assert originalFilename != null;
- int index = originalFilename.lastIndexOf(".");
- String extName = originalFilename.substring(index);
- String filePath = "/mnt/newdatadrive/data/runtime/jar-instance/zplma/tempFile/";
- if ("dev".equals(active)) {
- filePath = "D:\\WorkSpace\\file\\tempImport\\";
- }
- filePath += randomStr + extName;
- try {
- File tempFile = new File(filePath);
- if (!tempFile.exists()) {
- tempFile.mkdirs();
- }
- file.transferTo(tempFile);
- return saveExcelData(filePath, authUserId, createBy);
- } catch (IOException e) {
- e.printStackTrace();
- }
- log.info(">>>>>>>>>>>>>>>>文件临时路径:" + filePath);
- return null;
- }
- @Override
- public ResponseJson importLdmData(Integer authUserId) {
- List<LdmDataPo> ldmDataList = authMapper.getLdmData();
- ldmDataList.forEach(ldmData->{
- String lngAndLat = ldmData.getLngAndLat();
- if (StringUtils.isNotEmpty(lngAndLat)) {
- String[] split = lngAndLat.split(",");
- BigDecimal lng = new BigDecimal(split[0]);
- BigDecimal lat = new BigDecimal(split[1]);
- ldmData.setLng(lng);
- ldmData.setLat(lat);
- }
- String regId1 = ldmData.getRegId1();
- if (StringUtils.isNotEmpty(regId1)) {
- Integer provinceId = authMapper.getProvinceId(regId1);
- ldmData.setProvinceId(provinceId);
- }
- String regId2 = ldmData.getRegId2();
- if (StringUtils.isNotEmpty(regId2)) {
- Integer cityId = authMapper.getCityId(regId2);
- ldmData.setCityId(cityId);
- }
- String regId3 = ldmData.getRegId3();
- if (StringUtils.isNotEmpty(regId3)) {
- Integer townId = authMapper.getTownId(regId3);
- ldmData.setTownId(townId);
- }
- String pic1 = ldmData.getPic1();
- String pic2 = ldmData.getPic2();
- String pic3 = ldmData.getPic3();
- String pic4 = ldmData.getPic4();
- String pic5 = ldmData.getPic5();
- List<String> picList = new ArrayList<>();
- picList.add(pic1);
- picList.add(pic2);
- picList.add(pic3);
- picList.add(pic4);
- picList.add(pic5);
- String logo = null;
- List<String> addPicList = new ArrayList<>();
- for (String pic : picList) {
- if (StringUtils.isNotEmpty(pic)) {
- try {
- String imagePath = "https://wangdian.skinovachina.com" + pic;
- String fileName = imagePath.substring(imagePath.lastIndexOf("/") + 1);
- String imageUrl = uploadService.saveFileByUrl(imagePath, fileName);
- addPicList.add(imageUrl);
- if (null == logo) {
- logo = imageUrl;
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
- CmBrandAuthPo authPo = new CmBrandAuthPo();
- BeanUtils.copyProperties(ldmData, authPo);
- authPo.setAuthUserId(authUserId);
- authPo.setCreateBy(authUserId);
- authPo.setLogo(logo);
- authMapper.insertAuth(authPo);
- // 保存轮播图
- if (addPicList.size() > 0) {
- addPicList.forEach(banner -> authMapper.insertBanner(authPo.getId(), banner));
- }
- });
- return ResponseJson.success();
- }
- @Override
- public ResponseJson exportDataByExcel(Integer authUserId, HttpServletResponse response) {
- try {
- // 导出表格名
- String fileName = new String("机构商品数据.xls".getBytes("UTF-8"),"iso-8859-1");
- // 机构数据
- List<CmBrandAuthPo> authPartyList = authMapper.getAuthPartyList(authUserId);
- authPartyList.forEach(authParty->{
- // 商品参数数量最大值
- final Integer[] maxParamNum = {0};
- Integer authId = authParty.getId();
- List<ProductFormVo> productList = authProductMapper.getAuthProductList(authId);
- productList.forEach(product->{
- // 参数列表
- List<ProductParamPo> paramList = authProductMapper.getParamsByProductId(product.getProductId());
- product.setParamList(paramList);
- if (paramList.size() > maxParamNum[0]) {
- maxParamNum[0] = paramList.size();
- }
- });
- authParty.setMaxParamNum(maxParamNum[0]);
- authParty.setProductList(productList);
- });
- OutputStream outputStream = response.getOutputStream();
- response.reset();
- response.setHeader("Content-disposition",
- "attachment; filename="+fileName);
- response.setContentType("application/vnd.ms-excel");
- return exportData(authPartyList, outputStream);
- } catch (Exception e) {
- e.printStackTrace();
- return ResponseJson.error("导出失败");
- }
- }
- private ResponseJson saveExcelData(String filePath, Integer authUserId, Integer createBy) {
- //判断是否为excel类型文件
- if (!filePath.endsWith(".xls") && !filePath.endsWith(".xlsx")) {
- System.out.println("文件不是excel类型");
- }
- // 获取供应商品牌
- List<String> shopBrands = shopService.getShopBrands(authUserId);
- // 授权列表
- List<AuthImportPo> authImportList = new ArrayList<>();
- List<String> tempImageList = new ArrayList<>();
- try {
- FileInputStream fis = new FileInputStream(filePath);
- // 得到表格数据
- XSSFWorkbook workbook = new XSSFWorkbook(fis);
- // 获取工作表数量
- int sheetsNum = workbook.getNumberOfSheets();
- //得到第一个工作表(机构表)
- XSSFSheet authPartySheet = workbook.getSheetAt(0);
- //获得表头
- Row rowHead = authPartySheet.getRow(0);
- //判断表头是否正确
- if (1 != rowHead.getLastCellNum() || !"授权机构".equals(rowHead.getCell(0).getStringCellValue())) {
- return ResponseJson.error("授权机构表格式错误");
- }
- // 获得数据的总行数
- int authPartyRowNum = authPartySheet.getLastRowNum();
- // 商品sn码列表
- List<String> snCodeList = new ArrayList<>();
- //获得所有数据
- for (int i = 1; i <= authPartyRowNum; i++) {
- //获得第i行对象
- Row row = authPartySheet.getRow(i);
- //获得获得第i行第0列的机构名称
- Cell cell = row.getCell(0);
- // 机构名称
- String authParty = cell.getStringCellValue();
- if (StringUtils.isNotEmpty(authParty)) {
- /*
- * 授权数据
- */
- AuthImportPo authImportPo = new AuthImportPo();
- // 商品列表
- List<ProductSaveDto> productList = new ArrayList<>();
- // 得到机构对应的商品工作表
- XSSFSheet productSheet = i < sheetsNum ? workbook.getSheetAt(i) : null;
- String sheetName = null != productSheet ? productSheet.getSheetName() : null;
- if (null == productSheet || !authParty.equals(sheetName)) {
- // 遍历所有工作表,找到表名与授权机构名称相同的商品工作表
- for (int j = 1; j < sheetsNum; j++) {
- productSheet = workbook.getSheetAt(j);
- sheetName = productSheet.getSheetName();
- if (!authParty.equals(sheetName)) {
- // 没有该机构对应的商品表
- productSheet = null;
- }
- }
- }
- if (null != productSheet) {
- //获得表头
- Row productRowHead = productSheet.getRow(0);
- //判断表头是否正确
- short cellTotalNum = productRowHead.getLastCellNum();
- if (cellTotalNum < 13) {
- return ResponseJson.error(authParty + "机构商品表格式错误");
- }
- // 获取表格图片
- Map<String, XSSFPictureData> pictures = ExcelOperateUtil.getPictures(productSheet);
- Map<String, String> imageMap = ExcelOperateUtil.printImg(pictures);
- // 校验商品数据是否符合规范
- int productRowNum = productSheet.getLastRowNum();
- for (int k = 1; k <= productRowNum; k++) {
- XSSFRow productRow = productSheet.getRow(k);
- if (null != productRow && productRow.getCell(0) != null) {
- String errorReason = "";
- // 校验商品名称
- String productName = productRow.getCell(0).getStringCellValue();
- if (StringUtils.isEmpty(productName)) {
- errorReason = authParty + "机构商品表第" + (k + 1) + "行商品名称不能为空";
- }
- // 校验商品sn码
- String snCode = productRow.getCell(1).getStringCellValue();
- if (StringUtils.isEmpty(snCode)) {
- errorReason = authParty + "机构商品表第" + (k + 1) + "行商品名称不能为空";
- } else {
- Integer productIdBySnCode = authProductMapper.getProductIdBySnCode(snCode);
- if (null != productIdBySnCode || snCodeList.contains(snCode)) {
- errorReason = authParty + "机构商品表第" + (k + 1) + "行商品sn码已存在,请重新输入";
- } else {
- snCodeList.add(snCode);
- }
- }
- // 校验品牌名称
- String brand = productRow.getCell(2).getStringCellValue();
- Integer brandId = null;
- if (StringUtils.isEmpty(brand)) {
- errorReason = authParty + "机构商品表第" + (k + 1) + "行商品品牌不能为空";
- } else {
- if (!shopBrands.contains(brand)) {
- errorReason = authParty + "机构商品表第" + (k + 1) + "行商品品牌不存在";
- } else {
- brandId = authProductMapper.getBrandIdByBrandName(brand);
- }
- }
- // 校验商品图片
- String productImage = imageMap.get(k + "-3");
- if (StringUtils.isEmpty(productImage)) {
- errorReason = authParty + "机构商品表第" + (k + 1) + "行商品图片不能为空";
- }
- // 校验授权牌照
- String certificateImage = imageMap.get(k + "-4");
- if (StringUtils.isEmpty(certificateImage)) {
- errorReason = authParty + "机构商品表第" + (k + 1) + "行授权牌照不能为空";
- }
- List<ProductParamPo> paramList = new ArrayList<>();
- // 校验参数列表
- for (int a = 5; a + 1 < cellTotalNum; a += 2) {
- XSSFCell paramNameCell = productRow.getCell(a);
- XSSFCell paramContentCell = productRow.getCell(a + 1);
- boolean validName = null != paramNameCell;
- boolean validContent = null != paramContentCell;
- if (validName && validContent) {
- String paramName = paramNameCell.getStringCellValue();
- String paramContent = paramContentCell.getStringCellValue();
- validName = StringUtils.isNotEmpty(paramName);
- validContent = StringUtils.isNotEmpty(paramContent);
- if (validName && validContent) {
- ProductParamPo productParamPo = new ProductParamPo();
- productParamPo.setParamName(paramName);
- productParamPo.setParamContent(paramContent);
- paramList.add(productParamPo);
- } else if ((validName || validContent)) {
- errorReason = authParty + "机构商品表第" + (k + 1) + "行参数数据异常";
- }
- } else if (validName || validContent) {
- errorReason = authParty + "机构商品表第" + (k + 1) + "行参数数据异常";
- }
- }
- if (paramList.size() < 4) {
- errorReason = authParty + "机构商品表第" + (k + 1) + "行参数数量不足";
- }
- if (StringUtils.isNotEmpty(errorReason)) {
- // 删除临时图片文件
- for (String image : imageMap.values()) {
- if (StringUtils.isNotEmpty(image)) {
- File tempFile = new File(image);
- tempFile.delete();
- }
- }
- return ResponseJson.error(errorReason);
- }
- /*
- 组装商品数据
- */
- ProductSaveDto product = new ProductSaveDto();
- // 品牌id
- product.setBrandId(brandId);
- // 商品名称
- product.setProductName(productName);
- // sn码
- product.setSnCode(snCode);
- // 商品图片
- product.setProductImage(uploadImage(productImage));
- // 授权牌照
- product.setCertificateImage(uploadImage(certificateImage));
- // 参数列表
- product.setParamList(paramList);
- // 创建人
- product.setCreateBy(createBy);
- productList.add(product);
- tempImageList.add(productImage);
- tempImageList.add(certificateImage);
- }
- }
- }
- // 授权机构
- authImportPo.setAuthParty(authParty);
- // 商品列表
- authImportPo.setProductList(productList);
- // 添加数据
- authImportList.add(authImportPo);
- }
- }
- } catch (Exception e) {
- e.printStackTrace();
- return ResponseJson.error("导入失败,请检查表格数据");
- } finally {
- // 删除临时数据
- File tempFile = new File(filePath);
- boolean delete = tempFile.delete();
- log.info("【图片上传】>>>>>>>>>>>>>>>>删除临时表格:" + delete);
- tempImageList.forEach(tempImagePath->{
- File tempImage = new File(tempImagePath);
- boolean del = tempImage.delete();
- log.info("【图片上传】>>>>>>>>>>>>>>>>删除临时商品图片:" + del);
- });
- }
- // 保存授权数据
- authImportList.forEach(authImportPo -> {
- String authParty = authImportPo.getAuthParty();
- List<ProductSaveDto> productList = authImportPo.getProductList();
- Integer authId = authMapper.getAuthIdByAuthParty(authParty, authUserId);
- // 保存授权机构
- if (null == authId) {
- CmBrandAuthPo auth = new CmBrandAuthPo();
- auth.setAuthUserId(authUserId);
- auth.setAuthParty(authParty);
- auth.setCreateBy(createBy);
- ResponseJson responseJson = saveAuth(auth, null, true);
- CmBrandAuthPo authPo = (CmBrandAuthPo) responseJson.getData();
- authId = authPo.getId();
- }
- Integer finalAuthId = authId;
- // 保存商品列表
- productList.forEach(productDto -> {
- try {
- productDto.setAuthId(finalAuthId);
- // 上传商品图片和授权牌照
- String productImage = productDto.getProductImage();
- String certificateImage = productDto.getCertificateImage();
- productDto.setProductImage(productImage);
- productDto.setCertificateImage(certificateImage);
- authProductService.saveProduct(productDto, true);
- } catch (IOException e) {
- e.printStackTrace();
- }
- });
- });
- return ResponseJson.success("导入成功");
- }
- private ResponseJson exportData(List<CmBrandAuthPo> authPartyList, OutputStream outputStream) {
- try {
- HSSFWorkbook workbook = new HSSFWorkbook();
- // 创建机构工作表
- HSSFSheet authPartySheet = workbook.createSheet("授权机构");
- // sheet样式定义
- HSSFCellStyle topCellStyle = this.getTopCellStyle(workbook);
- HSSFCellStyle customCellStyle = this.getCustomCellStyle(workbook);
- // 创建列头行
- HSSFRow topRow = authPartySheet.createRow(0);
- HSSFCell topRowCell = topRow.createCell(0);
- topRowCell.setCellType(CellType.valueOf("STRING"));
- HSSFRichTextString text = new HSSFRichTextString("授权机构");
- topRowCell.setCellValue(text);
- topRowCell.setCellStyle(topCellStyle);
- // 行索引
- AtomicInteger authPartyRowNum = new AtomicInteger(1);
- // 每个机构创建一行数据
- authPartyList.forEach(authParty -> {
- HSSFRow authPartyRow = authPartySheet.createRow(authPartyRowNum.get());
- HSSFCell authPartyCell = authPartyRow.createCell(0);
- authPartyCell.setCellType(CellType.valueOf("STRING"));
- HSSFRichTextString authPartyName = new HSSFRichTextString(authParty.getAuthParty().trim());
- authPartyCell.setCellValue(authPartyName);
- authPartyCell.setCellStyle(customCellStyle);
- authPartyRowNum.getAndIncrement();
- });
- // 让列宽随着导出的列长自动适应
- int columnWidth = authPartySheet.getColumnWidth(0) / 256;
- for (int rowNum = 0; rowNum < authPartySheet.getLastRowNum(); rowNum++) {
- HSSFRow currentRow;
- // 当前行未被使用过
- if (authPartySheet.getRow(rowNum) == null) {
- currentRow = authPartySheet.createRow(rowNum);
- } else {
- currentRow = authPartySheet.getRow(rowNum);
- }
- if (currentRow.getCell(0) != null) {
- HSSFCell currentCell = currentRow.getCell(0);
- if (currentCell.getCellTypeEnum().equals(CellType.valueOf("STRING"))) {
- int length = currentCell.getStringCellValue()
- .getBytes().length;
- if (columnWidth < length) {
- columnWidth = length;
- }
- }
- }
- }
- authPartySheet.setColumnWidth(0, (columnWidth + 4) * 256);
- // 创建每个机构对应的商品表
- authPartyList.forEach(authParty -> {
- // 授权机构名称作为表名
- String productSheetName = authParty.getAuthParty();
- // 商品列表
- List<ProductFormVo> productList = authParty.getProductList();
- // 创建商品工作表
- HSSFSheet productSheet = workbook.createSheet(productSheetName);
- // 创建列头行
- HSSFRow productTopRow = productSheet.createRow(0);
- // 添加列头单元格(5个固定列+参数列表)
- String[] rowName = {"商品名称", "商品SN码", "所属品牌", "商品图片(尺寸:128px×88px)",
- "授权牌(尺寸:128px×88px)", "参数名称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 < 5 + (0 == authParty.getMaxParamNum() ? 4 : authParty.getMaxParamNum()) * 2; i++) {
- HSSFCell productTopRowCell = productTopRow.createCell(i);
- productTopRowCell.setCellType(CellType.valueOf("STRING"));
- HSSFRichTextString columnText = new HSSFRichTextString(rowName[i]);
- productTopRowCell.setCellValue(columnText);
- productTopRowCell.setCellStyle(topCellStyle);
- }
- // 添加商品数据到单元格中
- // 行索引
- AtomicInteger productRowNum = new AtomicInteger(1);
- productList.forEach(product -> {
- // 创建商品行
- HSSFRow productRow = productSheet.createRow(productRowNum.get());
- // 设置行高度
- productRow.setHeight((short) 2200);
- // 参数列表
- List<ProductParamPo> paramList = product.getParamList();
- // 组装商品数据
- List<String> productData = new ArrayList<>();
- productData.add(product.getProductName());
- productData.add(product.getSnCode());
- productData.add(product.getBrandName());
- productData.add(product.getProductImage());
- productData.add(product.getCertificateImage());
- paramList.forEach(param -> {
- productData.add(param.getParamName());
- productData.add(param.getParamContent());
- });
- for (int j = 0; j < 5 + paramList.size() * 2; j++) {
- HSSFCell productCell = productRow.createCell(j);
- if (j == 3 || j == 4) {
- // productSheet.addMergedRegion(new CellRangeAddress(j + 1,j + 1,j + 1,j + 1)) ;
- // 头像
- String imageUrl = productData.get(j);
- String fileType = imageUrl.substring(imageUrl.lastIndexOf(".") + 1);
- InputStream imageStream = getImageStream(imageUrl);
- if (null != imageStream) {
- try {
- BufferedImage bufferedImage = ImageIO.read(imageStream);
- ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
- ImageIO.write(bufferedImage, fileType, byteArrayOut);
- byte[] data = byteArrayOut.toByteArray();
- HSSFPatriarch drawingPatriarch = productSheet.createDrawingPatriarch();
- // 设置图片位置
- HSSFClientAnchor anchor = new HSSFClientAnchor(30, 30, 700, 200, (short) j, productRowNum.get(), (short) j, productRowNum.get());
- drawingPatriarch.createPicture(anchor, workbook.addPicture(data, HSSFWorkbook.PICTURE_TYPE_JPEG));
- } catch (Exception e) {
- e.printStackTrace();
- }
- } else {
- productCell.setCellType(CellType.valueOf("STRING"));
- productCell.setCellValue("");
- }
- } else {
- productCell.setCellType(CellType.valueOf("STRING"));
- HSSFRichTextString productCellValue = new HSSFRichTextString(productData.get(j));
- productCell.setCellValue(productCellValue);
- productCell.setCellStyle(customCellStyle);
- }
- }
- productRowNum.getAndIncrement();
- });
- // 让列宽随着导出的列长自动适应
- for (int colNum = 0; (colNum < 5 + authParty.getMaxParamNum() * 2); colNum++) {
- if (colNum == 3 || colNum == 4) {
- productSheet.setColumnWidth(colNum, 8200);
- } else {
- int productColumnWidth = productSheet.getColumnWidth(colNum) / 256;
- for (int rowNum = 0; rowNum < productSheet.getLastRowNum(); rowNum++) {
- HSSFRow currentRow;
- // 当前行未被使用过
- if (productSheet.getRow(rowNum) == null) {
- currentRow = productSheet.createRow(rowNum);
- } else {
- currentRow = productSheet.getRow(rowNum);
- }
- if (currentRow.getCell(colNum) != null) {
- HSSFCell 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);
- }
- }
- });
- outputStream.flush();
- workbook.write(outputStream);
- outputStream.close();
- } catch (Exception e) {
- e.printStackTrace();
- return ResponseJson.error("导出失败");
- }
- return ResponseJson.success("导出成功");
- }
- private String uploadImage(String filePath) throws IOException {
- // 临时图片
- File tempFile = new File(filePath);
- log.info("【图片上传】>>>>>>>>>>>>>>>>图片临时路径:" + filePath);
- String imageUrl = imageDomain + "/" + client.uploadFile(filePath);
- return imageUrl;
- }
- /**
- * 列头单元格样式
- */
- private HSSFCellStyle getTopCellStyle(HSSFWorkbook workbook) {
- // 设置字体
- HSSFFont font = workbook.createFont();
- // 设置字体大小
- font.setFontHeightInPoints((short) 11);
- // 字体加粗
- font.setBold(true);
- // 设置字体名字
- font.setFontName("Courier New");
- // 设置样式;
- HSSFCellStyle style = workbook.createCellStyle();
- // 设置底边框;
- style.setBorderBottom(BorderStyle.THIN);
- // 设置底边框颜色;
- style.setBottomBorderColor(IndexedColors.BLACK.index);
- // 设置左边框;
- style.setBorderLeft(BorderStyle.THIN);
- // 设置左边框颜色;
- style.setLeftBorderColor(IndexedColors.BLACK.index);
- // 设置右边框;
- style.setBorderRight(BorderStyle.THIN);
- // 设置右边框颜色;
- style.setRightBorderColor(IndexedColors.BLACK.index);
- // 设置顶边框;
- style.setBorderTop(BorderStyle.THIN);
- // 设置顶边框颜色;
- style.setTopBorderColor(IndexedColors.BLACK.index);
- // 在样式用应用设置的字体;
- style.setFont(font);
- // 设置自动换行;
- style.setWrapText(false);
- // 设置水平对齐的样式为居中对齐;
- style.setAlignment(HorizontalAlignment.CENTER);
- // 设置垂直对齐的样式为居中对齐;
- style.setVerticalAlignment(VerticalAlignment.CENTER);
- return style;
- }
- /**
- * 列数据信息单元格样式
- */
- private HSSFCellStyle getCustomCellStyle(HSSFWorkbook workbook) {
- // 设置字体
- HSSFFont font = workbook.createFont();
- // 设置字体大小
- // font.setFontHeightInPoints((short)10);
- // 字体加粗
- // font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
- // 设置字体名字
- font.setFontName("Courier New");
- // 设置样式;
- HSSFCellStyle style = workbook.createCellStyle();
- // 设置底边框;
- style.setBorderBottom(BorderStyle.THIN);
- // 设置底边框颜色;
- style.setBottomBorderColor(IndexedColors.BLACK.index);
- // 设置左边框;
- style.setBorderLeft(BorderStyle.THIN);
- // 设置左边框颜色;
- style.setLeftBorderColor(IndexedColors.BLACK.index);
- // 设置右边框;
- style.setBorderRight(BorderStyle.THIN);
- // 设置右边框颜色;
- style.setRightBorderColor(IndexedColors.BLACK.index);
- // 设置顶边框;
- style.setBorderTop(BorderStyle.THIN);
- // 设置顶边框颜色;
- style.setTopBorderColor(IndexedColors.BLACK.index);
- // 在样式用应用设置的字体;
- style.setFont(font);
- // 设置自动换行;
- style.setWrapText(false);
- // 设置水平对齐的样式为居中对齐;
- style.setAlignment(HorizontalAlignment.CENTER);
- // 设置垂直对齐的样式为居中对齐;
- style.setVerticalAlignment(VerticalAlignment.CENTER);
- return style;
- }
- public InputStream getImageStream(String url) {
- try {
- HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
- connection.setReadTimeout(5000);
- connection.setConnectTimeout(5000);
- connection.setRequestMethod("GET");
- if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
- InputStream inputStream = connection.getInputStream();
- return inputStream;
- }
- } catch (IOException e) {
- System.out.println("获取网络图片出现异常,图片路径为:" + url);
- e.printStackTrace();
- }
- return null;
- }
- }
|