jiangping
2024-10-17 14b70bacd63f6b136612cf70b160777142e2a996
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
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
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.*;
import com.doumee.dao.system.model.SystemDepartment;
import com.doumee.service.CateParamSelectService;
import com.doumee.service.business.BaseDataService;
import com.doumee.service.business.GoodsService;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import io.swagger.v3.oas.annotations.callbacks.Callback;
import lombok.extern.java.Log;
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.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
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.math.BigDecimal;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.*;
import java.util.stream.Collectors;
 
/**
 * 商品信息表Service实现
 * @author 江蹄蹄
 * @date 2023/05/12 13:58
 */
@Service
public class GoodsServiceImpl implements GoodsService {
 
    @Autowired
    private GoodsMapper goodsMapper;
    @Autowired
    @Lazy
    private BaseDataService baseDataService;
    @Autowired
    private BaseGoodsMapper baseGoodsMapper;
    @Autowired
    private BaseGoodsParamMapper baseGoodsParamMapper;
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private BaseCategoryMapper baseCategoryMapper;
    @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;
 
    @Lazy
    @Autowired
    private CateParamSelectService cateParamSelectService;
 
    @Autowired
    private RedisTemplate redisTemplate;
 
 
    @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();
    }
 
    @Async
    @Override
    @Transactional( rollbackFor = {Exception.class, BusinessException.class})
    public  Integer createPlat(GoodCreatePlatRequest param){
        LoginUserInfo user = (LoginUserInfo) SecurityUtils.getSubject().getPrincipal();
        if(!Constants.equalsInteger(user.getType(), Constants.UserType.COMPANY.getKey())){
            //非企业用户不能操作
            throw new BusinessException(ResponseStatus.NOT_ALLOWED);
        }
        if(param.getCategoryId() == null
                || param.getType() == null
                || param.getRate() == null
                || (Constants.equalsInteger(param.getType(), Constants.ONE)
                && (param.getGoodsParamList() == null
                || param.getGoodsParamList().size()==0))){
            throw  new BusinessException(ResponseStatus.BAD_REQUEST);
        }
        Category category = categoryMapper.selectById(param.getCategoryId());
        if(category ==null ||Constants.equalsInteger(category.getIsdeleted(), Constants.ONE) ||!Constants.equalsInteger(category.getCompanyId(), user.getCompanyId())){
            throw  new BusinessException(ResponseStatus.BAD_REQUEST.getCode(),"对不起,类别信息不正确,请刷新重试!");
        }
        if(category.getPlatCateId() == null){
            throw  new BusinessException(ResponseStatus.BAD_REQUEST.getCode(),"对不起,请前往【类别管理】先关联平台类别!");
        }
        BaseCategory baseCategory = baseCategoryMapper.selectById(category.getPlatCateId());
        if(baseCategory == null){
            throw  new BusinessException(ResponseStatus.BAD_REQUEST.getCode(),"对不起,请前往【类别管理】先关联平台类别!");
        }
 
        BaseGoods bp = new BaseGoods();
        bp.setCategoryId(category.getPlatCateId());
        bp.setIsdeleted(Constants.ZERO);
        List<BaseGoods> goodsList = new ArrayList<>();
        List<Integer> ids = null;
        if(Constants.equalsInteger(Constants.ONE, param.getType())){
            //如果选择部分商品
            for(PlatGoodsParam p : param.getGoodsParamList()){
                if(p.getGoodsId() == null || p.getPrice() == null){
                    throw  new BusinessException(ResponseStatus.BAD_REQUEST.getCode(),"对不起,请正确选择平台商品并配置入手价!");
                }
                if(ids == null){
                    ids = new ArrayList<>();
                }
                ids.add(p.getGoodsId());
            }
        }
        goodsList = baseGoodsMapper.selectList(new QueryWrapper<>(bp).lambda().in((ids!=null && ids.size()>0),BaseGoods::getId,ids));
        if(Constants.equalsInteger(Constants.ONE, param.getType()) &&( goodsList==null || ids.size()!=goodsList.size())){
            //  如果选择平台商品和查询结果对不上,提示错误
            throw  new BusinessException(ResponseStatus.BAD_REQUEST.getCode(),"对不起,请正确选择平台商品!");
        }
        List<Multifile> multifileList = new ArrayList<>();
        List<GoodsParam> goodsParamList = new ArrayList<>();
        try{
            for(BaseGoods model : goodsList){
                //遍历平台商品信息,进行商品信息同步
                //分类加价系数
 
                model.setCateRatePrice(baseCategory.getPriceRate());
                Goods goods = initGoodsPlatParam(user,model,param);
                if(goods == null){
                    continue;
                }
                goodsMapper.insert(goods);
                //开始处理附件
                dealPlatMultifule(goods.getId(),user,model,multifileList);
                //开始处理参数配置
                dealPlatGoodsParam(model,goods,user,goodsParamList);
            }
            if(multifileList.size()>0){
                multifileMapper.insertBatch(multifileList);
            }
            if(goodsParamList.size()>0){
                goodsParamMapper.insertBatch(goodsParamList);
            }
            cateParamSelectService.dealCateParamSelect();
        }catch (Exception e){
           e.printStackTrace();
        }finally {
            redisTemplate.opsForValue().set(user.getCompanyId()+Constants.OPEN_SYNC_SWITCH,false);
        }
        return 1;
    }
 
    private void dealPlatGoodsParam(BaseGoods model, Goods goods, LoginUserInfo user,List<GoodsParam> paramList) {
        BaseGoodsParam baseGoodsParam = new BaseGoodsParam();
        baseGoodsParam.setGoodsId(model.getId());
        baseGoodsParam.setIsdeleted(Constants.ZERO);
        List<BaseGoodsParam> goodsParamList = baseGoodsParamMapper.selectList(new QueryWrapper<>(baseGoodsParam));
        if(!Objects.isNull(goodsParamList)&&goodsParamList.size()>0){
            for (int i = 0; i < goodsParamList.size(); i++) {
                BaseGoodsParam bgParam = goodsParamList.get(i);
                //根据平台商品配置的平台参数信息查询企业绑定的参数信息 进行存储到 企业商品参数内
                CateParam cateParam = cateParamMapper.selectOne(new QueryWrapper<CateParam>()
                        .eq("CATEGORY_ID",goods.getCategoryId())
                        .eq("BASE_CATE_PARAM_ID",bgParam.getPramaId())
                        .eq("ISDELETED",Constants.ZERO)
                        .eq("STATUS",Constants.ZERO)
                        .last(" limit 1 "));
//                if(Objects.isNull(cateParam)){
//                    throw new BusinessException(ResponseStatus.DATA_EMPTY.getCode(),"企业分类数据同步异常请联系管理员");
//                }
                GoodsParam goodsParam = new GoodsParam();
                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());
                goodsParam.setVal(bgParam.getVal());
                goodsParam.setName(bgParam.getName());
                goodsParam.setPramaId(Objects.isNull(cateParam)?null:cateParam.getId());
                paramList.add(goodsParam);
//                goodsParamMapper.insert(goodsParam);
            }
        }
    }
 
    private Goods initGoodsPlatParam(LoginUserInfo user, BaseGoods model, GoodCreatePlatRequest param) {
        Goods goods = new Goods();
        goods.setIsdeleted(Constants.ZERO);
        goods.setGoodsId(model.getId());
        goods.setCompanyId(user.getCompanyId());
        if(goodsMapper.selectCount(new QueryWrapper<>(goods))>0){
            //如果已经同步过,跳过此次同步
            return  null;
        }
        goods.setType(Constants.ONE);
        goods.setStatus(Constants.ZERO);
        goods.setCreateDate(new Date());
        goods.setCreator(user.getId());
        goods.setCompanyId(user.getCompanyId());
        goods.setIsdeleted(Constants.ZERO);
        //处理拼音问题
        goods.setPinyin(PinYinUtil.getFullSpell(goods.getName()));
        goods.setShortPinyin(PinYinUtil.getFirstSpell(goods.getName()));
        goods.setName(model.getName());
        goods.setCategoryId(param.getCategoryId());
        //获取入手价格
        goods.setPrice(getPriceFromParam(model,param));
        goods.setZdPrice(model.getZdPrice());
        goods.setRemark(model.getRemark());
        goods.setImgurl(model.getImgurl());
        goods.setBrandId(model.getBrandId());
        return goods;
    }
 
    /**
     *  开始处理平台商品关联附件,复制一套到企业商品上
     */
    private void dealPlatMultifule(Integer id, LoginUserInfo user, BaseGoods model,List<Multifile> fileList ) {
        Multifile f = new Multifile();
        f.setObjId(model.getId());
        f.setObjType(Constants.ONE);
        f.setIsdeleted(Constants.ZERO);
        f.setObjType(Constants.ONE);
        List<Multifile> multifileList =multifileMapper.selectList(new QueryWrapper<>(f));
        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(id);
                multifile.setType(Constants.ZERO);
                multifile.setObjType(Constants.ZERO);
                multifile.setFileurl(multifile.getFileurl());
                multifile.setName(multifile.getName());
                multifile.setSortnum(multifile.getSortnum());
                multifile.setCompanyId(user.getCompanyId());
                fileList.add(multifile);
//                multifileMapper.insert(multifile);
            }
        }
    }
 
    private BigDecimal getPriceFromParam(BaseGoods model, GoodCreatePlatRequest param) {
        if(Constants.equalsInteger(Constants.ONE, param.getType())){
            for(PlatGoodsParam p: param.getGoodsParamList()){
                if(Constants.equalsInteger(model.getId(),p.getGoodsId())){
                    return p.getPrice().setScale(0,BigDecimal.ROUND_CEILING);
                }
            }
            throw new BusinessException(ResponseStatus.DATA_ERRO.getCode(),"数据异常请刷新重试");
        }
        //如果没有配置入手价,安装加价系数来计算
        if(model.getCateRatePrice()==null){
            model.setCateRatePrice(systemDictDataBiz.getGoodsPriceRate());
        }
        //返回 .multiply(model.getCateRatePrice())
        return (Constants.formatBigdecimal(model.getPrice()).multiply(model.getCateRatePrice()).multiply(param.getRate())).setScale(0,BigDecimal.ROUND_CEILING);
 
    }
 
 
    @Override
    public Integer companyCreate(Goods goods) {
        LoginUserInfo user = (LoginUserInfo) SecurityUtils.getSubject().getPrincipal();
        if(user.getType()==1){
            goods.setCompanyId(user.getCompanyId());
        }else{
            throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(),"当前登录用户类别错误,无法进行该操作");
        }
        if(goodsMapper.selectCount(new QueryWrapper<Goods>().eq("COMPANY_ID",user.getCompanyId()).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);
                if(StringUtils.isBlank(multifile.getFileurl())){
                    continue;
                }
                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);
                multifile.setCompanyId(goods.getCompanyId());
                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.setStatus(Constants.ZERO);
                goodsParam.setSortnum(i+Constants.ONE);
                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;
        }
        for(Integer id : ids){
            deleteById(id);
        }
