doum
15 小时以前 46124fe454f90d24171ebc5be0d9cfe2ab22cbc5
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
package com.doumee.service.business.impl;
 
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.utils.*;
import com.doumee.core.utils.tsp.TspSolver;
import com.doumee.core.utils.tsp.TspSolverSolutions;
import com.doumee.dao.admin.request.JkOrdersImport;
import com.doumee.dao.business.*;
import com.doumee.dao.business.model.*;
import com.doumee.service.business.third.model.LoginUserInfo;
import com.doumee.service.business.third.model.PageData;
import com.doumee.service.business.third.model.PageWrap;
import com.doumee.service.business.JkSketchService;
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.github.yulichang.wrapper.MPJLambdaWrapper;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.units.qual.C;
import org.springframework.beans.factory.annotation.Autowired;
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 java.math.BigDecimal;
import java.util.*;
import java.util.Date;
import java.util.concurrent.TimeUnit;
 
/**
 * 交控-线路优化记录信息表Service实现
 * @author 江蹄蹄
 * @date 2025/09/28 09:01
 */
@Service
public class JkSketchServiceImpl implements JkSketchService {
 
    @Autowired
    private JkSketchMapper jkSketchMapper;
    @Autowired
    private JkSketchLineMapper jkSketchLineMapper;
    @Autowired
    private JkSketchCustomerMapper jkSketchCustomerMapper;
    @Autowired
    private JkCustomerMapper jkCustomerMapper;
    @Autowired
    private JkLineMapper jkLineMapper;
 
    @Autowired
    private SystemDictDataBiz systemDictDataBiz;
    @Autowired
    private JkOrdersMapper jkOrdersMapper;
 
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
 
    @Override
    public Integer create(JkSketch jkSketch) {
        jkSketchMapper.insert(jkSketch);
        return jkSketch.getId();
    }
 
    @Override
    public void deleteById(Integer id) {
        jkSketchMapper.deleteById(id);
    }
 
    @Override
    public void delete(JkSketch jkSketch) {
        UpdateWrapper<JkSketch> deleteWrapper = new UpdateWrapper<>(jkSketch);
        jkSketchMapper.delete(deleteWrapper);
    }
 
