package com.ruoyi.project.service.impl; import com.alibaba.fastjson2.JSONArray; import com.alibaba.fastjson2.JSONObject; import com.baomidou.mybatisplus.core.toolkit.ObjectUtils; import com.fasterxml.jackson.databind.ObjectMapper; import com.ruoyi.common.core.domain.entity.SysUser; import com.ruoyi.common.exception.base.BaseException; import com.ruoyi.common.utils.StringUtils; import com.ruoyi.common.utils.http.HttpUtils; import com.ruoyi.project.domain.vo.DingTalkReqVo; import com.ruoyi.project.service.DingTalkService; import com.ruoyi.project.utils.DingTalkProxyClient; import com.ruoyi.system.mapper.SysUserMapper; import com.taobao.api.ApiException; import lombok.extern.log4j.Log4j; import org.apache.commons.collections4.CollectionUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * 智能中心 * * @author ls * @date 2023-05-23 */ @Service @Log4j public class DingTalkServiceImpl implements DingTalkService { @Value("${dingAppid}") private String dingAppid; @Value("${dingAppSecret}") private String dingAppSecret; @Value("${agentId}") private Long agentId; @Autowired private SysUserMapper sysUserMapper; @Autowired private DingTalkProxyClient dingTalkProxyClient; @Override public Boolean sendNotification(DingTalkReqVo dingTalkReqVo) { String body = null; List userIdlist = new ArrayList(); Boolean result = false; log.info("发送钉钉通知"); String accessToken = null; try { accessToken = dingTalkProxyClient.getAccessToken(); } catch (ApiException e) { e.printStackTrace(); } if (StringUtils.isNotEmpty(dingTalkReqVo.getNumber())) { // 使用代理客户端调用获取用户ID接口 Map params = new HashMap<>(); params.put("access_token", accessToken); params.put("mobile", dingTalkReqVo.getNumber()); try { body = dingTalkProxyClient.executeGet("/topapi/v2/user/getbymobile", params); String jsonObject = JSONObject.parseObject(body).getJSONObject("result").get("userid").toString(); userIdlist.add(jsonObject); } catch (ApiException e) { e.printStackTrace(); } } else { // 使用代理客户端调用获取部门用户ID列表接口 Map params = new HashMap<>(); params.put("access_token", accessToken); params.put("dept_id", String.valueOf(dingTalkReqVo.getDeptId())); try { body = dingTalkProxyClient.executeGet("/topapi/user/listid", params); } catch (ApiException e) { e.printStackTrace(); } // 解析为JSONObject JSONObject jsonObject = JSONObject.parseObject(body); if (jsonObject != null) { // 提取出JSONArray JSONArray jsonArray = new JSONArray(jsonObject.getJSONObject("result").getJSONArray("userid_list")); // 将JSONArray转为List列表 String str = JSONObject.toJSONString(jsonArray); userIdlist = JSONObject.parseObject(str, List.class); } } //userid数组 for (String urid : userIdlist) { // 构建发送消息的完整JSON对象,符合钉钉API格式 Map messageData = new HashMap<>(); messageData.put("userid_list", urid); messageData.put("agent_id", agentId); messageData.put("to_all_user", false); //发送内容处理 List> contents = dingTalkReqVo.getContents(); List> objects = new ArrayList<>(); for (int i = 0; i < contents.size(); i++) { ConcurrentHashMap map = contents.get(i); for (Map.Entry entry : map.entrySet()) { Map formItem = new HashMap<>(); formItem.put("key", entry.getKey()); if (entry.getKey().contains("审批时间")) { Date date = (Date) entry.getValue(); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); String format = simpleDateFormat.format(date); formItem.put("value", format); } else { if (entry.getValue() != null) { formItem.put("value", entry.getValue().toString()); } else { formItem.put("value", ""); } } objects.add(formItem); } } Map msg = new HashMap<>(); Map oa = new HashMap<>(); oa.put("message_url", dingTalkReqVo.getUrl()); oa.put("pc_message_url", dingTalkReqVo.getUrl()); Map head = new HashMap<>(); head.put("bgcolor", "00409eff"); oa.put("head", head); Map bodyContent = new HashMap<>(); bodyContent.put("title", dingTalkReqVo.getTitle()); bodyContent.put("form", objects); oa.put("body", bodyContent); msg.put("oa", oa); msg.put("msgtype", "oa"); messageData.put("msg", msg); // 将access_token作为URL参数传递 String messageJson = JSONObject.toJSONString(messageData); try { // 使用代理客户端发送POST请求 body = dingTalkProxyClient.executePost("/topapi/message/corpconversation/asyncsend_v2?access_token=" + accessToken, messageJson); JSONObject response = JSONObject.parseObject(body); result = response.getInteger("errcode") == 0; } catch (ApiException e) { log.error("发送钉钉消息失败: " + e.getErrMsg()); } } return result; } /** * 免登陆接口 * * @param authCode * @return */ public Map noLogin(String authCode) { try { String params = "access_token=" + dingTalkProxyClient.getAccessToken() + "&code=" + authCode; String result = HttpUtils.sendPost("https://oapi.dingtalk.com/topapi/v2/user/getuserinfo", params); ObjectMapper objectMapper = new ObjectMapper(); Map map = objectMapper.readValue(result, Map.class); return map; } catch (Exception e) { log.error(e.getMessage()); new BaseException("登录出异常了,请联系管理员处理"); } return null; } @Override public void deptidList(Long deptID, Integer begin) { try { //根据传过来的部门ID,去获取该部门下的用户信息 if (begin != 1) DingUserInfoList(deptID); //获取子部门的dept_id Map params = new HashMap<>(); params.put("access_token", dingTalkProxyClient.getAccessToken()); params.put("dept_id", deptID.toString()); params.put("language", "zh_CN"); String rspBody = dingTalkProxyClient.executeGet("/topapi/v2/department/listsub", params); ObjectMapper objectMapper = new ObjectMapper(); Map map = objectMapper.readValue(rspBody, Map.class); if (ObjectUtils.isNotEmpty(map)) { List> dingDetpInfoList = (List>) map.get("result"); if (Integer.valueOf(map.get("errcode").toString()) == 0) { for (int i = 0; i < dingDetpInfoList.size(); i++) { Map map1 = dingDetpInfoList.get(i); deptidList(Long.valueOf(map1.get("dept_id").toString()), 2); } } } } catch (Exception e) { log.error(e.getMessage()); new BaseException("登录出异常了,请联系管理员处理"); } } public void DingUserInfoList(Long deptId) { try { Map params = new HashMap<>(); params.put("access_token", dingTalkProxyClient.getAccessToken()); params.put("dept_id", deptId.toString()); params.put("cursor", "0"); params.put("size", "100"); params.put("language", "zh_CN"); String rspBody = dingTalkProxyClient.executeGet("/topapi/v2/user/list", params); //获取resp里的用户信息集合 ObjectMapper objectMapper = new ObjectMapper(); Map map = objectMapper.readValue(rspBody, Map.class); Map mapResult = (Map) map.get("result"); List> userInfoMapList = (List>) mapResult.get("list"); if (!CollectionUtils.isEmpty(userInfoMapList)) { //根据手机号,将userID写进对应的字段上 for (Map objectMap : userInfoMapList) { SysUser sysUser = new SysUser(); sysUser.setPhonenumber(objectMap.get("mobile").toString()); sysUser.setDingUserId(objectMap.get("userid").toString()); sysUserMapper.updateUser(sysUser); } } } catch (Exception e) { e.printStackTrace(); } } /** * 获取 access_token */ private String getAccessToken() throws ApiException { return dingTalkProxyClient.getAccessToken(); } }