package com.ruoyi.message.frequency.goeasymessage.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.code.PublicCommon;
import com.ruoyi.frequency.customer.service.UserService;
import com.ruoyi.message.frequency.goeasymessage.entity.GoeasyMessage;
import com.ruoyi.message.frequency.goeasymessage.mapper.GoeasyMessageMapper;
import com.ruoyi.message.frequency.goeasymessage.service.GoeasyMessageService;
import com.ruoyi.message.frequency.goeasymessagenew.entity.GoeasyMessageNew;
import com.ruoyi.message.frequency.goeasymessagenew.mapper.GoeasyMessageNewMapper;
import com.ruoyi.message.frequency.goeasymessagenew.service.GoeasyMessageNewService;
import com.ruoyi.vo.UserInfo;
import com.ruoyi.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * goeasy消息Service业务层处理
 *
 * @author liwenlong
 * @date 2024-04-17
 */
@Service
public class GoeasyMessageServiceImpl extends ServiceImpl<GoeasyMessageMapper, GoeasyMessage> implements GoeasyMessageService {
    @Autowired
    private GoeasyMessageMapper goeasyMessageMapper;

    /**
     * 查询goeasy消息
     *
     * @param id goeasy消息主键
     * @return goeasy消息
     */
    @Override
    public GoeasyMessage selectGoeasyMessageById(Long id) {
        GoeasyMessage goeasyMessage = goeasyMessageMapper.selectGoeasyMessageById(id);
        if (goeasyMessage != null) {
            Set<UserVo> userVoSet = new HashSet<>();
            userVoSet.add(new UserVo(goeasyMessage.getSenderUserType(), goeasyMessage.getSenderUserId()));
            userVoSet.add(new UserVo(goeasyMessage.getReceiverUserType(), goeasyMessage.getReceiverUserId()));

            //查询用户信息
            Map<UserVo, UserInfo> userMap = userService.selectUserInfoMap(userVoSet, null);

            goeasyMessage.setSendUserInfo(userMap.get(new UserVo(goeasyMessage.getSenderUserType(), goeasyMessage.getSenderUserId())));
            goeasyMessage.setReceiveUserInfo(userMap.get(new UserVo(goeasyMessage.getReceiverUserType(), goeasyMessage.getReceiverUserId())));


        }

        return goeasyMessage;
    }

    @Autowired
    private UserService userService;

    /**
     * 查询goeasy消息列表
     *
     * @param goeasyMessage goeasy消息
     * @return goeasy消息
     */
    @Override
    public List<GoeasyMessage> selectGoeasyMessageList(GoeasyMessage goeasyMessage) {
        List<GoeasyMessage> goeasyMessages = goeasyMessageMapper.selectGoeasyMessageList(goeasyMessage);
        //根據goeasy_time 來正序排列
        goeasyMessages.sort(Comparator.comparing(GoeasyMessage::getGoeasyTime));
        if (goeasyMessages.size() > 0) {
            Set<UserVo> userVoSet = new HashSet<>();
            goeasyMessages.stream().forEach(s -> {
                userVoSet.add(new UserVo(s.getSenderUserType(), s.getSenderUserId()));
                userVoSet.add(new UserVo(s.getReceiverUserType(), s.getReceiverUserId()));
            });

            //查询用户信息
            Map<UserVo, UserInfo> userMap = userService.selectUserInfoMap(userVoSet, null);

            goeasyMessages.stream().forEach(s -> {
                s.setSendUserInfo(userMap.get(new UserVo(s.getSenderUserType(), s.getSenderUserId())));
                s.setReceiveUserInfo(userMap.get(new UserVo(s.getReceiverUserType(), s.getReceiverUserId())));
            });
        }

        return goeasyMessages;
    }

    /**
     * 新增goeasy消息
     *
     * @param goeasyMessage goeasy消息
     * @return 结果
     */
    @Override
    public int insertGoeasyMessage(GoeasyMessage goeasyMessage) {
        goeasyMessage.setCreateData();
        return goeasyMessageMapper.insert(goeasyMessage);
    }

    /**
     * 修改goeasy消息
     *
     * @param goeasyMessage goeasy消息
     * @return 结果
     */
    @Override
    public int updateGoeasyMessage(GoeasyMessage goeasyMessage) {
        goeasyMessage.setUpdateData();
        return goeasyMessageMapper.updateGoeasyMessage(goeasyMessage);
    }

    /**
     * 批量删除goeasy消息
     *
     * @param ids 需要删除的goeasy消息主键
     * @return 结果
     */
    @Override
    public int deleteGoeasyMessageByIds(Long[] ids, Integer delFlag) {
        this.lambdaUpdate().set(GoeasyMessage::getDelFlag, delFlag).in(GoeasyMessage::getId, ids).update();
        return ids.length;
    }

    @Autowired
    private GoeasyMessageNewService goeasyMessageNewService;

    @Autowired
    private GoeasyMessageNewMapper goeasyMessageNewMapper;

    @Override
    public void goeasyMessage(List<GoeasyMessage> goeasyMessages) {

        // 使用 Map 存储唯一的 GoeasyMessage，键为 messageId，值为 GoeasyMessage 对象
        Map<String, GoeasyMessage> uniqueMessages = new HashMap<>();

        // 遍历列表，将每个消息按 messageId 存储到 Map 中
        for (GoeasyMessage message : goeasyMessages) {
            if (message == null) {
                continue;
            }
            uniqueMessages.put(message.getMessageId(), message);
        }

        Collection<GoeasyMessage> onlyList = uniqueMessages.values();
        try {
            this.saveBatch(onlyList);

            //更新 goeasy_message_new
            List<GoeasyMessageNew> goeasyMessageNewList = new ArrayList<>();

            onlyList.stream().forEach(x -> {
                Long userId = x.getSenderUserId();
                Long otherUserId = x.getReceiverUserId();

                GoeasyMessageNew goeasyMessageNew = goeasyMessageNewMapper.getMessage(userId, otherUserId);

                if (goeasyMessageNew == null) {
                    goeasyMessageNew = new GoeasyMessageNew();
                    goeasyMessageNew.setGoeasyTime(x.getGoeasyTime());
                    goeasyMessageNew.setUserId(userId);
                    goeasyMessageNew.setOtherUserId(otherUserId);
                    goeasyMessageNew.setType(x.getType());
                    goeasyMessageNew.setPayload(x.getPayload());
                    goeasyMessageNew.setDelFlag(PublicCommon.启用);
                } else {
                    goeasyMessageNew.setGoeasyTime(x.getGoeasyTime());
                    goeasyMessageNew.setPayload(x.getPayload());
                    goeasyMessageNew.setType(x.getType());
                }

                goeasyMessageNewList.add(goeasyMessageNew);
            });

            if (goeasyMessageNewList.size() > 0) {
                goeasyMessageNewService.saveOrUpdateBatch(goeasyMessageNewList);
            }

        } catch (Exception e) {
            log.error("goeasy消息发送失败", e);
        }

    }
}
