浏览代码

Merge branch 'fu-dev' of uskycloud/usky-cloud into master

gez 2 周之前
父节点
当前提交
5ab687398c
共有 14 个文件被更改,包括 530 次插入127 次删除
  1. 1 1
      base-common/ruoyi-common-datascope/src/main/java/com/ruoyi/common/datascope/aspect/DataScopeAspect.java
  2. 17 4
      base-modules/service-system/service-system-api/src/main/java/com/usky/system/RemoteMceService.java
  3. 62 0
      base-modules/service-system/service-system-api/src/main/java/com/usky/system/domain/MceRequestVO.java
  4. 12 10
      base-modules/service-system/service-system-api/src/main/java/com/usky/system/factory/RemoteMceFallbackFactory.java
  5. 2 0
      base-modules/service-system/service-system-biz/src/main/java/com/usky/system/RuoYiSystemApplication.java
  6. 8 1
      base-modules/service-system/service-system-biz/src/main/java/com/usky/system/controller/api/SysMceControllerApi.java
  7. 11 0
      base-modules/service-system/service-system-biz/src/main/java/com/usky/system/domain/SysNotice.java
  8. 3 0
      base-modules/service-system/service-system-biz/src/main/java/com/usky/system/service/MceContentService.java
  9. 3 0
      base-modules/service-system/service-system-biz/src/main/java/com/usky/system/service/MceReceiveService.java
  10. 36 8
      base-modules/service-system/service-system-biz/src/main/java/com/usky/system/service/impl/MceContentServiceImpl.java
  11. 34 33
      base-modules/service-system/service-system-biz/src/main/java/com/usky/system/service/impl/MceMbuserServiceImpl.java
  12. 295 55
      base-modules/service-system/service-system-biz/src/main/java/com/usky/system/service/impl/MceReceiveServiceImpl.java
  13. 38 14
      base-modules/service-system/service-system-biz/src/main/java/com/usky/system/service/impl/SysNoticeServiceImpl.java
  14. 8 1
      base-modules/service-system/service-system-biz/src/main/resources/mapper/system/SysNoticeMapper.xml

+ 1 - 1
base-common/ruoyi-common-datascope/src/main/java/com/ruoyi/common/datascope/aspect/DataScopeAspect.java

