fix
Helius
2021-10-09 594686940cf44b6b1f60702352bbb3bb5ea29414
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
package com.xzx.gc.system.service;
 
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xzx.gc.common.constant.Constants;
import com.xzx.gc.common.exception.RestException;
import com.xzx.gc.common.utils.BusinessUtil;
import com.xzx.gc.common.utils.RedisUtil;
import com.xzx.gc.entity.*;
import com.xzx.gc.model.admin.ItemModel;
import com.xzx.gc.model.admin.OrderModel;
import com.xzx.gc.model.admin.StorageModel;
import com.xzx.gc.model.order.FenceDto;
import com.xzx.gc.model.order.ItemDto;
import com.xzx.gc.model.system.QueryParentDTO;
import com.xzx.gc.model.system.SysEnvironmentalInfoListReq;
import com.xzx.gc.model.system.SysEnvironmentalInfoReq;
import com.xzx.gc.model.system.SysEnvironmentalInfoVo;
import com.xzx.gc.system.mapper.AddressMapper;
import com.xzx.gc.system.mapper.OrderItemInfoMapper;
import com.xzx.gc.system.mapper.OrderStorageDetailMapper;
import com.xzx.gc.system.mapper.SysEnvironmentalInfoMapper;
import com.xzx.gc.util.DoubleUtil;
import com.xzx.gc.util.SessionUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;
 
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;
 
@Service
@Transactional
@Slf4j
public class SysEnvironmentalInfoService{
 
    @Autowired
    private SysEnvironmentalInfoMapper sysEnvironmentalInfoMapper;
 
    @Autowired
    private UserService userService;
 
    @Autowired
    private BusinessUtil businessUtil;
 
    @Autowired
    private PartnerGaodeService partnerGaodeService;
    @Autowired
    private FenceService fenceService;
 
    @Autowired
    private AddressMapper addressMapper;
    @Autowired
    private CityPartnerService cityPartnerService;
 
    @Autowired
    private AddressLevelService addressLevelService;
 
    @Autowired
    private OrderService orderService;
 
    @Autowired
    private OrderItemInfoMapper orderItemInfoMapper;
 
    @Autowired
    private OrderStorageDetailMapper orderStorageDetailMapper;
 
    @Autowired
    private SysItemPriceService sysItemPriceService;
 
 
    public List<SysEnvironmentalInfoVo> getSysEnvironmentalInfoList(SysEnvironmentalInfoReq sysEnvironmentalInfoReq) {
 
        //回收员ID
        String receiver = sysEnvironmentalInfoReq.getReceiver();
        String townId=Constants.TIANXIN_CODE;
        int unionFlag = sysEnvironmentalInfoReq.getUnionFlag();
 
        List<SysEnvironmentalInfo> byPartnerId=CollUtil.newArrayList();
        //区域id  安卓会传送同时分类将显示所有合伙人区域下的分类取并集
        String areaId = sysEnvironmentalInfoReq.getAreaId();
 
        if (StrUtil.isBlank(areaId)) {
 
 
            if(StrUtil.isNotBlank(sysEnvironmentalInfoReq.getAddressId())){
 
                AddressInfo addressInfo = addressMapper.selectByPrimaryKey(sysEnvironmentalInfoReq.getAddressId());
                if(StrUtil.isNotBlank(addressInfo.getTownshipId())) {
                    FenceDto fence = fenceService.getFence(addressInfo.getTownshipId(), false, addressInfo.getLongitude(), addressInfo.getLatitude(), true);
                    if (StrUtil.isNotBlank(fence.getFenceId())) {
                        townId = fenceService.findTownId(addressInfo.getTownshipId(), fence.getFenceId());
                    }
                }else {
                    townId=Constants.DEFAULT_ID;
                }
            }else {
                //普通用户
                String longitude = sysEnvironmentalInfoReq.getLongitude();
 
                if(StrUtil.isNotBlank(longitude)){
                    String latitude = sysEnvironmentalInfoReq.getLatitude();
                    String location = longitude + "," + latitude;
                    //根据用户经纬度查询位置
                    AddressLevelInfo byLocation = userService.findByLocation(location);
                    if (byLocation != null) {
                        townId = byLocation.getLevel3Id();
                        FenceDto fence = fenceService.getFence(townId, false, location.split(",")[0], location.split(",")[1], true);
                        if(StrUtil.isNotBlank(fence.getFenceId())){
                            townId =fenceService.findTownId(townId, fence.getFenceId());
                        }
                    }
                }
            }
        } else {
            townId=sysEnvironmentalInfoReq.getAreaId();
 
            if(unionFlag==1) {
                //根据区域查询合伙人Id
                PartnerGaode byTownId = partnerGaodeService.findByTownId(townId);
                String partnerId = byTownId.getPartnerId();
                //根据合伙人查询所有分类
                byPartnerId =findByPartnerIdForSecond(partnerId);
            }
        }
 
        //要根据用户所在的市去查找对应的分类价格
        List<SysEnvironmentalInfoVo> list;
 
        //type 1为大类 2为物品
        Dict dict = Dict.create().set("type", 1);
        dict.set("cityId",townId);
 
        //是否首页展示
//        if("1".equals(sysEnvironmentalInfoReq.getHomeFlag())){
//            dict.set("showFlag","1");
//        }
 
        list = sysEnvironmentalInfoMapper.getSysEnvironmentalInfoListWithMap(dict);
        if(CollUtil.isNotEmpty(list)){
                setSecondList(list,townId,false,receiver);
                //合伙人区域下的分类取并集
                if(unionFlag==1){
                    setUnion(list, byPartnerId);
                }
 
        }else {
 
            //取天心区的分类 但不显示价格
            townId=Constants.TIANXIN_CODE;
            dict = Dict.create().set("type", 1);
            dict.set("cityId",townId);
            list = sysEnvironmentalInfoMapper.getSysEnvironmentalInfoListWithMap(dict);
            if(CollUtil.isNotEmpty(list)){
                setSecondList(list,townId,false,receiver);
            }
        }
        return list;
    }
 
