package com.mosty.hczx.controller;

import cn.hutool.core.date.DateUtil;
import com.mosty.base.utils.Constant;
import com.mosty.common.token.JwtSysUser;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.util.Date;


@Controller
@RequestMapping(path = "/hcSse")
public class SseHcController {


    @RequestMapping(value = "test", method = RequestMethod.GET)
    public Object test() {
        return DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss");
    }


    @GetMapping(path = "subscribe")
    @JwtSysUser
    public SseEmitter push(String id) throws IOException {
        System.out.println(id);
        // 超时时间设置为1小时
        SseEmitter sseEmitter = new SseEmitter(3600_000L);
        // 设置前端的重试时间为1s
        sseEmitter.send(SseEmitter.event().reconnectTime(1000).data("连接成功"));
        Constant.HcSse.put(id, sseEmitter);
        sseEmitter.onTimeout(() -> Constant.HcSse.remove(id));
        sseEmitter.onCompletion(() -> System.out.println("完成！！！"));
        return sseEmitter;
    }

    @PostMapping(path = "push")
    @ResponseBody
    @JwtSysUser
    public String push(String id, String content) throws IOException {
        SseEmitter sseEmitter = Constant.HcSse.get(id);
        if (sseEmitter != null) {
            sseEmitter.send(content);
        }
        return "push over";
    }

    @GetMapping(path = "close")
    @ResponseBody
    public String over(String id) throws IOException {
        SseEmitter sseEmitter = Constant.HcSse.get(id);
        if (sseEmitter != null) {
            sseEmitter.send("close");
            sseEmitter.send(SseEmitter.event().name("close").id(id).data(""));
            sseEmitter.complete();
            Constant.HcSse.remove(id);
        }
        return "close over";
    }


}
