jiangping
2023-09-06 5f70ee38a54d9fc1f2b2afb1e1bfbf96cd51dc03
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
package com.doumee.service.business.impl;
 
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.doumee.biz.system.SystemDictDataBiz;
import com.doumee.core.annotation.excel.ExcelImporter;
import com.doumee.core.constants.ResponseStatus;
import com.doumee.core.exception.BusinessException;
import com.doumee.core.model.LoginUserInfo;
import com.doumee.core.model.PageData;
import com.doumee.core.model.PageWrap;
import com.doumee.core.utils.Constants;
import com.doumee.core.utils.PinYinUtil;
import com.doumee.core.utils.Utils;
import com.doumee.dao.business.*;
import com.doumee.dao.business.join.GoodsJoinMapper;
import com.doumee.dao.business.model.*;
import com.doumee.dao.business.model.dto.GoodsRequest;
import com.doumee.service.business.GoodsService;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
 
/**
 * 商品信息表Service实现
 * @author 江蹄蹄
 * @date 2023/05/12 13:58
 */
@Service
public class GoodsServiceImpl implements GoodsService {
 
    @Autowired
    private GoodsMapper goodsMapper;
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private CateAttrMapper cateAttrMapper;
    @Autowired
    private CateParamMapper cateParamMapper;
    @Autowired
    private GoodsParamMapper goodsParamMapper;
    @Autowired
    private MultifileMapper multifileMapper;
    @Autowired
    @Lazy
    private SystemDictDataBiz systemDictDataBiz;
    @Autowired
    private BrandMapper brandMapper;
 
    @Autowired
    private GoodsJoinMapper goodsJoinMapper;
 
 
    @Override
    public Integer create(Goods goods) {
        LoginUserInfo user = (LoginUserInfo) SecurityUtils.getSubject().getPrincipal();
        if(goodsMapper.selectCount(new QueryWrapper<Goods>().eq("ISDELETED",Constants.ZERO).eq("name",goods.getName()))>0){
            throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(),"【"+goods.getName()+"】已存在");
        };
        goods.setStatus(Constants.ZERO);
        goods.setCreateDate(new Date());
        goods.setCreator(user.getId());
        goods.setIsdeleted(Constants.ZERO);
        //处理拼音问题
        goods.setPinyin(PinYinUtil.getFullSpell(goods.getName()));
        goods.setShortPinyin(PinYinUtil.getFirstSpell(goods.getName()));
        goodsMapper.insert(goods);
 
        List<Multifile> multifileList = goods.getMultifileList();
        if(!Objects.isNull(multifileList)&&multifileList.size()>Constants.ZERO){
            for (int i = 0; i < multifileList.size(); i++) {
                Multifile multifile = multifileList.get(i);
                multifile.setCreator(user.getId());
                multifile.setCreateDate(new Date());
                multifile.setIsdeleted(Constants.ZERO);
                multifile.setSortnum(i+Constants.ONE);
                multifile.setObjId(goods.getId());
                multifile.setType(Constants.ZERO);
                multifile.setObjType(Constants.ZERO);
                multifileMapper.insert(multifile);
            }
        }
        List<GoodsParam> goodsParamList = goods.getGoodsParamList();
        if(!Objects.isNull(goodsParamList)&&goodsParamList.size()>0){
            for (int i = 0; i < goodsParamList.size(); i++) {
                GoodsParam goodsParam = goodsParamList.get(i);
                goodsParam.setCreator(user.getId());
                goodsParam.setCreateDate(new Date());
                goodsParam.setIsdeleted(Constants.ZERO);
                goodsParam.setSortnum(i+Constants.ONE);
                goodsParam.setStatus(Constants.ZERO);
                goodsParam.setGoodsId(goods.getId());
                goodsParamMapper.insert(goodsParam);
            }
        }
 
