啊鑫
5 天以前 1f963e2344833ff02087c05411b112147492bd00
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
package com.gs.xky.service.Impl;
 
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiMessageCorpconversationAsyncsendV2Request;
import com.dingtalk.api.response.OapiMessageCorpconversationAsyncsendV2Response;
import com.gs.xky.entity.DingtalkInfo;
import com.gs.xky.entity.DingtalkMsg;
import com.gs.xky.mapper.DingtalkInfoMapper;
import com.gs.xky.mapper.DingtalkMsgMapper;
import com.gs.xky.service.DingtalkInfoService;
import com.gs.xky.service.SimpleExample;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
 
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
 
/**
 * @author 28567
 * @description 针对表【DINGTALK_INFO】的数据库操作Service实现
 * @createDate 2025-06-20 16:12:48
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class DingtalkInfoServiceImpl extends ServiceImpl<DingtalkInfoMapper, DingtalkInfo>
        implements DingtalkInfoService {
 
    private final SimpleExample simpleExample;
    private final DingtalkMsgMapper dingtalkMsgMapper;
 
    @Override
    public boolean sendMessage(String releaseNo) {
        try {
            // 查询钉钉消息内容
            LambdaQueryWrapper<DingtalkMsg> msgWrapper = new LambdaQueryWrapper<>();
            msgWrapper.eq(DingtalkMsg::getReleaseNo, releaseNo);
            DingtalkMsg dingtalkMsg = dingtalkMsgMapper.selectOne(msgWrapper);
 
            if (dingtalkMsg == null) {
                log.error("未找到检验单号为 {} 的钉钉消息内容", releaseNo);
                return false;
            }
 
            // 格式化日期
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String createDateStr = (dingtalkMsg.getCreateDate() != null) ?
                    dateFormat.format(dingtalkMsg.getCreateDate()) : "未知";
 
            // 构建消息内容
            String message = String.format("供应商[%s] 来料日期[%s] 项目[%s] 料号[%s]的不合格检验单被[%s]审批为[%s],请查收!",
                    dingtalkMsg.getSuppName(), createDateStr, dingtalkMsg.getProjectCodes(),
                    dingtalkMsg.getItemNo(), dingtalkMsg.getFname(), dingtalkMsg.getFngHandle());
 
            // 调用getDingtalkUserIdList方法获取UserIdList
            List<String> userIdList = getDingtalkUserIdList();
 
            if (userIdList == null || userIdList.isEmpty()) {
                log.warn("没有需要发送钉钉消息的用户");
                return false;
            }
 
            // 通过钉钉发送消息
            String userIdListStr = String.join(",", userIdList);
 
            OapiMessageCorpconversationAsyncsendV2Response rsp = sendMessage(userIdListStr, message);
            System.out.println(rsp.getBody());
            log.info("成功发送钉钉消息: {}", message);
            return true;
        } catch (Exception e) {
            log.error("发送钉钉消息失败", e);
            return false;
        }
    }
 
    private List<String> getDingtalkUserIdList() {
        try {
            LambdaQueryWrapper<DingtalkInfo> wrapper = new LambdaQueryWrapper<>();
            wrapper.ge(DingtalkInfo::getIsSendDingtalk, 1);
            List<DingtalkInfo> list = list(wrapper);
 
            if (list == null || list.isEmpty()) {
                return new ArrayList<>();
            }
 
            // 使用stream流过滤出list中dingtalkId为空的数据
            List<DingtalkInfo> emptyDingtalkIdList = list.stream()
                    .filter(info -> !StringUtils.hasText(info.getDingtalkId()))
                    .collect(Collectors.toList());
 
            // 如果存在为空的数据就通过钉钉的接口获取,为dingtalkId赋值,并且更新数据库
            if (!emptyDingtalkIdList.isEmpty()) {
                String accessToken = simpleExample.getAccessToken();
 
                for (DingtalkInfo info : emptyDingtalkIdList) {
                    if (StringUtils.hasText(info.getPhone())) {
                        try {
                            // 通过手机号获取钉钉用户ID
                            com.dingtalk.api.response.OapiV2UserGetbymobileResponse response =
                                    simpleExample.getOapiV2UserGetbymobileResponse(info.getPhone(), accessToken);
 
                            if (response != null && response.getResult() != null) {
                                info.setDingtalkId(response.getResult().getUserid());
                                // 更新数据库
                                updateById(info);
                            }
                        } catch (Exception e) {
                            log.error("获取钉钉用户ID失败,手机号:{}", info.getPhone(), e);
                        }
                    }
                }
            }
 
            // 不存在为空的数据或者处理完空数据后,返回所有有效的dingtalkId列表
            return list.stream()
                    .map(DingtalkInfo::getDingtalkId)
                    .filter(StringUtils::hasText)
                    .collect(Collectors.toList());
        } catch (Exception e) {
            log.error("获取钉钉用户列表失败", e);
            return new ArrayList<>();
        }
    }
 
    private OapiMessageCorpconversationAsyncsendV2Response sendMessage(String userIdListStr, String message) throws Exception {
 
        String accessToken = simpleExample.getAccessToken();
 
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2");
        OapiMessageCorpconversationAsyncsendV2Request request = new OapiMessageCorpconversationAsyncsendV2Request();
        request.setAgentId(3917187842L);
        request.setUseridList(userIdListStr);
        request.setToAllUser(false);
 
        OapiMessageCorpconversationAsyncsendV2Request.Msg msg = new OapiMessageCorpconversationAsyncsendV2Request.Msg();
        msg.setMsgtype("text");
        msg.setText(new OapiMessageCorpconversationAsyncsendV2Request.Text());
        msg.getText().setContent(message);
        request.setMsg(msg);
 
        return client.execute(request, accessToken);
 
    }
}