GoodsController.java 18 KB

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