package com.zcxk.mq;

import com.alibaba.fastjson.JSONObject;
import com.zcxk.Dto.MessageDto;
import com.zcxk.dao.MessageMapper;
import com.zcxk.dao.MessageTemplateMapper;
import com.zcxk.dao.MessageTypeMapper;
import com.zcxk.entity.Message;
import com.zcxk.entity.MessageTemplate;
import com.zcxk.entity.MessageType;
import com.zcxk.entity.WebsocketConnectInfo;
import com.zcxk.util.MessagePush;
import com.zcxk.util.Parser;
import com.zcxk.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Component
@Slf4j
public class DispatchMessage {
    @Autowired
    private RedisUtil redisUtil;
    @Value("${user.connections}")
    private String userConnections;
    @Autowired
    private AmqpTemplate rabbitTemplate;
    @Autowired
    private MessageTypeMapper messageTypeMapper;
    @Autowired
    private MessageTemplateMapper messageTemplateMapper;
    @Autowired
    private MessageMapper messageMapper;
    @RabbitListener(queues = "${dispath.queue}")
    public void dispatch(String message){

        Long size = redisUtil.opsForList().size(userConnections);
        Message receiveMessage= JSONObject.parseObject(message, Message.class);
        receiveMessage.setStatus(1);
        receiveMessage.setMessageStatus(0);
        Integer messageTemplateId = receiveMessage.getMessageTemplateId();
        Integer messageTypeId = receiveMessage.getMessageType();
        MessageTemplate messageTemplate = messageTemplateMapper.selectById(messageTemplateId);
        MessageType messageType = messageTypeMapper.selectById(messageTypeId);
        MessageDto messageDto = new MessageDto();
        String receiveMessageContent=receiveMessage.getMessageContent();
       try {
           if(messageTemplate!=null&&receiveMessageContent.contains("{")){
               String content = messageTemplate.getContent();
               Map<String,String> param = JSONObject.parseObject(receiveMessageContent, Map.class);
               String replaceContent = Parser.replaceAllClearBlanks(content, param);
               receiveMessage.setMessageContent(replaceContent);
           }
       }catch (Exception e){
           e.printStackTrace();
       }

        Integer channel=0;
        if(receiveMessage.getChannel()!=null){
            channel=receiveMessage.getChannel();
        }
        messageMapper.insert(receiveMessage);
        messageDto.setContent(receiveMessage.getMessageContent());
        messageDto.setType(messageType==null?"未知":messageType.getShortName());
        messageDto.setUserId(receiveMessage.getUserId()+"");
        messageDto.setTypeId(messageTypeId);
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String date=dtf2.format(now);
        messageDto.setDate(date);
        List<String> connectInfos = redisUtil.opsForList().range(userConnections, 0, size);
        if(channel==1){
            sendAppMsg(receiveMessage.getUserId()+"",receiveMessage.getMessageContent());

        }else{

            connectInfos.forEach(connectInfo ->{
                WebsocketConnectInfo websocketConnectInfo =
                        JSONObject.parseObject(connectInfo, WebsocketConnectInfo.class);
                String sendMessage = JSONObject.toJSONString(messageDto);
                String connectUserId=websocketConnectInfo.getUserId();
                String receiveUserId=receiveMessage.getUserId()+"";
                if(connectUserId.equals(receiveUserId)){
                    log.info("向用户："+websocketConnectInfo.getUserId()+"发送消息："+sendMessage);

                    rabbitTemplate.convertAndSend(websocketConnectInfo.getConnectServerExchange(),
                            websocketConnectInfo.getConnectServerRoutingKey(), sendMessage);

                }
            });
        }

    }
    //app推送
    private void sendAppMsg(String userId,String content){
        List<String>alias=new ArrayList<>();
        alias.add(userId);
        MessagePush.sendAlias(content,alias);

    }
}
