Helius
2021-11-01 110a99baa82a748bee993ad01ca03370c9dc0cf2
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
package com.matrix.system.hive.service.imp;
 
import cn.hutool.core.collection.CollUtil;
import com.google.common.collect.Lists;
import com.matrix.component.asyncmessage.AsyncMessageManager;
import com.matrix.core.constance.MatrixConstance;
import com.matrix.core.exception.GlobleException;
import com.matrix.core.pojo.PaginationVO;
import com.matrix.core.pojo.VerifyResult;
import com.matrix.core.tools.DateUtil;
import com.matrix.core.tools.LogUtil;
import com.matrix.core.tools.StringUtils;
import com.matrix.core.tools.WebUtil;
import com.matrix.system.app.dto.ServiceOrderListDto;
import com.matrix.system.app.vo.ServiceOrderListVo;
import com.matrix.system.common.bean.BusParameterSettings;
import com.matrix.system.common.bean.SysUsers;
import com.matrix.system.common.constance.AppConstance;
import com.matrix.system.common.dao.BusParameterSettingsDao;
import com.matrix.system.common.dao.SysUsersDao;
import com.matrix.system.common.service.BusParameterSettingService;
import com.matrix.system.constance.Dictionary;
import com.matrix.system.hive.bean.*;
import com.matrix.system.hive.dao.*;
import com.matrix.system.hive.plugin.util.MoneyUtil;
import com.matrix.system.hive.service.*;
import com.matrix.system.score.constant.ScoreSettingConstant;
import com.matrix.system.score.entity.ScoreVipDetail;
import com.matrix.system.score.service.ScoreVipDetailService;
import com.matrix.system.shopXcx.mqTask.AsyncMessageRouting;
import com.matrix.system.wechart.templateMsg.UniformMsgParam;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
 
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;
 
/**
 * @date 2016-07-03 20:57
 */
@Service("sysProjServicesService")
public class SysProjServicesServiceImpl implements SysProjServicesService {
 
    @Autowired
    SysBedStateDao sysBedStateDao;
    @Autowired
    private SysProjServicesDao sysProjServicesDao;
    @Resource
    private SysOrderItemService sysOrderItemService;
 
    @Autowired
    private SysBedStateDao bedStateDao;
 
    @Autowired
    private SysBeauticianStateDao beauticianStateDao;
    @Autowired
    private SysProjUseDao sysProjUseDao;
 
 
    @Autowired
    private SysOutStoreDao sysOutStoreDao;
 
    @Autowired
    private SysOutStoreItemDao sysOutStoreItemDao;
    @Autowired
    private SysBedInfoDao sysBedInfoDao;
    @Autowired
    TaiYanAliyunSmsService taiYanAliyunSmsService;
 
    @Autowired
    private SysStoreInfoDao storeInfoDao;
 
 
    @Autowired
    private CodeService codeService;
 
    @Autowired
    ServicesFlowDao servicesFlowDao;
 
    @Autowired
    private LastestWorkBeatuistaffDao LastestWorkBeatuistaffDao;
 
    @Autowired
    SysUsersDao userDao;
 
    @Autowired
    private MyBeauticianCountDao myBeauticianCountDao;
 
    @Autowired
    private ParameterSettingsDao parameterSettingsDao;
 
    @Autowired
    private MyBeaticianDao myBeaticianDao;
    @Autowired
    private AchieveNewService achieveNewService;
 
    @Autowired
    private ShoppingGoodsDao shoppingGoodsDao;
 
    @Autowired
    ShoppingGoodsAssembleDao shoppingGoodsAssembleDao;
    @Resource
    private SysProjUseService projUseService;
    @Resource
    private SysOrderService sysOrderService;
    @Autowired
    WarehouseDao warehouseDao;
    @Resource
    private ShoppingGoodsService shoppingGoodsService;
 
    @Autowired
    private AsyncMessageManager asyncMessageManager;
 
 
    @Autowired
    BusParameterSettingsDao busParameterSettingsDao;
 
    @Autowired
    BusParameterSettingService busParameterSettingService;
 
    @Autowired
    ScoreVipDetailService scoreVipDetailService;
 
    @Autowired
    SysVipInfoDao sysVipInfoDao;
 
 
    @Autowired
    ShoppingGoodsAssembleDao goodsAssembleDao;
 
