package cn.axzo.msg.center.message.service.impl;

import cn.axzo.msg.center.dal.MessageSendTwiceRecordDao;
import cn.axzo.msg.center.domain.entity.MessageSendTwiceRecord;
import cn.axzo.msg.center.message.service.MessageSendTwiceRecordService;
import cn.hutool.core.map.MapUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @description xxx
 * @author cold_blade
 * @date 2023/10/23
 * @version 1.0
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class MessageSendTwiceRecordServiceImpl implements MessageSendTwiceRecordService {

    private final MessageSendTwiceRecordDao messageSendTwiceRecordDao;

    @Override
    public List<Long> listByPerson(Long personId) {
        if (Objects.isNull(personId)) {
            log.info("personId is null.");
            return Collections.emptyList();
        }
        return messageSendTwiceRecordDao.lambdaQuery()
                .eq(MessageSendTwiceRecord::getReceiverPersonId, personId)
                .last("LIMIT 500")
                .orderByDesc(MessageSendTwiceRecord::getId)
                .select(MessageSendTwiceRecord::getOriginalMsgId)
                .list().stream()
                .map(MessageSendTwiceRecord::getOriginalMsgId)
                .collect(Collectors.toList());
    }

    @Override
    public void batchSave(Map<Long, Long> msgRecordIdPersonIdMap) {
        if (MapUtil.isEmpty(msgRecordIdPersonIdMap)) {
            return;
        }
        List<MessageSendTwiceRecord> records = msgRecordIdPersonIdMap.entrySet().stream()
                .map(e -> {
                    MessageSendTwiceRecord record = new MessageSendTwiceRecord();
                    record.setReceiverPersonId(e.getValue());
                    record.setOriginalMsgId(e.getKey());
                    return record;
                }).collect(Collectors.toList());
        messageSendTwiceRecordDao.saveBatch(records);
    }
}
