From e2ba28674fb5a6ab0fe85e2d0f09cd94fa496dff Mon Sep 17 00:00:00 2001
From: Administrator <2856754968@qq.com>
Date: 星期五, 14 十一月 2025 13:54:56 +0800
Subject: [PATCH] 111

---
 src/main/java/com/gs/xky/service/Impl/DingtalkInfoServiceImpl.java |  388 +++++++++++++++++++++++++++++++++++++++++++++++++++---
 1 files changed, 363 insertions(+), 25 deletions(-)

diff --git a/src/main/java/com/gs/xky/service/Impl/DingtalkInfoServiceImpl.java b/src/main/java/com/gs/xky/service/Impl/DingtalkInfoServiceImpl.java
index 7b91468..1121b42 100644
--- a/src/main/java/com/gs/xky/service/Impl/DingtalkInfoServiceImpl.java
+++ b/src/main/java/com/gs/xky/service/Impl/DingtalkInfoServiceImpl.java
@@ -8,18 +8,23 @@
 import com.dingtalk.api.response.OapiMessageCorpconversationAsyncsendV2Response;
 import com.gs.xky.entity.DingtalkInfo;
 import com.gs.xky.entity.DingtalkMsg;
+import com.gs.xky.entity.MesStaff;
 import com.gs.xky.mapper.DingtalkInfoMapper;
 import com.gs.xky.mapper.DingtalkMsgMapper;
+import com.gs.xky.mapper.MesStaffMapper;
 import com.gs.xky.service.DingtalkInfoService;
 import com.gs.xky.service.SimpleExample;
+import com.taobao.api.FileItem;
 import lombok.RequiredArgsConstructor;
 import lombok.extern.slf4j.Slf4j;
 import org.springframework.stereotype.Service;
 import org.springframework.util.StringUtils;
 
+import java.io.File;
 import java.text.SimpleDateFormat;
 import java.util.ArrayList;
 import java.util.List;
