package com.sikey.wa04.business.infrastructure.adapter.dao;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONUtil;
import com.sikey.wa04.business.domain.adapter.MessageCenterAdapter;
import com.sikey.wa04.business.domain.entity.MessageCenter;
import com.sikey.wa04.business.infrastructure.dto.model.MessageCenterModel;
import com.sikey.wa04.business.infrastructure.repository.MessageCenterRepository;
import com.sikey.wa04.common.enums.MessageCenterType;
import com.sikey.wa04.common.utils.ObjectMapperUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Limit;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Component;

import java.time.Instant;
import java.util.ArrayList;
import java.util.List;

/**
 * MessageCenterAdapterImpl
 *
 * @author qin
 */
@Slf4j
@Component
public class MessageCenterAdapterImpl implements MessageCenterAdapter {

    @Resource
    private MessageCenterRepository messageCenterRepository;

    @Override
    public void save(MessageCenter messageCenter, MessageCenterType messageType) {
        String childrenId = messageCenter.getCid();

        // 加入消息到消息中心
        MessageCenterModel messageCenterModel = new MessageCenterModel();
        messageCenterModel.setChildrenId(childrenId);
        messageCenterModel.setMessageType(messageCenter.getMessageType());
        messageCenterModel.setMessageParams(ObjectMapperUtil.convertValue(messageCenter.getMessageParams(), ObjectMapperUtil.getValueTypeRef()));
        //Instant 获取当前时间的时间戳（UTC 时区）,不带时区信息（始终是 UTC）
        messageCenterModel.setSendTime(Instant.now());

        messageCenterRepository.save(messageCenterModel);
    }

    /**
     * 查询消息
     *
     * @param childrenId 儿童id
     * @return
     */
    @Override
    public List<MessageCenter> findMessageCenterByChild(List<String> childrenId) {
        Sort sort = Sort.by(Sort.Direction.DESC, "sendTime");
        Limit limit = Limit.of(30);
        List<MessageCenterModel> messageCenterModel = messageCenterRepository.findByChildrenIdInOrderByCreatedAtDesc(childrenId,sort,limit);
        List<MessageCenter> messageCenters = new ArrayList<>(); // 直接初始化可变集合

        if(CollectionUtil.isNotEmpty(messageCenterModel)) {
            messageCenterModel.forEach(model -> {
                // 添加异常处理
                try {
                    MessageCenter messageCenter = new MessageCenter();
                    messageCenter.setCid(model.getChildrenId());
                    messageCenter.setMessageType(model.getMessageType());

                    messageCenter.setMessageParams(ObjectMapperUtil.convertValue(
                            model.getMessageParams(), ObjectMapperUtil.getValueTypeRef()
                    ));
                    messageCenter.setCreatedAt(model.getCreatedAt());

                    messageCenters.add(messageCenter);
                } catch (Exception e) {
                    // 处理转换异常
                    log.error("转换失败，跳过此条数据。model: {}, 错误: {}", JSONUtil.toJsonPrettyStr(model), e.getMessage());
                    // 捕获异常后不执行add操作，跳过当前数据, 不需要return，会自动继续下一次循环
                }
            });
        }

        return messageCenters;
    }

    /**
     * 删除消息中心
     *
     * @param childrenId  儿童编码
     * @param messageType 消息类型
     * @return
     */
    @Override
    public void deleteMessages(String childrenId, Integer messageType) {
        messageCenterRepository.deleteByChildrenIdAndMessageType(childrenId, messageType);
    }

}
