package cn.reghao.bnt.web.admin.service;

import cn.reghao.bnt.web.admin.model.constant.RoleType;
import cn.reghao.bnt.web.admin.model.po.UserMessage;
import cn.reghao.bnt.web.admin.db.repository.UserMessageRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author reghao
 * @date 2024-07-30 10:06:13
 */
@Slf4j
@Service
public class UserMessageService {
    private final UserMessageRepository userMessageRepository;
    private final AccountService accountService;

    public UserMessageService(UserMessageRepository userMessageRepository, AccountService accountService) {
        this.userMessageRepository = userMessageRepository;
        this.accountService = accountService;
    }

    public List<Integer> getAdminUserId() {
        String roleName = RoleType.ROLE_DEVOPS_ADMIN.name();
        return accountService.getUserIdsByRole(roleName);
    }

    public String getUnreadCount() {
        int userId = UserContext.getUserId();
        int unreadTotal = userMessageRepository.countByUserIdAndUnreadIsTrue(userId);
        String unreadMessage;
        if (unreadTotal > 99) {
            unreadMessage = "99+";
        } else {
            unreadMessage = String.valueOf(unreadTotal);
        }

        return unreadMessage;
    }

    public void sendUserMessage(String title, String content) {
        List<UserMessage> userMessageList = getAdminUserId().stream()
                .map(userId -> new UserMessage(userId, title, content))
                .collect(Collectors.toList());

        if (!userMessageList.isEmpty()) {
            userMessageRepository.saveAll(userMessageList);
        } else {
            log.error("admin user is empty");
        }
    }

    public Page<UserMessage> getMessages(int pageNumber, int pageSize) {
        int userId = UserContext.getUserId();
        PageRequest pageRequest = PageRequest.of(pageNumber-1, pageSize, Sort.by(Sort.Direction.DESC, "createTime"));
        Page<UserMessage> page = userMessageRepository.findByUserIdAndUnreadIsTrue(userId, pageRequest);
        return page;
    }

    public UserMessage getMessage(int messageId) {
        UserMessage userMessage = userMessageRepository.findById(messageId).orElse(null);
        String content = "";
        if (userMessage != null) {
            content = userMessage.getContent();

            userMessage.setUnread(false);
            userMessageRepository.save(userMessage);
            return userMessage;
        }

        return null;
    }

    @Transactional(rollbackFor = Exception.class)
    public void clearUserMessage() {
        int userId = UserContext.getUserId();
        userMessageRepository.deleteByUserId(userId);
    }
}