    /**
     * 新增服务单 jyy
     *
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public SysProjServices addSysProjServices(SysProjServices sysProjServices) throws GlobleException {
 
        //创建服务单
        if (WebUtil.getSession().getAttribute(MatrixConstance.LOGIN_KEY) != null) {
            SysUsers user = (SysUsers) WebUtil.getSession().getAttribute(MatrixConstance.LOGIN_KEY);
            sysProjServices.setCreateStaffId(user.getSuId());
            sysProjServices.setShopId(user.getShopId());
            sysProjServices.setCompanyId(user.getCompanyId());
        }
 
 
        if (sysProjServices.getId() == null) {
            sysProjServices.setCreateTime(new Date());
            sysProjServices.setServiceNo(codeService.getServiceOrderCode());
            int i = sysProjServicesDao.insert(sysProjServices);
        }
 
        Double hkPrice = 0.0;
        // 计算项目总时长
        int totalTime = 0;
        //处理订单明细
        for (SysBeauticianState sysBeauticianState : sysProjServices.getServiceItems()) {
 
            SysProjUse sysProjUse = projUseService.findById(sysBeauticianState.getPuseId());
            ShoppingGoods sysProjInfo = shoppingGoodsDao.selectById(sysProjUse.getProjId());
 
            totalTime = totalTime + (sysProjInfo.getTimeLength() == null ? 0 : sysProjInfo.getTimeLength());
            //更新余次
            SysProjUse upProjUse = new SysProjUse();
            // 如果该使用情况不为套餐卡,则修改单个项目余次信息
            upProjUse.setId(sysBeauticianState.getPuseId());
 
            //扣减次数
            int surplus = sysProjUse.getSurplusCount() - sysBeauticianState.getCount();
            upProjUse.setSurplusCount(surplus);
            // 项目使用完了
            if (surplus <= 0) {
                upProjUse.setIsOver(Dictionary.FLAG_YES_Y);
                upProjUse.setStatus(Dictionary.TAOCAN_STATUS_WX);
            }
            //本次消费金额
            Double bcxfje = MoneyUtil.mul(sysProjUse.getPrice(), Double.valueOf(sysBeauticianState.getCount()));
            upProjUse.setBalance(MoneyUtil.sub(sysProjUse.getBalance(), bcxfje));
 
            // 判断是否第一次使用该项目, 若是则根据商品消耗有效期更新到期时间
            List<SysBeauticianState> sysBeauticianStates = beauticianStateDao.selectBeauticianStateByPuseIdAndNoStatus(sysBeauticianState.getPuseId(), Dictionary.SERVICE_STATU_YYQX);
            if (CollectionUtils.isEmpty(sysBeauticianStates)) {
                Date useInvalidTime = shoppingGoodsService.calInvalidTime(sysProjInfo, 2, sysProjUse.getFailTime());
                upProjUse.setFailTime(useInvalidTime);
            }
 
            //更新余次信息
            sysProjUseDao.updateSurplusCount(upProjUse);
            //如果项目是套餐 中项目则判断套餐是否失效
            if (sysProjUse.getTaocanId() != null) {
                SysProjUse taocan = sysProjUseDao.selectById(sysProjUse.getTaocanId());
                SysProjUse taocanQuery = new SysProjUse();
                taocanQuery.setTaocanId(sysProjUse.getTaocanId());
                List<SysProjUse> taocanProjUses = sysProjUseDao.selectByModel(taocanQuery);
                List<SysProjUse> activeProjUse = taocanProjUses.stream().filter(item -> item.getIsOver().equals(Dictionary.FLAG_NO_N)).collect(Collectors.toList());
                if (CollectionUtils.isEmpty(activeProjUse)) {
                    //全部使用完成
                    taocan.setIsOver(Dictionary.FLAG_YES_Y);
                    taocan.setSurplusCount(0);
                    taocan.setStatus(Dictionary.TAOCAN_STATUS_WX);
                } else if (
                        Dictionary.FLAG_NO_N.equals(taocan.getIsCourse())
                                || (Dictionary.FLAG_YES_Y.equals(taocan.getIsCourse())
                                && (StringUtils.isBlank(taocan.getIsInfinite()) || Dictionary.FLAG_NO_N.equals(taocan.getIsInfinite())))) {
 
                    //任选套餐检查套餐整体剩余次数
                    int tcSurplusCount = taocan.getSurplusCount() - sysBeauticianState.getCount();
                    if (tcSurplusCount < 0) {
                        throw new GlobleException(taocan.getProjName() + "已经达到最大使用次数");
                    } else {
                        taocan.setSurplusCount(tcSurplusCount);
                    }
 
                    if (tcSurplusCount == 0) {
                        taocan.setIsOver(Dictionary.FLAG_YES_Y);
                        taocan.setStatus(Dictionary.TAOCAN_STATUS_WX);
                    }
                }
 
                // 根据套餐内所有项目查询该套餐是否第一次使用,若第一次使用则更新该套餐有效期
                List<SysBeauticianState> taocanHas = beauticianStateDao.selectByProjUse(taocanProjUses, Dictionary.SERVICE_STATU_YYQX);
                if (CollectionUtils.isEmpty(taocanHas)) {
                    ShoppingGoods taocanInfo = shoppingGoodsDao.selectById(taocan.getProjId());
                    Date useInvalidTime = shoppingGoodsService.calInvalidTime(taocanInfo, 2, sysProjUse.getFailTime());
                    taocan.setFailTime(useInvalidTime);
                }
                taocan.setBalance(MoneyUtil.sub(taocan.getBalance(), bcxfje));
                sysProjUseDao.updateSurplusCount(taocan);
            }
 
 
            // 设置划扣价
            hkPrice = MoneyUtil.add(hkPrice, bcxfje);
            //插入订单明细
            sysBeauticianState.setProjId(sysProjInfo.getId());
            sysBeauticianState.setServicesId(sysProjServices.getId());
            sysBeauticianState.setShopId(sysProjServices.getShopId());
            sysBeauticianState.setState(sysProjServices.getState());
            beauticianStateDao.insert(sysBeauticianState);
        }
        // 设置项目总时长
        sysProjServices.setTotalTime(totalTime);
        sysProjServices.setMoney(new BigDecimal(hkPrice).setScale(2, BigDecimal.ROUND_HALF_DOWN).doubleValue());
        sysProjServicesDao.update(sysProjServices);
        return sysProjServices;
    }
 
 
    /**
     * 校验服务单中的项目是否存在欠款
     *
     * @param sysProjServices
     * @return
     */
    @Override
    public VerifyResult checkBalance(SysProjServices sysProjServices) {
        //检测欠款
        for (SysBeauticianState sysBeauticianState : sysProjServices.getServiceItems()) {
 
            SysProjUse sysProjUse = projUseService.findById(sysBeauticianState.getPuseId());
 
            //检查是否已经处于无效状态
            if (Dictionary.TAOCAN_STATUS_WX.equals(sysProjUse.getStatus())) {
                return new VerifyResult(true, sysProjUse.getProjName() + "项目已经失效");
            }
 
            int kjcs = 1;
            if (sysProjUse.getTaocanId() != null) {
                kjcs = sysBeauticianState.getCount() * sysProjUse.getDeductionNum();
            }
            int surplusCount = sysProjUse.getSurplusCount() - kjcs;
            if (surplusCount < 0) {
                if (!Dictionary.SHOPPING_GOODS_TYPE_TCK.equals(sysProjUse.getType())) {
                    return new VerifyResult(true, sysProjUse.getProjName() + "余次不足");
                } else {
                    return new VerifyResult(true, sysProjUse.getProjName() + "余次不足");
                }
            }
        }
        return new VerifyResult(false);
    }
 
 
    @Override
    public int modify(SysProjServices sysProjServices) {
 
        return sysProjServicesDao.update(sysProjServices);
 
    }
 
    @Override
    public int remove(List<Long> list) {
 
        return sysProjServicesDao.deleteByIds(list);
 
    }
 
