package com.yfd.platform.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yfd.platform.component.ServerSendEventServer;
import com.yfd.platform.config.WebConfig;
import com.yfd.platform.constant.Constant;
import com.yfd.platform.system.domain.Message;
import com.yfd.platform.system.service.IMessageService;
import com.yfd.platform.system.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import javax.annotation.Resource;

/**
 * @author Huhailong
 */
@Slf4j
@RestController
@CrossOrigin
@RequestMapping("/sse")
@Api(tags = "SSE推送服务")
public class SSEController {

    @Resource
    private IMessageService messageService;

    @GetMapping("/connect/{token}")
    @ApiOperation("建立连接")
    public SseEmitter connect(@PathVariable String token) {
        SseEmitter connect = ServerSendEventServer.connect(token);
        long count =
                messageService.count(new LambdaQueryWrapper<Message>().eq(Message::getStatus, "1"));
        ServerSendEventServer.sendMessage(token, count + "");
        return connect;
    }

    @GetMapping("/sendmsg")
    @ApiOperation("发送消息")
    public void sendMessage(String token, String message) throws InterruptedException {

        ServerSendEventServer.sendMessage(token, message);
    }

    @GetMapping("/sendgroupmsg")
    @ApiOperation("多人发送消息")
    public void sendgroupmsg(String groupid, String message) throws InterruptedException {
        ServerSendEventServer.groupSendMessage(groupid, message);
    }

    @GetMapping("/disconnect/{token}")
    @ApiOperation("关闭连接")
    public void disconnect(@PathVariable String token) throws InterruptedException {
        ServerSendEventServer.removeUser(token);
    }
}