//        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 companyUpdateById(Goods goods) {
        LoginUserInfo user = (LoginUserInfo) SecurityUtils.getSubject().getPrincipal();
        if(user.getType()==1){
            goods.setCompanyId(user.getCompanyId());
        }else{
            throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(),"当前登录用户类别错误,无法进行该操作");
        }
        if(goodsMapper.selectCount(new QueryWrapper<Goods>().eq("COMPANY_ID",user.getCompanyId())
                .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())
                .eq("OBJ_TYPE",0).eq("COMPANY_ID",user.getCompanyId()));
        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.setCompanyId(goods.getCompanyId());
                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);
                //存储 cate_param_select 查询是否已存在
//                if(cateParamSelectMapper.selectCount(new QueryWrapper<CateParamSelect>()
//                        .eq("PARAM_ID",goodsParam.getPramaId()).eq("NAME",goodsParam.getName()))<=Constants.ZERO){
//                    CateParamSelect cateParamSelect = new CateParamSelect();
//                    cateParamSelect.setCreator(user.getId());
//                    cateParamSelect.setCreateDate(new Date());
//                    cateParamSelect.setName(goodsParam.getVal());
//                    cateParamSelect.setIsdeleted(Constants.ZERO);
//                    cateParamSelect.setStatus(Constants.ZERO);
//                    cateParamSelect.setParamId(goodsParam.getPramaId());
//                    cateParamSelect.setCategoryId(goods.getCategoryId());
//                    cateParamSelect.setStatus(Constants.ZERO);
//                    cateParamSelectMapper.insert(cateParamSelect);
//                };
            }
        }
    }
 
 
    @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 dbGoods = goodsMapper.selectById(goods.getId());
        if(Objects.isNull(dbGoods)){
            throw new BusinessException(ResponseStatus.DATA_EMPTY);
        }
        //拉式商品 且 上架时,需要限制 平台商品是否已下架
        if(dbGoods.getType().equals(Constants.goodsType.PULL.getValue())&&goods.getStatus().equals(Constants.ZERO)){
            BaseGoods baseGoods = baseGoodsMapper.selectById(dbGoods.getGoodsId());
            if(Objects.isNull(baseGoods)){
                throw new BusinessException(ResponseStatus.DATA_EMPTY.getCode(),"未查询到平台商品信息");
            }
            if(!baseGoods.getStatus().equals(Constants.ZERO)){
                throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(),"平台商品已下架,无法上架");
            }
        }
        goods.setEditDate(new Date());
        goods.setEditor(user.getId());
        goodsMapper.updateById(goods);
    }
 
    /**
     * 批量上下架
     * @param batchDisableDTO
     * @return
     */
    @Override
    public String batchUpdateDisableById(BatchDisableDTO batchDisableDTO) {
        LoginUserInfo user = (LoginUserInfo) SecurityUtils.getSubject().getPrincipal();
        if(StringUtils.isBlank(batchDisableDTO.getIds())){
            throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(),"请选择对应的商品进行该操作");
        }
        if(!(batchDisableDTO.getStatus().equals(Constants.ZERO)||batchDisableDTO.getStatus().equals(Constants.ONE))){
            throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(),"操作类型错误");
        }
        Integer okNum = 0;
        Integer errNum = 0;
        List<String> goodsList  = Arrays.asList(batchDisableDTO.getIds().split(","));
        for (String goodsId:goodsList) {
            Goods dbGoods = goodsMapper.selectById(goodsId);
            if(Objects.isNull(dbGoods)){
                errNum++;
                continue;
            }
            //拉式商品 且 上架时,需要限制 平台商品是否已下架
            if(dbGoods.getType().equals(Constants.goodsType.PULL.getValue())&&batchDisableDTO.getStatus().equals(Constants.ZERO)){
                BaseGoods baseGoods = baseGoodsMapper.selectById(dbGoods.getGoodsId());
                if(Objects.isNull(baseGoods)||!baseGoods.getStatus().equals(Constants.ZERO)){
                    errNum++;
                    continue;
                }
            }
            dbGoods.setEditDate(new Date());
            dbGoods.setEditor(user.getId());
            dbGoods.setStatus(batchDisableDTO.getStatus());
            goodsMapper.updateById(dbGoods);
            okNum++;
        }
        return "更新成功数量("+okNum+");更新失败数量("+errNum+")";
    }
 
 
 
 
    @Override
    public Goods findById(Integer id) {
        Goods goods = goodsMapper.selectById(id);
        String prefixUrl = systemDictDataBiz.queryByCode(Constants.OSS, Constants.RESOURCE_PATH).getCode()
                + systemDictDataBiz.queryByCode(Constants.OSS, Constants.GOODS_IMG).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_TYPE",Constants.ZERO).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);
        if(!Objects.isNull(goodsList)&&goodsList.size()>Constants.ZERO){
            this.dealGoodsMsg(goodsList);
        }
        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(BaseGoods::getZdPrice, Goods::getBaseZdPrice);
        queryWrapper.selectAs(BaseGoods::getPrice, Goods::getBasePrice);
        queryWrapper.selectAs(Brand::getName, Goods::getBrandName);
        queryWrapper.selectAs(Category::getAttrFirst, Goods::getAttrFirst);
        queryWrapper.selectAs(Category::getAttrSecond, Goods::getAttrSecond);
        queryWrapper.selectAs(BaseCategory::getPriceRate,Goods::getBasePriceRate);
        queryWrapper.leftJoin(Category.class, Category::getId, Goods::getCategoryId);
        queryWrapper.leftJoin(Brand.class, Brand::getId, Goods::getBrandId);
        queryWrapper.leftJoin(BaseGoods.class,BaseGoods::getId,Goods::getGoodsId);
        queryWrapper.leftJoin(BaseCategory.class,BaseCategory::getId,BaseGoods::getCategoryId);
 
        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().getType() != null) {
            queryWrapper.eq(Goods::getType, pageWrap.getModel().getType());
        }
        if (pageWrap.getModel().getCategoryId() != null) {
            queryWrapper.eq(Goods::getCategoryId, pageWrap.getModel().getCategoryId());
        }
        if (pageWrap.getModel().getBrandId() != null) {
            queryWrapper.eq(Goods::getBrandId, pageWrap.getModel().getBrandId());
        }
        if (pageWrap.getModel().getCompanyId() != null) {
            queryWrapper.eq(Goods::getCompanyId, pageWrap.getModel().getCompanyId());
        }
        queryWrapper.orderByDesc(Goods::getId);
        IPage<Goods> goodsIPage =  goodsJoinMapper.selectJoinPage(page, Goods.class, queryWrapper);
        String prefixUrl = systemDictDataBiz.queryByCode(Constants.OSS, Constants.RESOURCE_PATH).getCode()
                + systemDictDataBiz.queryByCode(Constants.OSS, Constants.GOODS_IMG).getCode();
        goodsIPage.getRecords().forEach(i->{
            i.setPrefixUrl(prefixUrl);
            if(i.getType().equals(Constants.ONE)){
                i.setBasePrice(Constants.formatBigdecimal(i.getBasePrice()).multiply(Constants.formatBigdecimal(i.getBasePriceRate())).setScale(0,BigDecimal.ROUND_CEILING));
            }
        });
        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.setCompanyId(user.getCompanyId());
            //品类数据
            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.setCompanyId(user.getCompanyId());
            //品类数据
            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());
            //品类数据
            QueryWrapper<Brand> qwrapper = new QueryWrapper<>(brand);
            qwrapper.lambda().and(wapper-> wapper.eq(Brand::getCompanyId ,user.getCompanyId()).or().eq(Brand::getType,Constants.ONE));
            brand = brandMapper.selectOne(qwrapper.last(" limit 1"));
            if(brand == null){
                throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(),"对不起,第【"+(num)+"】行商品品牌无效,请检查输入!");
            }
            if(goodsMapper.selectCount(new QueryWrapper<Goods>().eq("COMPANY_ID",user.getCompanyId()).eq("ISDELETED",Constants.ZERO).eq("name",m.getName()))>0){
                    throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(),"第【"+(num)+"】行【"+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.setCompanyId(user.getCompanyId());
            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()));
 
            String[] params =  StringUtils.defaultString(m.getParamStr(),"").split("\n");
            List<String> mulFiles = null;
            String proDir =systemDictDataBiz.queryByCode(Constants.SYSTEM,Constants.PROJECTS).getCode();
 
            String path = systemDictDataBiz.queryByCode(Constants.SYSTEM,Constants.GOODS_IMG_DIR).getCode()
                    + proDir + File.separator + user.getCompanyId();
            if(StringUtils.isNotBlank(path)){
                OssModel ossModel = baseDataService.initOssModel();
                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)){
                                //取第一张图片作为列表图
                                newModel.setImgurl(baseDataService.getOssImgurl(ossModel,ossModel.getGoodsFolder(),f));
                            }
                            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<>();
                                            }
                                            mulFiles.add(baseDataService.getOssImgurl(ossModel,ossModel.getGoodsFolder(),mf));
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            //查询商品信息
            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);
                    //存储 cate_param_select 查询是否已存在