    @Override
    public int removeById(Long id) {
 
        return sysProjServicesDao.deleteById(id);
 
    }
 
 
    @Override
    public List<SysProjServices> findByModel(SysProjServices sysProjServices) {
 
        return sysProjServicesDao.selectByModel(sysProjServices);
 
    }
 
 
    @Override
    public SysProjServices findById(Long id) {
 
        return sysProjServicesDao.selectById(id);
 
    }
 
 
    /**
     * TODO 做成配置项目 校验服务单中的项目是否存在欠款
     *
     * @param sysProjServices
     * @return
     */
    @Override
    public VerifyResult checkArrears(SysProjServices sysProjServices) {
        // 检测欠款
       /*for (SysBeauticianState sysBeauticianState : sysProjServices.getServiceItems()) {
            SysProjUse sysProjUse = projUseService.findById(sysBeauticianState.getPuseId());
 
            ShoppingGoods shoppingGoods = shoppingGoodsDao.selectById(sysProjUse.getProjId());
            SysOrderItem item = sysOrderItemService.findById(sysProjUse.getOrderItemId());
            SysOrder orderItem = sysOrderService.findById(item.getOrderId());
            if ("购买".equals(sysProjUse.getSource())) {
                // 如果用户有欠款,服务单总价不能超过已付金额
                if (orderItem!=null && orderItem.getArrears() > 0) {
                    // 本金-余额=已消费金额
                    double bj = shoppingGoods.getSealPice();
                    //单价* 单次划扣次数* 本次下单数 TODO 单次划扣数量存到projuse表中
                    double bcxfje = sysProjUse.getPrice() * sysBeauticianState.getCount();
 
 
                    // 计算消费金额
                    double yxfje = MoneyUtil.sub(bj, sysProjUse.getBalance());
                    // 本金-欠款=已付金额
                    double money = MoneyUtil.sub((bj - orderItem.getArrears()), (yxfje + bcxfje));
                    // 如果 已付金额  - (已消费金额+本次消费金额)<0 则不能再消费
                   if (money < 0) {
                        return new VerifyResult(true, shoppingGoods.getName() + "存在欠款" + orderItem.getArrears() + "元 , 订单编号[ " + orderItem.getOrderNo() + " ] ");
                    }
 
 
                }
            } else if ("赠送".equals(sysProjUse.getSource())) {
                if (orderItem!=null && orderItem.getArrears()!=null&&orderItem.getArrears() > 0) {
                    return new VerifyResult(true, shoppingGoods.getName() + "存在欠款" + orderItem.getArrears() + "元 , 不能消费赠送项目,订单编号[ " + sysOrderService.findById(orderItem.getOrderId()).getOrderNo() + " ] ");
                }
            }
        }*/
        return new VerifyResult(false);
    }
 
    // 排班 jyy
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int paiban(SysProjServices projServices, String dateTime2) throws GlobleException {
        /** 验证数据是否正确 */
        SysProjServices checkProjServices = sysProjServicesDao.selectById(projServices.getId());
        // 验证服务单是否存在或者取消
        if (checkProjServices.getState().equals(Dictionary.SERVICE_STATU_YYQX)
                || checkProjServices.getState().equals(Dictionary.SERVICE_STATU_FFJS)) {
            throw new GlobleException("该服务单已被取消或者不存在!");
        }
        // 验证是否选择床位
        if (sysBedInfoDao.selectById(projServices.getBedId()) == null) {
            throw new GlobleException("请选择床位!");
        }
        String dateTime = DateUtil.dateToString(projServices.getYyTime(), DateUtil.DATE_FORMAT_DD);
        // 设置床位排班时间
 
 
        /***********************************************/
        // 验证床位排班时间是否正确
 
        SysBedState sysBedState = projServices.getBedState();
        sysBedState.setEndTime(DateUtil.getNextNMinute(sysBedState.getStartTime(), projServices.getTotalTime()));
        sysBedState.setBedId(projServices.getBedId());
        sysBedState.setServiceId((projServices.getId()));
        sysBedState.setBedState(Dictionary.BED_STATE_SYZ);
 
        for (SysBeauticianState beauticianState : projServices.getServiceItems()) {
            if (DateUtil.isAffterDate(beauticianState.getEndTime(), beauticianState.getBeginTime())) {
                throw new GlobleException("美疗师的排班结束时间不能晚于美疗师排班的开始时间!");
            }
        }
 
        // 判断是否是编辑,还是新增,编辑则需要先释放资源
        if (!checkProjServices.getState().equals(Dictionary.SERVICE_STATU_DYY)) {
            // 释放床位资源
            bedStateDao.deleteByServiceId(checkProjServices.getId());
        }
        // 检测床位与美疗师占用情况
        if (bedStateDao.checkBedClash(sysBedState) > 0) {
            throw new GlobleException("该床位已被占用,请重新分配!");
        }
        bedStateDao.insert(sysBedState);
 
        // 排美疗师并且分配项目
        int projCount = 0;
        for (SysBeauticianState beauticianState : projServices.getServiceItems()) {
 
 
            if (beauticianStateDao.checkBeauticianClash(beauticianState) > 0) {
                throw new GlobleException("该美疗师已被占用,请重新分配!");
            }
//            beauticianState.setExcTime(beauticianState.getProjInfo().getTimeLength());
            beauticianState.setState(Dictionary.BEATUI_STATE_YYY);
            beauticianStateDao.update(beauticianState);
 
            if (beauticianState.getStaffId() == null || beauticianState.getStaffId().equals("")) {
                throw new GlobleException("美疗师至少分配一个项目!");
            }
        }
 
 
        if (Dictionary.SERVICE_STATU_DYY.equals(projServices.getState())) {
            // 设置成功状态
            projServices.setState(Dictionary.SERVICE_STATU_XPL);
        }
        // 判断当前门店是否有历史美疗师
        LastestWorkBeatuistaff lastWorkStaff = new LastestWorkBeatuistaff();
        lastWorkStaff.setShopId(checkProjServices.getShopId());
        List<LastestWorkBeatuistaff> lastWorkList = LastestWorkBeatuistaffDao.selectByModel(lastWorkStaff);
        // 如果有数据,则先清空
        if (lastWorkList.size() > 0) {
            // 清空排班员工
            LastestWorkBeatuistaffDao.deleteByModel(lastWorkStaff);
        }
        // 排班后记录当前最新的排班员工
        List<LastestWorkBeatuistaff> lastList = new ArrayList<>();
 
        for (SysBeauticianState beauticianState : projServices.getServiceItems()) {
            LastestWorkBeatuistaff lastWork = new LastestWorkBeatuistaff();
            lastWork.setChangeDate(new Date());
            lastWork.setStaffId(beauticianState.getStaffId());
            lastWork.setShopId(checkProjServices.getShopId());
            lastList.add(lastWork);
        }
        LastestWorkBeatuistaffDao.batchInsert(lastList);
        int i = sysProjServicesDao.update(projServices);
 
        //根据配置是否完成自动配料
        if (busParameterSettingService.isSettingOpen(AppConstance.OPEN_SERVICE_ORDER_AUTO_BATCHING, checkProjServices.getCompanyId())){
            autoBatching(projServices);
        }
 
 
        return i;
    }
 
 
    /**
     * 根据配置是否完成自动配料
     *
     * @param projServices
     */
    private void autoBatching(SysProjServices projServices) {
 
        //获取最新的服务单信息
        projServices=findById(projServices.getId());
        List<SysBeauticianState> beauticianStateList = beauticianStateDao.selectBySerIds(projServices.getId());
 
 
        List<SysOutStoreItem> outStoreItemList = Lists.newLinkedList();
        beauticianStateList.stream().forEach(item -> {
 
            List<ShoppingGoodsAssemble> shoppingGoodsAssembles = goodsAssembleDao.selectGoodsByShoppingGoodsIdAndType(item.getProjId(), ShoppingGoods.SHOPPING_GOODS_TYPE_JJCP);
 
            if (CollUtil.isNotEmpty(shoppingGoodsAssembles)) {
                outStoreItemList.addAll(shoppingGoodsAssembles.stream().map(assemble -> {
                    SysOutStoreItem outStoreItem = new SysOutStoreItem();
                    outStoreItem.setSkuId(assemble.getAssembleGoodId());
                    outStoreItem.setAmount(Double.parseDouble(assemble.getTotal()+""));
                    outStoreItem.setRemark("自动配料");
                    return outStoreItem;
                }).collect(Collectors.toList()));
            }
        });
        //组合配料参数
        projServices.setOutStoreItem(outStoreItemList);
        //调用配料出库方法
        try {
            modifyPLProjServices(projServices);
        }catch (GlobleException e){
            LogUtil.debug("配料失败:{}",e.getMessage());
        }
 
    }
 
 
    @Override
    public int add(SysProjServices sysProjServices) {
        return sysProjServicesDao.insert(sysProjServices);
    }
 
