package com.haha.admin.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.haha.admin.annotation.RequirePermission;
import com.haha.entity.dto.AnnouncementQueryDTO;
import com.haha.common.annotation.Log;
import com.haha.common.constant.AnnouncementConstants;
import com.haha.common.constant.ResponseEnum;
import com.haha.common.enums.OperationType;
import com.haha.common.vo.PageResult;
import com.haha.common.vo.Result;
import com.haha.entity.Announcement;
import com.haha.service.AnnouncementService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

/**
 * 系统公告管理控制器
 */
@Slf4j
@RequiredArgsConstructor
@RestController
@RequestMapping("/announcement")
public class AnnouncementController {

    private final AnnouncementService announcementService;

    /**
     * 分页查询公告列表
     */
    @RequirePermission("announcement:read")
    @GetMapping("/list")
    public Result<PageResult<Announcement>> list(AnnouncementQueryDTO queryDTO) {
        queryDTO.validate();

        IPage<Announcement> pageResult = announcementService.getPage(
                queryDTO.getPage(), queryDTO.getPageSize(), queryDTO);

        return Result.success("查询成功", PageResult.of(pageResult));
    }

    /**
     * 获取公告详情
     */
    @RequirePermission("announcement:read")
    @GetMapping("/{id}")
    public Result<Announcement> getDetail(@PathVariable Long id) {
        Announcement announcement = announcementService.getById(id);
        if (announcement == null) {
            return Result.error("公告不存在");
        }
        return Result.success(announcement);
    }

    /**
     * 创建公告
     */
    @RequirePermission("announcement:create")
    @Log(module = "公告管理", operation = OperationType.INSERT, summary = "创建公告")
    @PostMapping
    public Result<Announcement> create(@RequestBody Announcement announcement) {
        try {
            announcement.setIsTop(AnnouncementConstants.NOT_TOP);
            announcement.setReadCount(0);
            announcement.setCreateTime(LocalDateTime.now());
            announcement.setUpdateTime(LocalDateTime.now());

            if (announcement.getStatus() != null
                    && announcement.getStatus() == AnnouncementConstants.STATUS_PUBLISHED) {
                Long userId = StpUtil.getLoginIdAsLong();
                Object userNameObj = StpUtil.getSession().get("username");
                String userName = userNameObj != null ? userNameObj.toString() : userId.toString();
                announcement.setStatus(AnnouncementConstants.STATUS_PUBLISHED);
                announcement.setPublishTime(LocalDateTime.now());
                announcement.setPublisherId(userId);
                announcement.setPublisherName(userName);
            } else {
                announcement.setStatus(AnnouncementConstants.STATUS_DRAFT);
            }

            announcementService.save(announcement);
            return Result.success("创建成功", announcement);
        } catch (Exception e) {
            log.error("创建公告失败", e);
            return Result.error("创建失败：" + e.getMessage());
        }
    }

    /**
     * 更新公告
     */
    @RequirePermission("announcement:update")
    @Log(module = "公告管理", operation = OperationType.UPDATE, summary = "更新公告")
    @PutMapping("/{id}")
    public Result<Announcement> update(@PathVariable Long id, @RequestBody Announcement announcement) {
        try {
            Announcement existing = announcementService.getById(id);
            if (existing == null) {
                return Result.error("公告不存在");
            }

            // 只更新允许修改的字段
            existing.setTitle(announcement.getTitle());
            existing.setContent(announcement.getContent());
            existing.setType(announcement.getType());
            existing.setCoverImage(announcement.getCoverImage());
            existing.setUpdateTime(LocalDateTime.now());

            announcementService.updateById(existing);
            return Result.success("更新成功", existing);
        } catch (Exception e) {
            log.error("更新公告失败", e);
            return Result.error("更新失败：" + e.getMessage());
        }
    }

    /**
     * 删除公告
     */
    @RequirePermission("announcement:delete")
    @Log(module = "公告管理", operation = OperationType.DELETE, summary = "删除公告")
    @DeleteMapping("/{id}")
    public Result<String> delete(@PathVariable Long id) {
        try {
            Announcement existing = announcementService.getById(id);
            if (existing == null) {
                return Result.error("公告不存在");
            }

            announcementService.removeById(id);
            return Result.success("删除成功");
        } catch (Exception e) {
            log.error("删除公告失败", e);
            return Result.error("删除失败：" + e.getMessage());
        }
    }

    /**
     * 发布公告
     */
    @RequirePermission("announcement:update")
    @Log(module = "公告管理", operation = OperationType.UPDATE, summary = "发布公告")
    @PutMapping("/{id}/publish")
    public Result<String> publish(@PathVariable Long id) {
        try {
            Long userId = StpUtil.getLoginIdAsLong();
            Object userNameObj = StpUtil.getSession().get("username");
            String userName = userNameObj != null ? userNameObj.toString() : userId.toString();

            boolean success = announcementService.publish(id, userId, userName);
            if (success) {
                return Result.success("发布成功");
            } else {
                return Result.error("发布失败，公告不存在");
            }
        } catch (Exception e) {
            log.error("发布公告失败", e);
            return Result.error("发布失败：" + e.getMessage());
        }
    }

    /**
     * 下线公告
     */
    @RequirePermission("announcement:update")
    @Log(module = "公告管理", operation = OperationType.UPDATE, summary = "下线公告")
    @PutMapping("/{id}/offline")
    public Result<String> offline(@PathVariable Long id) {
        try {
            boolean success = announcementService.offline(id);
            if (success) {
                return Result.success("下线成功");
            } else {
                return Result.error("下线失败，公告不存在");
            }
        } catch (Exception e) {
            log.error("下线公告失败", e);
            return Result.error("下线失败：" + e.getMessage());
        }
    }

    /**
     * 置顶/取消置顶
     */
    @RequirePermission("announcement:update")
    @Log(module = "公告管理", operation = OperationType.UPDATE, summary = "置顶公告")
    @PutMapping("/{id}/top")
    public Result<String> setTop(@PathVariable Long id, @RequestParam Integer isTop) {
        try {
            boolean success = announcementService.setTop(id, isTop);
            if (success) {
                return Result.success(isTop == AnnouncementConstants.IS_TOP ? "置顶成功" : "取消置顶成功");
            } else {
                return Result.error("操作失败，公告不存在");
            }
        } catch (Exception e) {
            log.error("置顶操作失败", e);
            return Result.error("操作失败：" + e.getMessage());
        }
    }
}