    @Override
    public void deleteByIdInBatch(List<Integer> ids) {
        if (CollectionUtils.isEmpty(ids)) {
            return;
        }
        jkSketchMapper.deleteBatchIds(ids);
    }
    //线路优化
    @Override
    public JkSketch updateById(JkSketch jkSketch ) {
        JkSketch model = jkSketchMapper.selectById(jkSketch.getId());
        if(model == null ||Constants.equalsInteger(model.getIsdeleted(),Constants.ONE)){
            throw  new BusinessException(ResponseStatus.DATA_EMPTY);
        }
        if( model.getDateInfo() ==  null){
            throw  new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(),"该线路日期信息不正确,不支持优化!");
        }
       if(Constants.equalsInteger(Constants.ZERO,jkSketch.getForceUpdate()) && Constants.equalsInteger(model.getStatus(),Constants.ONE)){
            throw  new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(),"该线路存在正在优化中,请耐心等待优化完成或者选择强制优化操作!");
        }
 
         if(  jkSketch.getLineIdList() ==null || jkSketch.getLineIdList().size()==0 ){
            throw  new BusinessException(ResponseStatus.BAD_REQUEST.getCode(),"请选择有效合理的线路进行优化操作!");
        }
        //当前所有线路(符合条件的线路)
        List<JkLine> lineList =  jkLineMapper.selectJoinList(JkLine.class,new MPJLambdaWrapper<JkLine>()
                .selectAll(JkLine.class)
                .eq(JkLine::getWeeks,DateUtil.getWeekZhouOfDate(model.getDateInfo()))//只能选择当前的线路
                .eq(JkLine::getIsdeleted,Constants.ZERO)
                .in(JkLine::getId,jkSketch.getLineIdList())
        );
        Integer totalCus = 0,totalNum =0;
        for(JkLine line :lineList){
            totalCus += Constants.formatIntegerNum(line.getMaxCustomer());//总客户量
            totalNum += Constants.formatIntegerNum(line.getMaxOrder());//总送货量
        }
 
        if( totalCus < Constants.formatIntegerNum(model.getOrderNum())  ){
            throw  new BusinessException(ResponseStatus.BAD_REQUEST.getCode(),"该线路订单客户数量超过了线路总客户量限制,无法进行优化!");
        }
        if( totalNum < Constants.formatBigdecimal(model.getTotalNum()).doubleValue()){
            throw  new BusinessException(ResponseStatus.BAD_REQUEST.getCode(),"该线路订单送货量超过了线路总送货量限制,无法进行优化!");
        }
        model.setLineList(lineList);//线路集合
        model.setCustomerList(checkJketchCustomerLocation(model));//订单集合
        model.setStatus(Constants.ONE);
        model.setPlanLineNum(lineList.size());
        model.setEditDate(new Date());
        model.setEditor(jkSketch.getLoginUserInfo().getId());
        model.setPlanLineDate(model.getEditDate());
        model.setPlanLineUserId(jkSketch.getLoginUserInfo().getId());
        model.setJobId(UUID.randomUUID().toString());
        redisTemplate.opsForValue().set(Constants.RedisKeys.JKLINE_JOB+model.getJobId(),true );//做异步处理
        jkSketchMapper.updateById(model);
        return model;
    }
 
    @Override
    @Async
    public void startUpdateLineAsync(JkSketch model) {
        try {
            List<JkSketchCustomer> customerList = model.getCustomerList();
            List<JkLine> lineList = model.getLineList();
            TspSolver.DataModel dataModel = new TspSolver.DataModel();
            int vehicleNumber1 = lineList.size();//线路数量
            long[] vehicleCapacities1=new long[lineList.size()];//每辆车的最大订单量限制
            long[] demands1 = new long[customerList.size()+1]; //各个点的订单量
            long[][] distanceMatrix1 = new long[customerList.size()+1][customerList.size()+1];
            demands1[0] =0;//原点
            double cLatitude =0;
            double cLongitude =0;
            String location = systemDictDataBiz.queryByCode(Constants.SYSTEM,Constants.COMPANY_LOCATION).getCode();
            try {
                String[] ss = location.split(",");
                cLongitude = Double.parseDouble(ss[0]);
                cLatitude = Double.parseDouble(ss[1]);
            }catch (Exception e){
 
            }
 
            for (int i = 0; i < customerList.size(); i++) {
                distanceMatrix1[0][i] =  DistanceCalculator.calculateDistance(cLatitude,cLongitude,customerList.get(i).getLatitude().doubleValue(),customerList.get(i).getLongitude().doubleValue())/1000;
                distanceMatrix1[i][0] = distanceMatrix1[0][i];
                demands1[i+1] = Constants.formatBigdecimal( customerList.get(i).getTotalNum()).longValue();  //各个点的订单量
                List<Map<String,Object>> disList = customerList.get(i).getDistanceList();
                for (int j = 0; j< disList.size(); j++) {
                    if(disList.size()>j){
                        distanceMatrix1[i+1][j+1]  = (Long) disList.get(j).get("b")/1000;//构造距离矩阵
                    }else{
                        distanceMatrix1[i+1][j+1]  = 1l;
                    }
                }
            }
            for (int i = 0; i < lineList.size(); i++) {
                vehicleCapacities1[i] = lineList.get(i).getMaxOrder();//每辆车的最大订单量限制
            }
            //构造优化数据模型
            dataModel.initDataInfo(vehicleNumber1,demands1,vehicleCapacities1,distanceMatrix1);
            TspSolver.startSearch(dataModel);
            dealSearchSolution(model,dataModel);
        }catch (Exception e){
            e.printStackTrace();
            jkSketchMapper.update(null,new UpdateWrapper<JkSketch>().lambda()
                    .eq(JkSketch::getId,model.getId() )
                    .eq(JkSketch::getJobId,model.getJobId() )
                    .set(JkSketch::getPlanLineInfo,"最近一次线路优化失败!")
                    .set(JkSketch::getStatus,Constants.THREE)
                    .set(JkSketch::getPlanLineEndDate,new Date()));
        }
 
    }
 
    private void dealSearchSolution(JkSketch model, TspSolver.DataModel dataModel) {
        Date date = new Date();
        List<TspSolverSolutions> solutions = dataModel.getSolutions();
        List<JkSketchLine> sketchLineList = new ArrayList<>();
        List<JkSketchCustomer> sketchCustomerList  = new ArrayList<>();
        long totalDistance = 0l;
        if(solutions!=null && solutions.size()>0){
            for(TspSolverSolutions so : solutions){
                List<Integer> routes = so.getRouteIndex();
                if(routes.size() <=2) {
                    continue;//无客户的非有效路线
                }
                totalDistance+= so.getDistance();
                JkLine  line =model.getLineList().get(so.getLineIndex());
                JkSketchLine tModel =  new JkSketchLine();
                tModel.setSketchId(model.getId());
                tModel.setCreator(model.getEditor());
                tModel.setCreateDate(date);
                tModel.setLineId(line.getId());
                tModel.setTotalNum(new BigDecimal(0));
                tModel.setOrderNum(routes.size()-2);
                tModel.setDateInfo(model.getDateInfo());
                tModel.setSortnum(sketchLineList.size()+1);
                tModel.setEditDate(tModel.getCreateDate());
                tModel.setEditor(tModel.getCreator());
                tModel.setIsdeleted(Constants.ZERO);
                tModel.setDistance(so.getDistance());//
                sketchLineList.add(tModel);
                tModel.setCustomerList( new ArrayList<>());
                //有效路径
                for (Integer cIndex : routes){
                    if(cIndex ==0 || cIndex == routes.size()-1){
                        continue; //起始点不处理
                    }
                    JkSketchCustomer customer = model.getCustomerList().get(cIndex-1);
                    tModel.setTotalNum(tModel.getTotalNum().add(Constants.formatBigdecimal(customer.getTotalNum())));//送货量
                    JkSketchCustomer cModel =  new JkSketchCustomer();
                    cModel.setCreator(tModel.getCreator());
                    cModel.setOrderId(customer.getOrderId());
                    cModel.setCreateDate(tModel.getCreateDate());
                    cModel.setTotalNum(customer.getTotalNum());
                    cModel.setDateInfo(model.getDateInfo());
                    cModel.setSortnum(tModel.getCustomerList().size()+1);
                    cModel.setEditDate(tModel.getCreateDate());
                    cModel.setEditor(tModel.getCreator());
                    cModel.setIsdeleted(Constants.ZERO);
                    cModel.setSketchId(model.getId());
                    cModel.setCustomerId(customer.getCustomerId());
                    tModel.getCustomerList().add(cModel);
                    if(cIndex ==0 || cIndex == routes.size()-1){
                        continue; //起始点不处理
                    }
                }
            }
        }
        if(sketchLineList!=null && sketchLineList.size()>0){
            jkSketchLineMapper.update(null,new UpdateWrapper<JkSketchLine>().lambda()
                    .set(JkSketchLine::getIsdeleted,Constants.ONE)
                    .eq(JkSketchLine::getIsdeleted,Constants.ZERO)
                    .eq(JkSketchLine::getDateInfo,model.getDateInfo()));
            jkSketchCustomerMapper.update(null,new UpdateWrapper<JkSketchCustomer>().lambda()
                    .set(JkSketchCustomer::getIsdeleted,Constants.ONE)
                    .eq(JkSketchCustomer::getIsdeleted,Constants.ZERO)
                    .eq(JkSketchCustomer::getDateInfo,model.getDateInfo()));
            if(sketchLineList.size()>0){
                jkSketchLineMapper.insert(sketchLineList);
            }
            for(JkSketchLine l : sketchLineList){
                if(l.getCustomerList()!=null ){
                    for(JkSketchCustomer c :l.getCustomerList()){
                        c.setSketchLineId(l.getId());
                    }
                    sketchCustomerList.addAll(l.getCustomerList());
                }
            }
            if(sketchCustomerList.size()>0){
                jkSketchCustomerMapper.insert(sketchCustomerList);
            }
            jkSketchMapper.update(null,new UpdateWrapper<JkSketch>().lambda()
                    .eq(JkSketch::getId,model.getId() )
                    .eq(JkSketch::getJobId,model.getJobId() )
                    .set(JkSketch::getLineNum,sketchLineList.size() )
                    .set(JkSketch::getDistance,totalDistance)
                    .set(JkSketch::getPlanLineInfo,"最近一次线路优化成功,优化后总距离:"+(totalDistance/1000)+"公里!")
                    .set(JkSketch::getStatus,Constants.TWO)
                    .set(JkSketch::getPlanLineEndDate,date));
        }else{
            jkSketchMapper.update(null,new UpdateWrapper<JkSketch>().lambda()
                    .eq(JkSketch::getId,model.getId() )
                    .eq(JkSketch::getJobId,model.getJobId() )
                    .set(JkSketch::getPlanLineInfo,"最近一次线路优化失败,未找到最优路线!")
                    .set(JkSketch::getStatus,Constants.THREE)
                    .set(JkSketch::getPlanLineEndDate,date));
        }
    }
 
    private   List<JkSketchCustomer>  checkJketchCustomerLocation(JkSketch model) {
 
        MPJLambdaWrapper<JkSketchCustomer> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper.selectAll(JkSketchCustomer.class )
                .selectAs(JkCustomer::getName,JkSketchCustomer::getName)
                .selectAs(JkCustomer::getCode,JkSketchCustomer::getCode)
                .selectAs(JkCustomer::getLongitude,JkSketchCustomer::getLongitude)
                .selectAs(JkCustomer::getLatitude,JkSketchCustomer::getLatitude)
                .leftJoin(JkCustomer.class,JkCustomer::getId,JkSketchCustomer::getCustomerId )
                .eq(JkSketchCustomer::getSketchId, model.getId())
                .eq(JkSketchCustomer::getIsdeleted,Constants.ZERO)
                .orderByAsc(JkSketchCustomer::getSortnum);
        List<JkSketchCustomer> customerList = jkSketchCustomerMapper.selectJoinList(JkSketchCustomer.class,queryWrapper);
        if(customerList == null ||customerList.size() ==0){
            throw  new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(),"该线路客户信息为空,不满足优化条件!");
        }
        String errorMsg ="";
        for(JkSketchCustomer c : customerList){
            if(c.getLatitude()==null || c.getLongitude() ==null){
                errorMsg += c.getName()+"-"+c.getName()+";";
            }
        }
        if(StringUtils.isNotBlank(errorMsg)){
            throw  new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(),"该线路客户:"+errorMsg+"定位信息不完整,不满足优化条件!");
        }
        for(JkSketchCustomer c : customerList){
            List<Map<String,Object>> tmpList = new ArrayList<>();
            for(JkSketchCustomer cm : customerList){
                Map<String,Object> t = new HashMap<>();
                t.put("a",cm.getId());
                if(Constants.equalsInteger(c.getCustomerId(),cm.getCustomerId())){
                    t.put("b",0l);
                }else{
                    t.put("b", DistanceCalculator.calculateDistance(
                            Constants.formatBigdecimal(c.getLatitude()).doubleValue(),
                            Constants.formatBigdecimal(c.getLatitude()).doubleValue(),
                            Constants.formatBigdecimal(cm.getLatitude()).doubleValue(),
                            Constants.formatBigdecimal(cm.getLongitude()).doubleValue()));
                }
                tmpList.add(t);
            }
            c.setDistanceList(tmpList);
        }
 
        if(Constants.equalsInteger(Constants.ZERO,model.getStatus())){
            //如果是未优化状态,计算原始距离
            long totalDistance = 0;
            MPJLambdaWrapper<JkSketchLine> queryWrapper1 = new MPJLambdaWrapper<>();
            queryWrapper1.selectAll(JkSketchLine.class )
                    .eq(JkSketchLine::getSketchId, model.getId())
                    .eq(JkSketchLine::getIsdeleted,Constants.ZERO);
            List<JkSketchLine> lineList = jkSketchLineMapper.selectJoinList(JkSketchLine.class,queryWrapper1);//
            if(lineList!=null ||lineList.size()>0){
                double cLatitude =0;
                double cLongitude =0;
                String location = systemDictDataBiz.queryByCode(Constants.SYSTEM,Constants.COMPANY_LOCATION).getCode();
                try {
                    String[] ss = location.split(",");
                    cLongitude = Double.parseDouble(ss[0]);
                    cLatitude = Double.parseDouble(ss[1]);
                }catch (Exception e){
 
                }
                for(JkSketchLine line : lineList){
                    boolean isFirst =true;
                    JkSketchCustomer last = null;
                    for(JkSketchCustomer c : customerList){
                        if(Constants.equalsInteger(c.getSketchLineId(),line.getId())){
                            if(isFirst){
                                totalDistance += DistanceCalculator.calculateDistance(cLatitude,cLongitude
                                        ,Constants.formatBigdecimal(c.getLatitude()).doubleValue()
                                        ,Constants.formatBigdecimal(c.getLongitude()).doubleValue());
                            }else{
                                totalDistance += DistanceCalculator.calculateDistance(Constants.formatBigdecimal(c.getLatitude()).doubleValue()
                                        ,Constants.formatBigdecimal(c.getLongitude()).doubleValue()
                                        ,Constants.formatBigdecimal(last.getLatitude()).doubleValue()
                                        ,Constants.formatBigdecimal(last.getLongitude()).doubleValue());
                            }
                            last = c;
                            isFirst=false;
                        }
                        if(last!=null){
                            totalDistance += DistanceCalculator.calculateDistance(cLatitude,cLongitude
                                    ,Constants.formatBigdecimal(last.getLatitude()).doubleValue()
                                    ,Constants.formatBigdecimal(last.getLongitude()).doubleValue());
                        }
                    }
                }
 
            }
            model.setOriginDistance(totalDistance);
        }
 
        return customerList;
    }
 
    @Override
    public void updateByIdInBatch(List<JkSketch> jkSketchs) {
        if (CollectionUtils.isEmpty(jkSketchs)) {
            return;
        }
        for (JkSketch jkSketch: jkSketchs) {
            this.updateById(jkSketch);
        }
    }
 
    @Override
    public JkSketch findById(Integer id) {
        return jkSketchMapper.selectById(id);
    }
 
    @Override
    public JkSketch findOne(JkSketch jkSketch) {
        QueryWrapper<JkSketch> wrapper = new QueryWrapper<>(jkSketch);
        return jkSketchMapper.selectOne(wrapper);
    }
 
    @Override
    public List<JkSketch> findList(JkSketch jkSketch) {
        QueryWrapper<JkSketch> wrapper = new QueryWrapper<>(jkSketch);
        return jkSketchMapper.selectList(wrapper);
    }
  
    @Override
    public PageData<JkSketch> findPage(PageWrap<JkSketch> pageWrap) {
        IPage<JkSketch> page = new Page<>(pageWrap.getPage(), pageWrap.getCapacity());
        MPJLambdaWrapper<JkSketch> queryWrapper = new MPJLambdaWrapper<>();
        Utils.MP.blankToNull(pageWrap.getModel());
        pageWrap.getModel().setIsdeleted(Constants.ZERO);
        queryWrapper.selectAll(JkSketch.class )
                .selectAs(Category::getId,JkSketch::getCategoryId)
                .selectAs(Category::getName,JkSketch::getCategoryName)
                .leftJoin(Category.class,Category::getId,JkSketch::getCategoryId );
        queryWrapper.eq( pageWrap.getModel().getCategoryId()!=null,JkLine::getCategoryId, pageWrap.getModel().getCategoryId());
 
        if (pageWrap.getModel().getId() != null) {
            queryWrapper.eq(JkSketch::getId, pageWrap.getModel().getId());
        }
        if (pageWrap.getModel().getCreator() != null) {
            queryWrapper.eq(JkSketch::getCreator, pageWrap.getModel().getCreator());
        }
        if (pageWrap.getModel().getCreateDate() != null) {
            queryWrapper.ge(JkSketch::getCreateDate, Utils.Date.getStart(pageWrap.getModel().getCreateDate()));
            queryWrapper.le(JkSketch::getCreateDate, Utils.Date.getEnd(pageWrap.getModel().getCreateDate()));
        }
        if (pageWrap.getModel().getEditor() != null) {
            queryWrapper.eq(JkSketch::getEditor, pageWrap.getModel().getEditor());
        }
        if (pageWrap.getModel().getEditDate() != null) {
            queryWrapper.ge(JkSketch::getEditDate, Utils.Date.getStart(pageWrap.getModel().getEditDate()));
            queryWrapper.le(JkSketch::getEditDate, Utils.Date.getEnd(pageWrap.getModel().getEditDate()));
        }
        if (pageWrap.getModel().getIsdeleted() != null) {
            queryWrapper.eq(JkSketch::getIsdeleted, pageWrap.getModel().getIsdeleted());
        }
        if (pageWrap.getModel().getInfo() != null) {
            queryWrapper.eq(JkSketch::getInfo, pageWrap.getModel().getInfo());
        }
        if (pageWrap.getModel().getCategoryId() != null) {
            queryWrapper.eq(JkSketch::getCategoryId, pageWrap.getModel().getCategoryId());
        }
        if (pageWrap.getModel().getTotalNum() != null) {
            queryWrapper.eq(JkSketch::getTotalNum, pageWrap.getModel().getTotalNum());
        }
        if (pageWrap.getModel().getOrderNum() != null) {
            queryWrapper.eq(JkSketch::getOrderNum, pageWrap.getModel().getOrderNum());
        }
        if (pageWrap.getModel().getStatus() != null) {
            queryWrapper.eq(JkSketch::getStatus, pageWrap.getModel().getStatus());
        }
        if (pageWrap.getModel().getSortnum() != null) {
            queryWrapper.eq(JkSketch::getSortnum, pageWrap.getModel().getSortnum());
        }
        if (pageWrap.getModel().getDateInfo() != null) {
            queryWrapper.eq(JkSketch::getDateInfo,  pageWrap.getModel().getDateInfo());
        }
        if (pageWrap.getModel().getJobId() != null) {
            queryWrapper.eq(JkSketch::getJobId, pageWrap.getModel().getJobId());
        }
        queryWrapper.orderByDesc(JkSketch::getDateInfo);
        IPage<JkSketch> result = jkSketchMapper.selectJoinPage(page, JkSketch.class,queryWrapper);
        return PageData.from(result);
    }
 
    @Override
    public long count(JkSketch jkSketch) {
        QueryWrapper<JkSketch> wrapper = new QueryWrapper<>(jkSketch);
        return jkSketchMapper.selectCount(wrapper);
    }
 
 
    @Override
    @Transactional(rollbackFor = {Exception.class,BusinessException.class})
    public List<JkSketch> importBatch(MultipartFile file, String dateInfoStr, LoginUserInfo loginUser){
        if(StringUtils.isBlank(dateInfoStr)){
            throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(),"对不起,请选择送货日期!");
        }
        Date dateInfo = DateUtil.getDateFromShortString(dateInfoStr);
        if(dateInfo == null){
            throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(),"对不起,请选择正确的送货日期!");
        }
        Boolean importing = (Boolean) redisTemplate.opsForValue().get(Constants.RedisKeys.IMPORTING_JKORDERS);
        if(importing!=null && importing){
            throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(),"对不起,已存在导入任务正在执行中,请稍后再试!");
        }
        redisTemplate.opsForValue().set(Constants.RedisKeys.IMPORTING_JKORDERS,true,30, TimeUnit.MINUTES);
        try {
            ExcelImporter ie = null;
            List<JkOrdersImport> dataList =null;
            try {
                ie = new ExcelImporter(file,1,0);
                dataList = ie.getDataList(JkOrdersImport.class,null);
            }  catch (Exception e) {
                e.printStackTrace();
            }
            if(dataList == null || dataList.size() ==0){
                throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(),"对不起,录入数据为空!");
            }
            List<JkCustomer> customerList =  jkCustomerMapper.selectJoinList(JkCustomer.class,new MPJLambdaWrapper<JkCustomer>()
                    .selectAll(JkCustomer.class)
                    .eq(JkCustomer::getIsdeleted,Constants.ZERO)
            );
            String week =  DateUtil.getWeekZhouOfDate(dateInfo);
            //当前所有线路
            List<JkLine> lineList =  jkLineMapper.selectJoinList(JkLine.class,new MPJLambdaWrapper<JkLine>()
                    .selectAll(JkLine.class)
                    .eq(JkLine::getWeeks,week)//只能选择当前的线路
                    .eq(JkLine::getIsdeleted,Constants.ZERO)
            );
            List<JkOrders> newOrderList = new ArrayList<>();
            for(int i=0;i<dataList.size();i++){
                JkOrdersImport model = dataList.get(i);
                if(StringUtils.isBlank(model.getName())
                        &&StringUtils.isBlank(model.getCode())
                        &&StringUtils.isBlank(model.getNum())
                        &&StringUtils.isBlank(model.getSortnum())
                        &&StringUtils.isBlank(model.getDateInfo())
                        &&StringUtils.isBlank(model.getLineName()) ){
                    continue;
                }
                checkModelParam(model, newOrderList, i,dateInfo,loginUser,customerList,lineList );
            }
            if( newOrderList.size()==0){
                throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(),"对不起,录入有效数据为空!");
            }
            List<JkSketch> newList = initNewSketchList(newOrderList);//按照主线路分组
            if(  newList.size() ==0 ){
                throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(),"对不起,录入有效数据为空!");
            }
            jkSketchMapper.update(null,new UpdateWrapper<JkSketch>().lambda()
                    .set(JkSketch::getIsdeleted,Constants.ONE)
                    .eq(JkSketch::getIsdeleted,Constants.ZERO)
                    .eq(JkSketch::getDateInfo,dateInfo));
            jkOrdersMapper.update(null,new UpdateWrapper<JkOrders>().lambda()
                    .set(JkOrders::getIsdeleted,Constants.ONE)
                    .eq(JkOrders::getIsdeleted,Constants.ZERO)
                    .eq(JkOrders::getDateInfo,dateInfo));
            if(newList.size()>0){
                jkSketchMapper.insert(newList);
            }
            if(newOrderList.size()>0){
                jkOrdersMapper.insert(newOrderList);
            }
 
            List<JkSketchLine> sketchLineList = initNewSketchLineList(newList,newOrderList,lineList);
            jkSketchLineMapper.update(null,new UpdateWrapper<JkSketchLine>().lambda()
                    .set(JkSketchLine::getIsdeleted,Constants.ONE)
                    .eq(JkSketchLine::getIsdeleted,Constants.ZERO)
                    .eq(JkSketchLine::getDateInfo,dateInfo));
            if(sketchLineList.size()>0){
                jkSketchLineMapper.insert(sketchLineList);
            }
 
            List<JkSketchCustomer> sketchCuustomerList = initNewSketchCustomerList(sketchLineList,newOrderList);//按照主线路分组
            jkSketchCustomerMapper.update(null,new UpdateWrapper<JkSketchCustomer>().lambda()
                    .set(JkSketchCustomer::getIsdeleted,Constants.ONE)
                    .eq(JkSketchCustomer::getIsdeleted,Constants.ZERO)
                    .eq(JkSketchCustomer::getDateInfo,dateInfo));
            if(sketchCuustomerList.size()>0){
                jkSketchCustomerMapper.insert(sketchCuustomerList);
            }
            return newList;
        }catch (BusinessException e){
            throw e;
        }catch (Exception e){
            e.printStackTrace();
            throw  new BusinessException(ResponseStatus.SERVER_ERROR.getCode(),"信息导入失败,请稍后重试");
        }finally {
            redisTemplate.delete(Constants.RedisKeys.IMPORTING_JKORDERS);
        }
 
    }
 
 
 
    private List<JkSketchCustomer> initNewSketchCustomerList(List<JkSketchLine> sketchLineList, List<JkOrders> newOrderList) {
        List<JkSketchCustomer> list =new ArrayList<>();
        for(JkOrders orders : newOrderList){
            JkSketchLine line = findModelFromListByLineId(orders.getLineId(),sketchLineList);
            if( line!=null){
                JkSketchCustomer tModel =  new JkSketchCustomer();
                tModel.setCreator(orders.getCreator());
                tModel.setOrderId(orders.getId());
                tModel.setCreateDate(orders.getCreateDate());
                tModel.setTotalNum(orders.getNum());
                tModel.setDateInfo(orders.getDateInfo());
                tModel.setSortnum(list.size()+1);
                tModel.setEditDate(tModel.getCreateDate());
                tModel.setEditor(tModel.getCreator());
                tModel.setIsdeleted(Constants.ZERO);
                tModel.setSketchId(line.getSketchId());
                tModel.setCustomerId(orders.getCustomerId());
                tModel.setSketchLineId(line.getId());
                list.add(tModel);
            }
        }
        return list;
    }
    private List<JkSketchLine> initNewSketchLineList(List<JkSketch> newList, List<JkOrders> newOrderList,List<JkLine> lineList) {
        List<JkSketchLine> list =new ArrayList<>();
        for (JkLine line : lineList){
            JkSketchLine tModel =  new JkSketchLine();
            tModel.setSketchId(getSKetchIdByyCategoryId(line.getCategoryId(),newList));
            tModel.setCreator(newList.get(0).getCreator());
            tModel.setCreateDate(newList.get(0).getCreateDate());
            tModel.setLineId(line.getId());
            initOrderAndTotalNum(tModel,line.getId(),newOrderList);
            tModel.setDateInfo(newList.get(0).getDateInfo());
            tModel.setSortnum(list.size()+1);
            tModel.setEditDate(tModel.getCreateDate());
            tModel.setEditor(tModel.getCreator());
            tModel.setIsdeleted(Constants.ZERO);
            if(tModel.getSketchId()!=null && Constants.formatIntegerNum(tModel.getOrderNum()) >0){
                list.add(tModel);
            }
        }
        /*for(JkOrders orders : newOrderList){
            JkSketchLine tModel = findModelFromListByLineId(orders.getLineId(),list);
            if(tModel!=null){
                tModel.setTotalNum(  tModel.getTotalNum().add(orders.getNum()));//订单量累计
                tModel.setOrderNum(tModel.getOrderNum()+1);//客户数加1
            }else{
                tModel = new JkSketchLine();
                tModel.setSketchId(getSKetchIdByyCategoryId(orders.getCategoryId(),newList));
                tModel.setCreator(orders.getCreator());
                tModel.setCreateDate(orders.getCreateDate());
                tModel.setLineId(orders.getLineId());
                tModel.setTotalNum(orders.getNum());
                tModel.setOrderNum(1);
                tModel.setDateInfo(orders.getDateInfo());
                tModel.setSortnum(list.size()+1);
                tModel.setEditDate(tModel.getCreateDate());
                tModel.setEditor(tModel.getCreator());
                tModel.setIsdeleted(Constants.ZERO);
                if(tModel.getSketchId()!=null){
                    list.add(tModel);
                }
            }
        }*/
        return list;
    }
 
    private void initOrderAndTotalNum(JkSketchLine tModel, Integer id, List<JkOrders> newOrderList) {
        for(JkOrders orders : newOrderList){
            if(Constants.equalsInteger(orders.getLineId(),id)){
                tModel.setOrderNum(Constants.formatIntegerNum(tModel.getOrderNum())+1);
                tModel.setTotalNum(Constants.formatBigdecimal(tModel.getTotalNum()).add(Constants.formatBigdecimal(orders.getNum())));
            }
        }
    }
 
    private Integer getSKetchIdByyCategoryId(Integer categoryId, List<JkSketch> newList) {
        for(JkSketch model:newList){
            if(Constants.equalsInteger(model.getCategoryId(),categoryId)){
                return model.getId();
            }
        }
        return null;
    }
 
    private JkSketchLine findModelFromListByLineId(Integer lineId, List<JkSketchLine> list) {
        if(list !=null){
            for(JkSketchLine model : list){
                if(Constants.equalsInteger(lineId,model.getLineId())){
                    return  model;
                }
            }
        }
        return null;
    }
 
    private   List<JkSketch>  initNewSketchList(List<JkOrders> newOrderList) {
        List<JkSketch> list =new ArrayList<>();
        for(JkOrders orders : newOrderList){
            JkSketch tModel = findModelFromListByCateId(orders.getCategoryId(),list);
            if(tModel!=null){
                tModel.setTotalNum(  tModel.getTotalNum().add(orders.getNum()));//订单量累计
                tModel.setOrderNum(tModel.getOrderNum()+1);//客户数加1
            }else{
                tModel = new JkSketch();
                tModel.setLineNum(getLineNumByOrders(orders.getCategoryId(),newOrderList));
                tModel.setPlanLineNum(tModel.getLineNum());
                tModel.setCreator(orders.getCreator());
                tModel.setCreateDate(orders.getCreateDate());
                tModel.setCategoryId(orders.getCategoryId());
                tModel.setTotalNum(orders.getNum());
                tModel.setOrderNum(1);
                tModel.setDateInfo(orders.getDateInfo());
                tModel.setSortnum(list.size()+1);
                tModel.setEditDate(tModel.getCreateDate());
                tModel.setEditor(tModel.getCreator());
                tModel.setStatus(Constants.ZERO);
                tModel.setIsdeleted(Constants.ZERO);
                list.add(tModel);
            }
        }
        return list;
    }
 
    private Integer getLineNumByOrders(Integer cateId, List<JkOrders> newOrderList) {
        List<JkSketchLine> list =new ArrayList<>();
        for(JkOrders orders : newOrderList){
            if(!Constants.equalsInteger(orders.getCategoryId(),cateId)){
                continue;
            }
            JkSketchLine tModel = findModelFromListByLineId(orders.getLineId(),list);
            if(tModel ==null){
                tModel = new JkSketchLine();
                tModel.setLineId(orders.getLineId());
                list.add(tModel);
            }
        }
        return list.size();
    }
 
 
    private JkOrders checkModelParam(JkOrdersImport model
            , List<JkOrders> newOrderList
            ,int index
            ,Date dateInfo
            ,LoginUserInfo loginUserInfo
            ,List<JkCustomer> allList
            ,List<JkLine> lineList ) {
        if(StringUtils.isBlank(model.getName())
                ||StringUtils.isBlank(model.getCode())
                ||StringUtils.isBlank(model.getName())
                ||StringUtils.isBlank(model.getLineName()) ){
            throw  new BusinessException(ResponseStatus.BAD_REQUEST.getCode(),"对不起,第"+(index+3)+"行客户信息不完整,请检查表格内容!");
        }
        for(JkOrders param: newOrderList){
            if(StringUtils.isNotBlank(model.getCode())&&StringUtils.isNotBlank(param.getCode())) {
                if (StringUtils.equals(model.getCode(), param.getCode())) {
                    throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(), "对不起,第" + (index + 3) + "行客户简码【" + model.getName() + "】重复出现,请检查表格内容!");
                }
            }
        }
        JkCustomer customer = findModelFromList(model.getCode(),allList);
        if(customer == null){
            throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(), "对不起,第" + (index + 3) + "行客户编码【" + model.getCode() + "】不存在,请检查表格内容!");
        }
        if(!StringUtils.equals(customer.getName(),model.getName())){
            throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(), "对不起,第" + (index + 3) + "行客户名称【" + model.getName() + "】和编码不匹配,请检查表格内容!");
        }
        JkLine line = findLineFromListByName(model.getLineName(),lineList);
        if(line == null){
            throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(), "对不起,第" + (index + 3) + "行线路【" + model.getLineName() + "】不存在或者配送周期不符合,请检查表格内容!");
        }
 
        JkOrders tModel =   new JkOrders();
        tModel.setCreator(loginUserInfo.getId());
        tModel.setCreateDate(new Date());
        tModel.setName(model.getName());
        tModel.setCode(model.getCode());
        tModel.setNum(getDecimalByVal(model.getNum()));
        tModel.setCustomerId(customer.getId());
        tModel.setDateInfo(dateInfo);
        tModel.setLatitude(customer.getLatitude());
        tModel.setLongitude(customer.getLongitude());
        tModel.setSortnum(model.getSortnum());
        tModel.setLineId(line.getId());
        tModel.setCategoryId(line.getCategoryId());
        tModel.setEditDate(new Date());
        tModel.setEditor(loginUserInfo.getId());
        tModel.setIsdeleted(Constants.ZERO);
        newOrderList.add(tModel);
        return tModel;
    }
 
    private BigDecimal getDecimalByVal(String val) {
        try {
            return new BigDecimal(val);
        }catch (Exception e){
 
        }
        return null;
    }
 
    private JkCustomer findModelFromList(String code, List<JkCustomer> list) {
        if(list !=null){
            for(JkCustomer model : list){
                if(StringUtils.equals(code,model.getCode())){
                    return  model;
                }
            }
        }
        return null;
    }
    private JkSketch findModelFromListByCateId(Integer cateId, List<JkSketch> list) {
        if(list !=null){
            for(JkSketch model : list){
                if(Constants.equalsInteger(cateId,model.getCategoryId())){
                    return  model;
                }
            }
        }
        return null;
    }
    private JkLine findLineFromListByName(String name, List<JkLine> list) {
        if(list !=null){
            for(JkLine model : list){
                if(StringUtils.equals(name,model.getName())){
                    return model;
                }
            }
        }
        return null;
    }
}