1
0

GoodsController.java 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534
  1. package com.kmall.admin.controller;
  2. import com.alibaba.fastjson.JSON;
  3. import com.kmall.admin.dto.GoodsDetailsDto;
  4. import com.kmall.admin.dto.GoodsDto;
  5. import com.kmall.admin.entity.GoodsEntity;
  6. import com.kmall.admin.entity.GoodsGalleryEntity;
  7. import com.kmall.admin.entity.SysOssEntity;
  8. import com.kmall.admin.service.*;
  9. import com.kmall.admin.utils.ParamUtils;
  10. import com.kmall.admin.utils.ShiroUtils;
  11. import com.kmall.api.cache.UserTokenCache;
  12. import com.kmall.common.utils.ImgException;
  13. import com.kmall.common.constant.Dict;
  14. import com.kmall.common.constant.JxlsXmlTemplateName;
  15. import com.kmall.admin.fromcomm.entity.SysUserEntity;
  16. import com.kmall.common.fileserver.util.FileManager;
  17. import com.kmall.common.utils.*;
  18. import com.kmall.common.utils.excel.ExcelUtil;
  19. import org.apache.commons.fileupload.FileItem;
  20. import org.apache.commons.fileupload.FileItemFactory;
  21. import org.apache.commons.fileupload.disk.DiskFileItemFactory;
  22. import org.apache.commons.logging.Log;
  23. import org.apache.commons.logging.LogFactory;
  24. import org.apache.shiro.authz.annotation.RequiresPermissions;
  25. import org.springframework.beans.factory.annotation.Autowired;
  26. import org.springframework.web.bind.annotation.*;
  27. import org.springframework.web.multipart.MultipartFile;
  28. import java.io.*;
  29. import java.util.*;
  30. import org.apache.tools.zip.ZipEntry;
  31. import org.apache.tools.zip.ZipFile;
  32. import org.springframework.web.multipart.commons.CommonsMultipartFile;
  33. /**
  34. * Controller
  35. *
  36. * @author Scott
  37. * @email
  38. * @date 2017-08-21 21:19:49
  39. */
  40. @RestController
  41. @RequestMapping("goods")
  42. public class GoodsController {
  43. private static Log logger = LogFactory.getLog(UserTokenCache.class);
  44. @Autowired
  45. private GoodsService goodsService;
  46. @Autowired
  47. private GoodsGalleryService goodsGalleryService;
  48. @Autowired
  49. private OfflineCartService offlineCartService;
  50. @Autowired
  51. private ExcelUtil excelUtil;
  52. @Autowired
  53. private StoreService storeService;
  54. @Autowired
  55. private SysOssService sysOssService;
  56. /**
  57. * 查看列表
  58. */
  59. @RequestMapping("/list")
  60. @RequiresPermissions("goods:list")
  61. public R list(@RequestParam Map<String, Object> params) {
  62. ParamUtils.setQueryPowerByRoleType(params, "storeKey", "merchSn", "thirdPartyMerchCode");
  63. ParamUtils.setName(params, "name");
  64. //查询列表数据
  65. Query query = new Query(params);
  66. query.put("isDelete", 0);
  67. List<GoodsEntity> goodsList = goodsService.queryList(query);
  68. int total = goodsService.queryTotal(query);
  69. PageUtils pageUtil = new PageUtils(goodsList, total, query.getLimit(), query.getPage());
  70. return R.ok().put("page", pageUtil);
  71. }
  72. /**
  73. * 查看信息
  74. */
  75. @RequestMapping("/info/{id}")
  76. @RequiresPermissions("goods:info")
  77. public R info(@PathVariable("id") Integer id) {
  78. GoodsEntity goods = goodsService.queryObject(id);
  79. if(goods != null) {
  80. GoodsGalleryEntity goodsGalleryEntity =goodsGalleryService.queryVideoObjectByGoodId(goods.getId());
  81. if(goodsGalleryEntity != null){
  82. goods.setVideoUrl(goodsGalleryEntity.getImgUrl());
  83. }
  84. }
  85. return R.ok().put("goods", goods);
  86. }
  87. /**
  88. * 保存
  89. */
  90. @RequestMapping("/save")
  91. @RequiresPermissions("goods:save")
  92. public R save(@RequestBody GoodsEntity goods) {
  93. goodsService.save(goods);
  94. return R.ok();
  95. }
  96. /**
  97. * 修改
  98. */
  99. @RequestMapping("/update")
  100. @RequiresPermissions("goods:update")
  101. public R update(@RequestBody GoodsEntity goods) {
  102. goodsService.update(goods);
  103. return R.ok();
  104. }
  105. /**
  106. * 删除
  107. */
  108. @RequestMapping("/delete")
  109. @RequiresPermissions("goods:delete")
  110. public R delete(@RequestBody Integer[] ids) {
  111. goodsService.deleteBatch(ids);
  112. return R.ok();
  113. }
  114. /**
  115. * 查看所有列表
  116. */
  117. @RequestMapping("/queryAll")
  118. public R queryAll(@RequestParam Map<String, Object> params) {
  119. ParamUtils.setQueryPowerByRoleType(params, "storeKey", "merchSn", "thirdPartyMerchCode");
  120. params.put("isDelete", Integer.parseInt(Dict.isDelete.item_0.getItem()));
  121. params.put("isOnSale", Integer.parseInt(Dict.isOnSale.item_1.getItem()));
  122. List<GoodsEntity> list = goodsService.queryList(params);
  123. return R.ok().put("list", list);
  124. }
  125. /**
  126. * 商品回收站
  127. *
  128. * @param params
  129. * @return
  130. */
  131. @RequestMapping("/historyList")
  132. public R historyList(@RequestParam Map<String, Object> params) {
  133. ParamUtils.setQueryPowerByRoleType(params, "storeKey", "merchSn", "thirdPartyMerchCode");
  134. //查询列表数据
  135. Query query = new Query(params);
  136. query.put("isDelete", 1);
  137. List<GoodsEntity> goodsList = goodsService.queryList(query);
  138. int total = goodsService.queryTotal(query);
  139. PageUtils pageUtil = new PageUtils(goodsList, total, query.getLimit(), query.getPage());
  140. return R.ok().put("page", pageUtil);
  141. }
  142. /**
  143. * 商品从回收站恢复
  144. */
  145. @RequestMapping("/back")
  146. @RequiresPermissions("goods:back")
  147. public R back(@RequestBody Integer[] ids) {
  148. goodsService.back(ids);
  149. return R.ok();
  150. }
  151. /**
  152. * 总计
  153. */
  154. @RequestMapping("/queryTotal")
  155. public R queryTotal(@RequestParam Map<String, Object> params) {
  156. ParamUtils.setQueryPowerByRoleType(params, "storeKey", "merchSn", "thirdPartyMerchCode");
  157. params.put("isDelete", 0);
  158. int sum = goodsService.queryTotal(params);
  159. return R.ok().put("goodsSum", sum);
  160. }
  161. /**
  162. * 上架
  163. */
  164. @RequestMapping("/enSale")
  165. public R enSale(@RequestBody Integer id) {
  166. goodsService.enSale(id);
  167. return R.ok();
  168. }
  169. /**
  170. * 上架
  171. */
  172. @RequestMapping("/enSaleBatch")
  173. public R enSaleBatch(@RequestBody Integer[] ids) {
  174. goodsService.enSaleBatch(ids);
  175. return R.ok();
  176. }
  177. /**
  178. * 下架
  179. */
  180. @RequestMapping("/unSale")
  181. public R unSale(@RequestBody Integer id) {
  182. goodsService.unSale(id);
  183. return R.ok();
  184. }
  185. /**
  186. * 下架
  187. */
  188. @RequestMapping("/unSaleBatch")
  189. public R unSaleBatch(@RequestBody Integer[] ids) {
  190. goodsService.unSaleBatch(ids);
  191. return R.ok();
  192. }
  193. /**
  194. * 上传文件
  195. */
  196. @RequestMapping("/upload")
  197. public R upload(@RequestParam("file") MultipartFile file) {
  198. List<GoodsDto> goodsDtoList = new ArrayList<>();//商品信息
  199. try {
  200. Map<String, Object> beans = new HashMap<String, Object>();
  201. beans.put("GoodsDtoList", goodsDtoList);
  202. if (file.isEmpty()) {
  203. return R.error("文件不能为空!");
  204. }
  205. excelUtil.readExcel(JxlsXmlTemplateName.GOODS_DTO_LIST, beans, file.getInputStream());
  206. } catch (Exception e) {
  207. e.printStackTrace();
  208. return R.error("导入失败!");
  209. }
  210. goodsService.uploadExcel(goodsDtoList,Integer.parseInt(Dict.exportDataType.item_1.getItem()));
  211. //上传文件
  212. return R.ok();
  213. }
  214. /**
  215. * 上传文件
  216. */
  217. @RequestMapping("/generalGoodsUpload")
  218. public R generalGoodsUpload(@RequestParam("file") MultipartFile file) {
  219. List<GoodsDto> generalGoodsDtoList = new ArrayList<>();//商品信息
  220. try {
  221. Map<String, Object> beans = new HashMap<String, Object>();
  222. beans.put("GeneralGoodsDtoList", generalGoodsDtoList);
  223. if (file.isEmpty()) {
  224. return R.error("文件不能为空!");
  225. }
  226. excelUtil.readExcel(JxlsXmlTemplateName.GENERAL_GOODS_DTO_LIST, beans, file.getInputStream());
  227. } catch (Exception e) {
  228. e.printStackTrace();
  229. return R.error("导入失败!");
  230. }
  231. goodsService.uploadExcel(generalGoodsDtoList,Integer.parseInt(Dict.exportDataType.item_2.getItem()));
  232. //上传文件
  233. return R.ok();
  234. }
  235. /*@RequestMapping("/scannInfo")
  236. @RequiresPermissions("goods:scannInfo")
  237. public R scannInfo(@RequestParam Map<String, Object> params) {
  238. String goodsSn = (String)params.get("goodsSn");
  239. GoodsEntity goods = goodsService.queryObjectByGoodsSnAndBizType(goodsSn);
  240. if(goods == null) {
  241. return R.error("商品信息不存在");
  242. }
  243. List<OfflineCartEntity> cartEntityList = offlineCartService.offlineGoodsCart(goods);
  244. return R.ok().put("cartEntityList", cartEntityList);
  245. }*/
  246. @RequestMapping("/scannInfo/{prodBarcode}")
  247. @RequiresPermissions("goods:scannInfo")
  248. public R scannInfo(@PathVariable("prodBarcode")String prodBarcode) {
  249. SysUserEntity user = ShiroUtils.getUserEntity();
  250. if(user == null) {
  251. return R.error("用户登录超时,请重新登录");
  252. }
  253. if (!user.getRoleType().equalsIgnoreCase("2")) {
  254. return R.error("该操作只允许店员账户操作");
  255. }
  256. GoodsEntity goods = goodsService.queryObjectByProdBarcodeAndBizType(prodBarcode, user.getStoreId());
  257. if(goods == null) {
  258. return R.error("商品信息不存在");
  259. }
  260. return R.ok().put("goods", goods);
  261. }
  262. @RequestMapping("/details/{prodBarcode}")
  263. // @RequiresPermissions("goods:details") http://127.0.0.1:8080/goods/details/11111
  264. public R details(@PathVariable("prodBarcode")String prodBarcode) {
  265. SysUserEntity user = ShiroUtils.getUserEntity();
  266. if(user == null) {
  267. return R.error("用户登录超时,请重新登录");
  268. }
  269. if (!user.getRoleType().equalsIgnoreCase("2")) {
  270. return R.error("该操作只允许店员账户操作");
  271. }
  272. GoodsDetailsDto goods = goodsService.queryGoodsDetailsByProdBarcode(prodBarcode);
  273. if(goods == null) {
  274. return R.error("商品信息不存在");
  275. }
  276. return R.ok().put("goodsDetails", goods);
  277. }
  278. @RequestMapping("/generalGoodsImgUploadByZip")
  279. @ResponseBody
  280. public R batchAddImgByZip(@RequestParam("file") MultipartFile file) throws IOException {
  281. //上传文件
  282. batchAdd(file,2);
  283. return R.ok();
  284. }
  285. @RequestMapping("/generalGoodsImgUpload")
  286. @ResponseBody
  287. public R batchAddImg(@RequestParam("file") MultipartFile file) throws IOException {
  288. //上传文件
  289. batchAdd(file,1);
  290. return R.ok();
  291. }
  292. private Map<String, Object> batchAdd(MultipartFile file, int type) throws IOException {
  293. /*
  294. *创建临时文件夹
  295. * 解压文件
  296. */
  297. String fileName = file.getOriginalFilename();
  298. String path = "/data/project/img/";
  299. File dir = new File(path);
  300. dir.mkdirs();
  301. String filePath = "/data/project/img2/";
  302. File fileDir = new File(filePath);
  303. fileDir.mkdirs();
  304. File saveFile = new File(fileDir, fileName);//将压缩包解析到指定位置
  305. List<String>list = new ArrayList<>();
  306. try {
  307. file.transferTo(saveFile);
  308. String newFilePath = filePath + fileName;
  309. File zipFile = new File(newFilePath);
  310. unZipFiles(zipFile, path,list,type);//解压文件,获取文件路径
  311. } catch (Exception e) {
  312. e.printStackTrace();
  313. logger.info("解压执行失败");
  314. throw e;
  315. }finally {
  316. //程序结束时,删除临时文件
  317. deleteFiles(filePath);//删除压缩包文件夹
  318. deleteFiles(path);//删除解压文件夹**
  319. }
  320. logger.info(JSON.toJSONString(list));
  321. Map<String, Object> jsonMap = new HashMap<>();
  322. jsonMap.put("ret",list);
  323. return jsonMap;
  324. }
  325. public void deleteFiles(String filePath) {
  326. File file = new File(filePath);
  327. if ((!file.exists()) || (!file.isDirectory())) {
  328. System.out.println("file not exist");
  329. return;
  330. }
  331. String[] tempList = file.list();
  332. File temp = null;
  333. for (int i = 0; i < tempList.length; i++) {
  334. if (filePath.endsWith(File.separator)) {
  335. temp = new File(filePath + tempList[i]);
  336. }
  337. else {
  338. temp = new File(filePath + File.separator + tempList[i]);
  339. }
  340. if (temp.isFile()) {
  341. temp.delete();
  342. }
  343. if (temp.isDirectory()) {
  344. this.deleteFiles(filePath + "/" + tempList[i]);
  345. }
  346. }
  347. // 空文件的删除
  348. file.delete();
  349. }
  350. public void unZipFiles(File srcFile, String destDirPath, List<String> list, int type) throws RuntimeException {
  351. long start = System.currentTimeMillis();
  352. ZipFile zipFile = null;
  353. try {
  354. // 判断源文件是否存在
  355. if (!srcFile.exists()) {
  356. throw new RuntimeException(srcFile.getPath() + "所指文件不存在");
  357. }
  358. // 开始解压
  359. zipFile = new ZipFile(srcFile);
  360. zipFile.getEncoding();
  361. Enumeration<?> entries = zipFile.getEntries();
  362. List<ZipEntry> entryList = new ArrayList<>();
  363. while (entries.hasMoreElements()) {
  364. ZipEntry entry = (ZipEntry) entries.nextElement();
  365. logger.info("解压" + entry.getName());
  366. entryList.add(entry);
  367. // 如果是文件夹,就创建个文件夹
  368. }
  369. if(null==entryList){
  370. throw new RRException("文件夹内无图片信息,请检查后重试");
  371. }
  372. if(entryList.size()>100){
  373. throw new RRException("最多上传100张图片");
  374. }
  375. for(ZipEntry entry : entryList){
  376. if (entry.isDirectory()) {
  377. String dirPath = destDirPath + "/" + entry.getName();
  378. File dir = new File(dirPath);
  379. dir.mkdirs();
  380. } else {
  381. // 如果是文件,就先创建一个文件,然后用io流把内容copy过去
  382. File targetFile = new File(destDirPath + "/" + entry.getName());
  383. // 保证这个文件的父文件夹必须要存在
  384. if(!targetFile.getParentFile().exists()){
  385. }
  386. targetFile.createNewFile();
  387. // 将压缩文件内容写入到这个文件中
  388. InputStream is = zipFile.getInputStream(entry);
  389. FileOutputStream fos = new FileOutputStream(targetFile);
  390. int len;
  391. byte[] buf = new byte[1024];
  392. while ((len = is.read(buf)) != -1) {
  393. fos.write(buf, 0, len);
  394. }
  395. MultipartFile mulFileByPath = getMulFileByPath(destDirPath + "/" + entry.getName());
  396. long fileSize = mulFileByPath.getSize();
  397. int maxSize = 1 * 1024 * 1024;
  398. if (fileSize > maxSize) {
  399. throw new RRException("商品图片过大(最大1M),请检查!");
  400. }
  401. // String imgg = entry.getName().split("\\.")[1];
  402. // if (!"jpg".equals(imgg)&&!"jpeg".equals(imgg)) {
  403. // throw new RRException("图片格式不正确,请检查!");
  404. // }
  405. //上传文件
  406. String url = FileManager.upload(mulFileByPath);
  407. list.add(url);
  408. if(type == 1){
  409. String sku = entry.getName().split("\\.")[0];
  410. if (null==sku||"".equals(sku)) {
  411. throw new ImgException("文件为:" + sku + "的商品命名格式不正确,请检查!");
  412. }
  413. GoodsEntity goodsEntity = goodsService.queryBySku(sku);
  414. goodsEntity.setPrimaryPicUrl(url);
  415. goodsEntity.setListPicUrl(url);
  416. goodsService.updateForImgUrl(goodsEntity);
  417. }else if(type == 2){
  418. String barCode = entry.getName().split("/")[1];
  419. GoodsEntity goodsEntity = goodsService.queryByBarcode(barCode);
  420. goodsEntity.setPrimaryPicUrl(url);
  421. goodsEntity.setListPicUrl(url);
  422. goodsService.updateForImgUrl(goodsEntity);
  423. }
  424. //保存文件信息
  425. SysOssEntity ossEntity = new SysOssEntity();
  426. ossEntity.setUrl(url);
  427. ossEntity.setCreateDate(new Date());
  428. sysOssService.save(ossEntity);
  429. // 关流顺序,先打开的后关闭
  430. fos.close();
  431. is.close();
  432. }
  433. }
  434. long end = System.currentTimeMillis();
  435. System.out.println("解压完成,耗时:" + (end - start) +" ms");
  436. }catch (RRException e) {
  437. throw new RRException(e.getMessage(), e);
  438. }catch (Exception e) {
  439. throw new RuntimeException("unzip error from ZipUtils", e);
  440. } finally {
  441. if(zipFile != null){
  442. try {
  443. zipFile.close();
  444. } catch (IOException e) {
  445. e.printStackTrace();
  446. }
  447. }
  448. }
  449. }
  450. private static MultipartFile getMulFileByPath(String picPath) {
  451. FileItem fileItem = createFileItem(picPath);
  452. MultipartFile mfile = new CommonsMultipartFile(fileItem);
  453. return mfile;
  454. }
  455. private static FileItem createFileItem(String filePath)
  456. {
  457. FileItemFactory factory = new DiskFileItemFactory(16, null);
  458. String textFieldName = "textField";
  459. int num = filePath.lastIndexOf(".");
  460. String extFile = filePath.substring(num);
  461. FileItem item = factory.createItem(textFieldName, "text/plain", true,
  462. "MyFileName" + extFile);
  463. File newfile = new File(filePath);
  464. int bytesRead = 0;
  465. byte[] buffer = new byte[8192];
  466. try
  467. {
  468. FileInputStream fis = new FileInputStream(newfile);
  469. OutputStream os = item.getOutputStream();
  470. while ((bytesRead = fis.read(buffer, 0, 8192))
  471. != -1)
  472. {
  473. os.write(buffer, 0, bytesRead);
  474. }
  475. os.close();
  476. fis.close();
  477. }
  478. catch (IOException e)
  479. {
  480. e.printStackTrace();
  481. }
  482. return item;
  483. }
  484. }