package com.yonge.cooleshow.cms.task;

import com.yonge.cooleshow.cms.dal.entity.HelpCenterContent;
import com.yonge.cooleshow.cms.service.HelpCenterContentService;
import com.yonge.cooleshow.common.entity.HttpResponseResult;
import io.swagger.models.auth.In;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.Instant;
import java.util.Date;
import java.util.List;

/**
 * Description 公告发布轮询
 *
 * @author liujunchi
 * @date 2022-04-29
 */
@RestController
@RequestMapping("/task")
public class NoticeReleaseTask {
    private Logger LOGGER = LoggerFactory.getLogger(NoticeReleaseTask.class);
    @Autowired
    private HelpCenterContentService helpCenterContentService;

    /**
     * 公告发布轮询
     */
    // @GetMapping("/noticeRelease")
    public HttpResponseResult noticeRelease(){
        // 查询将要发布的公告 (0 ~ 当前时间 + 5 min 的未发布的公告) 循环发布
        List<HelpCenterContent> helpCenterContents = helpCenterContentService.getNeedReleaseNotice();
        for (HelpCenterContent helpCenterContent : helpCenterContents) {
            if (helpCenterContent.getReleaseTime().compareTo(new Date()) <= 0) {
                helpCenterContentService.noticeRelease(helpCenterContent);
            } else {
                // 休眠到时间后，发送消息
                new Thread(()->{
                    long time = helpCenterContent.getReleaseTime().toInstant().getEpochSecond()
                            - Instant.now().getEpochSecond();
                    try {
                        Thread.sleep(time * 1000);
                        helpCenterContentService.noticeRelease(helpCenterContent);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                        LOGGER.warn(e.getMessage());
                    }
                }).start();
            }
        }
        return HttpResponseResult.succeed();
    }

}
