package com.cool.store.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.util.ArrayUtil;
import com.alibaba.fastjson.JSONObject;
import com.cool.store.dao.MessageTemplateDAO;
import com.cool.store.entity.MessageTemplateDO;
import com.cool.store.entity.StoreMessageDO;
import com.cool.store.enums.ErrorCodeEnum;
import com.cool.store.exception.ServiceException;
import com.cool.store.vo.notice.StoreMessageVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.messaging.MessagingException;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * <p>
 * 消息下发 服务类
 * </p>
 *
 * @author wangff
 * @since 2025/9/5
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class MessageIssueService {
    private final MessageTemplateDAO messageTemplateDAO;
    private final SimpMessagingTemplate simpMessagingTemplate;

    /**
     * 下发即时通知消息
     *
     * @param list 门店消息列表
     */
    @Async("generalThreadPool")
    public void issueMessage(List<StoreMessageDO> list) {
        if (CollectionUtils.isEmpty(list)) return;
        log.info("下发即时通知, messageList:{}", JSONObject.toJSONString(list));
        try {
            Set<Long> messageTemplateIds = CollStreamUtil.toSet(list, StoreMessageDO::getMessageTemplateId);
            List<MessageTemplateDO> messageTemplateList = messageTemplateDAO.getByIds(new ArrayList<>(messageTemplateIds));
            Map<Long, MessageTemplateDO> messageTemplateMap = CollStreamUtil.toMap(messageTemplateList, MessageTemplateDO::getId, v -> v);

            for (StoreMessageDO storeMessageDO : list) {
                if (StringUtils.isNotBlank(storeMessageDO.getOperatorList())) {
                    String[] userIds = storeMessageDO.getOperatorList().split(",");
                    if (ArrayUtil.isNotEmpty(userIds)) {
                        MessageTemplateDO messageTemplateDO = messageTemplateMap.get(storeMessageDO.getMessageTemplateId());
                        if (Objects.isNull(messageTemplateDO)) {
                            throw new ServiceException(ErrorCodeEnum.MESSAGE_NOT_EXIST);
                        }
                        StoreMessageVO storeMessageVO = BeanUtil.toBean(storeMessageDO, StoreMessageVO.class);
                        BeanUtil.copyProperties(messageTemplateDO, storeMessageVO, "id");
                        String message = JSONObject.toJSONString(storeMessageVO);
                        for (String userId : userIds) {
                            try {
                                simpMessagingTemplate.convertAndSend("/queue/message/" + userId, message);
                            } catch (MessagingException e) {
                                log.info("即时通知下发异常, userId:{}, error:{}", userId, e.getMessage());
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.info("即时通知下发异常", e);
        }
    }
}