+import java.util.Optional;
 import java.util.stream.Collectors;
 
 /**
@@ -35,6 +40,7 @@
 
     private final SimpleExample simpleExample;
     private final DingtalkMsgMapper dingtalkMsgMapper;
+    private final MesStaffMapper mesStaffMapper;
 
     @Override
     public boolean sendMessage(String releaseNo) {
@@ -55,12 +61,58 @@
                     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());
+//            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();
+            String message = String.format(
+                    "渚涘簲鍟哰%s] 鏉ユ枡鏃ユ湡[%s] 椤圭洰[%s] 鏂欏彿[%s]鐨勪笉鍚堟牸妫�楠屽崟琚玔%s]瀹℃壒涓篬%s]锛岃鏌ユ敹!",
+                    Optional.ofNullable(dingtalkMsg.getSuppName()).orElse(" 鏈煡渚涘簲鍟�"),
+                    createDateStr,
+                    Optional.ofNullable(dingtalkMsg.getProjectCodes()).orElse(" 鏈煡椤圭洰"),
+                    Optional.ofNullable(dingtalkMsg.getItemNo()).orElse(" 鏈煡鏂欏彿"),
+                    Optional.ofNullable(dingtalkMsg.getFname()).orElse(" 鏈煡瀹℃壒浜�"),
+                    Optional.ofNullable(dingtalkMsg.getFngHandle()).orElse(" 鏈煡瀹℃壒缁撴灉"));
+
+            // 鏀堕泦闇�瑕佹帹閫佺殑浜哄憳sid
+            List<Long> sidList = new ArrayList<>();
+
+            // 1. 鍥哄畾鎺ㄩ�佷汉鍛橈紙isSendDingtalk=1锛�
+            List<DingtalkInfo> fixedList = baseMapper.selectList(
+                    new LambdaQueryWrapper<DingtalkInfo>().eq(DingtalkInfo::getIsSendDingtalk, 1)
+            );
+            for (DingtalkInfo info : fixedList) {
+                sidList.add(info.getSid());
+            }
+
+            // 2. 閲囪喘浜哄憳锛坋mployeeName锛�
+            if (StringUtils.hasText(dingtalkMsg.getEmployeeName())) {
+                MesStaff buyer = mesStaffMapper.selectOne(
+                        new LambdaQueryWrapper<MesStaff>().eq(MesStaff::getStaffName, dingtalkMsg.getEmployeeName()), false
+                );
+                if (buyer != null) {
+                    DingtalkInfo buyerInfo = baseMapper.selectOne(
+                            new LambdaQueryWrapper<DingtalkInfo>().eq(DingtalkInfo::getSid, buyer.getId()), false
+                    );
+                    if (buyerInfo != null) sidList.add(buyerInfo.getSid());
+                }
+            }
+
+            // 3. 瀹℃牳浜猴紙modify1By锛�
+            if (StringUtils.hasText(dingtalkMsg.getModify1By())) {
+                MesStaff auditor = mesStaffMapper.selectOne(
+                        new LambdaQueryWrapper<MesStaff>().eq(MesStaff::getStaffNo, dingtalkMsg.getModify1By())
+                );
+                if (auditor != null) {
+                    DingtalkInfo auditorInfo = baseMapper.selectOne(
+                            new LambdaQueryWrapper<DingtalkInfo>().eq(DingtalkInfo::getSid, auditor.getId())
+                    );
+                    if (auditorInfo != null) sidList.add(auditorInfo.getSid());
+                }
+            }
+
+            // 4. 鏍规嵁鏀堕泦鐨剆id鑾峰彇dingtalkId (澶嶇敤getDingtalkUserIdList鐨勫叧閿�昏緫)
+            List<String> userIdList = getDingtalkUserIdListBySids(sidList);
 
             if (userIdList == null || userIdList.isEmpty()) {
                 log.warn("娌℃湁闇�瑕佸彂閫侀拤閽夋秷鎭殑鐢ㄦ埛");
@@ -80,6 +132,311 @@
         }
     }
 
+    @Override
+    public boolean sendActionCardMessage() {
+        try {
+            // 1. 鑾峰彇闇�瑕佹帹閫佺殑鐢ㄦ埛鍒楄〃锛堝彲浠ユ槸鍥哄畾鎺ㄩ�佺敤鎴凤級
+            List<DingtalkInfo> fixedList = baseMapper.selectList(
+                    new LambdaQueryWrapper<DingtalkInfo>().eq(DingtalkInfo::getIsHead, 1)
+            );
+
+            List<Long> sidList = fixedList.stream()
+                    .map(DingtalkInfo::getSid)
+                    .collect(Collectors.toList());
+
+            List<String> userIdList = getDingtalkUserIdListBySids(sidList);
+
+            if (userIdList == null || userIdList.isEmpty()) {
+                log.warn("娌℃湁闇�瑕佸彂閫侀拤閽夋秷鎭殑鐢ㄦ埛");
+                return false;
+            }
+
+            String userIdListStr = String.join(",", userIdList);
+
+            // 2. 鏋勫缓娑堟伅鍐呭
+            String title = "鐢熶骇鏁版嵁鐪嬫澘";
+            String markdown = "璇风偣鍑讳笅鏂规寜閽煡鐪嬭缁咮I鎶ヨ〃";
+            String singleTitle = "鏌ョ湅鎶ヨ〃";
+            String singleUrl = "http://192.168.1.22:8081/design?fid=rpte6045ab079b211f0824bd3cfd50c6b93&fserid=4b198960bedd11f09f6f792bfe147b64&fsharetype=3";
+
+            // 3. 鍙戦�佹秷鎭�
+            OapiMessageCorpconversationAsyncsendV2Response rsp =
+                    sendActionCardMessage(userIdListStr, title, markdown, singleTitle, singleUrl);
+
+            log.info("鎴愬姛鍙戦�丄ctionCard娑堟伅: {}", rsp.getBody());
+            return true;
+        } catch (Exception e) {
+            log.error("鍙戦�丄ctionCard娑堟伅澶辫触", e);
+            return false;
+        }
+    }
+
+    @Override
+    public boolean sendFileMessage(String filePath) throws Exception {
+        try {
+            // 1. 妫�鏌ユ枃浠舵槸鍚﹀瓨鍦�
+            File file = new File(filePath);
+            if (!file.exists()) {
+                log.error("鏂囦欢涓嶅瓨鍦�: {}", filePath);
+                return false;
+            }
+
+            // 2. 鑾峰彇闇�瑕佹帹閫佺殑鐢ㄦ埛鍒楄〃锛堝彲鏍规嵁瀹為檯闇�姹傝皟鏁达紝杩欓噷浣跨敤isHead=1鐨勭敤鎴凤級
+            List<DingtalkInfo> fixedList = baseMapper.selectList(
+                    new LambdaQueryWrapper<DingtalkInfo>().eq(DingtalkInfo::getIsHead, 1)
+            );
+
+            if (fixedList == null || fixedList.isEmpty()) {
+                log.warn("娌℃湁闇�瑕佸彂閫佹枃浠剁殑鐢ㄦ埛锛坕sHead=1锛�");
+                return false;
+            }
+
+            List<Long> sidList = fixedList.stream()
+                    .map(DingtalkInfo::getSid)
+                    .collect(Collectors.toList());
+
+            List<String> userIdList = getDingtalkUserIdListBySids(sidList);
+
+            if (userIdList == null || userIdList.isEmpty()) {
+                log.warn("娌℃湁鏈夋晥鐨勯拤閽夌敤鎴稩D");
+                return false;
+            }
+
+            String userIdListStr = String.join(",", userIdList);
+
+            // 3. 涓婁紶鏂囦欢鍒伴拤閽夋湇鍔″櫒
+            log.info("寮�濮嬩笂浼犳枃浠�: {}", filePath);
+            String mediaId = uploadMedia(filePath, "file");
+
+            // 4. 鍙戦�佹枃浠舵秷鎭�
+            log.info("寮�濮嬪彂閫佹枃浠舵秷鎭紝mediaId: {}", mediaId);
+            OapiMessageCorpconversationAsyncsendV2Response response = sendFileMessageByMediaId(userIdListStr, mediaId);
+
+            log.info("鏂囦欢娑堟伅鍙戦�佸搷搴�: {}", response.getBody());
+            return response.getErrcode() == 0;
+
+        } catch (Exception e) {
+            log.error("鍙戦�佹枃浠舵秷鎭け璐�", e);
+            throw e;
+        }
+    }
+
+    /**
+     * 鏍规嵁鎸囧畾鐨剆id鍒楄〃鑾峰彇閽夐拤鐢ㄦ埛ID鍒楄〃
+     *
+     * @param sidList sid鍒楄〃
+     * @return 閽夐拤鐢ㄦ埛ID鍒楄〃
+     */
+    private List<String> getDingtalkUserIdListBySids(List<Long> sidList) {
+        try {
+            if (sidList == null || sidList.isEmpty()) {
+                return new ArrayList<>();
+            }
+
+            // 鍘婚噸
+            sidList = sidList.stream().distinct().collect(Collectors.toList());
+
+            // 鏍规嵁sid鏌ヨDingtalkInfo
+            List<DingtalkInfo> list = baseMapper.selectList(
+                    new LambdaQueryWrapper<DingtalkInfo>().in(DingtalkInfo::getSid, sidList)
+            );
+
+            if (list == null || list.isEmpty()) {
+                return new ArrayList<>();
+            }
+
+            // 浣跨敤stream娴佽繃婊ゅ嚭list涓璬ingtalkId涓虹┖鐨勬暟鎹�
+            List<DingtalkInfo> emptyDingtalkIdList = list.stream()
+                    .filter(info -> !StringUtils.hasText(info.getDingtalkId()))
+                    .collect(Collectors.toList());
+
+            // 濡傛灉瀛樺湪涓虹┖鐨勬暟鎹氨閫氳繃閽夐拤鐨勬帴鍙h幏鍙栵紝涓篸ingtalkId璧嬪�硷紝骞朵笖鏇存柊鏁版嵁搴�
+            if (!emptyDingtalkIdList.isEmpty()) {
+                String accessToken = simpleExample.getAccessToken();
+
+                for (DingtalkInfo info : emptyDingtalkIdList) {
+                    if (StringUtils.hasText(info.getPhone())) {
+                        try {
+                            // 閫氳繃鎵嬫満鍙疯幏鍙栭拤閽夌敤鎴稩D
+                            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)
+                    .distinct()
+                    .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(4104598880L);
+        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);
+
+    }
+
+    /**
+     * 鍙戦�乴ink娑堟伅锛堝湪閽夐拤鍐呯疆娴忚鍣ㄤ腑鎵撳紑锛�
+     *
+     * @param userIdListStr 鐢ㄦ埛ID鍒楄〃锛岄�楀彿鍒嗛殧
+     * @param title         娑堟伅鏍囬
+     * @param text          娑堟伅鍐呭
+     * @param messageUrl    鐐瑰嚮娑堟伅鍚庤烦杞殑URL
+     * @param picUrl        鍥剧墖URL锛堝彲閫夛級
+     * @return 鍝嶅簲缁撴灉
+     * @throws Exception 寮傚父
+     */
+    private OapiMessageCorpconversationAsyncsendV2Response sendLinkMessage(String userIdListStr, String title, String text, String messageUrl, String picUrl) 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(4104598880L);
+        request.setUseridList(userIdListStr);
+        request.setToAllUser(false);
+
+        OapiMessageCorpconversationAsyncsendV2Request.Msg msg = new OapiMessageCorpconversationAsyncsendV2Request.Msg();
+        msg.setMsgtype("link");
+        msg.setLink(new OapiMessageCorpconversationAsyncsendV2Request.Link());
+        msg.getLink().setTitle(title);
+        msg.getLink().setText(text);
+        msg.getLink().setMessageUrl(messageUrl);
+        if (StringUtils.hasText(picUrl)) {
+            msg.getLink().setPicUrl(picUrl);
+        }
+        request.setMsg(msg);
+
+        return client.execute(request, accessToken);
+
+    }
+
+    /**
+     * 鍙戦�丄ctionCard娑堟伅锛堝湪澶栭儴娴忚鍣ㄤ腑鎵撳紑閾炬帴锛岄�傚悎BI绛夊閮ㄧ郴缁燂級
+     *
+     * @param userIdListStr 鐢ㄦ埛ID鍒楄〃锛岄�楀彿鍒嗛殧
+     * @param title         娑堟伅鏍囬
+     * @param markdown      娑堟伅鍐呭锛堟敮鎸丮arkdown鏍煎紡锛�
+     * @param singleTitle   鎸夐挳鏂囧瓧锛屼緥濡傦細"鏌ョ湅璇︽儏"
+     * @param singleUrl     鐐瑰嚮鎸夐挳鍚庤烦杞殑URL锛堝閮ㄩ摼鎺ワ級
+     * @return 鍝嶅簲缁撴灉
+     * @throws Exception 寮傚父
+     */
+    private OapiMessageCorpconversationAsyncsendV2Response sendActionCardMessage(String userIdListStr, String title, String markdown, String singleTitle, String singleUrl) 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(4104598880L);
+        request.setUseridList(userIdListStr);
+        request.setToAllUser(false);
+
+        OapiMessageCorpconversationAsyncsendV2Request.Msg msg = new OapiMessageCorpconversationAsyncsendV2Request.Msg();
+        msg.setMsgtype("action_card");
+        msg.setActionCard(new OapiMessageCorpconversationAsyncsendV2Request.ActionCard());
+        msg.getActionCard().setTitle(title);
+        msg.getActionCard().setMarkdown(markdown);
+        msg.getActionCard().setSingleTitle(singleTitle);
+        msg.getActionCard().setSingleUrl(singleUrl);
+        request.setMsg(msg);
+
+        return client.execute(request, accessToken);
+
+    }
+
+    /**
+     * 涓婁紶鏂囦欢鍒伴拤閽夋湇鍔″櫒锛岃幏鍙杕edia_id
+     *
+     * @param filePath 鏈湴鏂囦欢璺緞
+     * @param fileType 鏂囦欢绫诲瀷锛歠ile(鏅�氭枃浠�), voice(璇煶鏂囦欢), video(瑙嗛鏂囦欢), image(鍥剧墖鏂囦欢)
+     * @return media_id
+     * @throws Exception 寮傚父
+     */
+    private String uploadMedia(String filePath, String fileType) throws Exception {
+        String accessToken = simpleExample.getAccessToken();
+
+        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/media/upload");
+        com.dingtalk.api.request.OapiMediaUploadRequest request = new com.dingtalk.api.request.OapiMediaUploadRequest();
+        request.setType(fileType);
+
+        // 浣跨敤 FileItem 鍖呰鏂囦欢
+        File file = new File(filePath);
+        FileItem fileItem = new FileItem(file);
+        request.setMedia(fileItem);
+
+        com.dingtalk.api.response.OapiMediaUploadResponse response = client.execute(request, accessToken);
+
+        if (response.getErrcode() == 0) {
+            log.info("鏂囦欢涓婁紶鎴愬姛锛宮edia_id: {}", response.getMediaId());
+            return response.getMediaId();
+        } else {
+            log.error("鏂囦欢涓婁紶澶辫触锛岄敊璇爜: {}, 閿欒淇℃伅: {}", response.getErrcode(), response.getErrmsg());
+            throw new Exception("鏂囦欢涓婁紶澶辫触: " + response.getErrmsg());
+        }
+    }
+
+    /**
+     * 閫氳繃media_id鍙戦�佹枃浠舵秷鎭�
+     *
+     * @param userIdListStr 鐢ㄦ埛ID鍒楄〃锛岄�楀彿鍒嗛殧
+     * @param mediaId       鏂囦欢鐨刴edia_id锛堥�氳繃uploadMedia鏂规硶鑾峰彇锛�
+     * @return 鍝嶅簲缁撴灉
+     * @throws Exception 寮傚父
+     */
+    private OapiMessageCorpconversationAsyncsendV2Response sendFileMessageByMediaId(String userIdListStr, String mediaId) 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(4104598880L);
+        request.setUseridList(userIdListStr);
+        request.setToAllUser(false);
+
+        OapiMessageCorpconversationAsyncsendV2Request.Msg msg = new OapiMessageCorpconversationAsyncsendV2Request.Msg();
+        msg.setMsgtype("file");
+        msg.setFile(new OapiMessageCorpconversationAsyncsendV2Request.File());
+        msg.getFile().setMediaId(mediaId);
+        request.setMsg(msg);
+
+        return client.execute(request, accessToken);
+
+    }
+
+    /**
+     * 鑾峰彇isSendDingtalk=1鐨勭敤鎴风殑閽夐拤鐢ㄦ埛ID鍒楄〃锛堜繚鐣欏師鏈夋柟娉曪紝鍚戝悗鍏煎锛�
+     */
     private List<String> getDingtalkUserIdList() {
         try {
             LambdaQueryWrapper<DingtalkInfo> wrapper = new LambdaQueryWrapper<>();
@@ -122,31 +479,12 @@
             return list.stream()
                     .map(DingtalkInfo::getDingtalkId)
                     .filter(StringUtils::hasText)
+                    .distinct()
                     .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);
-
     }
 }
 

--
Gitblit v1.9.3