        return goods.getId();
    }
 
    @Override
    public void deleteById(Integer id) {
        Goods goods = goodsMapper.selectById(id);
        if(Objects.isNull(goods)){
            throw new BusinessException(ResponseStatus.DATA_EMPTY.getCode(),"未查询到对象信息");
        }
        goods.setIsdeleted(Constants.ONE);
        goodsMapper.updateById(goods);
    }
 
    @Override
    public void delete(Goods goods) {
        UpdateWrapper<Goods> deleteWrapper = new UpdateWrapper<>(goods);
        goodsMapper.delete(deleteWrapper);
    }
 
    @Override
    public void deleteByIdInBatch(List<Integer> ids) {
        if (CollectionUtils.isEmpty(ids)) {
            return;
        }
        goodsMapper.deleteBatchIds(ids);
    }
 
    @Override
    public void updateById(Goods goods) {
        LoginUserInfo user = (LoginUserInfo) SecurityUtils.getSubject().getPrincipal();
        if(goodsMapper.selectCount(new QueryWrapper<Goods>().eq("ISDELETED",Constants.ZERO).ne("id",goods.getId()).eq("name",goods.getName()))>0){
            throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(),"【"+goods.getName()+"】已存在");
        };
        goods.setStatus(Constants.ZERO);
        goods.setEditDate(new Date());
        goods.setEditor(user.getId());
        goods.setIsdeleted(Constants.ZERO);
        //处理拼音问题
        goods.setPinyin(PinYinUtil.getFullSpell(goods.getName()));
        goods.setShortPinyin(PinYinUtil.getFirstSpell(goods.getName()));
        goodsMapper.updateById(goods);
 
        multifileMapper.delete(new QueryWrapper<Multifile>().eq("OBJ_ID",goods.getId()));
        List<Multifile> multifileList = goods.getMultifileList();
        if(!Objects.isNull(multifileList)&&multifileList.size()>Constants.ZERO){
            for (int i = 0; i < multifileList.size(); i++) {
                Multifile multifile = multifileList.get(i);
                multifile.setCreator(user.getId());
                multifile.setCreateDate(new Date());
                multifile.setIsdeleted(Constants.ZERO);
                multifile.setSortnum(i+Constants.ONE);
                multifile.setObjId(goods.getId());
                multifile.setType(Constants.ZERO);
                multifile.setObjType(Constants.ZERO);
                multifileMapper.insert(multifile);
            }
        }
        goodsParamMapper.delete(new QueryWrapper<GoodsParam>().eq("GOODS_ID",goods.getId()));
        List<GoodsParam> goodsParamList = goods.getGoodsParamList();
        if(!Objects.isNull(goodsParamList)&&goodsParamList.size()>0){
            for (int i = 0; i < goodsParamList.size(); i++) {
                GoodsParam goodsParam = goodsParamList.get(i);
                goodsParam.setCreator(user.getId());
                goodsParam.setCreateDate(new Date());
                goodsParam.setIsdeleted(Constants.ZERO);
                goodsParam.setSortnum(i+Constants.ONE);
                goodsParam.setStatus(Constants.ZERO);
                goodsParam.setGoodsId(goods.getId());
                goodsParamMapper.insert(goodsParam);
            }
        }
    }
 
    @Override
    public void updateByIdInBatch(List<Goods> goodss) {
        if (CollectionUtils.isEmpty(goodss)) {
            return;
        }
        for (Goods goods: goodss) {
            this.updateById(goods);
        }
    }
 
 
    @Override
    public void updateDisableById(Goods goods) {
        LoginUserInfo user = (LoginUserInfo) SecurityUtils.getSubject().getPrincipal();
        goods.setEditDate(new Date());
        goods.setEditor(user.getId());
        goodsMapper.updateById(goods);
    }
 
    @Override
    public Goods findById(Integer id) {
        Goods goods = goodsMapper.selectById(id);
        String prefixUrl = systemDictDataBiz.queryByCode(Constants.SYSTEM, Constants.FILE_DIR).getCode()
                + systemDictDataBiz.queryByCode(Constants.SYSTEM, Constants.PROJECTS).getCode();
        goods.setPrefixUrl(prefixUrl);
        Brand brand = brandMapper.selectById(goods.getBrandId());
        if(!Objects.isNull(brand)){
            goods.setBrandName(brand.getName());
        }
        Category category = categoryMapper.selectById(goods.getCategoryId());
        if(!Objects.isNull(category)){
            goods.setCategoryName(category.getName());
        }
        goods.setMultifileList(multifileMapper.selectList(new QueryWrapper<Multifile>().eq("OBJ_ID",id)));
        return goods;
    }
 
    @Override
    public Goods findOne(Goods goods) {
        QueryWrapper<Goods> wrapper = new QueryWrapper<>(goods);
        return goodsMapper.selectOne(wrapper);
    }
 
    @Override
    public List<Goods> findList(Goods goods) {
        MPJLambdaWrapper<Goods> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper.selectAll(Goods.class);
        queryWrapper.selectAs(Category::getName, Goods::getCategoryName);
        queryWrapper.selectAs(Brand::getName, Goods::getBrandName);
        queryWrapper.selectAs(Category::getAttrFirst, Goods::getAttrFirst);
        queryWrapper.selectAs(Category::getAttrSecond, Goods::getAttrSecond);
        queryWrapper.selectAs(Category::getImgurl, Goods::getCategoryImgurl);
        queryWrapper.leftJoin(Category.class, Category::getId, Goods::getCategoryId);
        queryWrapper.leftJoin(Brand.class, Brand::getId, Goods::getBrandId);
        queryWrapper.eq(Goods::getStatus,Constants.ZERO);
        queryWrapper.eq(Goods::getIsdeleted,Constants.ZERO);
        queryWrapper.like(StringUtils.isNotBlank(goods.getAttrFirstIds()),Goods::getAttrFirstIds,goods.getAttrFirstIds());
        queryWrapper.like(StringUtils.isNotBlank(goods.getAttrFirstNames()),Goods::getAttrFirstNames,goods.getAttrFirstNames());
        queryWrapper.like(StringUtils.isNotBlank(goods.getAttrSecodIds()),Goods::getAttrSecodIds,goods.getAttrSecodIds());
        queryWrapper.like(StringUtils.isNotBlank(goods.getAttrSecodNames()),Goods::getAttrSecodNames,goods.getAttrSecodNames());
        queryWrapper.eq(!Objects.isNull(goods.getBrandId()),Goods::getBrandId,goods.getBrandId());
        queryWrapper.eq(!Objects.isNull(goods.getCategoryId()),Goods::getCategoryId,goods.getCategoryId());
        queryWrapper.between(!Objects.isNull(goods.getSPrice())&&!Objects.isNull(goods.getEPrice()),
                Goods::getPrice,goods.getSPrice(),goods.getEPrice());
        queryWrapper.orderByDesc(Goods::getId);
        List<Goods> goodsList = goodsJoinMapper.selectJoinList(Goods.class,queryWrapper);
        String prefixUrl = systemDictDataBiz.queryByCode(Constants.SYSTEM, Constants.FILE_DIR).getCode()
                + systemDictDataBiz.queryByCode(Constants.SYSTEM, Constants.PROJECTS).getCode();
        goodsList.forEach(i->{
            i.setPrefixUrl(prefixUrl);
            i.setMultifileList(multifileMapper.selectList(new QueryWrapper<Multifile>().eq("OBJ_ID",i.getId()).orderByAsc(" SORTNUM ")));
            i.setGoodsParamList(goodsParamMapper.selectList(new QueryWrapper<GoodsParam>().eq("GOODS_ID",i.getId()).orderByAsc(" SORTNUM ")));
        });
        return goodsList;
    }
 
    @Override
    public PageData<Goods> findPage(PageWrap<Goods> pageWrap) {
        IPage<Goods> page = new Page<>(pageWrap.getPage(), pageWrap.getCapacity());
        MPJLambdaWrapper<Goods> queryWrapper = new MPJLambdaWrapper<>();
        Utils.MP.blankToNull(pageWrap.getModel());
        queryWrapper.selectAll(Goods.class);
 
        queryWrapper.selectAs(Category::getName, Goods::getCategoryName);
        queryWrapper.selectAs(Brand::getName, Goods::getBrandName);
        queryWrapper.selectAs(Category::getAttrFirst, Goods::getAttrFirst);
        queryWrapper.selectAs(Category::getAttrSecond, Goods::getAttrSecond);
        queryWrapper.leftJoin(Category.class, Category::getId, Goods::getCategoryId);
        queryWrapper.leftJoin(Brand.class, Brand::getId, Goods::getBrandId);
 
        queryWrapper.eq(Goods::getIsdeleted, Constants.ZERO);
        if (pageWrap.getModel().getId() != null) {
            queryWrapper.like(Goods::getId, pageWrap.getModel().getId());
        }
        if (pageWrap.getModel().getName() != null) {
            queryWrapper.like(Goods::getName, pageWrap.getModel().getName());
        }
        if (pageWrap.getModel().getStatus() != null) {
            queryWrapper.eq(Goods::getStatus, pageWrap.getModel().getStatus());
        }
 
        if (pageWrap.getModel().getCategoryId() != null) {
            queryWrapper.eq(Goods::getCategoryId, pageWrap.getModel().getCategoryId());
        }
        if (pageWrap.getModel().getBrandId() != null) {
            queryWrapper.eq(Goods::getBrandId, pageWrap.getModel().getBrandId());
        }
 
        queryWrapper.orderByDesc(Goods::getId);
 
        IPage<Goods> goodsIPage =  goodsJoinMapper.selectJoinPage(page, Goods.class, queryWrapper);
        String prefixUrl = systemDictDataBiz.queryByCode(Constants.SYSTEM, Constants.FILE_DIR).getCode()
                + systemDictDataBiz.queryByCode(Constants.SYSTEM, Constants.PROJECTS).getCode();
        goodsIPage.getRecords().forEach(i->{
            i.setPrefixUrl(prefixUrl);
        });
        return PageData.from(goodsIPage);
    }
 
 
 
    @Override
    public long count(Goods goods) {
        QueryWrapper<Goods> wrapper = new QueryWrapper<>(goods);
        return goodsMapper.selectCount(wrapper);
    }
    @Override
    public String h5Image() {
        String url = systemDictDataBiz.queryByCode(Constants.SYSTEM, Constants.FILE_DIR).getCode()
                + systemDictDataBiz.queryByCode(Constants.SYSTEM, Constants.HOME_IMAGE).getCode();
        return url;
    }
 
    @Transactional(rollbackFor = {Exception.class, BusinessException.class})
    @Override
    public Integer importBatch(MultipartFile file){
        LoginUserInfo user = (LoginUserInfo) SecurityUtils.getSubject().getPrincipal();
        ExcelImporter ie = null;
        List<GoodsImport> dataList =null;
        try {
            ie = new ExcelImporter(file,0,0);
            dataList = ie.getDataList(GoodsImport.class,null);
        }  catch (Exception e) {
            e.printStackTrace();
        }
        if(dataList == null || dataList.size() ==0){
            throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(),"对不起,录入数据为空!");
        }
 
        int num =1;
        for(GoodsImport m: dataList){
            if(StringUtils.isBlank(m.getName())
                    &&StringUtils.isBlank(m.getCategory())
                    &&StringUtils.isBlank(m.getZdPrice())
                    &&StringUtils.isBlank(m.getPrice())
                    &&StringUtils.isBlank(m.getId())
                    &&StringUtils.isBlank(m.getBrand())){
                continue;
            }
            if(StringUtils.isBlank(m.getName())
                    ||StringUtils.isBlank(m.getCategory())
                    ||StringUtils.isBlank(m.getZdPrice())
                    ||StringUtils.isBlank(m.getPrice())
                    ||StringUtils.isBlank(m.getId())
                    ||StringUtils.isBlank(m.getBrand())){
                throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(),"对不起,第【"+(num)+"】行数据无效,请检查输入!");
            }
            Goods g = new Goods();
            g.setIsdeleted(Constants.ZERO);
            g.setRemark(m.getId());
            //品类数据
            g = goodsMapper.selectOne(new QueryWrapper<>(g).last(" limit 1"));
            if(g != null){
                throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(),"对不起,第【"+(num)+"】行商品图片文件夹重复,请检查输入!");
            }
            Category cate = new Category();
            cate.setIsdeleted(Constants.ZERO);
            cate.setName(m.getCategory());
            //品类数据
            cate = categoryMapper.selectOne(new QueryWrapper<>(cate).last(" limit 1"));
            if(cate == null){
                throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(),"对不起,第【"+(num)+"】行商品类别无效,请检查输入!");
            }
            Brand brand = new Brand();
            brand.setIsdeleted(Constants.ZERO);
            brand.setName(m.getBrand());
            //品类数据
            brand = brandMapper.selectOne(new QueryWrapper<>(brand).last(" limit 1"));
            if(brand == null){
                throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(),"对不起,第【"+(num)+"】行商品品牌无效,请检查输入!");
            }
            if(goodsMapper.selectCount(new QueryWrapper<Goods>().eq("ISDELETED",Constants.ZERO).eq("name",m.getName()))>0){
                throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(),"【"+m.getName()+"】已存在");
            };
            Goods newModel = new Goods();
            newModel.setRemark(m.getId());
            newModel.setCategoryId(cate.getId());
            newModel.setBrandId(brand.getId());
            newModel.setIsdeleted(Constants.ZERO);
            newModel.setCreator(user.getId());
            newModel.setCreateDate(new Date());
            newModel.setName(m.getName());
            newModel.setStatus(Constants.ZERO);
            try {
                newModel.setZdPrice(BigDecimal.valueOf(Double.parseDouble(m.getZdPrice())));
                newModel.setPrice(BigDecimal.valueOf(Double.parseDouble(m.getPrice())));
            }catch (Exception e){
 
            }
            if(newModel.getZdPrice() == null){
                throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(),"对不起,第【"+(num)+"】行指导价无效,请检查输入!");
            }
            if(newModel.getPrice() == null){
                throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(),"对不起,第【"+(num)+"】行入手价无效,请检查输入!");
            }
            newModel.setPinyin(PinYinUtil.getFullSpell(m.getName()));
            newModel.setShortPinyin(PinYinUtil.getFirstSpell(m.getName()));
 
            CateAttr ca = new CateAttr();
            ca.setCategoryId(cate.getId());
            ca.setIsdeleted(Constants.ZERO);
            //查询全部属性1和属性2规格值
            List<CateAttr> allAttr = cateAttrMapper.selectList(new QueryWrapper<>(ca));
            //属性1集合
            String[] attrs = StringUtils.defaultString(m.getAttrFirstNames(),"").split("\n");
            //属性2集合
            String[] attrs2 = StringUtils.defaultString(m.getAttrSecodNames(),"").split("\n");
            //产品参数集合
            String[] params =  StringUtils.defaultString(m.getParamStr(),"").split("\n");
            if(attrs.length > 0){
                String attrids="" ,attrNames="";
                for(String s : attrs){
                    if(StringUtils.isBlank(s)){
                        continue;
                    }
                    //查询属性规格对象
                    CateAttr ta = getCateAttrByName(s,Constants.ZERO,allAttr);
                    if(ta == null){
                        throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(),"对不起,第【"+(num)+"】行属性1中【"+s+"】无效,请检查输入!");
                    }
                    if(StringUtils.isNotBlank(attrids)){
                        attrids += ",";
                        attrNames += ",";
                    }
                    attrids+= ta.getId();
                    attrNames+= ta.getName();
                }
                newModel.setAttrFirstIds(attrids);
                newModel.setAttrFirstNames(attrNames);
            }
            if(attrs2.length > 0){
                String attrids="" ,attrNames="";
                for(String s : attrs2){
                    if(StringUtils.isBlank(s)){
                        continue;
                    }
                    //查询属性规格对象
                    CateAttr ta = getCateAttrByName(s,Constants.ONE,allAttr);
                    if(ta == null){
                        throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(),"对不起,第【"+(num)+"】行属性1中【"+s+"】无效,请检查输入!");
                    }
                    if(StringUtils.isNotBlank(attrids)){
                        attrids += ",";
                        attrNames += ",";
                    }
                    attrids+= ta.getId();
                    attrNames+= ta.getName();
                }
                newModel.setAttrSecodIds(attrids);
                newModel.setAttrSecodNames(attrNames);
 
            }
            List<String> mulFiles = null;
            String proDir =systemDictDataBiz.queryByCode(Constants.SYSTEM,Constants.PROJECTS).getCode();
 
            String tf = proDir.substring(0,proDir.length()-1);
            String path = systemDictDataBiz.queryByCode(Constants.SYSTEM,Constants.GOODS_IMG_DIR).getCode()
                    + proDir;
            if(StringUtils.isNotBlank(path)){
                File dir =new File(path+File.separator+newModel.getRemark()+File.separator);
                if(dir!=null && dir.isDirectory()){
                    File[]  files = dir.listFiles();
                    if(files!=null && files.length>0){
                        for(File f:files){
                            if(StringUtils.isBlank(newModel.getImgurl()) && isImgFile(f)){
                                //取第一张图片作为列表图
                                String imgdir =f.getPath().substring(f.getPath().indexOf(tf)+tf.length()+1);
                                newModel.setImgurl(imgdir.replace(File.separator,"/"));
//                                 newModel.setImgurl(f.getPath().replace(path.replace(File.separator,"/"),""));
                            }
//                             else{
//                                 if(mulFiles==null){
//                                     mulFiles = new ArrayList<>();
//                                 }
//                                 mulFiles.add(f.getPath().replace(path.replace("/",File.separator),""));
//                             }
                            if((mulFiles ==null || mulFiles.size() == 0) && f.isDirectory()){
                                //如果是文件夹
                                File[] fs = f.listFiles();
                                if(fs!=null && fs.length>0){
                                    for(File mf : fs){
                                        if(isImgFile(mf)){
                                            if(mulFiles==null){
                                                mulFiles = new ArrayList<>();
                                            }
 
                                            String imgdir =mf.getPath().substring(mf.getPath().indexOf(tf)+tf.length()+1);
                                            mulFiles.add(imgdir.replace(File.separator,"/"));
//                                             newModel.setImgurl(imgdir);
////                                             mulFiles.add(mf.getName());
//                                             mulFiles.add(mf.getPath().replace(path.replace(File.separator,"/"),""));
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            //查询商品信息
            goodsMapper.insert(newModel);
            CateParam cp = new CateParam();
            cp.setIsdeleted(Constants.ZERO);
            cp.setCategoryId(cate.getId());
            //查询全部产品参数配置
            List<CateParam> allParams = cateParamMapper.selectList(new QueryWrapper<>(cp));
            if(params.length > 0){
                for(String s : params){
                    if(StringUtils.isBlank(s)){
                        continue;
                    }
                    s = s.replace(":",":");
                    String[] ts = s.split(":");
                    if(ts.length == 0){
                        continue;
                    }
                    //查询属性规格对象
                    CateParam ta = getCateParamByName(ts[0], allParams);
                    if(ta == null){
                        throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(),"对不起,第【"+(num)+"】行产品参数中【"+s+"】无效,请检查输入!");
                    }
                    GoodsParam gp = new GoodsParam();
                    gp.setIsdeleted(Constants.ZERO);
                    gp.setCreator(user.getId());
                    gp.setCreateDate(newModel.getCreateDate());
                    gp.setGoodsId(newModel.getId());
                    gp.setName(ta.getName());
                    gp.setPramaId(ta.getId());
                    gp.setStatus(Constants.ZERO);
                    gp.setVal(ts.length>1?ts[1]:null);
                    gp.setSortnum(ta.getSortnum());
                    //插入产品参数关联表
                    goodsParamMapper.insert(gp);
                }
            }
            if(mulFiles !=null && mulFiles.size()>0){
                for(int i=0;i<mulFiles.size();i++){
                    String s = mulFiles.get(i);
                    Multifile f = new Multifile();
                    f.setObjType(Constants.ZERO);
                    f.setName(s);
                    f.setType(Constants.ZERO);
                    f.setObjId(newModel.getId());
                    f.setCreateDate(newModel.getCreateDate());
                    f.setCreator(newModel.getCreator());
                    f.setIsdeleted(Constants.ZERO);
                    f.setSortnum(i);
                    f.setFileurl(s);
                    multifileMapper.insert(f);
                }
            }
            num++;
        }
        return  num;
 
    }
 
    private boolean isImgFile(File f) {
        if(f!=null && f.isFile() ){
            String name = f.getName();
            if(name.endsWith(".jpg")
                    ||name.endsWith(".JPG")
                    ||name.endsWith(".JPEG")
                    ||name.endsWith(".jpeg")
                    ||name.endsWith(".PNG")
                    ||name.endsWith(".png")){
                return  true;
            }
        }
        return  false;
    }
 
    private CateAttr getCateAttrByName(String s, int type, List<CateAttr> allAttr) {
        if(allAttr != null ){
            for(CateAttr ca :allAttr){
                if(Constants.equalsInteger(type,ca.getType()) && StringUtils.equals(s.trim(),ca.getName())){
                    return ca;
                }
            }
        }
        return  null;
 
    }
    private CateParam getCateParamByName(String s,  List<CateParam> allAttr) {
        if(allAttr != null ){
            for(CateParam ca :allAttr){
                if(  StringUtils.equals(s.trim(),ca.getName())){
                    return ca;
                }
            }
        }
        return  null;
 
    }
 
 
 
//    @Override
//    public void export(HttpServletRequest request, HttpServletResponse response) throws Exception {
//        //excel文件名
//        String fileName = "产品导入表"+System.currentTimeMillis()+".xls";
//        //创建HSSFWorkbook
//        HSSFWorkbook wb = new HSSFWorkbook();
//        //sheet名
//        String[] sheet1Title = {"商品ID","商品名称","商品类别","商品品牌","指导价","入手价","属性1","属性2","产品参数"};
//        ExcelUtil.createSheet("导入模板",sheet1Title, null, wb);
//        String[] sheet2Title = {"参数名称","参数"};
//        List<Category> categoryList = categoryMapper.selectList(new QueryWrapper<Category>()
//                .eq("ISDELETED","0")
//        );
//        ExcelUtil.createSheet("类别的产品参数模板",sheet2Title, null, wb);
//        //响应到客户端
//        try {
//        this.setResponseHeader(response, fileName);
//               OutputStream os = response.getOutputStream();
//               wb.write(os);
//               os.flush();
//               os.close();
//         } catch (Exception e) {
//               e.printStackTrace();
//         }
//    }
 
    public void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
            String encodeFileName = URLEncoder.encode(fileName, Charset.forName("UTF-8").toString());
            response.setHeader("Content-Disposition","attachment;filename=" + encodeFileName);
            response.setContentType("application/octet-stream");
            response.setHeader("eva-opera-type", "download");
            response.setHeader("eva-download-filename", encodeFileName);
 
 
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
 
 
 
    @Override
    public void export(HttpServletRequest request, HttpServletResponse response) throws Exception {
        try {
            String fileName = "产品导入表"+System.currentTimeMillis()+".xlsx";
            // 获取文件输入流
            InputStream inputStream =  this.getClass().getClassLoader().getResourceAsStream("static/file/goodsExcelTemp.xlsx");
            // 定义一个org.apache.poi.ss.usermodel.Workbook的变量
            Workbook workbook =  new XSSFWorkbook(inputStream);
            // 获取第一张表
            Sheet sheet = workbook.getSheetAt(1);
            CellStyle cs = workbook.createCellStyle();
            cs.setWrapText(true);
 
            // sheet.getPhysicalNumberOfRows()获取总的行数
            // 循环读取每一行
            Row row = sheet.createRow(1);
            List<Category> categoryList = categoryMapper.selectList(new QueryWrapper<Category>().eq("ISDELETED",0));
            categoryList.forEach(i->{
                i.setParamList(cateParamMapper.selectList(new QueryWrapper<CateParam>().eq("ISDELETED",0).eq("CATEGORY_ID",i.getId())));
            });
            //创建内容
            if(!Objects.isNull(categoryList)){
                for(int i=0;i<categoryList.size();i++){
                    Category category = categoryList.get(i);
                    row = sheet.createRow(i + 1);
                    row.createCell(0).setCellValue(category.getName());
                    List<CateParam> paramList = category.getParamList();
 
                    String param = "";
                    for (int j = 0; j < paramList.size() ; j++) {
                        if(j==0){
                            param = paramList.get(j).getName()+":";
                        }else{
                            param =param + "\r\n" +  paramList.get(j).getName()+":";
                        }
                    }
                    Cell cell = row.createCell(1);
                    cell.setCellStyle(cs);
                    cell.setCellValue(param);
                }
            }
            this.setResponseHeader(response, fileName);
            OutputStream os = response.getOutputStream();
            workbook.write(os);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
 
    @Override
    public PageData<Goods> getGoodsPage(PageWrap<GoodsRequest> pageWrap) {
        IPage<Goods> page = new Page<>(pageWrap.getPage(), pageWrap.getCapacity());
        MPJLambdaWrapper<Goods> queryWrapper = new MPJLambdaWrapper<>();
        Utils.MP.blankToNull(pageWrap.getModel());
        queryWrapper.selectAll(Goods.class);
        queryWrapper.selectAs(Category::getName, Goods::getCategoryName);
        queryWrapper.selectAs(Brand::getName, Goods::getBrandName);
        queryWrapper.selectAs(Category::getAttrFirst, Goods::getAttrFirst);
        queryWrapper.selectAs(Category::getAttrSecond, Goods::getAttrSecond);
        queryWrapper.selectAs(Category::getImgurl, Goods::getCategoryImgurl);
        queryWrapper.leftJoin(Category.class, Category::getId, Goods::getCategoryId);
        queryWrapper.leftJoin(Brand.class, Brand::getId, Goods::getBrandId);
        queryWrapper.eq(Goods::getStatus,Constants.ZERO);
        queryWrapper.eq(Goods::getIsdeleted,Constants.ZERO);
 
        queryWrapper.eq(!Objects.isNull(pageWrap.getModel()) && !Objects.isNull(pageWrap.getModel().getCategoryId()), Goods::getCategoryId, pageWrap.getModel().getCategoryId())
                .eq(!Objects.isNull(pageWrap.getModel()) && !Objects.isNull(pageWrap.getModel().getBrandId()), Goods::getBrandId, pageWrap.getModel().getBrandId())
                .and(!Objects.isNull(pageWrap.getModel()) && StringUtils.isNotBlank(pageWrap.getModel().getKeyword()),
                        i->i.like(Goods::getPinyin,pageWrap.getModel().getKeyword())
                                .or().like(Goods::getShortPinyin,pageWrap.getModel().getKeyword())
                                .or().like(Goods::getName,pageWrap.getModel().getKeyword())
                )
                .apply(!Objects.isNull(pageWrap.getModel()) && !Objects.isNull(pageWrap.getModel().getAttrFirst()), " find_in_set('"+pageWrap.getModel().getAttrFirst()+"',t.ATTR_FIRST_IDS) ")
                .apply(!Objects.isNull(pageWrap.getModel()) && !Objects.isNull(pageWrap.getModel().getAttrSecond()), " find_in_set('"+pageWrap.getModel().getAttrSecond()+"',t.ATTR_SECOD_IDS) ")
                .apply(!Objects.isNull(pageWrap.getModel()) && !Objects.isNull(pageWrap.getModel().getSPrice()), "  t.PRICE >=  "+pageWrap.getModel().getSPrice()+" ")
                .apply(!Objects.isNull(pageWrap.getModel()) && !Objects.isNull(pageWrap.getModel().getEPrice()), "  t.PRICE <=  "+pageWrap.getModel().getEPrice()+" ");
        queryWrapper.orderByDesc(Goods::getId);
        IPage<Goods> goodsIPage =  goodsJoinMapper.selectJoinPage(page, Goods.class, queryWrapper);
        String prefixUrl = systemDictDataBiz.queryByCode(Constants.SYSTEM, Constants.FILE_DIR).getCode()
                + systemDictDataBiz.queryByCode(Constants.SYSTEM, Constants.PROJECTS).getCode();
        goodsIPage.getRecords().forEach(i->{
            i.setPrefixUrl(prefixUrl);
            i.setMultifileList(multifileMapper.selectList(new QueryWrapper<Multifile>().eq("OBJ_ID",i.getId()).orderByAsc(" SORTNUM ")));
            i.setGoodsParamList(goodsParamMapper.selectList(new QueryWrapper<GoodsParam>().eq("GOODS_ID",i.getId()).orderByAsc(" SORTNUM ")));
        });
        return PageData.from(goodsIPage);
    }
 
 
    @Override
    public List<Goods> findListForH5(GoodsRequest goodsRequest) {
        MPJLambdaWrapper<Goods> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper.selectAll(Goods.class);
        queryWrapper.selectAs(Category::getName, Goods::getCategoryName);
        queryWrapper.selectAs(Brand::getName, Goods::getBrandName);
        queryWrapper.selectAs(Category::getAttrFirst, Goods::getAttrFirst);
        queryWrapper.selectAs(Category::getAttrSecond, Goods::getAttrSecond);
        queryWrapper.selectAs(Category::getImgurl, Goods::getCategoryImgurl);
        queryWrapper.leftJoin(Category.class, Category::getId, Goods::getCategoryId);
        queryWrapper.leftJoin(Brand.class, Brand::getId, Goods::getBrandId);
        queryWrapper.eq(Goods::getStatus,Constants.ZERO);
        queryWrapper.eq(Goods::getIsdeleted,Constants.ZERO);
        queryWrapper.eq(!Objects.isNull(goodsRequest) && !Objects.isNull(goodsRequest.getCategoryId()), Goods::getCategoryId, goodsRequest.getCategoryId())
                .eq(!Objects.isNull(goodsRequest) && !Objects.isNull(goodsRequest.getBrandId()), Goods::getBrandId, goodsRequest.getBrandId())
                .and(!Objects.isNull(goodsRequest) && StringUtils.isNotBlank(goodsRequest.getKeyword()),
                        i->i.like(Goods::getPinyin,goodsRequest.getKeyword())
                                .or().like(Goods::getShortPinyin,goodsRequest.getKeyword())
                                .or().like(Goods::getName,goodsRequest.getKeyword())
                )
                .apply(!Objects.isNull(goodsRequest) && !Objects.isNull(goodsRequest.getAttrFirst()), " find_in_set('"+goodsRequest.getAttrFirst()+"',t.ATTR_FIRST_IDS) ")
                .apply(!Objects.isNull(goodsRequest) && !Objects.isNull(goodsRequest.getAttrSecond()), " find_in_set('"+goodsRequest.getAttrSecond()+"',t.ATTR_SECOD_IDS) ")
                .apply(!Objects.isNull(goodsRequest) && !Objects.isNull(goodsRequest.getSPrice()), "  t.PRICE >=  "+goodsRequest.getSPrice()+" ")
                .apply(!Objects.isNull(goodsRequest) && !Objects.isNull(goodsRequest.getEPrice()), "  t.PRICE <=  "+goodsRequest.getEPrice()+" ");
        queryWrapper.orderByDesc(Goods::getId);
        List<Goods> goodsList = goodsJoinMapper.selectJoinList(Goods.class,queryWrapper);
        String prefixUrl = systemDictDataBiz.queryByCode(Constants.SYSTEM, Constants.FILE_DIR).getCode()
                + systemDictDataBiz.queryByCode(Constants.SYSTEM, Constants.PROJECTS).getCode();
        goodsList.forEach(i->{
            i.setPrefixUrl(prefixUrl);
            i.setMultifileList(multifileMapper.selectList(new QueryWrapper<Multifile>().eq("OBJ_ID",i.getId()).orderByAsc(" SORTNUM ")));
            i.setGoodsParamList(goodsParamMapper.selectList(new QueryWrapper<GoodsParam>().eq("GOODS_ID",i.getId()).orderByAsc(" SORTNUM ")));
        });
        return goodsList;
    }
 
}