fhx
2024-10-10 50e6378f56fd2f01b7d6e326d07396e97d2c5c23
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
package com.hx.phip.controller.appointment;
 
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hx.common.BaseController;
import com.hx.exception.TipsException;
import com.hx.mybatisTool.SqlSentence;
import com.hx.phiappt.common.OperatorConstants;
import com.hx.phiappt.common.RoleType;
import com.hx.phiappt.constants.tool.user.UserTool;
import com.hx.phiappt.dao.mapper.*;
import com.hx.phiappt.model.*;
import com.hx.phip.config.GlobalExceptionHandler;
import com.hx.resultTool.Result;
import com.hx.util.DateUtil;
import com.hx.util.StringUtils;
import com.hz.his.dto.appointment.AppointmentAutoMateDto;
import com.hz.his.dto.appointment.AppointmentDto;
import com.hz.his.dto.appointment.AppointmentV2Dto;
import com.hz.his.dto.user.UserDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
 
import javax.annotation.Resource;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
 
/**
 * CRM自助预约v2
 * 按phis医生排班和预约项目进行预约
 * @USER: fhx
 * @DATE: 2024/4/3
 **/
@Slf4j
@RestController
@RequestMapping("/appointment/crm/self/v2")
public class CrmSelfV2Controller extends BaseController {
 
    @Resource
    private AppAutoMateController appAutoMateController;
    @Resource
    private AppointmentController appointmentController;
 
    public static final String FORMAT = "yyyy-MM-ddHH:mm";
 
    /** 预约门店 */
    @RequestMapping("/shop/list")
    public Result shopList(){
        SqlSentence sqlSentence = new SqlSentence();
        sqlSentence.setSqlSentence(" select id, name, workTime, province, city, area, addr from shop where isDel = 0 and isUp = 1 ");
        List<Map<String, Object>> list = commonService.selectListMap(ShopMapper.class, sqlSentence);
        Map<String, Object> data = new HashMap<>();
        data.put("list", list);
        return Result.success(data);
    }
 
    /** 医生排班 */
    @RequestMapping("/doctor/time/list")
    public Result doctorTimeList(@RequestBody AppointmentAutoMateDto dto){
        if(StringUtils.isEmpty(dto.getShopId())){
            throw new TipsException("门店标识为空!");
        }
 
        if(StringUtils.isEmpty(dto.getStartTime())){
            throw new TipsException("开始时间为空!");
        }
 
        if(StringUtils.isEmpty(dto.getEndTime())){
            throw new TipsException("结束时间为空!");
        }
 
//        //版本1返回
//        return Result.success(doctorTimeListV1(dto));
        //版本2返回
        return Result.success(doctorTimeListV2(dto));
    }
 
 
    /** 预约项目SPU */
    @RequestMapping("/spu/list")
    public Result spuList(){
        SqlSentence sqlSentence = new SqlSentence();
        Map<String, Object> values = new HashMap<>();
        sqlSentence.setM(values);
        values.put("type", ProjectType.TYPE_APPOINTMENT);
        sqlSentence.setSqlSentence(" select id, name from project_general where isDel = 0 and type = #{m.type} and isUp = 1 order by orderNum asc ");
        List<Map<String, Object>> list = commonService.selectListMap(ProjectGeneralMapper.class, sqlSentence);
        Map<String, Object> data = new HashMap<>();
        data.put("list", list);
        return Result.success(data);
    }
 
    /** 预约项目 */
    @RequestMapping("/project/list")
    public Result projectList(@RequestBody AppointmentDto dto){
 
        if(dto.getPageSize() == null || dto.getPageSize() > 20){
            dto.setPageSize(20);
        }
 
        SqlSentence sqlSentence = new SqlSentence();
        Map<String, Object> values = new HashMap<>();
        sqlSentence.setM(values);
        values.put("type", ProjectType.TYPE_APPOINTMENT);
        StringBuilder sql = new StringBuilder();
        sql.append(" select p.id, p.name, p.isLifeBeauty, p.unit, p.specification  ")
                .append(", p.useDuration / 60 as useDuration ")
                .append(", p.palsyDuration / 60 as palsyDuration ")
                .append(", (p.useDuration + p.palsyDuration) / 60 as duration ")
//                .append(", (p.useDuration + p.palsyDuration + p.intervalDuration + p.readyDuration) / 60 as duration")
                .append(" from project p ")
                .append(" where p.isDel = 0 and p.isUp = 1 and p.isShow = 1 ")
                .append(" and p.type = #{m.type} ");
 
        if(StringUtils.noNull(dto.getKeyWord())){
            sql.append(" and p.name like '%").append(dto.getKeyWord()).append("%' ");
        }
 
        //spuId查询
        if(StringUtils.noNull(dto.getSpuId())){
            sql.append(" and p.projectGeneralId = '").append(dto.getSpuId()).append("' ");
        }
 
        sql.append(" order by p.orderNum asc ");
        sqlSentence.setSqlSentence(sql.toString());
        PageHelper.startPage(dto.getPageNum(), dto.getPageSize());
        List<Map<String, Object>> list = commonService.selectListMap(ProjectMapper.class, sqlSentence);
        PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(list);
 
        Map<String, Object> data = new HashMap<>();
        data.put("list", pageInfo.getList());
        data.put("pageNum", pageInfo.getPageNum());
        data.put("pageSize", pageInfo.getPageSize());
        data.put("pages", pageInfo.getPages());
        data.put("total", pageInfo.getTotal());
        data.put("isLastPage", pageInfo.isIsLastPage());
        return Result.success(data);
    }
 
 
    //////////////////////////////////////////////////////////////////////////////////////////
 
