package com.iformall.controller.websocket;

import com.alibaba.fastjson.JSONObject;
import com.iformall.interceptor.AuthHandshakeInterceptor;
import com.iformall.model.Message;
import com.iformall.service.UserService;
import com.iformall.util.Constance;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.DestinationVariable;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.simp.SimpMessageSendingOperations;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.web.bind.annotation.RestController;

import java.security.Principal;
import java.util.List;


/**
 * websocket Controller
 *
 * @author Stormeye
 */
@RestController
public class ReceiverController {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    SimpMessageSendingOperations simpMessageSendingOperations;

    @Autowired
    private AmqpTemplate amqpTemplate;

    @Autowired
    private UserService userService;

    /**
     * 接收客户端发来的消息
     */
    @MessageMapping("/message")
    public void handleSubscribe(String msg, StompHeaderAccessor stompHeaderAccessor) {
        Principal user = stompHeaderAccessor.getUser();
        String tenantId = (String) stompHeaderAccessor.getSessionAttributes().get(AuthHandshakeInterceptor.TENANT_ID);
        Long userId = (Long) stompHeaderAccessor.getSessionAttributes().get(AuthHandshakeInterceptor.LOGIN_USER_KEY);
        logger.info("客户端[" + stompHeaderAccessor.getSessionId() + "]发来消息：, " + msg + "\n" + stompHeaderAccessor.getSessionAttributes().toString());
        JSONObject json = JSONObject.parseObject(msg);
        String to = json.getString("to");
        if (StringUtils.isNotBlank(to)) {
            simpMessageSendingOperations.convertAndSendToUser(to, "/message", msg);
        } else {
            simpMessageSendingOperations.convertAndSendToUser("oX7SP4qpcX7LTmLjNuuFSQFXuK0M", "/message", msg);
        }
    }

    /**
     * 接收客户端发来的群聊消息
     */
    @MessageMapping("/chat-group/{roomId}")
    public void handleGroupMsg(@DestinationVariable String roomId, String msg) {
        logger.info("客户端发来群组消息：" + msg);
        simpMessageSendingOperations.convertAndSend("/topic/chat-group/" + roomId, msg);
    }

    /**
     * 个人聊天消息
     * @param message
     * @param headerAccessor
     */
    @MessageMapping("/p2p")
    public void p2p(Message message, SimpMessageHeaderAccessor headerAccessor) {
        String userId = userService.getSessionId(message.getTo());
        System.out.println(Constance.queue_pre+userId);
        amqpTemplate.convertAndSend("", Constance.queue_pre+userId, message.getMessage());
    }

    /**
     * 群发消息
     * @param message
     * @throws Exception
     */
    @MessageMapping("/sendall")
    public void group(Message message) throws Exception {
        List<String> users = userService.listSessionIds();
        for(String user:users){
            System.out.println(Constance.queue_pre+user);
            amqpTemplate.convertAndSend("", Constance.queue_pre+user, message.getMessage());
        }
    }


}