//                    if(cateParamSelectMapper.selectCount(new QueryWrapper<CateParamSelect>()
//                            .eq("PARAM_ID",gp.getPramaId()).eq("NAME",gp.getName()))<=Constants.ZERO){
//                        CateParamSelect cateParamSelect = new CateParamSelect();
//                        cateParamSelect.setCreator(user.getId());
//                        cateParamSelect.setCreateDate(new Date());
//                        cateParamSelect.setName(gp.getVal());
//                        cateParamSelect.setIsdeleted(Constants.ZERO);
//                        cateParamSelect.setStatus(Constants.ZERO);
//                        cateParamSelect.setParamId(gp.getPramaId());
//                        cateParamSelect.setCategoryId(newModel.getCategoryId());
//                        cateParamSelect.setStatus(Constants.ZERO);
//                        cateParamSelectMapper.insert(cateParamSelect);
//                    };
                }
            }
            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.setCompanyId(user.getCompanyId());
                    f.setFileurl(s);
                    multifileMapper.insert(f);
                }
            }
            num++;
        }
        return  num;
 
    }
    @Transactional(rollbackFor = {Exception.class, BusinessException.class})
    @Override
    public Integer importBatchImg(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.getId()) ){
                continue;
            }
            Goods g = new Goods();
            g.setIsdeleted(Constants.ZERO);
            g.setRemark(m.getId());
            g.setCompanyId(user.getCompanyId());
            //品类数据
            g = goodsMapper.selectOne(new QueryWrapper<>(g).last(" limit 1"));
            if(g == null){
                throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(),"对不起,第【"+(num)+"】行商品不存在,请检查输入!");
            }
 
            Goods newModel = new Goods();
            newModel.setId(g.getId());
            newModel.setEditor(user.getId());
            newModel.setEditDate(new Date());
 
            String[] params =  StringUtils.defaultString(m.getParamStr(),"").split("\n");
            List<String> mulFiles = null;
            String proDir =systemDictDataBiz.queryByCode(Constants.SYSTEM,Constants.PROJECTS).getCode();
 
            String path = systemDictDataBiz.queryByCode(Constants.SYSTEM,Constants.GOODS_IMG_DIR).getCode()
                    + proDir + File.separator + user.getCompanyId();
            if(StringUtils.isNotBlank(path)){
                OssModel ossModel = baseDataService.initOssModel();
                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)){
                                //取第一张图片作为列表图
                                newModel.setImgurl(baseDataService.getOssImgurl(ossModel,ossModel.getGoodsFolder(),f));
                            }
                            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<>();
                                            }
                                            mulFiles.add(baseDataService.getOssImgurl(ossModel,ossModel.getGoodsFolder(),mf));
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            //查询商品信息
            goodsMapper.updateById(newModel);
            if(mulFiles !=null && mulFiles.size()>0){
                multifileMapper.update(null,new UpdateWrapper<Multifile>().lambda()
                        .set(Multifile::getIsdeleted,Constants.ONE)
                        .eq(Multifile::getIsdeleted,Constants.ZERO)
                        .eq(Multifile::getObjId,g.getId())
                        .eq(Multifile::getType,Constants.ZERO));
                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.setCompanyId(user.getCompanyId());
                    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 {
            LoginUserInfo loginUserInfo = (LoginUserInfo) SecurityUtils.getSubject().getPrincipal();
            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)
                            .eq("COMPANY_ID",loginUserInfo.getCompanyId())
            );
            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().getAttrFirst()), " t.id in ( SELECT  gp.GOODS_ID   FROM  cate_param_select cps  ,  goods_param gp where     gp.PRAMA_ID = cps.PARAM_ID     and gp.VAL = cps.`NAME`  " +
                        " and cps.ID = '"+pageWrap.getModel().getAttrFirst()+"' ) ")
                .apply(!Objects.isNull(pageWrap.getModel()) && !Objects.isNull(pageWrap.getModel().getAttrSecond()), " t.id in ( SELECT  gp.GOODS_ID   FROM  cate_param_select cps  ,  goods_param gp where     gp.PRAMA_ID = cps.PARAM_ID     and gp.VAL = cps.`NAME`  " +
                        " and cps.ID = '"+pageWrap.getModel().getAttrSecond()+"' ) ")
                .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);
        if(!Objects.isNull(goodsIPage.getRecords())&&goodsIPage.getRecords().size()>Constants.ZERO){
            this.dealGoodsMsg(goodsIPage.getRecords());
        }
        return PageData.from(goodsIPage);
    }
 
 
 
    public void dealGoodsMsg(List<Goods> goodsList){
        String prefixUrl = systemDictDataBiz.queryByCode(Constants.OSS, Constants.RESOURCE_PATH).getCode()
                + systemDictDataBiz.queryByCode(Constants.OSS, Constants.GOODS_IMG).getCode();
        String prefixUrlCategory = systemDictDataBiz.queryByCode(Constants.OSS, Constants.RESOURCE_PATH).getCode()
                + systemDictDataBiz.queryByCode(Constants.OSS, Constants.CATEGORY_IMG).getCode();
        List<Integer> integerList = goodsList.stream().map(Goods::getId).collect(Collectors.toList());
 
        List<Multifile> mFileList = multifileMapper.selectList(new QueryWrapper<Multifile>()
                .lambda().in(Multifile::getObjId,integerList)
                .eq(Multifile::getType,Constants.ZERO)
                .eq(Multifile::getIsdeleted,Constants.ZERO)
                .eq(Multifile::getObjType,Constants.ZERO));
        List<GoodsParam> goodsParamList = goodsParamMapper.selectList(new QueryWrapper<GoodsParam>()
                    .in("GOODS_ID",integerList)
                    .orderByAsc(" SORTNUM "));
        goodsList.forEach(i->{
            i.setCategoryImgurl(prefixUrlCategory + i.getCategoryImgurl());
            i.setPrefixUrl(prefixUrl);
            i.setMultifileList(mFileList.stream().filter(s -> s.getObjId().equals(i.getId())).collect(Collectors.toList()));
            i.setGoodsParamList(goodsParamList.stream().filter(s -> s.getGoodsId().equals(i.getId())).collect(Collectors.toList()));
        });
    }
 
    @Override
    public List<Goods> findListForH5(GoodsRequest goodsRequest) {
        LoginUserInfo loginUserInfo = (LoginUserInfo) SecurityUtils.getSubject().getPrincipal();
        if(!loginUserInfo.getType().equals(Constants.UserType.ZHUBO.getKey())){
            throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(),"非主播用户无法使用");
        }
        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(Goods::getCompanyId,loginUserInfo.getCompanyId());
        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);
        if(!Objects.isNull(goodsList)&&goodsList.size()>Constants.ZERO){
            this.dealGoodsMsg(goodsList);
        }
        return goodsList;
    }
 
 
 
    @Override
    @Transactional
    public  void openSyncSwitch() {
        LoginUserInfo loginUserInfo = (LoginUserInfo) SecurityUtils.getSubject().getPrincipal();
        Boolean  openSyncSwitch = (Boolean)redisTemplate.opsForValue().get(loginUserInfo.getCompanyId()+Constants.OPEN_SYNC_SWITCH);
        if(openSyncSwitch!=null && openSyncSwitch ){
            throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(),"数据同步中,请稍后刷新重试");
        }
        redisTemplate.opsForValue().set(loginUserInfo.getCompanyId()+Constants.OPEN_SYNC_SWITCH,true);
    }
}