package com.usky.system.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
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.usky.common.core.bean.CommonPage;
import com.usky.common.core.exception.BusinessException;
import com.usky.common.security.utils.SecurityUtils;
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 com.usky.system.service.vo.MceReceiveResponseVO;
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>
 * 消息接收表 服务实现类
 * </p>
 *
 * @author han
 * @since 2024-05-09
 */
@Slf4j
@Service
public class MceReceiveServiceImpl extends AbstractCrudService<MceReceiveMapper, MceReceive> implements MceReceiveService {
    @Autowired
    private MceContentService mceContentService;

    @Autowired
    private MceMbuserService mceMbuserService;

    @Autowired
    private MceSettingService mceSettingService;

    @Autowired
    private ISysUserService iSysUserService;

    @Autowired
    private ISysDictDataService sysDictDataService;

    @Autowired
    private SysUserMapper userMapper;
    @Autowired
    private MceSettingMapper mceSettingMapper;

    @Autowired
    private MceReceiveMapper mceReceiveMapper;

    @Autowired
    private SysUserPersonService sysUserPersonService;

    @Override
    public CommonPage<Object> mceList(String infoTitle, String infoType, String startTime, String endTime, Integer id, Integer infoId, Integer current, Integer size) {
        List<Object> list = new ArrayList<>();

        if (infoId != null) {
            LambdaQueryWrapper<MceReceive> query = Wrappers.lambdaQuery();
            query.select(MceReceive::getContentId).eq(MceReceive::getId, infoId);
            MceReceive mceReceive = mceReceiveMapper.selectOne(query);
            if (mceReceive != null) {
                id = mceReceive.getContentId();
            } else {
                log.error("消息内容已不存在！消息id：{}", infoId);
                throw new BusinessException("消息内容已不存在！");
            }
        }

        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)
                .eq(MceContent::getTenantId, SecurityUtils.getTenantId());
        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++) {
                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, MceReceive::getCreateBy, MceReceive::getIssuerName)
                    .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)
                    .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);
            if (CollectionUtils.isNotEmpty(page.getRecords())) {
                for (int i = 0; i < page.getRecords().size(); i++) {
                    String infoType1 = page.getRecords().get(i).getInfoType();
                    Map<String, Object> map = new HashMap<>();
                    map.put("id", page.getRecords().get(i).getId());
                    map.put("infoType", infoType1);
                    map.put("readFlag", page.getRecords().get(i).getReadFlag());
                    map.put("moduleId", page.getRecords().get(i).getModuleId());
                    map.put("createTime", page.getRecords().get(i).getCreateTime());
                    map.put("createBy", page.getRecords().get(i).getCreateBy());
                    map.put("issuerName", page.getRecords().get(i).getIssuerName());
                    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("infoTitle", list1.get(j).getInfoTitle());
                                map.put("infoContent", list1.get(j).getInfoContent());
                            }
                        }
                    }
                    list.add(map);
                }
            }
        }
        return new CommonPage<>(list, page.getTotal(), page.getCurrent(), page.getSize());
    }

    @Override
//    @DataScope
    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)
//                .apply(DataScopeContextHolder.getDataScopeSql())
                .eq(MceContent::getTenantId, SecurityUtils.getTenantId())
                .orderByDesc(MceContent::getId);
        page = mceContentService.page(page, lambdaQuery1);

        if (CollectionUtils.isNotEmpty(page.getRecords())) {
            List<Integer> contentIds = new ArrayList<>();
            for (int i = 0; i < page.getRecords().size(); i++) {
                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);
            for (int i = 0; i < page.getRecords().size(); i++) {
                Map<String, Object> map = new HashMap<>();
                map.put("id", page.getRecords().get(i).getId());
                map.put("infoTitle", page.getRecords().get(i).getInfoTitle());
                map.put("infoContent", page.getRecords().get(i).getInfoContent());
                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"))) {
                        map.put("notReadCount", readStatisticList.get(j).get("notReadCount"));
                        map.put("readCount", readStatisticList.get(j).get("readCount"));
                        map.put("userName", readStatisticList.get(j).get("issuerName"));
                    }
                }
                list.add(map);
            }
        }

        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);
