ANDRU-PC\Andru
2023-09-14 fd9b0cb657b4712c733288cfb37716e4c3a9b6a8
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
package com.hx.phip.controller.consultation;
 
 
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hx.common.BaseController;
import com.hx.common.service.CommonService;
import com.hx.guide.model.VisitRecord;
import com.hx.mybatis.aes.springbean.VariableAesKey;
import com.hx.mybatisTool.SqlSentence;
import com.hx.phiappt.constants.tool.PageUtil;
import com.hx.phiappt.dao.mapper.ConsultationRecommendedProjectMapper;
import com.hx.phiappt.dao.mapper.DeductionJoinMapper;
import com.hx.phiappt.dao.mapper.UserProjectItemMapper;
import com.hx.phiappt.model.BaseEntity;
import com.hx.phiappt.model.ConsultationRecord;
import com.hx.phiappt.model.Employee;
import com.hx.phiappt.model.User;
import com.hx.phip.dao.mapper.*;
import com.hx.phip.service.SystemParameterService;
import com.hx.phip.service.consultation.ConsultationRecordService;
import com.hx.util.StringUtils;
import com.hz.his.dto.consultation.ConsultRecordDto;
import com.platform.exception.PlatTipsException;
import com.platform.resultTool.PlatformCode;
import com.platform.resultTool.PlatformResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
 
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
/**
 * 咨询记录
 */
@Slf4j
@RestController
@RequestMapping("/consultation/record")
public class ConsultationRecordController extends BaseController {
 
    @Resource
    private ConsultationRecordService consultationRecordService;
    @Resource
    private SystemParameterService systemParameterService;
 
    /**
     * 新增
     */
    @RequestMapping(value = "/add/or/edit", method = RequestMethod.POST)
    public PlatformResult addOrEditData(@RequestBody(required = false) ConsultRecordDto consultRecordDto) {
        //参数校验
        checkParams(consultRecordDto);
 
        if (!StringUtils.isEmpty(consultRecordDto.getId())) {
            ConsultationRecord consultationRecord = commonService.selectOneByKey(ConsultationRecordMapper.class, consultRecordDto.getId());
            if (consultationRecord == null) {
                throw new PlatTipsException(PlatformCode.ERROR_TIPS, "找不到咨询记录!");
            }
        }
 
        String id = consultationRecordService.insertOrEdit(consultRecordDto, systemParameterService, commonService);
        JSONObject data = new JSONObject();
        data.put("id", id);
        return PlatformResult.success(data);
    }
 
 
    /**
     * 详情
     */
    @RequestMapping(value = "/detail", method = RequestMethod.POST)
    public PlatformResult detail(@RequestBody(required = false) ConsultRecordDto consultRecordDto) {
 
        if (StringUtils.isEmpty(consultRecordDto.getId())) {
            throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "id为空");
        }
 
        ConsultationRecord consultationRecord = commonService.selectOneByKey(ConsultationRecordMapper.class, consultRecordDto.getId());
        if (consultationRecord == null) {
            throw new PlatTipsException(PlatformCode.ERROR_TIPS, "找不到咨询记录!");
        }
 
        BeanUtils.copyProperties(consultationRecord, consultRecordDto);
 
        SqlSentence sqlSentence = new SqlSentence();
        StringBuffer sql = new StringBuffer();
        Map<String, Object> values = new HashMap<>();
        sqlSentence.setM(values);
 
        values.put("isDel", BaseEntity.NO);
        values.put("consultationRecordId", consultationRecord.getId());
        values.put("userId", consultationRecord.getUserId());
 
        // 推荐项目列表
        sql.append("SELECT crp.projectId,crp.projectName FROM `consultation_recommended_project` AS crp LEFT JOIN project AS pro ON pro.id=crp.projectId WHERE  crp.userId=#{m.userId} AND crp.consultationRecordId =#{m.consultationRecordId} AND crp.isDel=#{m.isDel}");
        sqlSentence.setSqlSentence(sql.toString());
        List<Map<String, Object>> recommendedProjectList = commonService.selectListMap(ConsultationRecommendedProjectMapper.class, sqlSentence);
        consultRecordDto.setRecommendProjectList(recommendedProjectList);
 