    // 取消服务单 jyy
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int modifyCancelProjServices(SysProjServices projServices) throws GlobleException {
 
        SysProjServices checkProjServices = sysProjServicesDao.selectById(projServices.getId());
        if (checkProjServices.getState().equals(Dictionary.SERVICE_STATU_YYQX)) {
            throw new GlobleException("不能重复取消同一个订单");
        } else if (checkProjServices.getState().equals(Dictionary.SERVICE_STATU_DYY)) {
            // 回退项目余次
            backProjCount(checkProjServices);
        } else {
 
            // 释放床位资源
            SysBedState checkBedState = sysBedStateDao.selectBySerIdAndBedId(checkProjServices.getBedId(), checkProjServices.getId());
            if (checkBedState != null) {
                checkBedState.setBedState(Dictionary.BED_STATE_YYQX);
                bedStateDao.update(checkBedState);
            }
 
            List<SysBeauticianState> beauticianStateList = beauticianStateDao.selectBySerIds(checkProjServices.getId());
 
            for (SysBeauticianState checkbeauticianState : beauticianStateList) {
                // 释放美疗师
                checkbeauticianState.setState(Dictionary.BEATUI_STATE_YYQX);
                beauticianStateDao.update(checkbeauticianState);
            }
            // 回退项目余次
            backProjCount(checkProjServices);
        }
        checkProjServices.setState(Dictionary.SERVICE_STATU_YYQX);
 
        // 删除订单业绩
        AchieveNew achieveNew = new AchieveNew();
        achieveNew.setServiceOrderId(projServices.getId());
        achieveNewService.removeByModel(achieveNew);
 
        //删除出库单
        SysOutStore sysOutStore = sysOutStoreDao.selectByServiceId(projServices.getId());
        if (sysOutStore != null) {
            List<SysOutStoreItem> outStoreItemList = sysOutStoreItemDao.selectByOrderId(sysOutStore.getId());
            for (SysOutStoreItem item : outStoreItemList) {
                SysStoreInfo sysStoreInfo = storeInfoDao.selectById(item.getStoreId());
                ShoppingGoods shoppingGoods = shoppingGoodsDao.selectById(sysStoreInfo.getSkuId());
                sysStoreInfo.setStoreTotal(sysStoreInfo.getStoreTotal() + item.getAmount());
                //更新库存
                storeInfoDao.update(sysStoreInfo);
 
            }
            sysOutStoreDao.deleteById(sysOutStore.getId());
            sysOutStoreItemDao.deleteByOrderId(sysOutStore.getId());
        }
        //删除积分
        scoreVipDetailService.removeByBusinessId(checkProjServices.getVipId(), checkProjServices.getId());
 
        //更新服务单状态
        return sysProjServicesDao.update(checkProjServices);
    }
 
 
    /**
     * @Title: backProjCount  回退项目余次 @author:jyy @param projServices
     * void 返回类型 @date 2016年8月4日 上午11:30:42 @throws
     */
    private void backProjCount(SysProjServices projServices) {
        List<SysBeauticianState> beauticianStateList = beauticianStateDao.selectBySerIds(projServices.getId());
 
        backProjCountItems(beauticianStateList, 1);
    }
 