    /** 自助预约匹配时间 */
    @RequestMapping("/mate/time")
    public Result mateTime(@RequestBody AppointmentAutoMateDto dto){
 
        if(StringUtils.isEmpty(dto.getUserId())){
            throw new TipsException("预约用户标识为空!");
        }
 
        if(StringUtils.isEmpty(dto.getShopId())){
            throw new TipsException("预约门店标识为空!");
        }
 
        if(StringUtils.isEmpty(dto.getDoctorId())){
            throw new TipsException("预约医生标识为空!");
        }
 
        if(StringUtils.isEmpty(dto.getArriveDate())){
            throw new TipsException("预约日期为空!");
        }
 
        if(StringUtils.isEmpty(dto.getStartTime())){
            throw new TipsException("预约到店时间为空!");
        }
 
        if(StringUtils.isEmpty(dto.getProjectJson())){
            throw new TipsException("预约项目为空!");
        }
 
        Date startTime = DateUtil.parseString(dto.getArriveDate() + dto.getStartTime(), FORMAT);
        if(startTime == null){
            throw new TipsException("预约到店时间错误!");
        }
 
        //查询用户是否有到店记录
        dto.setOpType(OperatorConstants.OP_TYPE_USER);
        dto.setOpId(dto.getUserId());
        dto.setVisitType("医美");
        //判断用户没到店过,则初诊
        if(UserTool.getUserArrivalNum(commonService, dto.getUserId()) == 0){
            dto.setAppType(Appointment.APP_TYPE_FIRST);
        }else{
            dto.setAppType(Appointment.APP_TYPE_TREATMENT);
        }
        dto.setMateNum(3);
//        dto.setDaySpace(true);
 
        Result result;
        try{
            result = appAutoMateController.addApplyBland(dto);
        }catch (Exception e){
            log.info("获取用户自助预约时间失败:{}", GlobalExceptionHandler.getExceptionInformation(e));
            throw new TipsException("获取预约时间失败!");
        }
 
        //匹配报错提示文案
        JSONObject data = result.getJsonObject(result.getData());
        JSONArray arr = data.getJSONArray("list");
        if(arr != null && arr.size() > 0){
            data.remove("errMsg");
        }
 
        if(StringUtils.noNull(data.getString("errMsg")) ){
            throw new TipsException(data.getString("errMsg"));
        }
 
        return result;
    }
 
    /** 新增预约 */
    @RequestMapping("/add")
    public Result add(@RequestBody AppointmentV2Dto dto){
        if(StringUtils.isEmpty(dto.getUserId())){
            throw new TipsException("用户标识为空!");
        }
        dto.setOpId(dto.getUserId());
        dto.setOpType(OperatorConstants.OP_TYPE_USER); //操作人类型:用户
        dto.setAddMode(Appointment.ADD_MODE_CRM_SELF); //crm自助预约
        dto.setVisitType("医美");
        //判断用户没到店过,则初诊
        if(UserTool.getUserArrivalNum(commonService, dto.getUserId()) == 0){
            dto.setAppType(Appointment.APP_TYPE_FIRST);
        }else{
            dto.setAppType(Appointment.APP_TYPE_TREATMENT);
        }
        dto.setIsMicApprove(BaseEntity.NO); //无需MIC同意
        dto.setIsSendMsg(BaseEntity.YES); //发送短信通知
        dto.setIsArriveSendMsg(BaseEntity.YES); //发送短信通知
 
        //新增预约
        Result result = appointmentController.add(dto);
        if(!result.checkCode()){
            log.error("新增用户自助预约V2失败:{}", JSONObject.toJSONString(result));
            throw new TipsException("新增预约失败!");
        }
 
        JSONObject data = result.getJsonObject(result.getData());
        //查询返回对应预约信息
        SqlSentence sqlSentence = new SqlSentence();
        Map<String, Object> values = new HashMap<>();
        sqlSentence.setM(values);
        values.put("id", data.getString("id"));
        StringBuilder sql = new StringBuilder();
        sql.append(" select a.id, a.startTime, a.endTime , d.cnName as doctorName, a.doctorId ")
                .append(" , a.status, a.isArrive, a.projectNames, a.projectJson, a.addMode, a.createManName, a.createManType, remark ")
                .append(" , s.name as shopName, s.province, s.city, s.area, s.addr")
                .append(" from appointment a ")
                .append(" left join shop s on s.id = a.shopId ")
                .append(" left join employee d on d.id = a.doctorId ")
                .append(" where a.isDel = 0 and a.id = #{m.id}  ");
        sqlSentence.setSqlSentence(sql.toString());
        Map<String, Object> dataMap = commonService.selectOneMap(AppointmentMapper.class, sqlSentence);
        return Result.success(dataMap);
    }
 