//        if (CollectionUtils.isNotEmpty(page.getRecords())) {
//            List<Integer> userIds = new ArrayList<>();
//            for (int i = 0; i < page.getRecords().size(); i++) {
//                userIds.add(page.getRecords().get(i).getReceiverId());
//            }
//            List<Integer> distinctUserIds = userIds.stream()
//                    .distinct()
//                    .collect(Collectors.toList());
//            ApiResult<List<SysUser>> userApi = remoteUserService.userByIdList(distinctUserIds);
//            List<SysUser> list1 = userApi.getData();
//            for (int j = 0; j < page.getRecords().size(); j++) {
//                if (CollectionUtils.isNotEmpty(list1)){
//                    for (int k = 0; k < list1.size(); k++) {
//                        long longValue = list1.get(k).getUserId();
//                        Integer intValue = (int) longValue;
//                        if (page.getRecords().get(j).getReceiverId().equals(intValue)){
//                            page.getRecords().get(j).setUpdateBy(list1.get(k).getUserName());
//                        }
//                    }
//                }
//            }
//        }
        return new CommonPage<>(page.getRecords(), page.getTotal(), page.getCurrent(), page.getSize());
    }

    @Override
    public Map<String, Object> mceReceiveStatic() {
        LocalDateTime currentDate = LocalDateTime.now();
        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)
                .groupBy("info_type");
        List<Map<String, Object>> readStatisticList = this.listMaps(queryWrapper);
        LambdaQueryWrapper<MceReceive> lambdaQuery = Wrappers.lambdaQuery();
        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);
        map.put("infoTypeStatic", readStatisticList);
        return map;
    }

    @Override
    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());
        }
        this.update(updateWrapper);
    }

    public static List<Integer> convertObjectToList(Object object) {
        if (object instanceof List<?>) {
            @SuppressWarnings("unchecked")
            List<Integer> tempList = (List<Integer>) object;
            return tempList;
        } else {
            throw new IllegalArgumentException("The object is not a List");
        }
    }

    @Async
    @Override
    public void addMceReceive(MceRequestVO mceRequestVO) {
        log.info("本次发送消息内容: {}", mceRequestVO.toString());

        // 补充信息类型名称
        if (mceRequestVO.getInfoTypeName() == null) {
            String infoTypeName = sysDictDataService.selectDictLabel("message_type", mceRequestVO.getInfoType());
            mceRequestVO.setInfoTypeName(infoTypeName);
        }

//        // 获取发送者租户ID
//        Integer tenantId = getUserTenantId(mceRequestVO.getUserName());
//        if (tenantId == null) {
//            log.error("获取用户租户ID失败，未找到用户: {}", mceRequestVO.getUserName());
//            return;
//        }

        // 获取租户所有用户信息
        List<SysUser> allUsers = userMapper.tenantIdUserList(mceRequestVO.getTenantId());
        if (CollectionUtils.isEmpty(allUsers)) {
            log.warn("租户下未找到任何用户，租户ID: {}", mceRequestVO.getTenantId());
            return;
        }

        // 构建用户信息映射
        Map<Long, SysUser> userIdToUserMap = allUsers.stream()
                .collect(Collectors.toMap(SysUser::getUserId, user -> user));

        Map<String, String> userNameToNickNameMap = allUsers.stream()
                .collect(Collectors.toMap(SysUser::getUserName, SysUser::getNickName));



        // 筛选目标用户
        List<Long> targetUserIds = mceRequestVO.getUserIds();
        List<Long> validUserIds = allUsers.stream()
                .map(SysUser::getUserId)
                .filter(targetUserIds::contains)
                .collect(Collectors.toList());

        if (CollectionUtils.isEmpty(validUserIds)) {
            log.error("用户: {} 发送的{}，id: {}，抄送用户均不存在！消息发送终止",
                    mceRequestVO.getUserName(), mceRequestVO.getInfoTypeName(), mceRequestVO.getId());
            return;
        }

        // 获取用户消息配置
        List<MceMbuser> mbUserList = mceMbuserService.list(Wrappers.lambdaQuery(MceMbuser.class)
                .in(MceMbuser::getUserId, validUserIds));

        if (CollectionUtils.isEmpty(mbUserList)) {
            log.error("消息配置为空！用户id列表为: {}，id: {}，消息发送终止", validUserIds, mceRequestVO.getId());
            return;
        }

        // 构建用户ID到消息配置的映射
        Map<Long, MceMbuser> userIdToMbUserMap = mbUserList.stream()
                .collect(Collectors.toMap(MceMbuser::getUserId, mbUser -> mbUser));

        // 获取消息发送设置
        List<MceSetting> settings = mceSettingService.list(Wrappers.lambdaQuery(MceSetting.class)
                .eq(MceSetting::getCreateBy, mceRequestVO.getUserName()).eq(MceSetting::getTenantId, mceRequestVO.getTenantId()));

        if (CollectionUtils.isEmpty(settings)) {
            log.warn("未找到消息发送设置，用户: {}", mceRequestVO.getUserName());
            return;
        }

        MceSetting setting = settings.get(0);
        JSONObject appMode = JSONObject.parseObject(setting.getAppMode());
        JSONObject wcMode = JSONObject.parseObject(setting.getWcMode());

        // 保存消息内容
        Integer contentId = saveMessageContent(mceRequestVO, userIdToUserMap);
        if (contentId == null) {
            log.error("消息内容保存失败，用户: {}", mceRequestVO.getUserName());
            return;
        }

        // 处理每个目标用户的消息接收和发送
        for (Long userId : validUserIds) {
            SysUser user = userIdToUserMap.get(userId);
            if (user == null) {
                continue;
            }

            // 获取用户消息配置
            MceMbuser mbUser = userIdToMbUserMap.get(userId);
            if (mbUser == null) {
                continue;
            }

            // 登录不需要新增消息记录
            if ("0".equals(mceRequestVO.getInfoType())) {
                handleMessageDelivery(mbUser, mceRequestVO, 0, appMode, wcMode);
                return;
            }

            // 创建消息接收记录
            MceReceive mceReceive = createMceReceive(user, contentId, mceRequestVO, userNameToNickNameMap);
            boolean saveResult = this.save(mceReceive);
            if (!saveResult) {
                log.error("创建消息接收记录失败，用户ID: {}", userId);
                continue;
            }

            // 根据消息类型处理消息发送
            handleMessageDelivery(mbUser, mceRequestVO, mceReceive.getId(), appMode, wcMode);
        }
    }

    /**
     * 获取用户租户ID
     */
    private Integer getUserTenantId(String userName) {
        try {
            SysUser user = userMapper.selectOne(new LambdaQueryWrapper<SysUser>()
                    .eq(SysUser::getUserName, userName)
                    .select(SysUser::getTenantId));
            return user != null ? user.getTenantId() : null;
        } catch (Exception e) {
            log.error("获取用户租户ID失败，报错信息：{}", e.getMessage(), e);
            return null;
        }
    }

    /**
     * 保存消息内容
     */
    private Integer saveMessageContent(MceRequestVO mceRequestVO, Map<Long, SysUser> userIdToUserMap) {
        SysUser sender = userIdToUserMap.values().stream()
                .filter(user -> mceRequestVO.getUserName().equals(user.getUserName()))
                .findFirst()
                .orElse(null);

        if (sender == null) {
            log.error("未找到发送者信息，用户名: {}", mceRequestVO.getUserName());
            return null;
        }

        MceContent contentEntity = new MceContent();
        contentEntity.setInfoTitle(mceRequestVO.getInfoTitle());
        contentEntity.setInfoContent(mceRequestVO.getInfoContent());
        contentEntity.setInfoType(mceRequestVO.getInfoType());
        contentEntity.setCreateBy(sender.getUserName());
        contentEntity.setCreateTime(LocalDateTime.now());
        contentEntity.setDeptId(sender.getDeptId().intValue());
        contentEntity.setTenantId(sender.getTenantId());

        boolean saveResult = mceContentService.save(contentEntity);
        return saveResult ? contentEntity.getId() : null;
    }

    /**
     * 创建消息接收记录
     */
    private MceReceive createMceReceive(SysUser user, Integer contentId, MceRequestVO mceRequestVO,
                                        Map<String, String> userNameToNickNameMap) {
        MceReceive mceReceive = new MceReceive();
        mceReceive.setReceiverId(user.getUserId().intValue());
        mceReceive.setContentId(contentId);
        mceReceive.setReadFlag(0);
        mceReceive.setInfoType(mceRequestVO.getInfoType());
        mceReceive.setModuleId(mceRequestVO.getId());
        mceReceive.setIssuerName(userNameToNickNameMap.get(mceRequestVO.getUserName()));
        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 handleMessageDelivery(MceMbuser mbUser, MceRequestVO mceRequestVO,
                                       Integer mceReceiveId, JSONObject appMode, JSONObject wcMode) {
        String infoType = mceRequestVO.getInfoType();

        // 登录成功通知只给登录用户发送微信公众号消息
        if ("0".equals(infoType)) {
            SysUserPerson one = sysUserPersonService.lambdaQuery().select(SysUserPerson::getIsLoginNotify).eq(SysUserPerson::getUserId, mbUser.getUserId()).one();
            Integer isLoginNotify = one.getIsLoginNotify();
            if (isLoginNotify == 1) {
                sendWeChatMessage(mbUser, mceRequestVO, wcMode, infoType, mceReceiveId);
            } else {
                log.info("用户{}未开启登录通知", mbUser.getUserId());
            }
            return;
        }

        // 处理告警消息
        if ("4".equals(infoType)) {
            handleAlarmMessage(mbUser, mceRequestVO, mceReceiveId, appMode, wcMode, infoType);
            return;
        }

        // 处理普通消息(默认APP和微信都通知)
        handleNormalMessage(mbUser, mceRequestVO, mceReceiveId, appMode, wcMode, infoType);
    }

    /**
     * 处理告警消息
     */
    private void handleAlarmMessage(MceMbuser mbUser, MceRequestVO mceRequestVO, Integer mceReceiveId,
                                    JSONObject appMode, JSONObject wcMode, String infoType) {
        String alarmSendType = mceRequestVO.getAlarmSendType();
        switch (alarmSendType) {
            case "1":
                sendAppMessage(mbUser, mceRequestVO, appMode, infoType);
                break;
            case "2":
                sendWeChatMessage(mbUser, mceRequestVO, wcMode, infoType, mceReceiveId);
                break;
            default:
                log.error("未知的告警发送类型: {}", alarmSendType);
                break;
        }
    }

    /**
     * 发送普通消息
     */
    private void handleNormalMessage(MceMbuser mbUser, MceRequestVO mceRequestVO, Integer mceReceiveId,
                                     JSONObject appMode, JSONObject wcMode, String infoType) {
        sendAppMessage(mbUser, mceRequestVO, appMode, infoType);
        sendWeChatMessage(mbUser, mceRequestVO, wcMode, infoType, mceReceiveId);
    }

    /**
     * 发送APP消息
     */
    private void sendAppMessage(MceMbuser mbUser, MceRequestVO mceRequestVO, JSONObject mode, String infoType) {
        if (mode.getBoolean(infoType) && mbUser.getCids() != null) {
            try {
                mceContentService.sendAppNew(mceRequestVO, mbUser.getCids(), 0, 0);
            } catch (Exception e) {
                log.error("为用户ID: {} 发送应用消息失败，错误信息: {}", mbUser.getUserId(), e.getMessage(), e);
            }
        }
    }

    /**
     * 推送微信消息
     */
    private void sendWeChatMessage(MceMbuser mbUser, MceRequestVO mceRequestVO, JSONObject mode,
                                   String infoType, Integer mceReceiveId) {

        if (mbUser.getOpenid() == null) {
            return;
        }

        if ("0".equals(infoType) || mode.getBoolean(infoType)) {
            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);
        String infoTypeName = sysDictDataService.selectDictLabel("message_type", mceReceiveVO.get("infoType").toString());
        if (!mceReceiveVO.containsKey("infoTypeName")) {
            mceReceiveVO.put("infoTypeName", infoTypeName);
        }

//        Integer tenantId = null;
//        try {
//            tenantId = userMapper.selectOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getUserName, mceReceiveVO.get("userName")).select(SysUser::getTenantId)).getTenantId();
//        } catch (Exception e) {
//            log.error("获取用户租户ID失败，报错信息：{}, 未找到用户-{}-的租户", e.getMessage(), mceReceiveVO.get("userName"));
//        }
        List<SysUser> list = userMapper.tenantIdUserList(Integer.valueOf(mceReceiveVO.get("tenantId").toString()));
        // 获取用户昵称与真实姓名Map
        Map<String, String> userNameNickNameMap = list.stream().collect(Collectors.toMap(SysUser::getUserName, SysUser::getNickName));
        MceContent mceContent = new MceContent();
        Integer contentId = 0;

        if (CollectionUtils.isNotEmpty(list)) {
            List<Integer> userIds = new ArrayList<>();
            for (int g = 0; g < list.size(); g++) {
                userIds.add(list.get(g).getUserId().intValue());
                if (mceReceiveVO.get("userName").equals(list.get(g).getUserName())) {
                    mceContent.setInfoTitle(mceReceiveVO.get("infoTitle").toString());
                    mceContent.setInfoContent(mceReceiveVO.get("infoContent").toString());
                    mceContent.setInfoType(mceReceiveVO.get("infoType").toString());
                    mceContent.setCreateBy(list.get(g).getUserName());
                    mceContent.setCreateTime(LocalDateTime.now());
                    mceContent.setDeptId(list.get(g).getDeptId().intValue());
                    mceContent.setTenantId(list.get(g).getTenantId());
                    mceContentService.save(mceContent);
                    contentId = mceContent.getId();
                }
            }

            List<Integer> userIds1;
            if (mceReceiveVO.containsKey("userIds")) {
                userIds1 = convertObjectToList(mceReceiveVO.get("userIds"));
                userIds.retainAll(userIds1);
            }

            LambdaQueryWrapper<MceMbuser> lambdaQuery3 = Wrappers.lambdaQuery();
            lambdaQuery3.in(MceMbuser::getUserId, userIds);
            List<MceMbuser> list3 = mceMbuserService.list(lambdaQuery3);

            for (int i = 0; i < list.size(); i++) {
                if (CollectionUtils.isNotEmpty(list3)) {
                    for (int j = 0; j < list3.size(); j++) {
                        if (list.get(i).getUserId().equals(list3.get(j).getUserId())) {
                            MceReceive mceReceive1 = new MceReceive();
                            mceReceive1.setReceiverId(list.get(i).getUserId().intValue());
                            mceReceive1.setContentId(contentId);
                            mceReceive1.setReadFlag(0);
                            mceReceive1.setInfoType(mceReceiveVO.get("infoType").toString());
                            mceReceive1.setModuleId((int) mceReceiveVO.get("id"));
                            if (mceReceiveVO.containsKey("userName")) {
                                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());
                            mceReceive1.setCreateTime(LocalDateTime.now());
                            mceReceive1.setTenantId(list.get(i).getTenantId());
                            mceReceive1.setDeptId(list.get(i).getDeptId().intValue());
                            this.save(mceReceive1);
                            Integer mceReceiveId = mceReceive1.getId();

                            LambdaQueryWrapper<MceSetting> lambdaQuery = Wrappers.lambdaQuery();
                            lambdaQuery.eq(MceSetting::getCreateBy, list.get(i).getUserName()).eq(MceSetting::getTenantId, list.get(i).getTenantId());
                            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(mceReceiveVO.get("infoType").toString()).equals(true)) {
                                    if (list.get(i).getUserId().equals(list3.get(j).getUserId()) && StringUtils.isNotBlank(list3.get(j).getCids())) {
                                        try {
                                            mceContentService.sendApp(mceReceiveVO, list3.get(j).getCids(), 0, 0);
                                        } catch (Exception e) {
                                            log.error("为用户ID: {} 发送应用消息失败，错误信息: {}", list3.get(j).getUserId(), e.getMessage(), e);
                                        }
                                    }
                                }

                                if (wcMode.get(mceReceiveVO.get("infoType").toString()).equals(true)) {
                                    if (list.get(i).getUserId().equals(list3.get(j).getUserId()) && StringUtils.isNotBlank(list3.get(j).getOpenid())) {
                                        try {
                                            mceContentService.sendApp(mceReceiveVO, list3.get(j).getOpenid(), mceReceiveId, 1);
                                        } catch (Exception e) {
                                            log.error("为用户ID: {} 发送微信消息失败，错误信息: {}", list3.get(j).getUserId(), e.getMessage(), e);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    @Override
    public boolean removeById(Integer id) {
        LambdaQueryWrapper<MceReceive> lambdaQuery = Wrappers.lambdaQuery();
        lambdaQuery.eq(MceReceive::getContentId, id);
        this.remove(lambdaQuery);
        return mceContentService.removeById(id);
    }

    @Override
    public boolean deleteById(Integer id) {
        boolean f;
        Integer userId = SecurityUtils.getUserId().intValue();
        MceReceive mceReceive = mceReceiveMapper.selectOne(new LambdaQueryWrapper<MceReceive>().eq(MceReceive::getId, id));
        if (mceReceive != null) {
            if (userId.equals(mceReceive.getReceiverId())) {
                mceReceiveMapper.deleteById(id);
                f = true;
            } else {
                throw new BusinessException("您无权删除该条记录！");
            }
        } else {
            throw new BusinessException("记录不存在，删除失败！");
        }
        return f;
    }

    @Override
    public CommonPage<MceReceiveResponseVO> getMceReceiveResponseVOList(Integer pageNumber, Integer pageSize) {
        IPage<MceReceive> page = new Page<>(pageNumber, pageSize);
        Long userId = SecurityUtils.getUserId();
        List<MceReceiveResponseVO> returnList = new ArrayList<>();

        LambdaQueryWrapper<MceReceive> lambdaQuery = Wrappers.lambdaQuery();
        lambdaQuery.eq(MceReceive::getReceiverId, userId).orderByDesc(MceReceive::getId);
        page = this.page(page, lambdaQuery);
        List<MceReceive> mceReceiveList = page.getRecords();
        List<Integer> contentIdList = mceReceiveList.stream().map(MceReceive::getContentId).distinct().collect(Collectors.toList());

        List<MceContent> mceContentList = mceContentService.list(new LambdaQueryWrapper<MceContent>().in(MceContent::getId, contentIdList));

        for (MceContent mceContent : mceContentList) {
            MceReceive mceReceive = mceReceiveList.stream().filter(mceReceive1 -> mceReceive1.getContentId().equals(mceContent.getId())).findFirst().get();
            MceReceiveResponseVO mceReceiveResponseVO = new MceReceiveResponseVO();
            mceReceiveResponseVO.setMceId(mceReceive.getId());
            mceReceiveResponseVO.setInfoType(mceContent.getInfoType());
            mceReceiveResponseVO.setInfoTitle(mceContent.getInfoTitle());
            mceReceiveResponseVO.setContentId(mceContent.getId());
            mceReceiveResponseVO.setInfoContent(mceContent.getInfoContent());
            mceReceiveResponseVO.setCreateTime(mceContent.getCreateTime());
            mceReceiveResponseVO.setCreateBy(mceContent.getCreateBy());
            mceReceiveResponseVO.setModuleId(mceReceive.getModuleId());
            returnList.add(mceReceiveResponseVO);
        }

        return new CommonPage<>(returnList, page.getTotal(), page.getSize(), page.getCurrent());
    }

    /**
     * 新增消息-无需token
     * @param mceNoToken
     */
    @Override
    public void addNoToken(String mceNoToken) {
        JSONObject json = JSONObject.parseObject(mceNoToken);
        String infoTypeName = sysDictDataService.selectDictLabel("message_type", json.get("infoType").toString());
        if (!json.containsKey("infoTypeName")) {
            json.put("infoTypeName", infoTypeName);
        }
        List<String> userNames = JSONObject.parseArray(json.get("userNames").toString(), String.class);

        LambdaQueryWrapper<SysUser> lambdaQuery = Wrappers.lambdaQuery();
        lambdaQuery.select(SysUser::getUserId)
                .in(SysUser::getUserName, userNames);
        List<Long> userIdList = userMapper.selectList(lambdaQuery).stream().map(SysUser::getUserId).collect(Collectors.toList());

        MceRequestVO mceRequestVO = new MceRequestVO();
        mceRequestVO.setUserIds(userIdList);
        mceRequestVO.setInfoTitle(json.get("infoTitle").toString());
        mceRequestVO.setInfoContent(json.get("infoContent").toString());
        mceRequestVO.setInfoType(json.get("infoType").toString());
        mceRequestVO.setInfoTypeName(json.get("infoTypeName").toString());
        mceRequestVO.setId((Integer) json.get("id"));
        mceRequestVO.setUserName(json.get("userName").toString());
        mceRequestVO.setApprovalResult(json.get("approvalResult").toString());
        mceRequestVO.setProcessName(json.get("processName").toString());
        mceRequestVO.setApprovalNode(json.get("approvalNode").toString());
        mceRequestVO.setRealName(json.get("realName").toString());
        mceRequestVO.setOaType(json.get("oaType").toString());
        addMceReceive(mceRequestVO);
    }
}
