package com.example.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.common.config.TokenUtils;
import com.example.common.enums.ResultCodeEnum;
import com.example.entity.Account;
import com.example.entity.Announcement;
import com.example.exception.CustomException;
import com.example.mapper.AnnouncementMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * 公告服务类
 */
@Service
public class AnnouncementService {

    @Resource
    private AnnouncementMapper announcementMapper;
    
    /**
     * 添加公告
     * @param announcement 公告信息
     */
    public void add(Announcement announcement) {
        // 获取当前用户
        Account currentUser = TokenUtils.getCurrentUser();
        if (currentUser == null) {
            throw new CustomException(ResultCodeEnum.TOKEN_CHECK_ERROR);
        }
        
        // 验证权限
        if (!"admin".equals(currentUser.getRole())) {
            throw new CustomException(ResultCodeEnum.PARAM_ERROR.code, "只有管理员可以发布公告");
        }
        
        // 设置默认值
        if (announcement.getIsTop() == null) {
            announcement.setIsTop(false);
        }
        
        if (announcement.getStatus() == null) {
            announcement.setStatus(0); // 默认为草稿状态
        }
        
        announcement.setCreateTime(new Date());
        announcement.setPublisherId(currentUser.getId());
        announcement.setPublisherName(currentUser.getName());
        
        announcementMapper.insert(announcement);
    }
    
    /**
     * 更新公告
     * @param announcement 公告信息
     */
    public void update(Announcement announcement) {
        // 获取当前用户
        Account currentUser = TokenUtils.getCurrentUser();
        if (currentUser == null) {
            throw new CustomException(ResultCodeEnum.TOKEN_CHECK_ERROR);
        }
        
        // 验证权限
        if (!"admin".equals(currentUser.getRole())) {
            throw new CustomException(ResultCodeEnum.PARAM_ERROR.code, "只有管理员可以修改公告");
        }
        
        // 获取原公告
        Announcement dbAnnouncement = announcementMapper.selectById(announcement.getId());
        if (dbAnnouncement == null) {
            throw new CustomException(ResultCodeEnum.PARAM_ERROR.code, "公告不存在");
        }
        
        // 只更新部分字段，保留创建时间等信息
        dbAnnouncement.setTitle(announcement.getTitle());
        dbAnnouncement.setContent(announcement.getContent());
        dbAnnouncement.setIsTop(announcement.getIsTop());
        dbAnnouncement.setStatus(announcement.getStatus());
        
        announcementMapper.updateById(dbAnnouncement);
    }
    
    /**
     * 删除公告
     * @param id 公告ID
     */
    public void delete(Integer id) {
        // 获取当前用户
        Account currentUser = TokenUtils.getCurrentUser();
        if (currentUser == null) {
            throw new CustomException(ResultCodeEnum.TOKEN_CHECK_ERROR);
        }
        
        // 验证权限
        if (!"admin".equals(currentUser.getRole())) {
            throw new CustomException(ResultCodeEnum.PARAM_ERROR.code, "只有管理员可以删除公告");
        }
        
        announcementMapper.deleteById(id);
    }
    
    /**
     * 获取公告详情
     * @param id 公告ID
     * @return 公告信息
     */
    public Announcement getById(Integer id) {
        return announcementMapper.selectById(id);
    }
    
    /**
     * 获取所有已发布的公告（分页，所有用户可访问）
     * @param pageNum 页码
     * @param pageSize 每页大小
     * @param title 标题关键字
     * @return 分页公告列表
     */
    public PageInfo<Announcement> getPublishedPage(Integer pageNum, Integer pageSize, String title) {
        PageHelper.startPage(pageNum, pageSize);
        List<Announcement> list = announcementMapper.selectAllPublishedWithKeyword(title);
        return new PageInfo<>(list);
    }
    
    /**
     * 获取所有公告（分页，包括草稿，仅管理员可用）
     * @param pageNum 页码
     * @param pageSize 每页大小
     * @param title 标题关键字
     * @return 分页公告列表
     */
    public PageInfo<Announcement> getAllForAdmin(Integer pageNum, Integer pageSize, String title) {
        // 获取当前用户
        Account currentUser = TokenUtils.getCurrentUser();
        if (currentUser == null) {
            throw new CustomException(ResultCodeEnum.TOKEN_CHECK_ERROR);
        }
        
        // 验证权限
        if (!"admin".equals(currentUser.getRole())) {
            throw new CustomException(ResultCodeEnum.PARAM_ERROR.code, "只有管理员可以查看所有公告");
        }
        
        PageHelper.startPage(pageNum, pageSize);
        List<Announcement> list = announcementMapper.selectAllForAdmin(title);
        return new PageInfo<>(list);
    }
    
    /**
     * 获取最新的几条已发布公告（用于首页展示）
     * @param limit 限制条数
     * @return 公告列表
     */
    public List<Announcement> getLatestPublished(Integer limit) {
        PageHelper.startPage(1, limit);
        return announcementMapper.selectAllPublished();
    }
} 