guohongjin
2024-05-01 1901fceb6ddaa56a57f3131191454554c3e77e68
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
package cn.stylefeng.rest.modular.home.service;
 
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.json.JSONUtil;
import cn.stylefeng.guns.modular.business.dto.ImPushDataDTO;
import cn.stylefeng.guns.modular.business.dto.MentalTestContentJsonDTO;
import cn.stylefeng.guns.modular.business.dto.request.MentalTestAnswerSubmitRequest;
import cn.stylefeng.guns.modular.business.entity.*;
import cn.stylefeng.guns.modular.business.service.*;
import cn.stylefeng.guns.modular.business.service.impl.ImBizService;
import cn.stylefeng.roses.kernel.customer.modular.entity.Customer;
import cn.stylefeng.roses.kernel.customer.modular.service.CustomerService;
import cn.stylefeng.roses.kernel.rule.enums.*;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
 
import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
 
@Slf4j
@Service
public class MentalTestBizService {
 
    @Resource
    ImBizService imBizService;
 
    @Resource
    IOrderMentalTestService orderMentalTestService;
 
 
    @Resource
    IMentalTestTopicService mentalTestTopicService;
 
    @Resource
    IMentalTestOptionService mentalTestOptionService;
 
    @Resource
    IMentalTestResultService mentalTestResultService;
 
    @Resource
    IMentalTestRecordService mentalTestRecordService;
 
    @Resource
    IMentalTestResultSetService mentalTestResultSetService;
 
    @Resource
    IOrderConsultOneService orderConsultOneService;
 
    @Resource
    CustomerService customerService;
 