@@ -101,7 +101,7 @@ public class DataScopeAspect
             else if (DATA_SCOPE_CUSTOM.equals(dataScope))
             {
                 sqlString.append(StringUtils.format(" OR {}.dept_id IN ( SELECT dept_id FROM sys_role_dept WHERE role_id = {} ) ", deptAlias, role.getRoleId()));
-                sqlLambda.append(StringUtils.format(" OR dept_id IN ( SELECT dept_id FROM sys_role_dept WHERE role_id = {} ) ", deptAlias, role.getRoleId()));
+                sqlLambda.append(StringUtils.format(" OR dept_id IN ( SELECT dept_id FROM sys_role_dept WHERE role_id = {} ) ", role.getRoleId()));
             }
             else if (DATA_SCOPE_DEPT.equals(dataScope))
             {

+ 17 - 4
base-modules/service-system/service-system-api/src/main/java/com/usky/system/RemoteMceService.java

@@ -2,6 +2,8 @@ package com.usky.system;
 
 
 import com.usky.common.core.bean.ApiResult;
+
+import com.usky.system.domain.MceRequestVO;
 import com.usky.system.factory.RemoteMceFallbackFactory;
 import org.springframework.cloud.openfeign.FeignClient;
 import org.springframework.http.MediaType;
@@ -11,19 +13,30 @@ import org.springframework.web.bind.annotation.RequestBody;
 
 /**
  * 消息服务
- * 
+ *
  * @author ruoyi
  */
 @FeignClient(contextId = "remoteMceService", value = "usky-system", fallbackFactory = RemoteMceFallbackFactory.class)
-public interface RemoteMceService
-{
+public interface RemoteMceService {
     /**
      * 新增消息推送
      *
      * @param mceInfo 消息信息
      * @return 结果
      */
-    @PostMapping(value = "/addMce",produces= MediaType.APPLICATION_JSON_UTF8_VALUE,consumes = "application/json;" +
+    @PostMapping(value = "/addMce", produces = MediaType.APPLICATION_JSON_UTF8_VALUE, consumes = "application/json;" +
             "charset=UTF-8")
     public ApiResult<Void> addMce(@RequestBody String mceInfo);
+
+    /**
+     * @description: 消息推送-新
+     * @author: fyc
+     * @email yuchuan.fu@chinausky.com
+     * @date: 2025/3/14 14:58
+     * @param: [mceInfo]
+     * @return: com.usky.common.core.bean.ApiResult<java.lang.Void>
+     **/
+    @PostMapping(value = "/addMceReceive")
+    ApiResult<Void> addMceReceive(MceRequestVO mceInfo);
+
 }

+ 62 - 0
base-modules/service-system/service-system-api/src/main/java/com/usky/system/domain/MceRequestVO.java

@@ -0,0 +1,62 @@
+package com.usky.system.domain;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.usky.common.core.bean.BaseEntity;
+import lombok.Data;
+import lombok.EqualsAndHashCode;
+import lombok.extern.slf4j.Slf4j;
+
+import javax.validation.constraints.NotBlank;
+import javax.validation.constraints.NotNull;
+import java.util.List;
+
+/**
+ *
+ * @author fyc
+ * @email yuchuan.fu@chinausky.com
+ * @date 2025/3/13
+ */
+@EqualsAndHashCode(callSuper = true)
+@Slf4j
+@Data
+public class MceRequestVO  extends BaseEntity {
+
+    /** 字典标签  */
+    private String infoTypeName;
+
+    /** 消息类型  */
+    @NotBlank(message = "消息类型 infoType 不能为空!")
+    private String infoType;
+
+    /** 消息标题  */
+    @NotBlank(message = "消息标题 infoTitle 不能为空!")
+    private String infoTitle;
+
+    /** 消息内容  */
+    @NotBlank(message = "消息内容 infoContent 不能为空!")
+    private String infoContent;
+
+    /** 消息发布人  */
+    @NotBlank(message = "消息发布人 userName 不能为空!")
+    private String userName;
+
+    /** 消息详情id  */
+    @NotNull(message = "消息详情 id 不能为空!")
+    private Integer id;
+
+    /** 消息接收人userId集合  */
+    @NotNull(message = "消息接收人 userIds 不能为空!")
+    private List<Long> userIds;
+
+    @Override
+    public String toString() {
+        ObjectMapper objectMapper = new ObjectMapper();
+        try {
+            return objectMapper.writeValueAsString(this);
+        } catch (JsonProcessingException e) {
+            log.error("MceRequestVO toString error: {}", e.getMessage());
+            return "{}";
+        }
+    }
+}

+ 12 - 10
base-modules/service-system/service-system-api/src/main/java/com/usky/system/factory/RemoteMceFallbackFactory.java

@@ -3,6 +3,7 @@ package com.usky.system.factory;
 
 import com.usky.common.core.bean.ApiResult;
 import com.usky.system.RemoteMceService;
+import com.usky.system.domain.MceRequestVO;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.springframework.cloud.openfeign.FallbackFactory;
@@ -10,24 +11,25 @@ import org.springframework.stereotype.Component;
 
 /**
  * 消息服务降级处理
- * 
+ *
  * @author ruoyi
  */
 @Component
-public class RemoteMceFallbackFactory implements FallbackFactory<RemoteMceService>
-{
+public class RemoteMceFallbackFactory implements FallbackFactory<RemoteMceService> {
     private static final Logger log = LoggerFactory.getLogger(RemoteMceFallbackFactory.class);
 
     @Override
-    public RemoteMceService create(Throwable throwable)
-    {
+    public RemoteMceService create(Throwable throwable) {
         log.error("用户服务调用失败:{}", throwable.getMessage());
-        return new RemoteMceService()
-        {
+        return new RemoteMceService() {
             @Override
-            public ApiResult<Void> addMce(String mceInfo)
-            {
-                return ApiResult.error("500","新增消息失败:" + throwable.getMessage());
+            public ApiResult<Void> addMce(String mceInfo) {
+                return ApiResult.error("500", "新增消息失败:" + throwable.getMessage());
+            }
+
+            @Override
+            public ApiResult<Void> addMceReceive(MceRequestVO mceInfo) {
+                return ApiResult.error("500", "新增消息失败:" + throwable.getMessage());
             }
         };
     }

+ 2 - 0
base-modules/service-system/service-system-biz/src/main/java/com/usky/system/RuoYiSystemApplication.java

@@ -12,6 +12,7 @@ import org.springframework.context.ConfigurableApplicationContext;
 import org.springframework.context.annotation.ComponentScan;
 import org.springframework.context.annotation.EnableAspectJAutoProxy;
 import org.springframework.core.env.Environment;
+import org.springframework.scheduling.annotation.EnableAsync;
 
 import java.net.InetAddress;
 import java.net.UnknownHostException;
@@ -28,6 +29,7 @@ import java.net.UnknownHostException;
 @MapperScan(value = "com.usky.system.mapper")
 @ComponentScan(basePackages = {"com.usky"})
 @SpringBootApplication
+@EnableAsync
 public class RuoYiSystemApplication
 {
     private static final Logger LOGGER = LoggerFactory.getLogger(RuoYiSystemApplication.class);

+ 8 - 1
base-modules/service-system/service-system-biz/src/main/java/com/usky/system/controller/api/SysMceControllerApi.java

@@ -2,15 +2,16 @@ package com.usky.system.controller.api;
 
 import com.usky.common.core.bean.ApiResult;
 import com.usky.system.RemoteMceService;
+import com.usky.system.domain.MceRequestVO;
 import com.usky.system.service.MceReceiveService;
 import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.web.bind.annotation.RequestBody;
 import org.springframework.web.bind.annotation.RestController;
 
 
 @RestController
 public class SysMceControllerApi implements RemoteMceService {
 
-
     @Autowired
     private MceReceiveService mceReceiveService;
 
@@ -19,4 +20,10 @@ public class SysMceControllerApi implements RemoteMceService {
         mceReceiveService.add(mceInfo);
         return ApiResult.success();
     }
+
+    @Override
+    public ApiResult<Void> addMceReceive(@RequestBody MceRequestVO mceRequestVO) {
+        mceReceiveService.addMceReceive(mceRequestVO);
+        return ApiResult.success();
+    }
 }

+ 11 - 0
base-modules/service-system/service-system-biz/src/main/java/com/usky/system/domain/SysNotice.java

@@ -73,6 +73,9 @@ public class SysNotice {
     @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
     private LocalDateTime updateTime;
 
+    /** 租户id */
+    private Integer tenantId;
+
     public Integer getNoticeId() {
         return noticeId;
     }
@@ -190,6 +193,14 @@ public class SysNotice {
         this.updateTime = updateTime;
     }
 
+    public Integer getTenantId() {
+        return tenantId;
+    }
+
+    public void setTenantId(Integer tenantId) {
+        this.tenantId = tenantId;
+    }
+
     @Override
     public String toString() {
         return new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE)

+ 3 - 0
base-modules/service-system/service-system-biz/src/main/java/com/usky/system/service/MceContentService.java

@@ -3,6 +3,7 @@ package com.usky.system.service;
 import com.alibaba.fastjson.JSONObject;
 import com.usky.system.domain.MceContent;
 import com.usky.common.mybatis.core.CrudService;
+import com.usky.system.domain.MceRequestVO;
 
 /**
  * <p>
@@ -13,6 +14,8 @@ import com.usky.common.mybatis.core.CrudService;
  * @since 2024-05-09
  */
 public interface MceContentService extends CrudService<MceContent> {
+
     void sendApp(JSONObject mceReceiveVO, String cids, Integer mceReceiveId, Integer sendType);
 
+    void sendAppNew(MceRequestVO mceRequestVO, String cids, Integer mceReceiveId, Integer sendType);
 }

+ 3 - 0
base-modules/service-system/service-system-biz/src/main/java/com/usky/system/service/MceReceiveService.java

@@ -3,6 +3,7 @@ package com.usky.system.service;
 import com.usky.common.core.bean.CommonPage;
 import com.usky.system.domain.MceReceive;
 import com.usky.common.mybatis.core.CrudService;
+import com.usky.system.domain.MceRequestVO;
 
 import java.util.Map;
 
@@ -26,6 +27,8 @@ public interface MceReceiveService extends CrudService<MceReceive> {
 
     void updateMceReceive(MceReceive mceReceive);
 
+    void addMceReceive(MceRequestVO mceRequestVO);
+
     void add(String mceReceive);
 
     boolean removeById(Integer id);

+ 36 - 8
base-modules/service-system/service-system-biz/src/main/java/com/usky/system/service/impl/MceContentServiceImpl.java

@@ -10,10 +10,12 @@ import com.usky.system.service.MceMbuserService;
 import com.usky.system.service.config.websocket.HttpClientUtils;
 import com.usky.system.service.vo.SendWeChatMessageRequestVO;
 import lombok.extern.slf4j.Slf4j;
+import org.apache.commons.lang3.StringUtils;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.beans.factory.annotation.Value;
 import org.springframework.scheduling.annotation.Async;
 import org.springframework.stereotype.Service;
+import com.usky.system.domain.MceRequestVO;
 
 /**
  * <p>
@@ -33,20 +35,20 @@ public class MceContentServiceImpl extends AbstractCrudService<MceContentMapper,
     @Value("${appUrl}")
     private String appUrl;
 
-    //异步多线程调用
-    @Async("asyncServiceExecutor")
-    public void sendApp(JSONObject mceReceiveVO, String cids, Integer mceReceiveId, Integer sendType){
-        if (sendType.equals(0)){
+    // 异步多线程调用
+    @Async
+    public void sendApp(JSONObject mceReceiveVO, String cids, Integer mceReceiveId, Integer sendType) {
+        if (sendType.equals(0)) {
             JsonObject jsonObject = new JsonObject();
             JsonObject jsonObject1 = new JsonObject();
             jsonObject1.addProperty("infoType", mceReceiveVO.get("infoType").toString());
-            jsonObject1.addProperty("moduleId", (int)mceReceiveVO.get("id"));
+            jsonObject1.addProperty("moduleId", (int) mceReceiveVO.get("id"));
             jsonObject.addProperty("cids", cids);
             jsonObject.addProperty("title", mceReceiveVO.get("infoTitle").toString());
             jsonObject.addProperty("content", mceReceiveVO.get("infoContent").toString());
-            jsonObject.add("payload",jsonObject1);
-            String resultString = HttpClientUtils.doPostJson(appUrl,jsonObject.toString());
-        }else if (sendType.equals(1)){
+            jsonObject.add("payload", jsonObject1);
+            String resultString = HttpClientUtils.doPostJson(appUrl, jsonObject.toString());
+        } else if (sendType.equals(1)) {
             SendWeChatMessageRequestVO sendWeChatMessageRequestVO = new SendWeChatMessageRequestVO();
             sendWeChatMessageRequestVO.setInfoContent(mceReceiveVO.get("infoContent").toString());
             sendWeChatMessageRequestVO.setInfoTitle(mceReceiveVO.get("infoTitle").toString());
@@ -59,4 +61,30 @@ public class MceContentServiceImpl extends AbstractCrudService<MceContentMapper,
             mceMbuserService.sendWeChatMessage(sendWeChatMessageRequestVO);
         }
     }
+
+    @Async
+    public void sendAppNew(MceRequestVO mceReceiveVO, String cids, Integer mceReceiveId, Integer sendType) {
+        if (sendType.equals(0)) {
+            JsonObject jsonObject = new JsonObject();
+            JsonObject jsonObject1 = new JsonObject();
+            jsonObject1.addProperty("infoType", mceReceiveVO.getInfoType());
+            jsonObject1.addProperty("moduleId", mceReceiveVO.getId());
+            jsonObject.addProperty("cids", cids);
+            jsonObject.addProperty("title", mceReceiveVO.getInfoTitle());
+            jsonObject.addProperty("content", mceReceiveVO.getInfoContent());
+            jsonObject.add("payload", jsonObject1);
+            String resultString = HttpClientUtils.doPostJson(appUrl, jsonObject.toString());
+        } else if (sendType.equals(1)) {
+            SendWeChatMessageRequestVO sendWeChatMessageRequestVO = new SendWeChatMessageRequestVO();
+            sendWeChatMessageRequestVO.setInfoContent(mceReceiveVO.getInfoContent());
+            sendWeChatMessageRequestVO.setInfoTitle(mceReceiveVO.getInfoTitle());
+            sendWeChatMessageRequestVO.setInfoId(mceReceiveId);
+            sendWeChatMessageRequestVO.setOpenId(cids);
+            sendWeChatMessageRequestVO.setInfoType(mceReceiveVO.getInfoType());
+            if (StringUtils.isNotEmpty(mceReceiveVO.getInfoTypeName())) {
+                sendWeChatMessageRequestVO.setInfoTypeName(mceReceiveVO.getInfoTypeName());
+            }
+            mceMbuserService.sendWeChatMessage(sendWeChatMessageRequestVO);
+        }
+    }
 }

+ 34 - 33
base-modules/service-system/service-system-biz/src/main/java/com/usky/system/service/impl/MceMbuserServiceImpl.java

@@ -61,13 +61,13 @@ public class MceMbuserServiceImpl extends AbstractCrudService<MceMbuserMapper, M
         return null;
     }
 
-    public static long getTimeDifference(String oldTime,String newTime) throws ParseException {
+    public static long getTimeDifference(String oldTime, String newTime) throws ParseException {
 
         SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
-        long NTime =df.parse(newTime).getTime();
-        //从对象中拿到时间
+        long NTime = df.parse(newTime).getTime();
+        // 从对象中拿到时间
         long OTime = df.parse(oldTime).getTime();
-        long diff=(NTime-OTime)/1000/60;
+        long diff = (NTime - OTime) / 1000 / 60;
         return diff;
     }
 
@@ -79,60 +79,61 @@ public class MceMbuserServiceImpl extends AbstractCrudService<MceMbuserMapper, M
         Integer infoId = requestVO.getInfoId();
         String openId = requestVO.getOpenId();
 
-        //access_token时效校验,判断获取access_token获取时间是否超过有效时间,超过就调用更新,保证一直有效
-        if(!redisHelper.hasKey("access_key")){
+        // access_token时效校验,判断获取access_token获取时间是否超过有效时间,超过就调用更新,保证一直有效
+        if (!redisHelper.hasKey("access_key")) {
             redisHelper.set("access_time", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
-            redisHelper.set("access_key",this.getWeChatAccessToken());
-        }else{
-            try{
+            redisHelper.set("access_key", this.getWeChatAccessToken());
+        } else {
+            try {
                 String access_time = redisHelper.get("access_time").toString();
                 String now_time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
-                long i = getTimeDifference(access_time,now_time);
-                if(i > 115){ //大于115分钟
-                    redisHelper.set("access_time",LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
-                    redisHelper.set("access_key",this.getWeChatAccessToken());
+                long i = getTimeDifference(access_time, now_time);
+                if (i > 115) { // 大于115分钟
+                    redisHelper.set("access_time", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
+                    redisHelper.set("access_key", this.getWeChatAccessToken());
                 }
-            }catch (Exception e){
+            } catch (Exception e) {
                 throw new BusinessException(e.getMessage());
             }
 
         }
 
         Object obj = redisHelper.get("access_key");
-        if(obj == null){
-            throw new BusinessException("token不能为空");
+        if (obj == null) {
+            log.error("消息接收id:" + requestVO.getInfoId() + ",token为空,发送微信服务号消息失败");
+            return null;
         }
 
         String token = obj.toString();
 
-        TemplateMsgEntityVO messageVo=new TemplateMsgEntityVO();
+        TemplateMsgEntityVO messageVo = new TemplateMsgEntityVO();
         messageVo.setTTitle(infoTitle);
         messageVo.setTKeyword1(infoContent);
         messageVo.setTKeyword3(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
         messageVo.setTRemark(infoContent);
-        if(Objects.nonNull(requestVO.getInfoTypeName())){
-            messageVo.setTUrl(String.format(constant.WE_CHAT_CUSTOMER_CALL_URL,requestVO.getInfoType(),requestVO.getInfoTypeName(),infoId));
+        if (Objects.nonNull(requestVO.getInfoTypeName())) {
+            messageVo.setTUrl(String.format(constant.WE_CHAT_CUSTOMER_CALL_URL, requestVO.getInfoType(), requestVO.getInfoTypeName(), infoId));
             messageVo.setTKeyword2(requestVO.getInfoTypeName());
-        }else{
-            messageVo.setTUrl(String.format(constant.WE_CHAT_CUSTOMER_CALL_URL1,requestVO.getInfoType(),infoId));
+        } else {
+            messageVo.setTUrl(String.format(constant.WE_CHAT_CUSTOMER_CALL_URL1, requestVO.getInfoType(), infoId));
             messageVo.setTKeyword2("");
         }
 
         messageVo.setTemplateId(constant.WE_CHAT_TEMPLATE_ID);
 
-        String requestUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="  + token;
-        Map<String,Object> content=new HashMap<>();
+        String requestUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + token;
+        Map<String, Object> content = new HashMap<>();
         Map<String, TemplateData> data = new HashMap<>();
-        data.put("first",new TemplateData(messageVo.getTTitle(),"#44b549"));
-        data.put("keyword1",new TemplateData(messageVo.getTKeyword1(),"#173177"));
-        data.put("keyword2",new TemplateData(messageVo.getTKeyword2(),"#173177"));
-        data.put("keyword3",new TemplateData(messageVo.getTKeyword3(),"#173177"));
-        data.put("remark",new TemplateData(messageVo.getTRemark(),"#173177"));
-
-        content.put("touser",openId);
-        content.put("url",messageVo.getTUrl());
-        content.put("template_id",messageVo.getTemplateId());
-        content.put("data",data);
+        data.put("first", new TemplateData(messageVo.getTTitle(), "#44b549"));
+        data.put("keyword1", new TemplateData(messageVo.getTKeyword1(), "#173177"));
+        data.put("keyword2", new TemplateData(messageVo.getTKeyword2(), "#173177"));
+        data.put("keyword3", new TemplateData(messageVo.getTKeyword3(), "#173177"));
+        data.put("remark", new TemplateData(messageVo.getTRemark(), "#173177"));
+
+        content.put("touser", openId);
+        content.put("url", messageVo.getTUrl());
+        content.put("template_id", messageVo.getTemplateId());
+        content.put("data", data);
         String resp = HttpUtil.post(requestUrl, JSONUtil.parseObj(content).toString());
         System.out.println(content.toString());
         System.out.println(JSONUtil.parseObj(content));

+ 295 - 55
base-modules/service-system/service-system-biz/src/main/java/com/usky/system/service/impl/MceReceiveServiceImpl.java

@@ -10,23 +10,22 @@ import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
 import com.baomidou.mybatisplus.core.toolkit.StringUtils;
 import com.baomidou.mybatisplus.core.toolkit.Wrappers;
 import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
-import com.ruoyi.common.datascope.annotation.DataScope;
-import com.ruoyi.common.datascope.context.DataScopeContextHolder;
-import com.usky.common.core.bean.ApiResult;
 import com.usky.common.core.bean.CommonPage;
 import com.usky.common.security.utils.SecurityUtils;
-import com.usky.system.RemoteUserService;
 import com.usky.system.domain.*;
 import com.usky.system.mapper.MceReceiveMapper;
+import com.usky.system.mapper.MceSettingMapper;
 import com.usky.system.mapper.SysUserMapper;
 import com.usky.system.service.*;
 import com.usky.common.mybatis.core.AbstractCrudService;
 import lombok.extern.slf4j.Slf4j;
 import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.scheduling.annotation.Async;
 import org.springframework.stereotype.Service;
 
 import java.time.LocalDateTime;
 import java.util.*;
+import java.util.stream.Collectors;
 
 /**
  * <p>
@@ -56,35 +55,37 @@ public class MceReceiveServiceImpl extends AbstractCrudService<MceReceiveMapper,
 
     @Autowired
     private SysUserMapper userMapper;
+    @Autowired
+    private MceSettingMapper mceSettingMapper;
 
     @Override
     public CommonPage<Object> mceList(String infoTitle, String infoType, String startTime, String endTime, Integer id, Integer current, Integer size) {
         List<Object> list = new ArrayList<>();
         LambdaQueryWrapper<MceContent> lambdaQuery1 = Wrappers.lambdaQuery();
         lambdaQuery1.select(MceContent::getId, MceContent::getInfoTitle, MceContent::getInfoContent)
-                .like(StringUtils.isNotBlank(infoTitle),MceContent::getInfoTitle,infoTitle)
-                .eq(id != null,MceContent::getId,id);
+                .like(StringUtils.isNotBlank(infoTitle), MceContent::getInfoTitle, infoTitle)
+                .eq(id != null, MceContent::getId, id);
         List<MceContent> list1 = mceContentService.list(lambdaQuery1);
         IPage<MceReceive> page = new Page<>(current, size);
         List<Integer> contentIds = new ArrayList<>();
-        if (CollectionUtils.isNotEmpty(list1)){
-            for(int i=0;i<list1.size();i++){
+        if (CollectionUtils.isNotEmpty(list1)) {
+            for (int i = 0; i < list1.size(); i++) {
                 contentIds.add(list1.get(i).getId());
             }
             Long userId = SecurityUtils.getUserId();
             LambdaQueryWrapper<MceReceive> lambdaQuery = Wrappers.lambdaQuery();
             lambdaQuery.select(MceReceive::getId, MceReceive::getInfoType,
-                    MceReceive::getContentId, MceReceive::getReadFlag, MceReceive::getCreateTime,
-                    MceReceive::getReceiverId,MceReceive::getModuleId)
-                    .between(StringUtils.isNotBlank(startTime)&&StringUtils.isNotBlank(endTime),MceReceive::getCreateTime,
-                            startTime,endTime)
-                    .eq(StringUtils.isNotBlank(infoType),MceReceive::getInfoType, infoType)
+                            MceReceive::getContentId, MceReceive::getReadFlag, MceReceive::getCreateTime,
+                            MceReceive::getReceiverId, MceReceive::getModuleId)
+                    .between(StringUtils.isNotBlank(startTime) && StringUtils.isNotBlank(endTime), MceReceive::getCreateTime,
+                            startTime, endTime)
+                    .eq(StringUtils.isNotBlank(infoType), MceReceive::getInfoType, infoType)
                     .eq(MceReceive::getReceiverId, SecurityUtils.getUserId())
-                    .in(CollectionUtils.isNotEmpty(contentIds),MceReceive::getContentId,contentIds)
+                    .in(CollectionUtils.isNotEmpty(contentIds), MceReceive::getContentId, contentIds)
                     .orderByDesc(MceReceive::getId);
 //                .inSql(StringUtils.isNotBlank(infoTitle),MceReceive::getContentId,"SELECT id FROM mce_content WHERE " +
 //                        "info_title like '%" + infoTitle + "%' AND tenant_id = "+SecurityUtils.getTenantId()+"");
-            page = this.page(page,lambdaQuery);
+            page = this.page(page, lambdaQuery);
             if (CollectionUtils.isNotEmpty(page.getRecords())) {
                 for (int i = 0; i < page.getRecords().size(); i++) {
                     Map<String, Object> map = new HashMap<>();
@@ -96,7 +97,7 @@ public class MceReceiveServiceImpl extends AbstractCrudService<MceReceiveMapper,
                     if (CollectionUtils.isNotEmpty(list1)) {
                         for (int j = 0; j < list1.size(); j++) {
                             if (page.getRecords().get(i).getContentId().equals(list1.get(j).getId())) {
-                                map.put("contentId",list1.get(j).getId());
+                                map.put("contentId", list1.get(j).getId());
                                 map.put("infoTitle", list1.get(j).getInfoTitle());
                                 map.put("infoContent", list1.get(j).getInfoContent());
                             }
@@ -106,7 +107,7 @@ public class MceReceiveServiceImpl extends AbstractCrudService<MceReceiveMapper,
                 }
             }
         }
-        return new CommonPage<>(list,page.getTotal(),page.getCurrent(),page.getSize());
+        return new CommonPage<>(list, page.getTotal(), page.getCurrent(), page.getSize());
     }
 
     @Override
@@ -114,16 +115,16 @@ public class MceReceiveServiceImpl extends AbstractCrudService<MceReceiveMapper,
     public CommonPage<Object> mceManageList(String infoTitle, String infoType, String startTime, String endTime, Integer current, Integer size) {
         List<Object> list = new ArrayList<>();
         IPage<MceContent> page = new Page<>(current, size);
-        //查询消息内容
+        // 查询消息内容
         LambdaQueryWrapper<MceContent> lambdaQuery1 = Wrappers.lambdaQuery();
-        lambdaQuery1.select(MceContent::getId, MceContent::getInfoTitle, MceContent::getInfoContent, MceContent::getCreateTime,MceContent::getInfoType)
-                .like(StringUtils.isNotBlank(infoTitle),MceContent::getInfoTitle,infoTitle)
-                .between(StringUtils.isNotBlank(startTime)&&StringUtils.isNotBlank(endTime),MceContent::getCreateTime, startTime,endTime)
-                .eq(StringUtils.isNotBlank(infoType),MceContent::getInfoType, infoType)
+        lambdaQuery1.select(MceContent::getId, MceContent::getInfoTitle, MceContent::getInfoContent, MceContent::getCreateTime, MceContent::getInfoType)
+                .like(StringUtils.isNotBlank(infoTitle), MceContent::getInfoTitle, infoTitle)
+                .between(StringUtils.isNotBlank(startTime) && StringUtils.isNotBlank(endTime), MceContent::getCreateTime, startTime, endTime)
+                .eq(StringUtils.isNotBlank(infoType), MceContent::getInfoType, infoType)
 //                .apply(DataScopeContextHolder.getDataScopeSql())
-                .eq(MceContent::getTenantId,SecurityUtils.getTenantId())
+                .eq(MceContent::getTenantId, SecurityUtils.getTenantId())
                 .orderByDesc(MceContent::getId);
-        page = mceContentService.page(page,lambdaQuery1);
+        page = mceContentService.page(page, lambdaQuery1);
 
         if (CollectionUtils.isNotEmpty(page.getRecords())) {
             List<Integer> contentIds = new ArrayList<>();
@@ -131,11 +132,11 @@ public class MceReceiveServiceImpl extends AbstractCrudService<MceReceiveMapper,
                 contentIds.add(page.getRecords().get(i).getId());
             }
             QueryWrapper<MceReceive> queryWrapper = Wrappers.query();
-            queryWrapper.select("content_id AS contentId","COUNT(read_flag=0 or null) as notReadCount","COUNT" +
-                    "(read_flag=1 or null) as readCount","issuer_name AS issuerName")
-                    .in("content_id",contentIds)
-                    .groupBy("content_id","issuer_name");
-            List<Map<String,Object>> readStatisticList = this.listMaps(queryWrapper);
+            queryWrapper.select("content_id AS contentId", "COUNT(read_flag=0 or null) as notReadCount", "COUNT" +
+                            "(read_flag=1 or null) as readCount", "issuer_name AS issuerName")
+                    .in("content_id", contentIds)
+                    .groupBy("content_id", "issuer_name");
+            List<Map<String, Object>> readStatisticList = this.listMaps(queryWrapper);
             for (int i = 0; i < page.getRecords().size(); i++) {
                 Map<String, Object> map = new HashMap<>();
                 map.put("id", page.getRecords().get(i).getId());
@@ -144,7 +145,7 @@ public class MceReceiveServiceImpl extends AbstractCrudService<MceReceiveMapper,
                 map.put("infoType", page.getRecords().get(i).getInfoType());
                 map.put("createTime", page.getRecords().get(i).getCreateTime());
                 for (int j = 0; j < readStatisticList.size(); j++) {
-                    if (page.getRecords().get(i).getId().equals(readStatisticList.get(j).get("contentId"))){
+                    if (page.getRecords().get(i).getId().equals(readStatisticList.get(j).get("contentId"))) {
                         map.put("notReadCount", readStatisticList.get(j).get("notReadCount"));
                         map.put("readCount", readStatisticList.get(j).get("readCount"));
                         map.put("userName", readStatisticList.get(j).get("issuerName"));
@@ -154,15 +155,15 @@ public class MceReceiveServiceImpl extends AbstractCrudService<MceReceiveMapper,
             }
         }
 
-        return new CommonPage<>(list,page.getTotal(),page.getCurrent(),page.getSize());
+        return new CommonPage<>(list, page.getTotal(), page.getCurrent(), page.getSize());
     }
 
     @Override
     public CommonPage<MceReceive> mceManageById(Integer id, Integer current, Integer size) {
         IPage<MceReceive> page = new Page<>(current, size);
         LambdaQueryWrapper<MceReceive> lambdaQuery = Wrappers.lambdaQuery();
-        lambdaQuery.eq(MceReceive::getContentId,id);
-        page = this.page(page,lambdaQuery);
+        lambdaQuery.eq(MceReceive::getContentId, id);
+        page = this.page(page, lambdaQuery);
 //        if (CollectionUtils.isNotEmpty(page.getRecords())) {
 //            List<Integer> userIds = new ArrayList<>();
 //            for (int i = 0; i < page.getRecords().size(); i++) {
@@ -185,7 +186,7 @@ public class MceReceiveServiceImpl extends AbstractCrudService<MceReceiveMapper,
 //                }
 //            }
 //        }
-        return new CommonPage<>(page.getRecords(),page.getTotal(),page.getCurrent(),page.getSize());
+        return new CommonPage<>(page.getRecords(), page.getTotal(), page.getCurrent(), page.getSize());
     }
 
     @Override
@@ -194,15 +195,15 @@ public class MceReceiveServiceImpl extends AbstractCrudService<MceReceiveMapper,
         LocalDateTime oneYearAgo = currentDate.minusYears(1);
         LocalDateTime zeroTime = oneYearAgo.withHour(0).withMinute(0).withSecond(0);
         QueryWrapper<MceReceive> queryWrapper = Wrappers.query();
-        queryWrapper.select("COUNT(read_flag=0 or null) as notReadCount","COUNT(read_flag=1 or null) as readCount"
-                ,"info_type AS infoType")
-                .eq("receiver_id",SecurityUtils.getUserId())
-                .between("create_time",zeroTime,currentDate)
+        queryWrapper.select("COUNT(read_flag=0 or null) as notReadCount", "COUNT(read_flag=1 or null) as readCount"
+                        , "info_type AS infoType")
+                .eq("receiver_id", SecurityUtils.getUserId())
+                .between("create_time", zeroTime, currentDate)
                 .groupBy("info_type");
-        List<Map<String,Object>> readStatisticList = this.listMaps(queryWrapper);
+        List<Map<String, Object>> readStatisticList = this.listMaps(queryWrapper);
         LambdaQueryWrapper<MceReceive> lambdaQuery = Wrappers.lambdaQuery();
-        lambdaQuery.eq(MceReceive::getReceiverId,SecurityUtils.getUserId())
-                .eq(MceReceive::getReadFlag,0);
+        lambdaQuery.eq(MceReceive::getReceiverId, SecurityUtils.getUserId())
+                .eq(MceReceive::getReadFlag, 0);
         Integer notReadCount = this.count(lambdaQuery);
         Map<String, Object> map = new HashMap<>();
         map.put("notReadCount", notReadCount);
@@ -211,19 +212,19 @@ public class MceReceiveServiceImpl extends AbstractCrudService<MceReceiveMapper,
     }
 
     @Override
-    public void updateMceReceive(MceReceive mceReceive){
+    public void updateMceReceive(MceReceive mceReceive) {
         LambdaUpdateWrapper<MceReceive> updateWrapper = new UpdateWrapper<MceReceive>().lambda();
-        if (Objects.nonNull(mceReceive.getId())&&!mceReceive.getId().equals(0)){
-            updateWrapper.eq(MceReceive::getId,mceReceive.getId())
-                    .set(MceReceive::getReadFlag,1)
-                    .set(MceReceive::getUpdateBy,SecurityUtils.getUsername())
-                    .set(MceReceive::getUpdateTime,LocalDateTime.now());
-        }else {
-            updateWrapper.eq(MceReceive::getReceiverId,SecurityUtils.getUserId())
-                    .eq(MceReceive::getReadFlag,0)
-                    .set(MceReceive::getReadFlag,1)
-                    .set(MceReceive::getUpdateBy,SecurityUtils.getUsername())
-                    .set(MceReceive::getUpdateTime,LocalDateTime.now());
+        if (Objects.nonNull(mceReceive.getId()) && !mceReceive.getId().equals(0)) {
+            updateWrapper.eq(MceReceive::getId, mceReceive.getId())
+                    .set(MceReceive::getReadFlag, 1)
+                    .set(MceReceive::getUpdateBy, SecurityUtils.getUsername())
+                    .set(MceReceive::getUpdateTime, LocalDateTime.now());
+        } else {
+            updateWrapper.eq(MceReceive::getReceiverId, SecurityUtils.getUserId())
+                    .eq(MceReceive::getReadFlag, 0)
+                    .set(MceReceive::getReadFlag, 1)
+                    .set(MceReceive::getUpdateBy, SecurityUtils.getUsername())
+                    .set(MceReceive::getUpdateTime, LocalDateTime.now());
         }
         this.update(updateWrapper);
     }
@@ -238,6 +239,241 @@ public class MceReceiveServiceImpl extends AbstractCrudService<MceReceiveMapper,
         }
     }
 
+    @Async
+    public void addMceReceive(MceRequestVO mceRequestVO) {
+        // 如果 infoTypeName 为空,则从字典数据中获取
+        if (mceRequestVO.getInfoTypeName() == null) {
+            String infoTypeName = sysDictDataService.selectDictLabel("message_type", mceRequestVO.getInfoType());
+            mceRequestVO.setInfoTypeName(infoTypeName);
+        }
+
+        // 获取当前租户的所有用户
+        List<SysUser> userList = userMapper.tenantIdUserList(SecurityUtils.getTenantId());
+        if (CollectionUtils.isEmpty(userList)) {
+            return;
+        }
+
+        // 获取用户昵称与真实姓名的映射
+        Map<String, String> userNameNickNameMap = userList.stream()
+                .collect(Collectors.toMap(SysUser::getUserName, SysUser::getNickName));
+
+        LocalDateTime currentTime = LocalDateTime.now();
+        List<Long> userIdList = new ArrayList<>();
+        MceContent contentEntity = new MceContent();
+        Integer generatedContentId = 0;
+
+        // 遍历用户列表,处理消息内容
+        for (SysUser user : userList) {
+            userIdList.add(user.getUserId());
+            if (mceRequestVO.getUserName().equals(user.getUserName())) {
+                contentEntity.setInfoTitle(mceRequestVO.getInfoTitle());
+                contentEntity.setInfoContent(mceRequestVO.getInfoContent());
+                contentEntity.setInfoType(mceRequestVO.getInfoType());
+                contentEntity.setCreateBy(user.getUserName());
+                contentEntity.setCreateTime(currentTime);
+                contentEntity.setDeptId(user.getDeptId().intValue());
+                contentEntity.setTenantId(user.getTenantId());
+                mceContentService.save(contentEntity);
+                generatedContentId = contentEntity.getId();
+            }
+        }
+
+        // 筛选符合用户ID条件的用户
+        List<Long> targetUserIds = mceRequestVO.getUserIds();
+        userIdList.retainAll(targetUserIds);
+
+        // 查询符合条件的 MceMbuser 列表
+        List<MceMbuser> mbUserList = mceMbuserService.list(Wrappers.lambdaQuery(MceMbuser.class).in(MceMbuser::getUserId, userIdList));
+
+        // 遍历用户列表,处理消息接收记录
+        for (Long userId : userIdList) {
+            if (CollectionUtils.isEmpty(mbUserList)) {
+                continue;
+            }
+
+            Optional<MceMbuser> mbUserOptional = mbUserList.stream()
+                    .filter(mbUser -> mbUser.getUserId().equals(userId))
+                    .findFirst();
+
+
+            for (SysUser user : userList) {
+                if (user.getUserId().equals(userId)) {
+                    // 创建消息接收记录
+                    List<MceSetting> setting =  mceSettingService.list(Wrappers.lambdaQuery(MceSetting.class).eq(MceSetting::getCreateBy, user.getUserName()));
+                    Integer receiveId = 0;
+                    if (CollectionUtils.isNotEmpty(setting)){
+                        MceReceive mceReceive = createMceReceive(user, generatedContentId, mceRequestVO, userNameNickNameMap);
+                        this.save(mceReceive);
+                       receiveId =  mceReceive.getId();
+                    }
+
+                    if (mbUserOptional.isPresent()) {
+                        MceMbuser mbUser = mbUserOptional.get();
+                        // 处理消息发送设置
+                        handleMessageSettings(mbUser, mceRequestVO, receiveId);
+                    }
+                }
+            }
+        }
+    }
+
+    // 创建消息接收记录
+    private MceReceive createMceReceive(SysUser user, Integer generatedContentId, MceRequestVO mceRequestVO, Map<String, String> userNameNickNameMap) {
+        MceReceive mceReceive = new MceReceive();
+        mceReceive.setReceiverId(user.getUserId().intValue());
+        mceReceive.setContentId(generatedContentId);
+        mceReceive.setReadFlag(0);
+        mceReceive.setInfoType(mceRequestVO.getInfoType());
+        mceReceive.setModuleId(mceRequestVO.getId());
+
+        String userName = mceRequestVO.getUserName();
+        String nickName = userNameNickNameMap.get(userName);
+        mceReceive.setIssuerName(nickName);
+
+        mceReceive.setReceiverName(user.getUserName());
+        mceReceive.setCreateBy(mceRequestVO.getUserName());
+        mceReceive.setCreateTime(LocalDateTime.now());
+        mceReceive.setTenantId(user.getTenantId());
+        mceReceive.setDeptId(Math.toIntExact(user.getDeptId()));
+        return mceReceive;
+    }
+
+    // 处理消息发送设置
+    private void handleMessageSettings(MceMbuser mbUser, MceRequestVO mceRequestVO, Integer mceReceiveId) {
+        List<MceSetting> settingList = mceSettingService.list(Wrappers.lambdaQuery(MceSetting.class).eq(MceSetting::getCreateBy, mceRequestVO.getUserName()));
+
+        if (CollectionUtils.isNotEmpty(settingList)) {
+            MceSetting setting = settingList.get(0);
+            JSONObject appMode = JSONObject.parseObject(setting.getAppMode());
+            JSONObject wcMode = JSONObject.parseObject(setting.getWcMode());
+
+            String infoType = mceRequestVO.getInfoType();
+
+            // 处理应用消息发送
+            if (appMode.getBoolean(infoType)) {
+                if (mbUser.getCids() != null) {
+                    try {
+                        mceContentService.sendAppNew(mceRequestVO, mbUser.getCids(), 0, 0);
+                    } catch (Exception e) {
+                        log.error("为用户ID: {} 发送应用消息失败,错误信息: {}", mbUser.getUserId(), e.getMessage(), e);
+                    }
+                }
+            }
+
+            // 处理微信消息发送
+            if (wcMode.getBoolean(infoType)) {
+                if (mbUser.getOpenid() != null) {
+                    try {
+                        mceContentService.sendAppNew(mceRequestVO, mbUser.getOpenid(), mceReceiveId, 1);
+                    } catch (Exception e) {
+                        log.error("为用户ID: {} 发送微信消息失败,错误信息: {}", mbUser.getUserId(), e.getMessage(), e);
+                    }
+                }
+            }
+        }
+    }
+
+    /*
+    @Async
+    @Override
+    public void addMceReceive(MceRequestVO mceRequestVO) {
+        if (mceRequestVO.getInfoTypeName() == null) {
+            String infoTypeName = sysDictDataService.selectDictLabel("message_type", mceRequestVO.getInfoType());
+            mceRequestVO.setInfoTypeName(infoTypeName);
+        }
+
+        List<SysUser> userList = userMapper.tenantIdUserList(SecurityUtils.getTenantId());
+        // 获取用户昵称与真实姓名Map
+        Map<String, String> userNameNickNameMap = userList.stream().collect(Collectors.toMap(SysUser::getUserName, SysUser::getNickName));
+
+        if (CollectionUtils.isNotEmpty(userList)) {
+            LocalDateTime currentTime = LocalDateTime.now();
+            List<Integer> userIdList = new ArrayList<>();
+            MceContent contentEntity = new MceContent();
+            Integer generatedContentId = 0;
+            for (SysUser user : userList) {
+                userIdList.add(user.getUserId().intValue());
+                if (mceRequestVO.getUserName().equals(user.getUserName())) {
+                    contentEntity.setInfoTitle(mceRequestVO.getInfoTitle());
+                    contentEntity.setInfoContent(mceRequestVO.getInfoContent());
+                    contentEntity.setInfoType(mceRequestVO.getInfoType());
+                    contentEntity.setCreateBy(user.getUserName());
+                    contentEntity.setCreateTime(currentTime);
+                    contentEntity.setDeptId(user.getDeptId().intValue());
+                    contentEntity.setTenantId(user.getTenantId());
+                    mceContentService.save(contentEntity);
+                    generatedContentId = contentEntity.getId();
+                }
+            }
+
+            List<Long> userIds1;
+            userIds1 = mceRequestVO.getUserIds();
+            userList.retainAll(userIds1);
+
+            LambdaQueryWrapper<MceMbuser> lambdaQuery3 = Wrappers.lambdaQuery();
+            lambdaQuery3.in(MceMbuser::getUserId, userList);
+            List<MceMbuser> list3 = mceMbuserService.list(lambdaQuery3);
+
+            for (int i = 0; i < userList.size(); i++) {
+                if (CollectionUtils.isNotEmpty(list3)) {
+                    for (int j = 0; j < list3.size(); j++) {
+                        if (userList.get(i).getUserId().equals(list3.get(j).getUserId())) {
+                            MceReceive mceReceive1 = new MceReceive();
+                            mceReceive1.setReceiverId(userList.get(i).getUserId().intValue());
+                            mceReceive1.setContentId(generatedContentId);
+                            mceReceive1.setReadFlag(0);
+                            mceReceive1.setInfoType(mceRequestVO.getInfoType());
+                            mceReceive1.setModuleId(mceRequestVO.getId());
+
+                            String userName = mceRequestVO.getUserName();
+                            String nickName = userNameNickNameMap.get(userName);
+                            mceReceive1.setIssuerName(nickName);
+
+                            mceReceive1.setReceiverName(userList.get(i).getUserName());
+                            mceReceive1.setCreateBy(mceRequestVO.getUserName());
+                            mceReceive1.setCreateTime(LocalDateTime.now());
+                            mceReceive1.setTenantId(userList.get(i).getTenantId());
+                            mceReceive1.setDeptId(Math.toIntExact(userList.get(i).getDeptId()));
+                            this.save(mceReceive1);
+                            Integer mceReceiveId = mceReceive1.getId();
+
+                            LambdaQueryWrapper<MceSetting> lambdaQuery = Wrappers.lambdaQuery();
+                            lambdaQuery.eq(MceSetting::getCreateBy, userList.get(i).getUserName());
+                            List<MceSetting> list1 = mceSettingService.list(lambdaQuery);
+
+                            if (CollectionUtils.isNotEmpty(list1)) {
+                                JSONObject appMode = JSONObject.parseObject(list1.get(0).getAppMode());
+                                JSONObject wcMode = JSONObject.parseObject(list1.get(0).getWcMode());
+
+                                if (appMode.get(mceRequestVO.getInfoType()).equals(true)) {
+                                    if (userList.get(i).getUserId().equals(list3.get(j).getUserId()) && StringUtils.isNotBlank(list3.get(j).getCids())) {
+                                        try {
+                                            mceContentService.sendAppNew(mceRequestVO, list3.get(j).getCids(), 0, 0);
+                                        } catch (Exception e) {
+                                            log.error("为用户ID: {} 发送应用消息失败,错误信息: {}", list3.get(j).getUserId(), e.getMessage(), e);
+                                        }
+                                    }
+                                }
+
+                                if (wcMode.get(mceRequestVO.getInfoType()).equals(true)) {
+                                    if (userList.get(i).getUserId().equals(list3.get(j).getUserId()) && StringUtils.isNotBlank(list3.get(j).getOpenid())) {
+                                        try {
+                                            mceContentService.sendAppNew(mceRequestVO, list3.get(j).getOpenid(), mceReceiveId, 1);
+                                        } catch (Exception e) {
+                                            log.error("为用户ID: {} 发送微信消息失败,错误信息: {}", list3.get(j).getUserId(), e.getMessage(), e);
+                                        }
+                                    }
+                                }
+                            }
+                        }
+                    }
+                }
+            }
+        }
+    }
+    */
+
+    @Async
     @Override
     public void add(String mceReceive) {
         JSONObject mceReceiveVO = JSONObject.parseObject(mceReceive);
@@ -247,6 +483,8 @@ public class MceReceiveServiceImpl extends AbstractCrudService<MceReceiveMapper,
         }
 
         List<SysUser> list = userMapper.tenantIdUserList(SecurityUtils.getTenantId());
+        // 获取用户昵称与真实姓名Map
+        Map<String, String> userNameNickNameMap = list.stream().collect(Collectors.toMap(SysUser::getUserName, SysUser::getNickName));
         MceContent mceContent = new MceContent();
         Integer contentId = 0;
 
@@ -288,7 +526,9 @@ public class MceReceiveServiceImpl extends AbstractCrudService<MceReceiveMapper,
                             mceReceive1.setInfoType(mceReceiveVO.get("infoType").toString());
                             mceReceive1.setModuleId((int) mceReceiveVO.get("id"));
                             if (mceReceiveVO.containsKey("userName")) {
-                                mceReceive1.setIssuerName(mceReceiveVO.get("userName").toString());
+                                String userName = mceReceiveVO.get("userName").toString();
+                                String nickName = userNameNickNameMap.get(userName);
+                                mceReceive1.setIssuerName(nickName);
                             }
                             mceReceive1.setReceiverName(list.get(i).getUserName());
                             mceReceive1.setCreateBy(mceReceiveVO.get("userName").toString());
@@ -336,7 +576,7 @@ public class MceReceiveServiceImpl extends AbstractCrudService<MceReceiveMapper,
     @Override
     public boolean removeById(Integer id) {
         LambdaQueryWrapper<MceReceive> lambdaQuery = Wrappers.lambdaQuery();
-        lambdaQuery.eq(MceReceive::getContentId,id);
+        lambdaQuery.eq(MceReceive::getContentId, id);
         this.remove(lambdaQuery);
         return mceContentService.removeById(id);
     }

+ 38 - 14
base-modules/service-system/service-system-biz/src/main/java/com/usky/system/service/impl/SysNoticeServiceImpl.java

@@ -3,9 +3,10 @@ package com.usky.system.service.impl;
 
 import com.alibaba.fastjson.JSONObject;
 import com.baomidou.mybatisplus.core.toolkit.Wrappers;
-import com.google.gson.JsonObject;
-import com.usky.common.core.bean.ApiResult;
+import com.usky.common.core.exception.BusinessException;
 import com.usky.common.mybatis.core.AbstractCrudService;
+import com.usky.common.security.utils.SecurityUtils;
+import com.usky.system.domain.MceRequestVO;
 import com.usky.system.domain.SysNotice;
 import com.usky.system.domain.SysUser;
 import com.usky.system.mapper.SysNoticeMapper;
@@ -15,11 +16,8 @@ import com.usky.system.service.MceReceiveService;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Service;
 
-import java.sql.Wrapper;
 import java.util.Arrays;
-import java.util.HashMap;
 import java.util.List;
-import java.util.Map;
 import java.util.stream.Collectors;
 
 /**
@@ -57,6 +55,7 @@ public class SysNoticeServiceImpl extends AbstractCrudService<SysNoticeMapper, S
      */
     @Override
     public List<SysNotice> selectNoticeList(SysNotice notice) {
+        notice.setTenantId(SecurityUtils.getTenantId());
         return noticeMapper.selectNoticeList(notice);
     }
 
@@ -68,6 +67,7 @@ public class SysNoticeServiceImpl extends AbstractCrudService<SysNoticeMapper, S
      */
     @Override
     public int insertNotice(SysNotice notice) {
+        notice.setTenantId(SecurityUtils.getTenantId());
         noticeMapper.insertNotice(notice);
         int insertId = notice.getNoticeId();
 
@@ -76,19 +76,43 @@ public class SysNoticeServiceImpl extends AbstractCrudService<SysNoticeMapper, S
         List<Long> usersIds = sysUserMapper.selectList(Wrappers.lambdaQuery(SysUser.class).select(SysUser::getUserId).in(SysUser::getDeptId, deptIds)).stream().map(SysUser::getUserId).collect(Collectors.toList());
 
         if (!deptIds.isEmpty()) {
-            JSONObject jsonObject = new JSONObject();
-            jsonObject.put("infoTitle", notice.getNoticeTitle());
-            jsonObject.put("infoContent", notice.getNoticeContent());
-            jsonObject.put("infoType", 1);
-            jsonObject.put("id", insertId);
-            jsonObject.put("infoTypeName", "通知公告");
-            jsonObject.put("userName", notice.getCreateBy());
-            jsonObject.put("userIds", usersIds);
-            mceReceiveService.add(jsonObject.toString());
+            sendNotice(notice.getNoticeTitle(), insertId, notice.getCreateBy(), usersIds);
         }
+
         return insertId;
     }
 
+    /**
+     * 发送消息
+     * @param infoContent 消息内容
+     * @param id 通知公告id
+     * @param userName 发布人
+     * @param userIds 接收人
+     */
+    private void sendNotice(String infoContent, Integer id, String userName, List<Long> userIds) {
+
+        // JSONObject jsonObject = new JSONObject();
+        // jsonObject.put("infoTitle", "通知公告");
+        // jsonObject.put("infoContent", infoContent);
+        // jsonObject.put("infoType", 1);
+        // jsonObject.put("id", id);
+        // jsonObject.put("userName", userName);
+        // jsonObject.put("userIds", userIds);
+        MceRequestVO mceRequestVO = new MceRequestVO();
+        mceRequestVO.setInfoTitle("通知公告");
+        mceRequestVO.setInfoContent(infoContent);
+        mceRequestVO.setInfoType("1");
+        mceRequestVO.setId(id);
+        mceRequestVO.setUserName(userName);
+        mceRequestVO.setUserIds(userIds);
+        try {
+            //mceReceiveService.add(jsonObject.toString());
+            mceReceiveService.addMceReceive(mceRequestVO);
+        } catch (Exception e) {
+            log.error(String.format("公告:%d,消息发送失败:%s", id, e.getMessage()));
+        }
+    }
+
     /**
      * 修改公告
      *

+ 8 - 1
base-modules/service-system/service-system-biz/src/main/resources/mapper/system/SysNoticeMapper.xml

@@ -17,6 +17,7 @@
         <result property="fileUrl" column="file_url"/>
         <result property="author" column="author"/>
         <result property="deptId" column="dept_id"/>
+        <result property="tenantId" column="tenant_id"/>
     </resultMap>
 
     <sql id="selectNoticeVo">
@@ -31,7 +32,8 @@
                update_time,
                file_url,
                author,
-               dept_id
+               dept_id,
+               tenant_id
         from sys_notice
     </sql>
 
@@ -61,6 +63,9 @@
             <if test="startTime != null and endTime != null">
                 AND create_time BETWEEN #{startTime} AND #{endTime}
             </if>
+            <if test="tenantId != null and tenantId != ''">
+                AND tenant_id = #{tenantId}
+            </if>
         </where>
         order by notice_id desc
     </select>
@@ -76,6 +81,7 @@
         <if test="fileUrl != null and fileUrl != ''">file_url,</if>
         <if test="author != null and author != ''">author,</if>
         <if test="deptId != null and deptId != ''">dept_id,</if>
+        <if test="tenantId != null and tenantId != ''">tenant_id,</if>
         create_time
         )values(
         <if test="noticeTitle != null and noticeTitle != ''">#{noticeTitle},</if>
@@ -86,6 +92,7 @@
         <if test="fileUrl != null and fileUrl != ''">#{fileUrl},</if>
         <if test="author != null and author != ''">#{author},</if>
         <if test="deptId != null and deptId != ''">#{deptId},</if>
+        <if test="tenantId != null and tenantId != ''">#{tenantId},</if>
         sysdate()
         )
     </insert>