package cn.reghao.devops.mgr.admin.service;

import cn.reghao.devops.mgr.admin.db.repository.SysMessageRepository;
import cn.reghao.devops.mgr.admin.model.po.SysMessage;
import cn.reghao.devops.mgr.admin.model.vo.SysMsg;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author reghao
 * @date 2024-07-30 10:06:13
 */
@Service
public class SysMessageService {
    private final SysMessageRepository sysMessageRepository;

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

    public Page<SysMsg> getSysMessages() {
        PageRequest pageRequest = PageRequest.of(0, 10, Sort.by(Sort.Direction.DESC, "createTime"));
        return sysMessageRepository.findByUnreadIsTrue(pageRequest).map(SysMsg::new);
    }

    public void clearUnread() {
        List<SysMessage> list = sysMessageRepository.findByUnreadIsTrue(PageRequest.of(0, 100)).getContent();
        if (!list.isEmpty()) {
            list.forEach(sysMessage -> sysMessage.setUnread(false));
            sysMessageRepository.saveAll(list);
        }
    }

    public String getUnreadCount() {
        int unreadTotal = sysMessageRepository.countByUnread(true);
        String unreadMessage;
        if (unreadTotal > 9) {
            unreadMessage = "9+";
        } else {
            unreadMessage = String.valueOf(unreadTotal);
        }

        return unreadMessage;
    }

    public void putSysMessage(String title, String content) {
        if (content.length() > 200) {
            content = content.substring(0, 200);
        }
        SysMessage sysMessage = new SysMessage(title, content);
        sysMessageRepository.save(sysMessage);
    }

    public SysMessage getSysMessage(int id) {
        SysMessage sysMessage = sysMessageRepository.findById(id).orElse(null);
        if (sysMessage != null) {
            sysMessage.setUnread(false);
            sysMessageRepository.save(sysMessage);
        }

        return sysMessage;
    }
}