    private void backProjCountItems(List<SysBeauticianState> beauticianStateList, int type) {
        Map<Long, List<SysProjUse>> taocanMap = new HashMap<>();
        // 回退项目余额
        for (SysBeauticianState beauticianState : beauticianStateList) {
            if (type == 1) {
                // 该修改为 有效日期判断更新所有
                beauticianState.setState(Dictionary.BEATUI_STATE_YYQX);
                beauticianStateDao.update(beauticianState);
            } else {
                beauticianStateDao.deleteById(beauticianState.getId());
            }
 
            SysProjUse sysProjUse = sysProjUseDao.selectById(beauticianState.getPuseId());
            if (sysProjUse != null && sysProjUse.getId() != null) {
                sysProjUse = sysProjUseDao.selectById(sysProjUse.getId());
 
                SysProjUse upProjUse = new SysProjUse();
                upProjUse.setId(sysProjUse.getId());
                // 项目如果已使用完,将使用完成状态改为未使用完
                if (sysProjUse.getSurplusCount() == 0) {
                    upProjUse.setIsOver(Dictionary.DELETED_N);
                    upProjUse.setStatus(Dictionary.MONEYCARD_STATUS_YX);
                }
                int surplus = sysProjUse.getSurplusCount() + beauticianState.getCount();
                upProjUse.setSurplusCount(surplus);
 
                BigDecimal backBlance = new BigDecimal(sysProjUse.getPrice() * beauticianState.getCount());
 
                upProjUse.setBalance(MoneyUtil.add(sysProjUse.getBalance(), backBlance.doubleValue()));
 
 
                if (sysProjUse.getTaocanId() != null) {
                    SysProjUse taocanProjUse = sysProjUseDao.selectById(sysProjUse.getTaocanId());
                    taocanProjUse.setIsOver(Dictionary.DELETED_N);
                    taocanProjUse.setStatus(Dictionary.MONEYCARD_STATUS_YX);
                    taocanProjUse.setBalance(MoneyUtil.add(taocanProjUse.getBalance(), backBlance.doubleValue()));
                    if (Dictionary.FLAG_YES_Y.equals(taocanProjUse.getIsCourse())) {
                        if (StringUtils.isBlank(taocanProjUse.getIsInfinite()) || Dictionary.FLAG_NO_N.equals(taocanProjUse.getIsInfinite())) {
                            taocanProjUse.setSurplusCount(taocanProjUse.getSurplusCount() + beauticianState.getCount());
                        }
                    }
                    sysProjUseDao.update(taocanProjUse);
                }
 
 
                // 取消时,判断该项目之前是否有使用过,若使用过则非第一次使用,则不更新有效日期,若未使用表明此次为第一次使用,则更新有效日期为购买日期或统一失效日期
                List<SysBeauticianState> hasBeautician = beauticianStateDao.selectBeauticianStateByPuseIdAndNoStatus(beauticianState.getPuseId(), Dictionary.BEATUI_STATE_YYQX);
                if (hasBeautician.isEmpty()) {
                    ShoppingGoods shoppingGoods = shoppingGoodsDao.selectById(beauticianState.getProjId());
                    Date useInvalidTime = shoppingGoodsService.calInvalidTime(shoppingGoods, 1, null);
                    upProjUse.setFailTime(useInvalidTime);
                }
 
                if (sysProjUse.getTaocanId() != null) {
                    List<SysProjUse> sysProjUses = taocanMap.get(sysProjUse.getTaocanId());
                    if (CollectionUtils.isEmpty(sysProjUses)) {
                        List<SysProjUse> taocanItems = new ArrayList<>();
                        taocanItems.add(sysProjUse);
                        taocanMap.put(sysProjUse.getTaocanId(), taocanItems);
                    } else {
                        sysProjUses.add(sysProjUse);
                        taocanMap.put(sysProjUse.getTaocanId(), sysProjUses);
                    }
                }
                sysProjUseDao.updateSurplusCount(upProjUse);
            }
        }
 
        if (taocanMap.size() != 0) {
            for (Map.Entry<Long, List<SysProjUse>> entry : taocanMap.entrySet()) {
                List<SysBeauticianState> taocanUse = beauticianStateDao.selectByProjUse(entry.getValue(), Dictionary.BEATUI_STATE_YYQX);
                if (CollectionUtils.isEmpty(taocanUse)) {
                    SysProjUse taocan = sysProjUseDao.selectById(entry.getKey());
                    ShoppingGoods shoppingGoods = shoppingGoodsDao.selectById(taocan.getProjId());
                    Date buyInvalidDate = shoppingGoodsService.calInvalidTime(shoppingGoods, 1, null);
                    taocan.setFailTime(buyInvalidDate);
 
                    sysProjUseDao.update(taocan);
                }
            }
        }
    }
 
    @Override
    public int deleteProjServiceItemById(Long id) {
        SysBeauticianState sysBeauticianState = beauticianStateDao.selectById(id);
        List<SysBeauticianState> list = new ArrayList<>();
        list.add(sysBeauticianState);
 
        backProjCountItems(list, 2);
        return 1;
    }
 
    // 划扣 jyy
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int modifyHKProjServices(SysProjServices projServices) throws GlobleException {
        projServices = sysProjServicesDao.selectById(projServices.getId());
        if (!projServices.getState().equals(Dictionary.SERVICE_STATU_FWWC)) {
            throw new GlobleException("该服务单状态为" + projServices.getState() + ",不可以进行当前操作!");
        } else {
            SysUsers users = WebUtil.getSessionAttribute(MatrixConstance.LOGIN_KEY);
            if (skipServiceOrderStep(Dictionary.SERVICE_OVER_BEGIN_END)) {
                SysBeauticianState checkBeauticianState = new SysBeauticianState();
                checkBeauticianState.setServicesId(projServices.getId());
                checkBeauticianState.setState(Dictionary.BEATUI_STATE_FWJS);
                beauticianStateDao.chengItemState(checkBeauticianState);
 
                // 释放床位资源
                SysBedState checkBedState = sysBedStateDao.selectBySerIdAndBedId(projServices.getId(), projServices.getBedId());
                if (checkBedState != null) {
                    checkBedState.setBedState(Dictionary.BED_STATE_SYJS);
                    bedStateDao.update(checkBedState);
                }
                projServices.setEndTime(new Date());
                // 计算时差
                long minspace = DateUtil.getDifTimeMin(projServices.getStartTime(), projServices.getEndTime()) - projServices.getTotalTime();
                // 判断是服务超时还是服务提前结束,如果minspace大于0则是超时服务,小于0则是提前结束服务
                projServices.setIsOverTime(minspace + "");
                projServices.setState(Dictionary.SERVICE_STATU_FWWC);
                sysProjServicesDao.update(projServices);
            }
 
            projServices.setState(Dictionary.SERVICE_STATU_FFJS);
            projServices.setConsumeTime(new Date());
            int result = sysProjServicesDao.update(projServices);
            achieveNewService.addAchieveByServiceOrder(projServices);
 
            //设置会员积分
            addVipScore(projServices);
 
            //发送微信公众号提醒
            UniformMsgParam uniformMsgParam = new UniformMsgParam(projServices.getCompanyId(), UniformMsgParam.GZH_FWWC);
            uniformMsgParam.put("serviceId", projServices.getId());
            asyncMessageManager.sendMsg(AsyncMessageRouting.SEND_UNIFORM_TEMPLATE_MSG, uniformMsgParam);
            //发送划扣短信提醒
            taiYanAliyunSmsService.sendHkNotice(projServices);
 
            return result;
        }
 
 
    }
 