    @Transactional(rollbackFor = Exception.class)
    public MentalTestRecord answerSubmit(MentalTestAnswerSubmitRequest req) {
        // 获取用户信息
        Customer customer = customerService.getById(req.getUserId());
        if (customer == null) {
            throw new RuntimeException("获取用户信息失败!");
        }
        // 获取用户咨询顾问ID
        Long consultWorkerId;
        if (customer != null && customer.getConsultWorkerId() != null) {
            consultWorkerId = customer.getConsultWorkerId();
        } else {
            // 没有则分配咨询顾问
            consultWorkerId = customerService.randomWorkerIdByLineStatusAndPost(ImStatusEnum.ON_LINE.getCode(), null, PostIdEnum.PO_21.getCode(), CustomerWorkStatusEnum.ON_WORK.getCode());
            if (consultWorkerId == null) {
                consultWorkerId = customerService.randomWorkerIdByLineStatusAndPost(null, null, PostIdEnum.PO_21.getCode(), CustomerWorkStatusEnum.ON_WORK.getCode());
            }
            if (consultWorkerId != null) {
                // 更新用户咨询顾问ID
                customerService.update(
                        Wrappers.<Customer>lambdaUpdate()
                                .set(Customer::getConsultWorkerId, consultWorkerId)
                                .eq(Customer::getCustomerId, req.getUserId())
                );
            } else {
                log.error("心理测试完成,未分配咨询顾问!");
            }
        }
 
        // 心理测试选项
        List<MentalTestOption> optionList = mentalTestOptionService.list(
                Wrappers.<MentalTestOption>lambdaQuery()
                        .eq(MentalTestOption::getTopicId, req.getTopicId())
        );
 
        // 答题编号(心理测试订单编号)
        String answerNo = req.getMentalTestOrderNo();
 
        if (CollUtil.isEmpty(req.getQuestionRequestsList())) {
            throw new RuntimeException("心理测试未完成答题");
        }
 
        // 每个项都是1条数据,被逗号拼接了,拆成多项
        req.setQuestionRequestsList(req.getQuestionRequestsList().stream()
                .flatMap(item -> {
                    // 检查itemNo中是否包含逗号,并相应地拆分
                    String[] itemNoParts = item.getItemNo().split(",");
                    // 为每个拆分后的itemNo部分创建一个新的实体
                    return Arrays.stream(itemNoParts).map(part -> {
                        MentalTestAnswerSubmitRequest.QuestionRequest newItem = new MentalTestAnswerSubmitRequest.QuestionRequest();
                        newItem.setQuestionId(item.getQuestionId());
                        newItem.setItemNo(part);
                        return newItem;
                    });
                })
                .collect(Collectors.toList()));
 
        // 心理测试结果
        List<MentalTestResult> mentalTestResultList = req.getQuestionRequestsList().stream()
                .map(o -> {
                    MentalTestResult result = new MentalTestResult();
                    result.setAnswerNo(answerNo);
                    result.setTopicId(req.getTopicId());
                    result.setUserId(req.getUserId());
                    result.setQuestionId(o.getQuestionId());
                    result.setItemNo(o.getItemNo());
                    result.setScore(optionList.stream()
                            .filter(op -> op.getQuestionId().equals(o.getQuestionId()) && op.getItemNo().equals(o.getItemNo()))
                            .findFirst()
                            .map(MentalTestOption::getScore)
                            .orElse(0)
                    );
                    return result;
                })
                .collect(Collectors.toList());
 
 
        // 心理测试结果
        mentalTestResultService.saveBatch(mentalTestResultList);
 
        // 获取心理测试题库
        MentalTestTopic topic = mentalTestTopicService.getById(req.getTopicId());
        // 题库测试人数+1
        mentalTestTopicService.update(
                Wrappers.<MentalTestTopic>lambdaUpdate()
                        .set(MentalTestTopic::getTestPeopleNum, topic.getTestPeopleNum() + 1)
                        .eq(MentalTestTopic::getId, req.getTopicId())
        );
 
        // 标记心理测试订单已测试提交
        orderMentalTestService.update(
                Wrappers.<OrderMentalTest>lambdaUpdate()
                        .set(OrderMentalTest::getTestFlag, true)
                        .eq(OrderMentalTest::getOrderNo, req.getMentalTestOrderNo())
        );
 
        // 心理测试记录
        MentalTestRecord record = MentalTestRecord.builder()
                .answerNo(answerNo)
                .topicId(req.getTopicId())
                .resultCalculateMode(topic.getResultCalculateMode())
                .userId(req.getUserId())
                .build();
 
        // 结果计算方式:0得分,1选项,2测试
        if (topic.getResultCalculateMode() == 0) {
            // 得分总和
            Integer scoreSum = mentalTestResultList.stream().mapToInt(MentalTestResult::getScore).sum();
 
            // 心理测试结果配置
            MentalTestResultSet resultSet = mentalTestResultSetService.getOne(
                    Wrappers.<MentalTestResultSet>lambdaQuery()
                            .eq(MentalTestResultSet::getTopicId, req.getTopicId())
                            .eq(MentalTestResultSet::getResultCalculateMode, topic.getResultCalculateMode())
                            .ge(MentalTestResultSet::getMax, scoreSum)
                            .le(MentalTestResultSet::getMin, scoreSum)
                            .last("limit 1")
            );
 
            // 心理测试分数
            record.setScore(scoreSum);
            record.setContent(resultSet != null ? resultSet.getContent() : "");
        } else {
            // 分组统计选项数量
            Map<String, Integer> optionScoreMap = optionList.stream()
                    // 创建一个Map来存储itemNo和questionId的组合作为键,score作为值
                    .collect(Collectors.toMap(
                            // 键是questionId和itemNo的组合
                            op -> op.getQuestionId() + "-" + op.getItemNo(),
                            // 值是score
                            MentalTestOption::getScore,
                            // 如果两个选项有相同的键,则它们的score会被累加
                            Integer::sum
                    ));
 
            // 创建一个Map来存储itemNo作为键,累积的score作为值
            Map<String, Integer> itemScoreMap = new HashMap<>(2);
 
            // 遍历QuestionRequest列表,并累加分数
            req.getQuestionRequestsList().forEach(request -> {
                String itemNo = request.getItemNo();
                String key = request.getQuestionId() + "-" + itemNo;
                // 如果找不到键,则使用0作为默认值
                Integer score = optionScoreMap.getOrDefault(key, 0);
                // 累加分数
                itemScoreMap.merge(itemNo, score, Integer::sum);
            });
 
            // 心理测试结果配置
            List<MentalTestResultSet> resultSetList = mentalTestResultSetService.list(
                    Wrappers.<MentalTestResultSet>lambdaQuery()
                            .eq(MentalTestResultSet::getTopicId, req.getTopicId())
                            .eq(MentalTestResultSet::getResultCalculateMode, topic.getResultCalculateMode())
            );
            // 封装配置结果数据
            List<MentalTestContentJsonDTO> itemScoreList = itemScoreMap.entrySet()
                    .stream().map(m ->
                            MentalTestContentJsonDTO.builder()
                                    .itemNo(m.getKey())
                                    .score(m.getValue())
                                    .itemName(resultSetList.stream().filter(rs -> rs.getItemNo().equals(m.getKey())).map(MentalTestResultSet::getItemName).findFirst().orElse(""))
                                    .build()
                    )
                    .sorted(Comparator.comparing(MentalTestContentJsonDTO::getItemNo))
                    .collect(Collectors.toList());
            record.setContent(JSONUtil.toJsonStr(itemScoreList));
        }
 
        // 含有1V1咨询
        if (topic.getConsultOne() == 1 && consultWorkerId != null) {
            // 延迟任务(提醒用户下1v1咨询单)
            ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
            Long finalConsultWorkerId = consultWorkerId;
            executor.schedule(() -> tipOrderConsultOne(record.getId(), req.getUserId(), finalConsultWorkerId), 5, TimeUnit.MINUTES);
        }
 
        // 保存心理测试记录
        mentalTestRecordService.save(record);
 
        return record;
    }
 
    public void tipOrderConsultOne(Long mentalTestRecordId, Long userId, Long consultWorkerId) {
        log.info("有1v1咨询的,但是用户完成测试后没有选择,那么需要通知到咨询顾问");
        if (consultWorkerId != null) {
            long count = orderConsultOneService.count(
                    Wrappers.<OrderConsultOne>lambdaQuery()
                            .eq(OrderConsultOne::getMentalTestRecordId, mentalTestRecordId)
            );
            if (count == 0) {
                // 推送消息内容
                String pushContent = "用户完成心理测试,没有选择1v1咨询";
                // IM推送数据json
                ImPushDataDTO pushData = ImPushDataDTO.builder()
                        .type(ImPushTypeEnum.S_TO_W_TIP_1V1_CONSULT.getCode())
                        .objId(ObjUtil.toString(mentalTestRecordId))
                        .title("通知")
                        .content(pushContent)
//                        .extra(null)
                        .data1(ObjUtil.toString(userId))
                        .data2(ObjUtil.toString(consultWorkerId))
                        .build();
                // 通知咨询顾问,用户没有选择1v1咨询
                imBizService.messageSendSystem(userId+"", new String[]{consultWorkerId+""}, pushData, ImUserTypeEnum.WORKER, PostIdEnum.PO_21, true);
            }
        }
    }
 
}