package com.kmall.admin.controller; import com.alibaba.fastjson.JSON; import com.kmall.admin.dto.GoodsDetailsDto; import com.kmall.admin.dto.GoodsDto; import com.kmall.admin.entity.GoodsEntity; import com.kmall.admin.entity.GoodsGalleryEntity; import com.kmall.admin.entity.SysOssEntity; import com.kmall.admin.service.*; import com.kmall.admin.utils.ParamUtils; import com.kmall.admin.utils.ShiroUtils; import com.kmall.api.cache.UserTokenCache; import com.kmall.common.utils.ImgException; import com.kmall.common.constant.Dict; import com.kmall.common.constant.JxlsXmlTemplateName; import com.kmall.admin.fromcomm.entity.SysUserEntity; import com.kmall.common.fileserver.util.FileManager; import com.kmall.common.utils.*; import com.kmall.common.utils.excel.ExcelUtil; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileItemFactory; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import java.io.*; import java.util.*; import org.apache.tools.zip.ZipEntry; import org.apache.tools.zip.ZipFile; import org.springframework.web.multipart.commons.CommonsMultipartFile; /** * Controller * * @author Scott * @email * @date 2017-08-21 21:19:49 */ @RestController @RequestMapping("goods") public class GoodsController { private static Log logger = LogFactory.getLog(UserTokenCache.class); @Autowired private GoodsService goodsService; @Autowired private GoodsGalleryService goodsGalleryService; @Autowired private OfflineCartService offlineCartService; @Autowired private ExcelUtil excelUtil; @Autowired private StoreService storeService; @Autowired private SysOssService sysOssService; /** * 查看列表 */ @RequestMapping("/list") @RequiresPermissions("goods:list") public R list(@RequestParam Map params) { ParamUtils.setQueryPowerByRoleType(params, "storeKey", "merchSn", "thirdPartyMerchCode"); ParamUtils.setName(params, "name"); //查询列表数据 Query query = new Query(params); query.put("isDelete", 0); List goodsList = goodsService.queryList(query); int total = goodsService.queryTotal(query); PageUtils pageUtil = new PageUtils(goodsList, total, query.getLimit(), query.getPage()); return R.ok().put("page", pageUtil); } /** * 查看信息 */ @RequestMapping("/info/{id}") @RequiresPermissions("goods:info") public R info(@PathVariable("id") Integer id) { GoodsEntity goods = goodsService.queryObject(id); if(goods != null) { GoodsGalleryEntity goodsGalleryEntity =goodsGalleryService.queryVideoObjectByGoodId(goods.getId()); if(goodsGalleryEntity != null){ goods.setVideoUrl(goodsGalleryEntity.getImgUrl()); } } return R.ok().put("goods", goods); } /** * 保存 */ @RequestMapping("/save") @RequiresPermissions("goods:save") public R save(@RequestBody GoodsEntity goods) { goodsService.save(goods); return R.ok(); } /** * 修改 */ @RequestMapping("/update") @RequiresPermissions("goods:update") public R update(@RequestBody GoodsEntity goods) { goodsService.update(goods); return R.ok(); } /** * 删除 */ @RequestMapping("/delete") @RequiresPermissions("goods:delete") public R delete(@RequestBody Integer[] ids) { goodsService.deleteBatch(ids); return R.ok(); } /** * 查看所有列表 */ @RequestMapping("/queryAll") public R queryAll(@RequestParam Map params) { ParamUtils.setQueryPowerByRoleType(params, "storeKey", "merchSn", "thirdPartyMerchCode"); params.put("isDelete", Integer.parseInt(Dict.isDelete.item_0.getItem())); params.put("isOnSale", Integer.parseInt(Dict.isOnSale.item_1.getItem())); List list = goodsService.queryList(params); return R.ok().put("list", list); } /** * 商品回收站 * * @param params * @return */ @RequestMapping("/historyList") public R historyList(@RequestParam Map params) { ParamUtils.setQueryPowerByRoleType(params, "storeKey", "merchSn", "thirdPartyMerchCode"); //查询列表数据 Query query = new Query(params); query.put("isDelete", 1); List goodsList = goodsService.queryList(query); int total = goodsService.queryTotal(query); PageUtils pageUtil = new PageUtils(goodsList, total, query.getLimit(), query.getPage()); return R.ok().put("page", pageUtil); } /** * 商品从回收站恢复 */ @RequestMapping("/back") @RequiresPermissions("goods:back") public R back(@RequestBody Integer[] ids) { goodsService.back(ids); return R.ok(); } /** * 总计 */ @RequestMapping("/queryTotal") public R queryTotal(@RequestParam Map params) { ParamUtils.setQueryPowerByRoleType(params, "storeKey", "merchSn", "thirdPartyMerchCode"); params.put("isDelete", 0); int sum = goodsService.queryTotal(params); return R.ok().put("goodsSum", sum); } /** * 上架 */ @RequestMapping("/enSale") public R enSale(@RequestBody Integer id) { goodsService.enSale(id); return R.ok(); } /** * 上架 */ @RequestMapping("/enSaleBatch") public R enSaleBatch(@RequestBody Integer[] ids) { goodsService.enSaleBatch(ids); return R.ok(); } /** * 下架 */ @RequestMapping("/unSale") public R unSale(@RequestBody Integer id) { goodsService.unSale(id); return R.ok(); } /** * 下架 */ @RequestMapping("/unSaleBatch") public R unSaleBatch(@RequestBody Integer[] ids) { goodsService.unSaleBatch(ids); return R.ok(); } /** * 上传文件 */ @RequestMapping("/upload") public R upload(@RequestParam("file") MultipartFile file) { List goodsDtoList = new ArrayList<>();//商品信息 try { Map beans = new HashMap(); beans.put("GoodsDtoList", goodsDtoList); if (file.isEmpty()) { return R.error("文件不能为空!"); } excelUtil.readExcel(JxlsXmlTemplateName.GOODS_DTO_LIST, beans, file.getInputStream()); } catch (Exception e) { e.printStackTrace(); return R.error("导入失败!"); } goodsService.uploadExcel(goodsDtoList,Integer.parseInt(Dict.exportDataType.item_1.getItem())); //上传文件 return R.ok(); } /** * 上传文件 */ @RequestMapping("/generalGoodsUpload") public R generalGoodsUpload(@RequestParam("file") MultipartFile file) { List generalGoodsDtoList = new ArrayList<>();//商品信息 try { Map beans = new HashMap(); beans.put("GeneralGoodsDtoList", generalGoodsDtoList); if (file.isEmpty()) { return R.error("文件不能为空!"); } excelUtil.readExcel(JxlsXmlTemplateName.GENERAL_GOODS_DTO_LIST, beans, file.getInputStream()); } catch (Exception e) { e.printStackTrace(); return R.error("导入失败!"); } goodsService.uploadExcel(generalGoodsDtoList,Integer.parseInt(Dict.exportDataType.item_2.getItem())); //上传文件 return R.ok(); } /*@RequestMapping("/scannInfo") @RequiresPermissions("goods:scannInfo") public R scannInfo(@RequestParam Map params) { String goodsSn = (String)params.get("goodsSn"); GoodsEntity goods = goodsService.queryObjectByGoodsSnAndBizType(goodsSn); if(goods == null) { return R.error("商品信息不存在"); } List cartEntityList = offlineCartService.offlineGoodsCart(goods); return R.ok().put("cartEntityList", cartEntityList); }*/ @RequestMapping("/scannInfo/{prodBarcode}") @RequiresPermissions("goods:scannInfo") public R scannInfo(@PathVariable("prodBarcode")String prodBarcode) { SysUserEntity user = ShiroUtils.getUserEntity(); if(user == null) { return R.error("用户登录超时,请重新登录"); } if (!user.getRoleType().equalsIgnoreCase("2")) { return R.error("该操作只允许店员账户操作"); } GoodsEntity goods = goodsService.queryObjectByProdBarcodeAndBizType(prodBarcode, user.getStoreId()); if(goods == null) { return R.error("商品信息不存在"); } return R.ok().put("goods", goods); } @RequestMapping("/details/{prodBarcode}") // @RequiresPermissions("goods:details") http://127.0.0.1:8080/goods/details/11111 public R details(@PathVariable("prodBarcode")String prodBarcode) { SysUserEntity user = ShiroUtils.getUserEntity(); if(user == null) { return R.error("用户登录超时,请重新登录"); } if (!user.getRoleType().equalsIgnoreCase("2")) { return R.error("该操作只允许店员账户操作"); } GoodsDetailsDto goods = goodsService.queryGoodsDetailsByProdBarcode(prodBarcode); if(goods == null) { return R.error("商品信息不存在"); } return R.ok().put("goodsDetails", goods); } @RequestMapping("/generalGoodsImgUploadByZip") @ResponseBody public R batchAddImgByZip(@RequestParam("file") MultipartFile file) throws IOException { //上传文件 batchAdd(file,2); return R.ok(); } @RequestMapping("/generalGoodsImgUpload") @ResponseBody public R batchAddImg(@RequestParam("file") MultipartFile file) throws IOException { //上传文件 batchAdd(file,1); return R.ok(); } private Map batchAdd(MultipartFile file, int type) throws IOException { /* *创建临时文件夹 * 解压文件 */ String fileName = file.getOriginalFilename(); String path = "/data/project/img/"; File dir = new File(path); dir.mkdirs(); String filePath = "/data/project/img2/"; File fileDir = new File(filePath); fileDir.mkdirs(); File saveFile = new File(fileDir, fileName);//将压缩包解析到指定位置 Listlist = new ArrayList<>(); try { file.transferTo(saveFile); String newFilePath = filePath + fileName; File zipFile = new File(newFilePath); unZipFiles(zipFile, path,list,type);//解压文件,获取文件路径 } catch (Exception e) { e.printStackTrace(); logger.info("解压执行失败"); throw e; }finally { //程序结束时,删除临时文件 deleteFiles(filePath);//删除压缩包文件夹 deleteFiles(path);//删除解压文件夹** } logger.info(JSON.toJSONString(list)); Map jsonMap = new HashMap<>(); jsonMap.put("ret",list); return jsonMap; } public void deleteFiles(String filePath) { File file = new File(filePath); if ((!file.exists()) || (!file.isDirectory())) { System.out.println("file not exist"); return; } String[] tempList = file.list(); File temp = null; for (int i = 0; i < tempList.length; i++) { if (filePath.endsWith(File.separator)) { temp = new File(filePath + tempList[i]); } else { temp = new File(filePath + File.separator + tempList[i]); } if (temp.isFile()) { temp.delete(); } if (temp.isDirectory()) { this.deleteFiles(filePath + "/" + tempList[i]); } } // 空文件的删除 file.delete(); } public void unZipFiles(File srcFile, String destDirPath, List list, int type) throws RuntimeException { long start = System.currentTimeMillis(); ZipFile zipFile = null; try { // 判断源文件是否存在 if (!srcFile.exists()) { throw new RuntimeException(srcFile.getPath() + "所指文件不存在"); } // 开始解压 zipFile = new ZipFile(srcFile); zipFile.getEncoding(); Enumeration entries = zipFile.getEntries(); List entryList = new ArrayList<>(); while (entries.hasMoreElements()) { ZipEntry entry = (ZipEntry) entries.nextElement(); logger.info("解压" + entry.getName()); entryList.add(entry); // 如果是文件夹,就创建个文件夹 } if(null==entryList){ throw new RRException("文件夹内无图片信息,请检查后重试"); } if(entryList.size()>100){ throw new RRException("最多上传100张图片"); } for(ZipEntry entry : entryList){ if (entry.isDirectory()) { String dirPath = destDirPath + "/" + entry.getName(); File dir = new File(dirPath); dir.mkdirs(); } else { // 如果是文件,就先创建一个文件,然后用io流把内容copy过去 File targetFile = new File(destDirPath + "/" + entry.getName()); // 保证这个文件的父文件夹必须要存在 if(!targetFile.getParentFile().exists()){ } targetFile.createNewFile(); // 将压缩文件内容写入到这个文件中 InputStream is = zipFile.getInputStream(entry); FileOutputStream fos = new FileOutputStream(targetFile); int len; byte[] buf = new byte[1024]; while ((len = is.read(buf)) != -1) { fos.write(buf, 0, len); } MultipartFile mulFileByPath = getMulFileByPath(destDirPath + "/" + entry.getName()); long fileSize = mulFileByPath.getSize(); int maxSize = 1 * 1024 * 1024; if (fileSize > maxSize) { throw new RRException("商品图片过大(最大1M),请检查!"); } // String imgg = entry.getName().split("\\.")[1]; // if (!"jpg".equals(imgg)&&!"jpeg".equals(imgg)) { // throw new RRException("图片格式不正确,请检查!"); // } //上传文件 String url = FileManager.upload(mulFileByPath); list.add(url); if(type == 1){ String sku = entry.getName().split("\\.")[0]; if (null==sku||"".equals(sku)) { throw new ImgException("文件为:" + sku + "的商品命名格式不正确,请检查!"); } GoodsEntity goodsEntity = goodsService.queryBySku(sku); goodsEntity.setPrimaryPicUrl(url); goodsEntity.setListPicUrl(url); goodsService.updateForImgUrl(goodsEntity); }else if(type == 2){ String barCode = entry.getName().split("/")[1]; GoodsEntity goodsEntity = goodsService.queryByBarcode(barCode); goodsEntity.setPrimaryPicUrl(url); goodsEntity.setListPicUrl(url); goodsService.updateForImgUrl(goodsEntity); } //保存文件信息 SysOssEntity ossEntity = new SysOssEntity(); ossEntity.setUrl(url); ossEntity.setCreateDate(new Date()); sysOssService.save(ossEntity); // 关流顺序,先打开的后关闭 fos.close(); is.close(); } } long end = System.currentTimeMillis(); System.out.println("解压完成,耗时:" + (end - start) +" ms"); }catch (RRException e) { throw new RRException(e.getMessage(), e); }catch (Exception e) { throw new RuntimeException("unzip error from ZipUtils", e); } finally { if(zipFile != null){ try { zipFile.close(); } catch (IOException e) { e.printStackTrace(); } } } } private static MultipartFile getMulFileByPath(String picPath) { FileItem fileItem = createFileItem(picPath); MultipartFile mfile = new CommonsMultipartFile(fileItem); return mfile; } private static FileItem createFileItem(String filePath) { FileItemFactory factory = new DiskFileItemFactory(16, null); String textFieldName = "textField"; int num = filePath.lastIndexOf("."); String extFile = filePath.substring(num); FileItem item = factory.createItem(textFieldName, "text/plain", true, "MyFileName" + extFile); File newfile = new File(filePath); int bytesRead = 0; byte[] buffer = new byte[8192]; try { FileInputStream fis = new FileInputStream(newfile); OutputStream os = item.getOutputStream(); while ((bytesRead = fis.read(buffer, 0, 8192)) != -1) { os.write(buffer, 0, bytesRead); } os.close(); fis.close(); } catch (IOException e) { e.printStackTrace(); } return item; } }