        // 治疗项目
        sql.delete(0, sql.length());
        sql.append("SELECT crp.projectId,crp.projectName FROM `consultation_treat_project` AS crp LEFT JOIN project AS pro ON pro.id=crp.projectId WHERE  crp.userId=#{m.userId} AND crp.consultationRecordId =#{m.consultationRecordId} AND crp.isDel=#{m.isDel}");
        sqlSentence.setSqlSentence(sql.toString());
        List<Map<String, Object>> treatProjectList = commonService.selectListMap(ConsultationTreatProjectMapper.class, sqlSentence);
        consultRecordDto.setTreatProjectList(treatProjectList);
 
        //面诊医生
        Employee faceEmp = commonService.selectOneByKey(EmployeeMapper.class, consultRecordDto.getFaceDoctorId());
        consultRecordDto.setFaceDoctorName(faceEmp == null ? null : faceEmp.getCnName());
 
        //治疗医生
        Employee treatEmp = commonService.selectOneByKey(EmployeeMapper.class, consultRecordDto.getTreatDoctorId());
        consultRecordDto.setTreatDoctorName(treatEmp == null ? null : treatEmp.getCnName());
 
        //查询用户顾问名称
        User user = commonService.selectOneByKey(UserMapper.class, consultRecordDto.getUserId());
        if (user != null) {
            if (!StringUtils.isEmpty(user.getHisCorpUserId())) {
                Employee corpEmp = commonService.selectOneByKey(EmployeeMapper.class, user.getHisCorpUserId());
                consultRecordDto.setHisCorpUserName(corpEmp == null ? null : corpEmp.getCnName());
            }
            //手机号
            if(StringUtils.isEmpty(user.getTel()) || user.getTel().equals("测试服不存")) {
                consultRecordDto.setTel("-");
            }else {
                consultRecordDto.setTel(user.getTel().substring(0, 3) + "****" + user.getTel().substring(7));
            }
        }
 
        //返回基本信息
//        if (StringUtils.isEmpty(consultRecordDto.getContent())) {
//            sql.delete(0, sql.length());
//            sql.append(" select * from consultation_record where isDel = 0 and id!= #{m.consultationRecordId} and userId = #{m.userId} order by createTime desc limit 1 ");
//            sqlSentence.setSqlSentence(sql.toString());
//            ConsultationRecord consultContent = commonService.selectOne(ConsultationRecordMapper.class, sqlSentence);
//            consultRecordDto.setContent(consultContent != null ? consultContent.getContent() : null);
//        }
 
        //非初复诊返回下面的值
        if (consultRecordDto.getConsultType() >= 2) {
            if (StringUtils.isEmpty(consultRecordDto.getLastTreatDoctorId())) {
                //为空 查询上一次的咨询记录的数据 拿到咨询医生 ID、名称
                Map<String, Object> lastDetail = lastDetail(consultRecordDto.getUserId(), consultRecordDto.getId(),1);
                if (lastDetail != null) {
                    if (lastDetail.containsKey("treatDoctorId") && lastDetail.get("treatDoctorId") != null && !StringUtils.isEmpty(lastDetail.get("treatDoctorId").toString())) {
                        consultRecordDto.setLastTreatDoctorId(lastDetail.get("treatDoctorId").toString());
                    }
 
                    if (lastDetail.containsKey("treatDoctorName") && lastDetail.get("treatDoctorName") != null && !StringUtils.isEmpty(lastDetail.get("treatDoctorName").toString()))
                        consultRecordDto.setLastTreatDoctorName(lastDetail.get("treatDoctorName").toString());
                }
            } else {
                //不为空 则拿取当前的数据
                consultRecordDto.setLastTreatDoctorId(consultationRecord.getLastTreatDoctorId());
                Employee docEmp = commonService.selectOneByKey(EmployeeMapper.class, consultationRecord.getLastTreatDoctorId());
                consultRecordDto.setLastTreatDoctorName(docEmp.getCnName());
            }
 
            List<Map<String, Object>> lastTreatProjectList;
            //为空 查询上一次的咨询记录的数据 拿到上一条记录存储的治疗项目数据
            if (StringUtils.isEmpty(consultRecordDto.getLastTreatProjects())
                    || "[]".equals(consultRecordDto.getLastTreatProjects())
                    || "null".equals(consultRecordDto.getLastTreatProjects())) {
 
                Map<String, Object> lastDetail = lastDetail(consultRecordDto.getUserId(), consultRecordDto.getId(),1);
                if (lastDetail.containsKey("lastTreatProject")
                        && lastDetail.get("lastTreatProject") != null
                        && !StringUtils.isEmpty(lastDetail.get("lastTreatProject").toString())
                        && !"[]".equals(lastDetail.get("lastTreatProject").toString())
                        && !"null".equals(lastDetail.get("lastTreatProject").toString())) {
                    lastTreatProjectList = JSON.parseObject(JSON.toJSONString(lastDetail.get("lastTreatProject")), new TypeReference<List<Map<String, Object>>>() {
                    });
                    consultRecordDto.setLastTreatProjectList(lastTreatProjectList);
                }
            } else {
                //不为空 则拿取当前存储的上一次治疗项目数据
                lastTreatProjectList = JSON.parseObject(consultRecordDto.getLastTreatProjects(), new TypeReference<List<Map<String, Object>>>() {
                });
                consultRecordDto.setLastTreatProjectList(lastTreatProjectList);
            }
        }
 