    /** 取消预约 */
    @RequestMapping("/cancel")
    public Result cancel(@RequestBody AppointmentV2Dto dto){
        if(StringUtils.isEmpty(dto.getUserId())){
            throw new TipsException("用户标识为空!");
        }
        dto.setOpId(dto.getUserId());
        dto.setOpType(OperatorConstants.OP_TYPE_USER);
        return appointmentController.cancel(dto);
    }
 
    /** 用户预约列表 */
    @RequestMapping("/list")
    public Result list(@RequestBody UserDto dto){
 
        if(StringUtils.isEmpty(dto.getUserId())){
            throw new TipsException("用户标识为空!");
        }
 
        SqlSentence sqlSentence = new SqlSentence();
        Map<String, Object> values = new HashMap<>();
        sqlSentence.setM(values);
        values.put("userId", dto.getUserId());
        values.put("addMode9", Appointment.ADD_MODE_CRM_CREATE);
 
        StringBuilder sql = new StringBuilder();
        sql.append(" select a.id, a.startTime, a.endTime, d.cnName as doctorName, a.doctorId, a.addMode ")
                .append(" , a.status, a.isArrive, a.projectJson, a.addMode, a.createManName, a.createManType, a.remark ")
                .append(" , s.name as shopName, s.province, s.city, s.area, s.addr")
                .append(" from appointment a ")
                .append(" left join shop s on s.id = a.shopId ")
                .append(" left join employee d on d.id = a.doctorId ")
                .append(" where a.isDel = 0 and a.userId = #{m.userId}  ")
                //只查询预约成功和取消的
                .append(" and a.status in (").append(Appointment.STATUS_SUC).append(",").append(Appointment.STATUS_CANCEL).append(") ")
//                .append(" and a.addMode != #{m.addMode9} ")
                .append(" order by a.startTime desc ");
        sqlSentence.setSqlSentence(sql.toString());
 
        //分页插件
        PageHelper.startPage(dto.getPageNum(), dto.getPageSize());
        List<Map<String, Object>> list = commonService.selectListMap(AppointmentMapper.class, sqlSentence);
        PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(list);
 
        Map<String, Object> data = new HashMap<>();
        data.put("list", pageInfo.getList());
        data.put("pageNum", pageInfo.getPageNum());
        data.put("pageSize", pageInfo.getPageSize());
        data.put("pages", pageInfo.getPages());
        data.put("total", pageInfo.getTotal());
        data.put("isLastPage", pageInfo.isIsLastPage());
        return Result.success(data);
    }
 
    ///////////////////////////////////////////////////////////////////////////////////////////
 
//    private void checkTime(Date startTime){
//        Calendar calendar = Calendar.getInstance();
//        calendar.setTime(startTime);
//        int hour = calendar.get(Calendar.HOUR);
//        if(hour ){}
//    }
 
