package com.example.controller;

import com.example.common.Result;
import com.example.entity.Announcement;
import com.example.service.AnnouncementService;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 公告控制器
 */
@RestController
@RequestMapping("/announcement")
public class AnnouncementController {

    @Resource
    private AnnouncementService announcementService;
    
    /**
     * 添加公告
     * @param announcement 公告信息
     * @return 结果
     */
    @PostMapping
    public Result add(@RequestBody Announcement announcement) {
        announcementService.add(announcement);
        return Result.success();
    }
    
    /**
     * 更新公告
     * @param announcement 公告信息
     * @return 结果
     */
    @PutMapping
    public Result update(@RequestBody Announcement announcement) {
        announcementService.update(announcement);
        return Result.success();
    }
    
    /**
     * 删除公告
     * @param id 公告ID
     * @return 结果
     */
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        announcementService.delete(id);
        return Result.success();
    }
    
    /**
     * 获取公告详情
     * @param id 公告ID
     * @return 公告信息
     */
    @GetMapping("/{id}")
    public Result getById(@PathVariable Integer id) {
        Announcement announcement = announcementService.getById(id);
        return Result.success(announcement);
    }
    
    /**
     * 获取所有已发布的公告（分页，所有用户可访问）
     * @param pageNum 页码
     * @param pageSize 每页大小
     * @param title 标题关键字
     * @return 分页公告列表
     */
    @GetMapping("/page")
    public Result getPublishedPage(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String title) {
        PageInfo<Announcement> pageInfo = announcementService.getPublishedPage(pageNum, pageSize, title);
        return Result.success(pageInfo);
    }
    
    /**
     * 获取所有公告（分页，包括草稿，仅管理员可用）
     * @param pageNum 页码
     * @param pageSize 每页大小
     * @param title 标题关键字
     * @return 分页公告列表
     */
    @GetMapping("/adminPage")
    public Result getAllForAdmin(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String title) {
        PageInfo<Announcement> pageInfo = announcementService.getAllForAdmin(pageNum, pageSize, title);
        return Result.success(pageInfo);
    }
    
    /**
     * 获取最新的几条已发布公告（用于首页展示）
     * @param limit 限制条数
     * @return 公告列表
     */
    @GetMapping("/latest")
    public Result getLatestPublished(
            @RequestParam(defaultValue = "5") Integer limit) {
        List<Announcement> list = announcementService.getLatestPublished(limit);
        return Result.success(list);
    }
} 