package cn.reghao.oss.console.sys.controller;

import cn.reghao.oss.console.sys.db.repository.SysMessageRepository;
import cn.reghao.oss.console.sys.model.po.SysMessage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

/**
 * @author reghao
 * @date 2021-04-04 21:24:18
 */
@Api(tags = "系统页面")
@Controller
public class SysPageController {
    private final SysMessageRepository sysMessageRepository;

    public SysPageController(SysMessageRepository sysMessageRepository) {
        this.sysMessageRepository = sysMessageRepository;
    }

    @ApiOperation(value = "系统实时日志页面")
    @GetMapping("/sys/log")
    public String logPage() {
        return "/sys/syslog";
    }

    @ApiOperation(value = "系统消息页面")
    @GetMapping("/sys/message")
    public String messagePage(Model model) {
        PageRequest pageRequest = PageRequest.of(0, 10, Sort.by(Sort.Direction.DESC, "createTime"));
        Page<SysMessage> page = sysMessageRepository.findByUnreadIsTrue(pageRequest);
        model.addAttribute("page", page);
        model.addAttribute("list", page.getContent());
        return "/sys/sysmsg";
    }

    @ApiOperation(value = "系统消息内容")
    @GetMapping("/sys/message/detail/{id}")
    public String messageDetail(@PathVariable("id") int id, Model model) {
        SysMessage sysMessage = sysMessageRepository.findById(id).orElse(null);
        String content = "";
        if (sysMessage != null) {
            content = sysMessage.getContent();

            sysMessage.setUnread(false);
            sysMessageRepository.save(sysMessage);
        }

        model.addAttribute("content", content);
        return "/sys/sysmsgdetail";
    }
}