    /** 医生排班(按日期选医生) */
    private Map<String, Object> doctorTimeListV1(AppointmentAutoMateDto dto){
 
        SqlSentence sqlSentence = new SqlSentence();
        Map<String, Object> values = new HashMap<>();
        sqlSentence.setM(values);
        values.put("timeType", DoctorTime.TIME_TYPE_WORK);
        values.put("shopId", dto.getShopId());
        values.put("startTime", dto.getStartTime());
        values.put("endTime", dto.getEndTime());
        StringBuilder sql = new StringBuilder();
        sql.append(" select dt.doctorId, e.cnName as doctorName, e.imgUrl ")
                .append(" , date_format(dt.startTime, '%Y-%m-%d') as startTime ")
                .append(" from doctor_time dt ")
                .append(" left join employee e on e.id = dt.doctorId ")
                .append(" where dt.isDel = 0 and dt.timeType = #{m.timeType} and dt.shopId = #{m.shopId} ")
                .append(" and dt.dayTime >= #{m.startTime} and dt.endTime <= #{m.endTime} ")
                .append(" order by dt.dayTime asc ");
        sqlSentence.setSqlSentence(sql.toString());
 
        List<Map<String, Object>> list = commonService.selectListMap(DoctorTimeMapper.class, sqlSentence);
        if(list == null || list.size() < 1){
            return null;
        }
 
        //先遍历按日期归类
        List<Map<String, Object>> dataList;
        TreeMap<Object, List<Map<String, Object>>> treeMap = new TreeMap<>();
        for(Map<String, Object> map : list){
            dataList = treeMap.get(map.get("startTime"));
            if(!treeMap.containsKey(map.get("startTime"))){
                dataList = new ArrayList<>();
                treeMap.put(map.get("startTime"), dataList);
            }
            dataList.add(map);
        }
 
        //然后再组装
        JSONArray arr = new JSONArray();
        JSONObject json;
        for(Map.Entry<Object, List<Map<String, Object>>> entry : treeMap.entrySet()){
            json = new JSONObject();
            json.put("dateTime", entry.getKey());
            json.put("doctorList", entry.getValue());
            arr.add(json);
        }
 
        json = new JSONObject();
        json.put("list", arr);
        json.put("version", "1");
        return json;
    }
 
    /** 医生排班(按医生选日期) */
    private Map<String, Object> doctorTimeListV2(AppointmentAutoMateDto dto){
 
        SqlSentence sqlSentence = new SqlSentence();
        Map<String, Object> values = new HashMap<>();
        sqlSentence.setM(values);
        values.put("shopId", dto.getShopId());
        values.put("roleUniqueStr", RoleType.UNIQUE_STR_DOCTOR);
        StringBuilder sql = new StringBuilder();
 
        //查询门店下的医生员工
        sql.append(" select e.id as doctorId, e.cnName as doctorName, e.imgUrl ")
                .append(" from employee_role r ")
                .append(" join employee e on e.id = r.employeeId ")
                .append(" where r.isDel = 0 and e.isDel = 0 and e.isJob = 1 ")
                .append(" and r.shopId = #{m.shopId} and r.roleUniqueStr = #{m.roleUniqueStr} ");
        sqlSentence.setSqlSentence(sql.toString());
        List<Map<String, Object>> doctorList = commonService.selectListMap(EmployeeMapper.class, sqlSentence);
 
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("list", doctorList);
        dataMap.put("version", "2");
 
        if(doctorList == null || doctorList.size() < 1){
            return dataMap;
        }
 
        //查询门店下对应日期范围的医生排班
        values.put("timeType", DoctorTime.TIME_TYPE_WORK);
        values.put("startTime", dto.getStartTime());
        values.put("endTime", dto.getEndTime());
        sql.setLength(0);
        sql.append(" select dt.doctorId, date_format(dt.startTime, '%Y-%m-%d') as startTime ")
                .append(" from doctor_time dt ")
                .append(" left join employee e on e.id = dt.doctorId ")
                .append(" where dt.isDel = 0 and dt.timeType = #{m.timeType} and dt.shopId = #{m.shopId} ")
                .append(" and dt.dayTime >= #{m.startTime} and dt.endTime <= #{m.endTime} ")
                .append(" order by dt.dayTime asc ");
        sqlSentence.setSqlSentence(sql.toString());
 
        List<Map<String, Object>> doctorTimeList = commonService.selectListMap(DoctorTimeMapper.class, sqlSentence);
        if(doctorTimeList == null || doctorTimeList.size() < 1){
            return dataMap;
        }
 
        //按医生id分组归类排班数据
        Map<String, List<Map<String, Object>>> doctorTimeMap = doctorTimeList.stream().collect(Collectors.groupingBy(m->m.get("doctorId").toString()));
 
        //先遍历按日期归类
        List<Map<String, Object>> dateList;
        for(Map<String, Object> doctorMap : doctorList){
            dateList = doctorTimeMap.get(doctorMap.get("doctorId"));
            if(dateList == null || dateList.size() < 1){
                continue;
            }
            //按时间排序
            dateList.sort(Comparator.comparing((Map<String, Object> h) -> ((String) h.get("startTime"))));
            doctorMap.put("dateList", dateList);
        }
 
        return dataMap;
    }
}