        JSONObject data = new JSONObject();
        consultRecordDto.setLastTreatProjects(null);
        data.put("info", consultRecordDto);
 
        return PlatformResult.success(data);
 
    }
 
 
    /**
     * 删除
     */
    @RequestMapping(value = "/del", method = RequestMethod.POST)
    public PlatformResult del(@RequestBody(required = false) ConsultRecordDto consultRecordDto) {
 
        if (StringUtils.isEmpty(consultRecordDto.getId())) {
            throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "id为空");
        }
 
        ConsultationRecord consultationRecord = commonService.selectOneByKey(ConsultationRecordMapper.class, consultRecordDto.getId());
        if (consultationRecord == null) {
            throw new PlatTipsException(PlatformCode.ERROR_TIPS, "找不到咨询记录!");
        }
 
 
        SqlSentence sqlSentence = new SqlSentence();
        Map<String, Object> values = new HashMap<>();
        sqlSentence.setM(values);
 
        values.put("isDel", BaseEntity.NO);
        values.put("consultationRecordId", consultationRecord.getId());
 
        sqlSentence.setSqlSentence(" isDel = #{m.isDel} where id = #{m.consultationRecordId} and isDel = 0 ");
        commonService.updateWhere(ConsultationRecordMapper.class, sqlSentence);
 
        return PlatformResult.success();
 
    }
 
 
    /**
     * 列表
     */
    @RequestMapping(value = "/user/list", method = RequestMethod.POST)
    public PlatformResult list(@RequestBody(required = false) ConsultRecordDto consultRecordDto) {
 
        if (consultRecordDto == null) {
            throw new PlatTipsException(PlatformCode.ERROR_BODY_DATA, "数据参数为空");
        }
 
//        if (StringUtils.isEmpty(consultRecordDto.getUserId())) {
//            throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "用户ID为空");
//        }
 
        SqlSentence sqlSentence = new SqlSentence();
        StringBuffer sql = new StringBuffer();
        Map<String, Object> values = new HashMap<>();
        sqlSentence.setM(values);
        values.put("key", VariableAesKey.AES_KEY);
 
        sql.append(" select cr.*, u.CIQ, f.cnName AS faceDoctorName ,t.cnName AS treatDoctorName,s.name as shopName,u.name as userName ");
        sql.append(" ,insert(CONVERT(AES_DECRYPT(UNHEX(u.tel), #{m.key}) , CHAR), 4, 4, '****') as tel");
        sql.append(" ,uStatistics.recentVisitType,uStatistics.recentVisitStatus,uStatistics.isMakeADeal");
        sql.append(" FROM consultation_record cr ");
        sql.append(" LEFT JOIN user u ON cr.userId = u.id ");
        sql.append(" LEFT JOIN employee f ON cr.faceDoctorId = f.id");
        sql.append(" LEFT JOIN employee t ON cr.treatDoctorId = t.id ");
        sql.append(" LEFT JOIN shop s on cr.shopId = s.id ");
        sql.append(" LEFT JOIN user_statistics AS uStatistics ON uStatistics.userId = cr.userId ");
        sql.append(" WHERE cr.isDel = 0 ");
 
        // 咨询方式代码查找
        if (!StringUtils.isEmpty(consultRecordDto.getMethodCode())) {
            sql.append(" AND cr.methodCode=#{m.methodCode}");
            values.put("methodCode", consultRecordDto.getMethodCode());
        }
 
        //用户搜索
        if (!StringUtils.isEmpty(consultRecordDto.getUserId())) {
            values.put("userId", consultRecordDto.getUserId());
            sql.append(" and cr.userId = #{m.userId} ");
        }
 
        //时间搜索
        if (!StringUtils.isEmpty(consultRecordDto.getStartTime())) {
            values.put("startTime", consultRecordDto.getStartTime() + "00:00:00");
            sql.append(" and cr.createTime >= #{m.startTime} ");
        }
        if (!StringUtils.isEmpty(consultRecordDto.getEndTime())) {
            sql.append(" and cr.createTime <= #{m.endTime} ");
            values.put("endTime", consultRecordDto.getEndTime() + "23:59:59");
        }
 
        // 用户名查找
        if (!StringUtils.isEmpty(consultRecordDto.getUserName())) {
            sql.append(" AND (u.name LIKE #{m.userName} OR u.tel LIKE #{m.userName} OR u.CIQ LIKE #{m.userName} OR u.memberNO LIKE #{m.userName})");
            values.put("userName", "%" + consultRecordDto.getUserName() + "%");
        }
 
        // 关键字搜索
        if (!StringUtils.isEmpty(consultRecordDto.getKeyWord())) {
            sql.append(" AND (cr.content LIKE #{m.keyWord} OR cr.description LIKE #{m.keyWord} OR cr.remark LIKE #{m.keyWord})");
            values.put("keyWord", "%" + consultRecordDto.getKeyWord() + "%");
        }
 
        // 咨询师
        if (!StringUtils.isEmpty(consultRecordDto.getHisCorpUserId())) {
            sql.append(" AND u.hisCorpUserId=#{m.hisCorpUserId}");
            values.put("hisCorpUserId", consultRecordDto.getHisCorpUserId());
        }
 
        // 电网咨询师
        if (!StringUtils.isEmpty(consultRecordDto.getInternetCorpUserId())) {
            sql.append(" AND u.internetCorpUserId=#{m.internetCorpUserId}");
            values.put("internetCorpUserId", consultRecordDto.getInternetCorpUserId());
        }
 
        // 客服
        if (!StringUtils.isEmpty(consultRecordDto.getChatCorpUserId())) {
            sql.append(" AND u.chatCorpUserId=#{m.chatCorpUserId}");
            values.put("chatCorpUserId", consultRecordDto.getChatCorpUserId());
        }
 
        // 创建人
        if (!StringUtils.isEmpty(consultRecordDto.getCreateEmployeeId())) {
            sql.append(" AND cr.adminId=#{m.createEmployeeId}");
            values.put("createEmployeeId", consultRecordDto.getCreateEmployeeId());
        }
 
        // 创建人部门
        if (!StringUtils.isEmpty(consultRecordDto.getCreateEmployeePartId())) {
            // 根据部门查询数据
            String employeePartQuery = handlerAppendQuery("cr.adminId", consultRecordDto.getCreateEmployeePartId(), 1);
            // 判断是否有查询数据
            if (!StringUtils.isEmpty(employeePartQuery)) {
                sql.append(employeePartQuery);
            } else {
                // 未查询到数据处理
                sql.append(" AND cr.adminId=''");
            }
        }
 
        // 关注活动
        if (!StringUtils.isEmpty(consultRecordDto.getFocusActivityId())) {
            // 根据关注活动查询数据
            String employeePartQuery = handlerAppendQuery("cr.id", consultRecordDto.getFocusActivityId(), 2);
            // 判断是否有查询数据
            if (!StringUtils.isEmpty(employeePartQuery)) {
                sql.append(employeePartQuery);
            } else {
                // 未查询到数据处理
                sql.append(" AND cr.id=''");
            }
        }
 
        // 推荐项目
        if (!StringUtils.isEmpty(consultRecordDto.getRecommendProjectIds())) {
            // 根据推荐项目查询数据
            String employeePartQuery = handlerAppendQuery("cr.id", consultRecordDto.getRecommendProjectIds(), 5);
            // 判断是否有查询数据
            if (!StringUtils.isEmpty(employeePartQuery)) {
                sql.append(employeePartQuery);
            } else {
                // 未查询到数据处理
                sql.append(" AND cr.id=''");
            }
        }
 
        // 治疗项目
        if (!StringUtils.isEmpty(consultRecordDto.getTreatProjectIds())) {
            // 根据推荐项目查询数据
            String employeePartQuery = handlerAppendQuery("cr.id", consultRecordDto.getTreatProjectIds(), 6);
            // 判断是否有查询数据
            if (!StringUtils.isEmpty(employeePartQuery)) {
                sql.append(employeePartQuery);
            } else {
                // 未查询到数据处理
                sql.append(" AND cr.id=''");
            }
        }
 
        // 客户来源一级渠道
        if (!StringUtils.isEmpty(consultRecordDto.getChannelId())) {
            sql.append(" AND u.channelId = #{m.channelId} ");
            values.put("channelId", consultRecordDto.getChannelId());
        }
 
        // 客户来源二级渠道
        if (!StringUtils.isEmpty(consultRecordDto.getChannel2Id())) {
            sql.append(" AND u.channel2Id = #{m.channel2Id} ");
            values.put("channel2Id", consultRecordDto.getChannel2Id());
        }
 
 
        // 到访类型
        if (!StringUtils.isEmpty(consultRecordDto.getRecentVisitType())) {
            sql.append(" AND uStatistics.recentVisitType = #{m.recentVisitType} ");
            values.put("recentVisitType", consultRecordDto.getRecentVisitType());
        }
 
        // 到访状态
        if (consultRecordDto.getRecentVisitStatus() != null) {
            sql.append(" AND uStatistics.recentVisitStatus = #{m.recentVisitStatus} ");
            values.put("recentVisitStatus", consultRecordDto.getRecentVisitStatus());
        }
 
        // 是否成交
        if (consultRecordDto.getIsMakeADeal() != null) {
            sql.append(" AND uStatistics.isMakeADeal = #{m.isMakeADeal} ");
            values.put("isMakeADeal", consultRecordDto.getIsMakeADeal());
        }
 
        // 是否草稿
        if (consultRecordDto.getIsDraft() != null) {
            sql.append(" AND cr.isDraft = #{m.isDraft} ");
            values.put("isDraft", consultRecordDto.getIsDraft());
        }
 
        // 门店查找
        if (!StringUtils.isEmpty(consultRecordDto.getShopId())) {
            sql.append(" and cr.shopId=#{m.shopId}");
            values.put("shopId", consultRecordDto.getShopId());
        }
 
        sql.append(" group by cr.id ");
        sqlSentence.setSqlSentence(sql.toString());
        PageHelper.startPage(consultRecordDto.getPageNum(), consultRecordDto.getPageSize(), " cr.createTime desc ");
        List<Map<String, Object>> consultationRecordList = commonService.selectListMap(ConsultationRecordMapper.class, sqlSentence);
 
        sql.delete(0, sql.length());
        sql.append(" select * from consultation_treat_project where consultationRecordId = #{m.recordId} and isDel = 0  ");
        if (consultationRecordList != null && consultationRecordList.size() > 0) {
            consultationRecordList.forEach(c -> {
                values.put("recordId", c.get("id"));
                sqlSentence.setSqlSentence(sql.toString());
                List<Map<String, Object>> treatProjectList = commonService.selectListMap(ConsultationTreatProjectMapper.class, sqlSentence);
                c.put("treatProjectList", treatProjectList);
            });
        }
 
        sql.delete(0, sql.length());
        sql.append(" select * from consultation_recommended_project where consultationRecordId = #{m.recordId} and isDel = 0  ");
        if (consultationRecordList != null && consultationRecordList.size() > 0) {
            consultationRecordList.forEach(c -> {
                values.put("recordId", c.get("id"));
                sqlSentence.setSqlSentence(sql.toString());
                List<Map<String, Object>> recommendedProjectList = commonService.selectListMap(ConsultationTreatProjectMapper.class, sqlSentence);
                c.put("recommendedProjectList", recommendedProjectList);
            });
        }
 
        PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(consultationRecordList);
        return PlatformResult.success(pageInfo);
 
    }
 
    /**
     * 获取上一次的信息
     */
    @RequestMapping(value = "/last/detail", method = RequestMethod.POST)
    public PlatformResult lastDetail(@RequestBody(required = false) ConsultRecordDto consultRecordDto) {
 
        if (consultRecordDto == null) {
            throw new PlatTipsException(PlatformCode.ERROR_BODY_DATA, "数据参数为空");
        }
 
        if (StringUtils.isEmpty(consultRecordDto.getUserId())) {
            throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "用户ID为空");
        }
 
        JSONObject data = new JSONObject();
        data.put("lastInfo", lastDetail(consultRecordDto.getUserId(), null,0));
 
        return PlatformResult.success(data);
 
    }
 
 
    /**
     * 本次治疗项目或者 上次治疗项目下拉使用 已划扣执行的项目列表
     */
    @RequestMapping("/deduction/project/list")
    public PlatformResult deductionProjectList(@RequestBody(required = false) ConsultRecordDto consultRecordDto) {
 
        if (consultRecordDto == null) {
            throw new PlatTipsException(PlatformCode.ERROR_BODY_DATA, "数据参数为空");
        }
 
        if (StringUtils.isEmpty(consultRecordDto.getUserId())) {
            throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "用户ID为空");
        }
 
        PageHelper.startPage(PageUtil.getPageNum(consultRecordDto.getPageNum()),PageUtil.getPageSize(consultRecordDto.getPageSize()));
        List<Map<String, Object>> list = deductionProjectList(consultRecordDto.getUserId(),consultRecordDto.getUseType(), commonService);
        PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(list);
 
        return PlatformResult.success(pageInfo);
 
    }
 
 
    //////////////////////////////////////////////////////
 
 
    //封装获取上一次咨询的 治疗医生 治疗项目
    public Map<String, Object> lastDetail(String userId, String detailId,Integer isInfo) {
 
        SqlSentence sqlSentence = new SqlSentence();
        StringBuffer sql = new StringBuffer();
        Map<String, Object> values = new HashMap<>();
        sqlSentence.setM(values);
        values.put("userId", userId);
        ConsultationRecord consultationRecord;
 
        if (!StringUtils.isEmpty(detailId) && isInfo!= null && isInfo == 1) {
            values.put("id", detailId);
            sql.delete(0, sql.length());
            sql.append(" select * from consultation_record where isDel = 0 and userId = #{m.userId} and id!= #{m.id} order by createTime desc limit 1 ");
            sqlSentence.setSqlSentence(sql.toString());
            consultationRecord = commonService.selectOne(ConsultationRecordMapper.class, sqlSentence);
        }else {
            sql.delete(0, sql.length());
            sql.append(" select * from consultation_record where isDel = 0 and userId = #{m.userId} order by createTime desc limit 1 ");
            sqlSentence.setSqlSentence(sql.toString());
            consultationRecord = commonService.selectOne(ConsultationRecordMapper.class, sqlSentence);
        }
 
        Map<String, Object> data = new HashMap<>();
        if (consultationRecord != null) {
            values.put("isDel", BaseEntity.NO);
            values.put("consultationRecordId", consultationRecord.getId());
 
            //治疗医生
            Employee docEmp = commonService.selectOneByKey(EmployeeMapper.class, consultationRecord.getTreatDoctorId());
            data.put("treatDoctorName", docEmp == null ? null : docEmp.getCnName());
            data.put("treatDoctorId", docEmp == null ? null : docEmp.getId());
 
            //面诊医生
            Employee faceEmp = commonService.selectOneByKey(EmployeeMapper.class, consultationRecord.getFaceDoctorId());
            data.put("faceDoctorName", faceEmp == null ? null : faceEmp.getCnName());
            data.put("faceDoctorId", faceEmp == null ? null : faceEmp.getId());
 
            //基本信息
//            data.put("content", consultationRecord.getContent());
 
            List<Map<String, Object>> lastTreatProject;
            if( !StringUtils.isEmpty(consultationRecord.getLastTreatProjects())
                    && !"[]".equals(consultationRecord.getLastTreatProjects())
                    && !"null".equals(consultationRecord.getLastTreatProjects())){
                // 治疗项目
                lastTreatProject = JSON.parseObject(consultationRecord.getLastTreatProjects(), new TypeReference<List<Map<String, Object>>>() {
                });
                data.put("lastTreatProject", lastTreatProject);
            } else {
                sql.delete(0, sql.length());
                sql.append("SELECT crp.projectId as id ,crp.projectName as name FROM `consultation_treat_project` AS crp LEFT JOIN project AS pro ON pro.id=crp.projectId WHERE  crp.userId=#{m.userId} AND crp.consultationRecordId =#{m.consultationRecordId} AND crp.isDel=#{m.isDel}");
                sqlSentence.setSqlSentence(sql.toString());
                lastTreatProject = commonService.selectListMap(ConsultationTreatProjectMapper.class, sqlSentence);
                data.put("lastTreatProject", lastTreatProject);
            }
        } else {
            //治疗医生
            VisitRecord visitRecord = visitRecordInfo(userId);
            if (visitRecord != null) {
                data.put("treatDoctorName", StringUtils.isEmpty(visitRecord.getDoctorName()) ? null : visitRecord.getDoctorName());
                data.put("treatDoctorId", StringUtils.isEmpty(visitRecord.getDoctorId()) ? null : visitRecord.getDoctorId());
            }
 
            //面诊医生 参与人员是多个时 拿取第一个数据作为面诊医生
            List<Map<String, Object>> deductionList = deductionProjectList(userId,null, commonService);
            if (deductionList != null && deductionList.size() != 0) {
                Map<String, Object> deductionJsonEmp = deductionJsonEmp(deductionList.get(0).get("deductionSingleId").toString());
                if (deductionJsonEmp != null) {
                    if (deductionJsonEmp.containsKey("employeeId") && !StringUtils.isEmpty(deductionJsonEmp.get("employeeId").toString())) {
                        data.put("faceDoctorId", deductionJsonEmp.get("employeeId"));
                    }
                    if (deductionJsonEmp.containsKey("employeeName") && !StringUtils.isEmpty(deductionJsonEmp.get("employeeName").toString())) {
                        data.put("faceDoctorName", deductionJsonEmp.get("employeeName"));
                    }
                }
            }
        }
        return data;
    }
 
 
    /**
     * 参数校验
     */
    public void checkParams(ConsultRecordDto consultRecordDto) {
 
        if (consultRecordDto == null) {
            throw new PlatTipsException(PlatformCode.ERROR_BODY_DATA, "数据参数为空");
        }
 
        if (consultRecordDto.getSatisfie() == null) {
            throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "满意度为空");
        }
 
        if (StringUtils.isEmpty(consultRecordDto.getUserId())) {
            throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "用户ID为空");
        }
 
        if (StringUtils.isEmpty(consultRecordDto.getFaceDoctorId())) {
            throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "面诊医生为空");
        }
 
        if (consultRecordDto.getConsultType() == null) {
            throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "咨询类型为空");
        }
 
        if (consultRecordDto.getConsultType() == 1) {
            if (StringUtils.isEmpty(consultRecordDto.getAppealDetail())) {
                throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "主要诉求为空");
            }
 
            if (StringUtils.isEmpty(consultRecordDto.getTreatPlanQuote())) {
                throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "治疗方案&报价为空");
            }
 
            if (StringUtils.isEmpty(consultRecordDto.getRecommendProjectIds())) {
                throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "推荐项目为空");
            }
        }
 
        if (consultRecordDto.getConsultType() == 2) {
            if (StringUtils.isEmpty(consultRecordDto.getFacePlan())) {
                throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL, "面诊方案为空");
            }
        }
    }
 
 
    /**
     * 处理多个条件查询 拼接Sql
     **/
    private String handlerAppendQuery(String fieldName, String keyId, Integer type) {
        SqlSentence sqlSentence = new SqlSentence();
        Map<String, Object> sqlValue = new HashMap<>();
        sqlValue.put("isDel", BaseEntity.NO);
        sqlValue.put("keyId", keyId);
        String sql = "";
        String getId = "";
        if (type == 1) {
            // 根据部门名称查询
            sql = "SELECT DISTINCT empl.id FROM employee AS empl LEFT JOIN employee_role AS erole ON erole.employeeId=empl.id  " +
                    "WHERE empl.isDel=#{m.isDel} AND erole.departmentId=#{m.keyId}";
            getId = "id";
        } else if (type == 2) {
            // 根据关注活动查询
            sql = "SELECT DISTINCT consultationRecordId FROM `consultation_focus_activity` WHERE activityId =#{m.keyId} AND isDel=#{m.isDel}";
            getId = "consultationRecordId";
        }
//        else if(type == 3){
//            // 根据咨询项目类别查询
//            sql = "SELECT DISTINCT consultationRecordId FROM `consultation_needed_project` WHERE projectTypeId =#{m.keyId} AND isDel=#{m.isDel}";
//            getId = "consultationRecordId";
//        } else if(type == 4){
//            // 根据潜在项目类别查询
//            sql = "SELECT DISTINCT consultationRecordId FROM `consultation_potential_project` WHERE projectTypeId =#{m.keyId} AND isDel=#{m.isDel}";
//            getId = "consultationRecordId";
//        }
        else if (type == 5) {
            // 根据推荐项目查询
            sql = "SELECT DISTINCT consultationRecordId FROM `consultation_recommended_project` WHERE projectId =#{m.keyId} AND isDel=#{m.isDel}";
            getId = "consultationRecordId";
        } else if (type == 6) {
            // 根据治疗项目查询
            sql = "SELECT DISTINCT consultationRecordId FROM `consultation_treat_project` WHERE projectId =#{m.keyId} AND isDel=#{m.isDel}";
            getId = "consultationRecordId";
        }
        sqlSentence.sqlSentence(sql, sqlValue);
        List<Map<String, Object>> mapList = commonService.selectListMap(com.hx.phiappt.dao.mapper.EmployeeMapper.class, sqlSentence);
        if (mapList != null && mapList.size() > 0) {
            StringBuilder sqlBuilder = new StringBuilder();
            sqlBuilder.append(" and ").append(fieldName).append(" in ( ");
            for (Map<String, Object> mapInfo : mapList) {
                if (mapInfo != null) {
                    sqlBuilder.append("'").append(mapInfo.get(getId)).append("'").append(",");
                }
            }
            sqlBuilder.delete(sqlBuilder.length() - 1, sqlBuilder.length());
            sqlBuilder.append(")");
            return sqlBuilder.toString();
        }
        return null;
    }
 
 
    /**
     * 已执行划扣的项目
     **/
    public static List<Map<String, Object>> deductionProjectList(String userId,String useType, CommonService commonService) {
        SqlSentence sqlSentence = new SqlSentence();
        Map<String, Object> values = new HashMap<>();
        sqlSentence.setM(values);
        values.put("userId", userId);
 
        StringBuffer sql = new StringBuffer();
        sql.append(" SELECT dp.deductionSingleId,p.id,p.name,p.specification ");
 
        if(!StringUtils.isEmpty(useType) && useType.equals("admin")){
            sql.append(" ,p.unit,p.treatmentItemsNum AS courseCount,p.category,p.price,p.originalPrice,p.coding");
        }
 
        sql.append(" FROM user_project_item upi ");
        sql.append(" LEFT JOIN user_project up ON up.id = upi.userProjectId ");
        sql.append(" LEFT JOIN USER us ON us.id = upi.userId ");
        sql.append(" LEFT JOIN deduction_project dp ON upi.id = dp.userProjectItemId ");
        sql.append(" LEFT JOIN project p on up.goodsId = p.id  ");
        sql.append(" WHERE 1 = 1 AND upi.userId = #{m.userId} ");
        sql.append(" AND ( upi.effectiveStatus = 3 OR ( upi.effectiveStatus = 1 AND upi.notUsedNum = 0 AND upi.usedNum > 0 ) ");
        sql.append(" OR ( upi.effectiveStatus = 1 AND upi.usedNum > 0 AND upi.notUsedNum > 0 )) ");
        sql.append(" AND up.isDel = 0 AND upi.isDel = 0 ");
        sql.append("  GROUP BY upi.id");
        sql.append(" ORDER BY upi.createTime DESC, upi.goodsName DESC");
        sqlSentence.setSqlSentence(sql.toString());
        List<Map<String, Object>> list = commonService.selectListMap(UserProjectItemMapper.class, sqlSentence);
        return list;
    }
 
 
    /**
     * 划扣参与人 - 治疗医生
     **/
    private Map<String, Object> deductionJsonEmp(String deductionSingleId) {
        SqlSentence sqlSentence = new SqlSentence();
        Map<String, Object> values = new HashMap<>();
        sqlSentence.setM(values);
 
        values.put("isDel", BaseEntity.NO);
        values.put("id", deductionSingleId);
        values.put("roleUniqueStr", "doctor");
 
        sqlSentence.setSqlSentence("SELECT employeeId,employeeName FROM deduction_join WHERE deductionSingleId=#{m.id} AND isDel=#{m.isDel} and  roleUniqueStr = #{m.roleUniqueStr} order by createTime desc limit 1 ");
        Map<String, Object> subMap = commonService.selectOneMap(DeductionJoinMapper.class, sqlSentence);
        return subMap;
    }
 
 
    /**
     * 划扣参与人 - 治疗医生
     **/
    private VisitRecord visitRecordInfo(String userId) {
        SqlSentence sqlSentence = new SqlSentence();
        Map<String, Object> values = new HashMap<>();
        sqlSentence.setM(values);
 
        values.put("userId", userId);
        sqlSentence.setSqlSentence("select * from v_visit_record where isDel = 0 and userId = #{m.userId} order by createTime desc limit 1");
        VisitRecord visitRecord = commonService.selectOne(VisitRecordMapper.class, sqlSentence);
        return visitRecord;
    }
 
 
}