package com.ruoyi.project.common.controller;

import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.project.common.domain.MessageVo;
import com.ruoyi.project.common.dto.MessageChatDto;
import com.ruoyi.project.common.service.ISseChatEmitterService;
import com.ruoyi.project.common.service.ISseEmitterService;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import javax.annotation.Resource;

/**
 * @Author: zhaoby
 * @date: 2023-11-29 9:18:16
 */
@RestController
@RequestMapping("/sse")
public class SseEmitterController {
    @Resource
    private ISseEmitterService sseEmitterService;

    @Resource
    private ISseChatEmitterService iSseChatEmitterService;


    @GetMapping(value = "/createConnect", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter createConnect(String clientId, String lastEventId) {
        return sseEmitterService.createConnect(clientId, lastEventId);
    }

    @CrossOrigin
    @PostMapping("/broadcast")
    public void sendMessageToAllClient(@RequestBody(required = false) String msg) {
        sseEmitterService.sendMessageToAllClient(msg);
    }

    @CrossOrigin
    @PostMapping("/sendMessage")
    public void sendMessageToOneClient(@RequestBody(required = false) MessageVo messageVo) {
        if (messageVo.getClientId().isEmpty()) {
            return;
        }
        sseEmitterService.sendMessageToOneClient(messageVo.getClientId(), messageVo.getData());
    }

    @CrossOrigin
    @PostMapping("/sendMessageByclientId")
    public void sendMessageByclientId() {
        sseEmitterService.sendMessageToUserId(SecurityUtils.getUserId(), true);
    }

    @CrossOrigin
    @GetMapping("/closeConnect")
    public void closeConnect(@RequestParam(required = true) String clientId) {
        sseEmitterService.closeConnect(clientId);
    }


    @GetMapping(value = "/createChatRoomConnect", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter createChatRoomConnect(String clientId) {
        return iSseChatEmitterService.createChatRoomConnect(clientId);
    }


    @CrossOrigin
    @PostMapping("/createChatRoom")
    public AjaxResult createChatRoom(@RequestBody MessageChatDto dto) {
        iSseChatEmitterService.createChatRoom(dto);
        return AjaxResult.success();
    }

    @CrossOrigin
    @PostMapping("toSendInputMessage")
    public AjaxResult toSendInputMessage(@RequestBody MessageChatDto dto) {
        iSseChatEmitterService.toSendInputMessage(dto);
        return AjaxResult.success();
    }


}