    /**
     * 设置会员消费积分
     */
    private void addVipScore(SysProjServices projServices) {
 
        SysVipInfo vipInfo = sysVipInfoDao.selectById(projServices.getVipId());
 
        List<SysBeauticianState> sysBeauticianStates = beauticianStateDao.selectBySerIds(projServices.getId());
 
 
        double principalPrice = 0D;
        double giftPrice = 0D;
        for (SysBeauticianState sysBeauticianState : sysBeauticianStates) {
            SysProjUse projUse = sysBeauticianState.getProjUse();
            if (projUse.getSource().equals(Dictionary.TAOCAN_SOURCE_ZS)) {
                giftPrice += projUse.getPrice();
            } else {
                principalPrice += projUse.getPrice();
            }
        }
 
        int[] principalConsumScore = {0, 0, 0};
        BusParameterSettings principalConsumption = busParameterSettingsDao.selectCompanyParamByCode(ScoreSettingConstant.PRINCIPAL_CONSUMPTION, vipInfo.getCompanyId());
        //本金消耗
        if (principalPrice > 0
                && StringUtils.isNotBlank(principalConsumption.getParamValue())) {
 
            principalConsumScore[0] = (int) (principalPrice / Double.parseDouble(principalConsumption.getParamValue()));
 
            if (StringUtils.isNotBlank(principalConsumption.getParamValue1())) {
                principalConsumScore[1] = (int) (principalPrice / Double.parseDouble(principalConsumption.getParamValue1()));
            }
 
            if (StringUtils.isNotBlank(principalConsumption.getParamValue2())) {
                principalConsumScore[2] = (int) (principalPrice / Double.parseDouble(principalConsumption.getParamValue2()));
            }
        }
 
        int[] giveConsumScore = {0, 0, 0};
        BusParameterSettings giveConsumption = busParameterSettingsDao.selectCompanyParamByCode(ScoreSettingConstant.GIVE_CONSUMPTION, vipInfo.getCompanyId());
        //本金消耗
        if (giftPrice > 0
                && StringUtils.isNotBlank(giveConsumption.getParamValue())) {
 
            giveConsumScore[0] = (int) (giftPrice / Double.parseDouble(giveConsumption.getParamValue()));
 
            if (StringUtils.isNotBlank(giveConsumption.getParamValue1())) {
                giveConsumScore[1] = (int) (giftPrice / Double.parseDouble(giveConsumption.getParamValue1()));
            }
 
            if (StringUtils.isNotBlank(giveConsumption.getParamValue2())) {
                giveConsumScore[2] = (int) (giftPrice / Double.parseDouble(giveConsumption.getParamValue2()));
            }
        }
 
        int selfScore = principalConsumScore[0] + giveConsumScore[0];
        int parentScore = principalConsumScore[1] + giveConsumScore[1];
        int topParentScore = principalConsumScore[2] + giveConsumScore[2];
 
        //添加自己的积分
        if (selfScore > 0) {
            scoreVipDetailService.addScore(
                    vipInfo.getId(),
                    projServices.getCreateStaffId(),
                    projServices.getShopId(),
                    selfScore,
                    projServices.getId(),
                    ScoreVipDetail.SCORE_VIP_TYPE_CASH,
                    "消耗奖励"
            );
        }
 
        if (vipInfo.getRecommendId() != null) {
            //推荐注册老带新积分奖励
            SysVipInfo referrerVip = sysVipInfoDao.selectById(vipInfo.getRecommendId());
            if (parentScore > 0) {
                scoreVipDetailService.addScore(
                        referrerVip.getId(),
                        projServices.getCreateStaffId(),
                        projServices.getShopId(),
                        parentScore,
                        projServices.getId(),
                        ScoreVipDetail.SCORE_VIP_TYPE_CASH,
                        "推荐消耗奖励"
                );
            }
            //推荐注册二级带新积分奖励
            if (referrerVip.getRecommendId() != null) {
                SysVipInfo topVipInfo = sysVipInfoDao.selectById(referrerVip.getRecommendId());
                if (topParentScore > 0) {
                    scoreVipDetailService.addScore(
                            topVipInfo.getId(),
                            projServices.getCreateStaffId(),
                            projServices.getShopId(),
                            topParentScore,
                            projServices.getId(),
                            ScoreVipDetail.SCORE_VIP_TYPE_CASH,
                            "推荐消耗奖励"
                    );
                }
            }
        }
    }
 
 
    // 派单 jyy
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int modifyPDProjServices(SysProjServices projServices) throws GlobleException {
 
        SysProjServices services = sysProjServicesDao.selectById(projServices.getId());
        if (!services.getState().equals(Dictionary.SERVICE_STATU_YYCG)) {
            throw new GlobleException("该服务单状态为" + projServices.getState() + ",不可以进行当前操作!");
        } else {
 
            // TODO 更新服务单状态 可配置
            services.setState(Dictionary.SERVICE_STATU_XPL);
            // 派单就设置业绩
            achieveNewService.addAchieveByServiceOrder(projServices);
            return sysProjServicesDao.update(services);
        }
    }
 