    public List<SysEnvironmentalInfoVo> homeAppliance(String townId) {
        townId=Constants.TIANXIN_CODE;
        List<SysEnvironmentalInfoVo> byCityId = getByTownIdForHome(townId);
        if(CollUtil.isEmpty(byCityId)){
            townId=Constants.TIANXIN_CODE;
            byCityId=getByTownIdForHome(townId);
        }
        return  byCityId;
    }
 
    private List<SysEnvironmentalInfoVo> getByTownIdForHome(String townId){
        Dict dict = Dict.create().set("type", 1);
        dict.set("cityId",townId);
        List<SysEnvironmentalInfoVo> list = sysEnvironmentalInfoMapper.getSysEnvironmentalInfoListWithMap(dict);
        list=list.stream().filter(x->x.getItemType().equals(Constants.HOUSE_HOLD_ITEM_TYPE)||x.getItemType().equals(Constants.HOUSE_HOLD_OTHER_ITEM_TYPE)).collect(Collectors.toList());
        if(CollUtil.isNotEmpty(list)){
            setSecondList(list,townId,false,null);
        }
        return list;
    }
 
    public List<SysEnvironmentalInfo>  findByPartnerIdForSecond(String partnerId){
        Example example=new Example(SysEnvironmentalInfo.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("delFlag",Constants.DEL_NOT_FLAG);
        criteria.andEqualTo("partnerId",partnerId);
        criteria.andIsNotNull("parentId");
        return sysEnvironmentalInfoMapper.selectByExample(example);
    }
 
 
    private void setUnion(  List<SysEnvironmentalInfoVo> list,List<SysEnvironmentalInfo> byPartnerId){
 
        List<SysEnvironmentalInfoVo> allList=CollUtil.newArrayList();
        for (SysEnvironmentalInfoVo sysEnvironmentalInfoVo:list){
            List<SysEnvironmentalInfoVo> list1 = sysEnvironmentalInfoVo.getList();
            CollUtil.addAll(allList,list1);
        }
 
 
        for (SysEnvironmentalInfo sysEnvironmentalInfo : byPartnerId) {
            String itemType = sysEnvironmentalInfo.getItemType();
            long count = allList.stream().filter(x -> x.getItemType().equals(itemType)).count();
            if(count==0){
                //不属于当前区域的价格全都置于0
                SysEnvironmentalInfoVo sysEnvironmentalInfoVo=new SysEnvironmentalInfoVo();
                BeanUtil.copyProperties(sysEnvironmentalInfo,sysEnvironmentalInfoVo);
                sysEnvironmentalInfoVo.setPrice(Constants.MONEY_INIT.toString());
                sysEnvironmentalInfoVo.setSecondPrice(Constants.MONEY_INIT.toString());
                sysEnvironmentalInfoVo.setPutStoragePrice(Constants.MONEY_INIT);
                allList.add(sysEnvironmentalInfoVo);
            }
        }
 
        for (int i = 0; i < list.size(); i++) {
            SysEnvironmentalInfoVo sysEnvironmentalInfoVo = list.get(i);
            if(i==0) {
                sysEnvironmentalInfoVo.setList(allList);
            }else {
                sysEnvironmentalInfoVo.setList(CollUtil.newArrayList());
            }
        }
    }
    /**
     * 获取二级分类
     * @param list
     * @param cityId
     * @param hidePrice 是否隐藏价格
     */
    private void setSecondList(  List<SysEnvironmentalInfoVo> list,String cityId,boolean hidePrice,String receiver){
        for (SysEnvironmentalInfoVo sysEnvironmentalInfoVo : list) {
            Long id = sysEnvironmentalInfoVo.getId();
            if(hidePrice){
                sysEnvironmentalInfoVo.setPutStoragePrice(null);
                sysEnvironmentalInfoVo.setSecondPrice(null);
                sysEnvironmentalInfoVo.setPrice(null);
            }
            Dict dict = Dict.create();
            dict.set("parentId",id);
            dict.set("type",2);
            dict.set("cityId",cityId);
            List<SysItemPrice> priceList=null;
            if(StrUtil.isNotBlank(receiver)) {
                priceList=sysItemPriceService.findPriceByUserId(receiver);
            }
            List<SysEnvironmentalInfoVo> sysEnvironmentalInfoList = sysEnvironmentalInfoMapper.getSysEnvironmentalInfoListWithMap(dict);
            for (SysEnvironmentalInfoVo environmentalInfoVo : sysEnvironmentalInfoList) {
                if(hidePrice){
                    environmentalInfoVo.setPutStoragePrice(null);
                    environmentalInfoVo.setSecondPrice(null);
                    environmentalInfoVo.setPrice(null);
                }
 
                //根据每个分类查询出回收员设定的价格
                if(CollUtil.isNotEmpty(priceList)){
                    List<SysItemPrice> byItemAndList = sysItemPriceService.findByItemAndList(priceList, environmentalInfoVo.getItemType());
                    environmentalInfoVo.setPriceList(byItemAndList);
                }
 
            }
 
 
            //查询所有分类的售卖次数  按合伙人区分
//            if(businessUtil.getVersion(request.getHeader("version")).compareTo(Convert.toDouble(CommonEnum.版本号1点6.getValue()))>=0) {
//                if(CollUtil.isNotEmpty(sysEnvironmentalInfoList)){
//                    //根据区域查找合伙人
//                    String partnerId=null;
//                    PartnerGaode byCityId=null;
//                    if(level==2){
//                        byCityId = partnerGaodeService.findByCityId(cityId);
//                    }else if(level==3){
//                        byCityId = partnerGaodeService.findByTownId(cityId);
//                    }
//
//                    if(byCityId!=null){
//                        partnerId = byCityId.getPartnerId();
//                        List<OrderItemInfo> orderItemInfos = orderItemService.sumGroupTypeByPatnerId(partnerId);
//                        if(CollUtil.isNotEmpty(orderItemInfos)){
//                            for (SysEnvironmentalInfoVo environmentalInfoVo : sysEnvironmentalInfoList) {
//                                String itemType = environmentalInfoVo.getItemType();
//                                List<OrderItemInfo> collect = orderItemInfos.stream().filter(x -> x.getItemType().equals(itemType)).collect(Collectors.toList());
//                                if(CollUtil.isNotEmpty(collect)){
//                                    int saleNum = collect.get(0).getSaleNum();
//                                    String s = StringUtils.intChange2Str(saleNum);
//                                    environmentalInfoVo.setSaleNum(s);
//                                }
//                            }
//                        }
//                    }
//                }
//            }
 
            /**
             * 根据分类查订单分类
             */
            sysEnvironmentalInfoVo.setList(sysEnvironmentalInfoList);
        }
    }
 
 
    /**
     * 批量修改分类价格
     */
    public void batchUpdateSysEnvironmentalInfo(SysEnvironmentalInfoListReq infoListReq){
        String areaId = infoListReq.getAreaId();
        String partnerId = infoListReq.getPartnerId();
        List<SysEnvironmentalInfoReq> sysEnvironmentalInfoList= infoListReq.getSysEnvironmentalInfoList();
        if (CollUtil.isNotEmpty(sysEnvironmentalInfoList)){
                for (SysEnvironmentalInfoReq req : sysEnvironmentalInfoList) {
                    int unionFlag = req.getUnionFlag();
                    SysEnvironmentalInfo sysEnvironmentalInfo=new SysEnvironmentalInfo();
                    sysEnvironmentalInfo.setPrice(req.getPrice());
                    sysEnvironmentalInfo.setSecondPrice(req.getSecondPrice());
                    sysEnvironmentalInfo.setPutStoragePrice(businessUtil.changeMul(Convert.toBigDecimal(req.getPutStoragePrice())));
                    if(unionFlag==0){
                        //根据区域和itemType修改
                        Example example=new Example(SysEnvironmentalInfo.class);
                        Example.Criteria criteria = example.createCriteria();
                        criteria.andEqualTo("delFlag",Constants.DEL_NOT_FLAG);
                        criteria.andEqualTo("cityId",areaId);
                        criteria.andEqualTo("itemType",req.getItemType());
                        sysEnvironmentalInfoMapper.updateByExampleSelective(sysEnvironmentalInfo,example);
                    }else if(unionFlag==1){
                        //应用到所有  根据合伙人和itemType修改
                        Example example=new Example(SysEnvironmentalInfo.class);
                        Example.Criteria criteria = example.createCriteria();
                        criteria.andEqualTo("delFlag",Constants.DEL_NOT_FLAG);
                        criteria.andEqualTo("partnerId",partnerId);
                        criteria.andEqualTo("itemType",req.getItemType());
                        sysEnvironmentalInfoMapper.updateByExampleSelective(sysEnvironmentalInfo,example);
                    }
                }
        }
    }
 
 
    /**
     * 后台分类列表查询
     * @param item
     * @return
     */
    public Map<String, Object> querOperaIteml(ItemModel item) {
 
        List<String> partnerIds = new ArrayList<>();
        if(null!=item.getPartnerId()&&!"".equals(item.getPartnerId())){
            partnerIds.add(item.getPartnerId());
        }else{
            partnerIds = cityPartnerService.queryPartnerByCurrent();
        }
        if (null != partnerIds && partnerIds.size() > 0) {
            List<String> townIds = cityPartnerService.queryTownIdsByPartnerId(partnerIds.get(0));
            item.setTownIdList(townIds);
        }
        Map<String, Object> map = new HashMap<>();
        PageHelper.startPage(item.getPageNum(),item.getLimitNum());
        List<ItemModel> list = sysEnvironmentalInfoMapper.queryOperaIteml(item);
        PageInfo<ItemModel> pageInfo=new PageInfo<>(list);
        for (ItemModel itemModel : list) {
            String townId = itemModel.getCityId();
            if (null != townId && !"".equals(townId)) {
                Map<String, Object> objmap = addressLevelService.queryCityByTownId(townId);
                String cityId = objmap.get("cid").toString();
                String pid = objmap.get("pid").toString();
 
                List<List<String>> resList = new ArrayList<>();
                List<String> detailList = new ArrayList<>();
                detailList.add(pid);
                detailList.add(cityId);
                detailList.add(townId);
                resList.add(detailList);
                itemModel.setResultArea(resList);
 
            }
 
        }
        map.put("data", list);
        map.put("count", pageInfo.getTotal());
        map.put("code", 0);
        return map;
    }
 
    /**
     * 后台类别查询
     * @param item
     * @return
     */
    public Map<String, Object> queryOperateItemList(ItemModel item) {
        Map<String, Object> map = new HashMap<>();
        PageHelper.startPage(item.getPageNum(),item.getLimitNum());
        List<ItemModel> list =  sysEnvironmentalInfoMapper.queryOperateItemList(item);
        PageInfo<ItemModel> pageInfo=new PageInfo<>(list);
 
        for (ItemModel obj : list) {
            obj = queryChildItem(obj);
        }
        map.put("data", list);
        map.put("count", pageInfo.getTotal());
        map.put("code", 0);
        return map;
    }
 
 
    /**
     * 无限子类算法(时间有限)
     *
     * @param item
     * @return
     */
    private ItemModel queryChildItem(ItemModel item) {
        List<ItemModel> child = sysEnvironmentalInfoMapper.queryOperateItemChildren(item);
        List<ItemModel> childm = new ArrayList<>();
        for (ItemModel obj : child) {
            childm.add(obj);
        }
        item.setChildren(childm);
        for (ItemModel cObj : childm) {
            if (null != cObj.getParentId()) {
                queryChildItem(cObj);
            }
        }
        return item;
    }
 
    public Map<String, Object> updateOperateItem(ItemModel item) {
        Map<String, Object> map = new HashMap<>();
        String cityId = item.getCityId();
        PartnerGaode byTownId = partnerGaodeService.findByTownId(cityId);
 
        //根据区域查询围栏
        List<String>  townIds = cityPartnerService.queryFenceIdByPartnerId(byTownId.getPartnerId());
        List<OrderModel> orderList = orderService.queryOrderByCityId(cityId,townIds);
        if(CollUtil.isNotEmpty(orderList)) {
            throw new RestException("存在待入库和入库中的订单");
        }
        String title=item.getTitle();
 
        SysEnvironmentalInfo sysEnvironmentalInfo = sysEnvironmentalInfoMapper.selectByPrimaryKey(item.getId());
        if(!sysEnvironmentalInfo.getTitle().equals(title)){
            SysEnvironmentalInfo byCityAndTitle = findByCityAndTitle(title, cityId);
            if(byCityAndTitle!=null){
                throw new RestException("当前分类已存在");
            }
        }
 
 
        // 对排序字段进行处理
        setSort(item);
 
        int i = updateItem(item);
 
        //父类隐藏则子类都隐藏
        if(0==Convert.toInt(item.getShowFlag(),1)) {
            if (sysEnvironmentalInfo.getParentId() == null) {
                List<ItemModel> children = item.getChildren();
                for (ItemModel child : children) {
                    SysEnvironmentalInfo obj = new SysEnvironmentalInfo();
                    obj.setId(child.getId());
                    obj.setShowFlag(Convert.toShort(0));
                    sysEnvironmentalInfoMapper.updateByPrimaryKeySelective(obj);
                }
            }
        }
        setSortAggin(item);
        map.put("code", 0);
        map.put("num", i);
        return map;
    }
 
 
    private int updateItem(ItemModel item){
        return sysEnvironmentalInfoMapper.updateItem(item);
    }
 
 
    private void setSort(ItemModel item) {
        ItemModel im = new ItemModel();
        im.setLimit(1000);
        im.setParentId(item.getParentId());
        List<ItemModel> list = sysEnvironmentalInfoMapper.querIteml(im);
        // 找到原始的sort数据
        int originalSort = item.getSort();
 
        for (ItemModel imx : list) {
            if (originalSort <= imx.getSort()) {
                imx.setSort(imx.getSort() + 1);
            }
        }
        for (ItemModel imx : list) {
            updateItem(imx);
        }
    }
 
 
    private void setSortAggin(ItemModel item) {
        ItemModel im = new ItemModel();
        im.setLimit(1000);
        im.setParentId(item.getParentId());
        List<ItemModel> list = sysEnvironmentalInfoMapper.querIteml(im);
        list.sort((x, y) -> Integer.compare(x.getSort(), y.getSort()));
        int f = 1;
        for (ItemModel itemModel : list) {
            itemModel.setSort(f++);
        }
        for (ItemModel itemModel : list) {
            updateItem(itemModel);
        }
    }
 
    /**
     * 根据城市和标题查询
     * @param title
     * @param cityId
     * @return
     */
    public SysEnvironmentalInfo findByCityAndTitle(String title,String cityId){
        SysEnvironmentalInfo sysEnvironmentalInfo=new SysEnvironmentalInfo();
        sysEnvironmentalInfo.setCityId(Convert.toInt(cityId));
        sysEnvironmentalInfo.setTitle(title);
        sysEnvironmentalInfo.setDelFlag(0);
        return sysEnvironmentalInfoMapper.selectOne(sysEnvironmentalInfo);
    }
 
    public SysEnvironmentalInfo findById(Long id){
        return sysEnvironmentalInfoMapper.selectByPrimaryKey(id);
    }
 
    public SysEnvironmentalInfo findByItemTypeAndAreaNotDel(String itemType,Integer areaId) {
        Example example=new Example(SysEnvironmentalInfo.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("itemType",itemType);
        criteria.andEqualTo("cityId",areaId);
        criteria.andEqualTo("delFlag",Constants.DEL_NOT_FLAG);
        SysEnvironmentalInfo sysEnvironmentalInfo1 = sysEnvironmentalInfoMapper.selectOneByExample(example);
        return  sysEnvironmentalInfo1;
    }
 
 
    public Map<String, Object> addOperateParent(ItemModel item) {
        List<String> townIdList = item.getTownIdList();
        String cityId = townIdList.get(0);
        PartnerGaode byTownId = partnerGaodeService.findByTownId(cityId);
        item.setPartnerId(byTownId.getPartnerId());
        String title = item.getTitle();
        Map<String, Object> map = new HashMap<>();
        Long parentId = item.getParentId();
 
        //验证 如果是天心区 大类和物品都不能出现重复标题  不是天心区,则要验证物品不能出现重复名称
        if(Constants.TIANXIN_CODE.equals(cityId)){
            SysEnvironmentalInfo byCityAndTitle = findByCityAndTitle(title, cityId);
            if(byCityAndTitle!=null){
                throw new RestException("已经有相同的物品");
            }
        }else{
            if(parentId!=null) {
                SysEnvironmentalInfo byCityAndTitle = findByCityAndTitle(title, cityId);
                if(byCityAndTitle!=null){
                    throw new RestException("已经有相同的物品");
                }
            }
        }
 
 
        String itemType=System.currentTimeMillis() + "" + (int) (Math.random() * (10000 - 10) + 10);
 
        //添加大类 必须和总部保持一致
        if(!Constants.TIANXIN_CODE.equals(cityId)&&parentId==null) {
            SysEnvironmentalInfo byCityAndTitle = findByCityAndTitle(title, Constants.TIANXIN_CODE);
            itemType=byCityAndTitle.getItemType();
        }
 
        item.setItemType(itemType);
        item.setCreateTime(DateUtil.now());
        // 对排序字段进行处理
        setSort(item);
 
        int i = 0;
        for (String townId : townIdList) {
            item.setCityId(townId);
            i = sysEnvironmentalInfoMapper.insertItemOperate(item);
        }
        setSortAggin(item);
        map.put("count", i);
        map.put("code", 0);
        return map;
    }
 
 
 
    /**
     * 删除后台分类
     * @param item
     * @return
     */
    public Map<String, Object> delOperateItem(ItemModel item) {
        Map<String, Object> map = new HashMap<>();
        ItemModel im = new ItemModel();
        im.setLimit(10);
        im.setParentId(item.getId());
        List<ItemModel> list = sysEnvironmentalInfoMapper.querIteml(im);
        if (list.size() > 0) {
            map.put("code", -1);
            map.put("num", 0);
            return map;
        }
        int i = sysEnvironmentalInfoMapper.delItem(item);
        map.put("code", 0);
        map.put("num", i);
        return map;
    }
 
    public Map<String,Object> queryTypeData(StorageModel storageModel){
        List<String> partnerIds = new ArrayList<>();
        if(StrUtil.isNotBlank(storageModel.getPartnerId())){
            partnerIds.add(storageModel.getPartnerId());
        }else{
            partnerIds = cityPartnerService.queryPartnerByCurrent();
        }
 
        Map<String,String> lastMap = new HashMap<>();
        Map<String,Object> detailImage = new HashMap<>();
        if(null!=storageModel.getImageType()&&!"".equals(storageModel.getImageType())) {
            if (storageModel.getImageType().equals("day")) {
                lastMap.put("startTime", cn.hutool.core.date.DateUtil.today() +" 00:00:00");
                lastMap.put("endTime",cn.hutool.core.date.DateUtil.today()+" 23:59:59");
            } else {
                List<Map<String,String>> weekOrMonthImgList  = com.xzx.gc.util.DateUtil.query12MonthStartTimeAndEndTime();
                lastMap = weekOrMonthImgList.get(0);
            }
        }
        detailImage = queryPageSysStorageTypeName(lastMap.get("startTime"),lastMap.get("endTime"),storageModel.getTypeName(),storageModel.getPage(),storageModel.getLimit(),partnerIds,storageModel.getParentId(),storageModel.getDelFlag());
 
        return detailImage;
    }
 
    private Map<String,Object> queryPageSysStorageTypeName(String startTime,String endTime,String typeName,int page,int limit,List<String> partnerIds,String parentId,String delFlag){
        String partnerId="";
        if(null!=partnerIds&&partnerIds.size()>0){
            partnerId = partnerIds.get(0);
        }
        PageHelper.startPage(page,limit);
 
        List<SysEnvironmentalInfo> list = sysEnvironmentalInfoMapper.findPage(partnerId,typeName,parentId,delFlag);
 
 
        for (SysEnvironmentalInfo sysEnvironmentalInfo : list) {
            ItemDto orderItem = orderItemInfoMapper.findByTypeAndPartnerAndTime(sysEnvironmentalInfo.getPartnerId(), sysEnvironmentalInfo.getItemType(), startTime, endTime);
            orderItem=orderItem==null?new ItemDto():orderItem;
            sysEnvironmentalInfo.setOldMoney(orderItem.getMoney());
            ItemDto storageItem = orderStorageDetailMapper.findByTypeAndPartnerAndTime(sysEnvironmentalInfo.getPartnerId(), sysEnvironmentalInfo.getItemType(), startTime, endTime);
            storageItem=storageItem==null?new ItemDto():storageItem;
            BigDecimal moneyError = NumberUtil.sub(Convert.toBigDecimal(storageItem.getMoney()), Convert.toBigDecimal(orderItem.getMoney()));
            BigDecimal weightError = NumberUtil.sub(Convert.toBigDecimal(storageItem.getWeight()), Convert.toBigDecimal(orderItem.getWeight()));
            BigDecimal money = Convert.toBigDecimal(orderItem.getMoney()).divide(new BigDecimal("10000"),2);
            BigDecimal moneyErrorBig = new BigDecimal(moneyError.toString()).divide(new BigDecimal("10000"),2);
            BigDecimal weight = Convert.toBigDecimal(orderItem.getWeight()).divide(new BigDecimal("1000"),3);
            BigDecimal weightErrorBig = new BigDecimal(weightError.toString()).divide(new BigDecimal("1000"),3);
            sysEnvironmentalInfo.setMoney(DoubleUtil.roundTwo(money+""));
            sysEnvironmentalInfo.setMoneyError(DoubleUtil.roundTwo(moneyErrorBig+""));
            sysEnvironmentalInfo.setWeight(DoubleUtil.roundThree(weight+""));
            sysEnvironmentalInfo.setWeightError(DoubleUtil.roundThree(weightErrorBig+""));
        }
        PageInfo<SysEnvironmentalInfo> pageInfo = new PageInfo<>(list);
        int count = Convert.toInt(pageInfo.getTotal());
 
        //总金额
        BigDecimal totalMoney = new BigDecimal("0");
 
        for (SysEnvironmentalInfo sysEnvironmentalInfo:list) {
            totalMoney = totalMoney.add(Convert.toBigDecimal(sysEnvironmentalInfo.getOldMoney()));
        }
 
        for (SysEnvironmentalInfo sysEnvironmentalInfo:list) {
            BigDecimal rate;
            if(totalMoney.compareTo(BigDecimal.ZERO)==0){
                rate=BigDecimal.ZERO;
            }else {
                rate = Convert.toBigDecimal(sysEnvironmentalInfo.getOldMoney(), Constants.MONEY_INIT).divide(totalMoney, 2, RoundingMode.HALF_UP);
            }
            sysEnvironmentalInfo.setRate(rate.multiply(new BigDecimal("100")).toString()+"%");
        }
 
        Map<String,Object> imageData = new HashMap<>();
        imageData.put("totalMoney",DoubleUtil.roundTwo(totalMoney.toString()));
        imageData.put("data",list);
        imageData.put("count",count);
        return imageData;
    }
 
    public List<SysEnvironmentalInfo> queryParent(QueryParentDTO queryParentDTO) {
        Example example=new Example(SysEnvironmentalInfo.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("cityId",queryParentDTO.getCityId());
        criteria.andIsNull("parentId");
        return sysEnvironmentalInfoMapper.selectByExample(example);
    }
 
 
}