    /**
     * 配料
     *
     * @author 姜友瑶
     * @time 2018-08-03
     */
 
 
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int modifyPLProjServices(SysProjServices projServicesVo) throws GlobleException {
        SysProjServices projServices = sysProjServicesDao.selectById(projServicesVo.getId());
        SysUsers sysUsers = WebUtil.getSessionAttribute(MatrixConstance.LOGIN_KEY);
        if (!projServices.getState().equals(Dictionary.SERVICE_STATU_XPL)) {
            throw new GlobleException("该服务单状态为" + projServices.getState() + ",不可以进行当前操作!");
        }
        projServicesVo.setCompanyId(projServices.getCompanyId());
        if (isNeedOutStore(projServicesVo)) {
 
            // 生成出库单
            Long warehouseId = warehouseDao.findShopWarehouse(projServices.getShopId()).get(0).getId();
            SysOutStore outStore = new SysOutStore();
 
            outStore.setOutStoreNo(codeService.getOutStoreCode());
            outStore.setShopId(projServices.getShopId());
            if (projServices.getDevisionId() != null) {
                outStore.setStaffId(projServices.getDevisionId());
            } else {
 
                outStore.setStaffId(sysUsers.getSuId());
            }
            outStore.setServiceId(projServices.getId());
            outStore.setType(Dictionary.OUT_STORE_XHCPCK);
            outStore.setTime(new Date());
            outStore.setCompanyId(projServices.getCompanyId());
            sysOutStoreDao.insert(outStore);
            //出库明细,根据批次维度定义
            List<SysOutStoreItem> realOutStoreItemList = new ArrayList<>();
 
            // 生成出库单明细
            for (SysOutStoreItem item : projServicesVo.getOutStoreItem()) {
                if (item.getAmount() != null && item.getAmount() > 0) {
 
                    SysOutStoreItem sysOutStoreItem = new SysOutStoreItem();
 
 
                    ShoppingGoods shoppingGoods = shoppingGoodsDao.selectById(item.getSkuId());
 
                    List<SysStoreInfo> stores = storeInfoDao.selectStoInfoBySku(item.getSkuId(), warehouseId);
                    double sum = stores.stream().mapToDouble(item2 -> item2.getStoreTotal()).sum();
                    Double needAmount = MoneyUtil.div(item.getAmount(), Double.valueOf(shoppingGoods.getVolume()));
                    if (sum < needAmount) {
                        throw new GlobleException("出库失败:【" + shoppingGoods.getName() + "-" + shoppingGoods.getCode() + "库存不足】");
                    }
                    //循环获取所有批次产品,并扣减库存
                    for (SysStoreInfo storeInfo : stores) {
                        Double oldStoreTotal = storeInfo.getStoreTotal();
                        Double surplus = storeInfo.getStoreTotal() - needAmount;
                        //更新库存
                        storeInfo.setStoreTotal(surplus < 0 ? 0 : surplus);
 
                        item.setId(null);
                        //每次扣减库存都创建一个出库记录
                        BeanUtils.copyProperties(item, sysOutStoreItem);
                        sysOutStoreItem.setOutStoreId(outStore.getId());
                        sysOutStoreItem.setStoreId(storeInfo.getId());
                        sysOutStoreItem.setAmount(oldStoreTotal - storeInfo.getStoreTotal());
                        realOutStoreItemList.add(sysOutStoreItem);
                        storeInfoDao.update(storeInfo);
                        //扣除后剩余库存大于0则跳出扣除,否则剩余数量的负数的绝对值就是再次扣减的数量
                        if (surplus > 0) {
                            break;
                        } else {
                            needAmount = Math.abs(surplus);
                        }
                    }
 
                } else {
                    LogUtil.debug("未选择配料跳过sku={},amount={}", item.getSkuId(), item.getAmount());
                }
            }
            sysOutStoreItemDao.batchInsert(realOutStoreItemList);
        }
        // 设置服务单状态
//        projServices.setState(Dictionary.SERVICE_STATU_PLWC);
 
        if (projServices.getDevisionId() == null) {
            //如果没有设置配料师则默认为操作配料的人为配料师
            projServices.setDevisionId(sysUsers.getSuId());
        }
 
        // 判断是否跳过开始/结束服务
        if (skipServiceOrderStep(Dictionary.SERVICE_OVER_BEGIN_END)) {
            projServices.setStartTime(new Date());
            projServices.setState(Dictionary.SERVICE_STATU_FWWC);
        } else {
            projServices.setState(Dictionary.SERVICE_STATU_PLWC);
        }
        // 释放床位资源
//        SysBedState checkBedState = sysBedStateDao.selectBySerIdAndBedId(projServices.getBedId(), projServices.getId());
//        if (checkBedState != null) {
//            checkBedState.setBedState(Dictionary.BED_STATE_SYJS);
//            bedStateDao.update(checkBedState);
//        }
//        projServices.setStartTime(new Date());
//        projServices.setEndTime(new Date());
//        // 计算时差
//        long minspace = DateUtil.getDifTimeMin(projServices.getStartTime(), projServices.getEndTime())
//                - projServices.getTotalTime();
//        // 判断是服务超时还是服务提前结束,如果minspace大于0则是超时服务,小于0则是提前结束服务
//        projServices.setIsOverTime(minspace + "");
//        projServices.setState(Dictionary.SERVICE_STATU_FWWC);
        return sysProjServicesDao.update(projServices);
    }
 
    /**
     * 服务单收费需要生成出库记录
     *
     * @param projServicesVo
     * @return
     */
    private boolean isNeedOutStore(SysProjServices projServicesVo) {
 
        if (CollectionUtils.isNotEmpty(projServicesVo.getOutStoreItem())) {
            BusParameterSettings manageStockSetting = busParameterSettingsDao.selectCompanyParamByCode(AppConstance.WAREHOUSE_MANAGE_STOCK, projServicesVo.getCompanyId());
            if (AppConstance.IS_Y.equals(manageStockSetting.getParamValue())) {
                for (SysOutStoreItem item : projServicesVo.getOutStoreItem()) {
                    if (item.getAmount() != null && item.getAmount() > 0) {
                        return true;
                    }
                }
            }
        }
        return false;
    }
 
    // 服务开始 jyy
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int modifyFWKSProjServices(SysProjServices projServices) throws GlobleException {
        // 验证操作人
        projServices = sysProjServicesDao.selectById(projServices.getId());
        SysUsers users = (SysUsers) WebUtil.getSession().getAttribute(MatrixConstance.LOGIN_KEY);
        SysBeauticianState checkBeauticianState = null;
 
        List<SysBeauticianState> beauticianStateList = beauticianStateDao.selectBySerIds(projServices.getId());
 
        for (SysBeauticianState beauticianState : beauticianStateList) {
            if (users.getSuId().equals(beauticianState.getStaffId())) {
                checkBeauticianState = beauticianState;
                break;
            }
        }
        if (checkBeauticianState == null) {
            throw new GlobleException("无权限开始服务!");
        }
 
        if ((!projServices.getState().equals(Dictionary.SERVICE_STATU_PLWC)
                && !(projServices.getState().equals(Dictionary.SERVICE_STATU_FWZ)))) {
            throw new GlobleException("该服务单状态为" + projServices.getState() + ",不可以进行当前操作!");
        } else if (projServices.getState().equals(Dictionary.SERVICE_STATU_PLWC)) {
            projServices.setStartTime(new Date());
            projServices.setState(Dictionary.SERVICE_STATU_FWZ);
            sysProjServicesDao.update(projServices);
        }
        // 设置美疗师实际开始时间
        checkBeauticianState.setState(Dictionary.BEATUI_STATE_SYZ);
        projServices.getVipId();
        return beauticianStateDao.update(checkBeauticianState);
    }
 
    // 服务结束 jyy
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int modifyFWJSrojServices(SysProjServices projServices) throws GlobleException {
        SysUsers users = (SysUsers) WebUtil.getSession().getAttribute(MatrixConstance.LOGIN_KEY);
        SysProjServices checkprojServices = sysProjServicesDao.selectById(projServices.getId());
        if (!checkprojServices.getState().equals(Dictionary.SERVICE_STATU_FWZ)) {
            throw new GlobleException("该服务单状态为" + checkprojServices.getState() + ",不可以进行当前操作!");
        }
        SysBeauticianState checkBeauticianState = new SysBeauticianState();
        checkBeauticianState.setServicesId(projServices.getId());
        checkBeauticianState.setState(Dictionary.BEATUI_STATE_FWJS);
        int rerunlt = beauticianStateDao.chengItemState(checkBeauticianState);
 
        // 验证是否是最后一个美疗师结束服务
        boolean isOver = true;
        List<SysBeauticianState> beauticianStateList = beauticianStateDao.selectBySerIds(checkprojServices.getId());
        for (SysBeauticianState beauticianState : beauticianStateList) {
            if (!beauticianState.getState().equals(Dictionary.BEATUI_STATE_FWJS)) {
                isOver = false;
                break;
            }
        }
        if (isOver) {
            // 释放床位资源
            SysBedState checkBedState = sysBedStateDao.selectBySerIdAndBedId(checkprojServices.getBedId(), checkprojServices.getId());
            if (checkBedState != null) {
                checkBedState.setBedState(Dictionary.BED_STATE_SYJS);
                bedStateDao.update(checkBedState);
            }
            checkprojServices.setEndTime(new Date());
            // 计算时差
            long minspace = DateUtil.getDifTimeMin(checkprojServices.getStartTime(), checkprojServices.getEndTime())
                    - checkprojServices.getTotalTime();
            // 判断是服务超时还是服务提前结束,如果minspace大于0则是超时服务,小于0则是提前结束服务
            checkprojServices.setIsOverTime(minspace + "");
            checkprojServices.setState(Dictionary.SERVICE_STATU_FWWC);
            sysProjServicesDao.update(checkprojServices);
        }
 
        return rerunlt;
    }
 
    @Override
    public List<SysProjServices> findInPage(SysProjServices sysProjServices, PaginationVO pageVo) {
        return sysProjServicesDao.selectInPage(sysProjServices, pageVo);
    }
 
    @Override
    public int findTotal(SysProjServices sysProjServices) {
 
        return sysProjServicesDao.selectTotalRecord(sysProjServices);
 
    }
 
    @Override
    public List<ServiceOrderListVo> findApiServiceOrderListInPage(ServiceOrderListDto serviceOrderListDto, PaginationVO pageVo) {
        return sysProjServicesDao.selectApiServiceOrderListInPage(serviceOrderListDto, pageVo);
    }
 
    @Override
    public int findApiServiceOrderListTotal(ServiceOrderListDto serviceOrderListDto) {
        return sysProjServicesDao.selectApiServiceOrderListTotal(serviceOrderListDto);
    }
 
    /**
     * 跳过服务单某步骤
     */
    @Override
    public boolean skipServiceOrderStep(String step) {
        SysUsers users = (SysUsers) WebUtil.getSession().getAttribute(MatrixConstance.LOGIN_KEY);
        ParameterSettings ps = new ParameterSettings();
        ps.setCompanyId(users.getCompanyId());
        ps.setCategory("店务配置");
        List<ParameterSettings> settings = parameterSettingsDao.getByCategory(ps);
 
        boolean flag = false;
        if (CollUtil.isNotEmpty(settings)) {
            for (ParameterSettings setting : settings) {
                if (step.equals(setting.getCode()) && Dictionary.FLAG_YES.equals(setting.getUserValue())) {
                    flag = true;
                    break;
                }
            }
        }
 
        return flag;
    }
 
 
    @Override
    public int confirmServiceOrder(Long id) {
        SysProjServices services = new SysProjServices();
        services.setId(id);
        services.setState(Dictionary.BEATUI_STATE_DYY);
        int i = modify(services);
        if (i > 0) {
            //发送微信公众号提醒
            services = findById(services.getId());
            UniformMsgParam uniformMsgParam = new UniformMsgParam(services.getCompanyId(), UniformMsgParam.GZH_YYCG);
            uniformMsgParam.put("serviceId", services.getId());
            asyncMessageManager.sendMsg(AsyncMessageRouting.SEND_UNIFORM_TEMPLATE_MSG, uniformMsgParam);
 
            taiYanAliyunSmsService.sendYycgNotice(services);
 
 
        }
        return i;
    }
 
 
}