package com.weather.modules.sys.controller;

import com.weather.common.annotation.LogOperation;
import com.weather.common.constant.Constant;
import com.weather.common.page.PageData;
import com.weather.common.utils.Result;
import com.weather.common.validator.AssertUtils;
import com.weather.common.validator.ValidatorUtils;
import com.weather.common.validator.group.AddGroup;
import com.weather.common.validator.group.DefaultGroup;
import com.weather.common.validator.group.UpdateGroup;
import com.weather.modules.sys.alert.SseAlertService;
import com.weather.modules.sys.dto.SysAlertDTO;
import com.weather.modules.sys.service.SysAlertService;
import com.weather.modules.sys.vo.SysAlertVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.util.List;
import java.util.Map;

/**
 * 系统通知
 */
@RestController
@RequestMapping("sys/alert")
@Tag(name = "系统通知")
@AllArgsConstructor
public class SysAlertController {
    private final SysAlertService sysAlertService;
    private final SseAlertService sseAlertService;

    // ===== 前端轮询接口（无需权限，登录即可访问） =====

    @GetMapping("active")
    @Operation(summary = "获取所有有效通知")
    public Result<List<SysAlertVO>> active() {
        List<SysAlertVO> list = sysAlertService.getActiveAlerts();
        return new Result<List<SysAlertVO>>().ok(list);
    }

    @GetMapping("active/since")
    @Operation(summary = "增量获取通知")
    @Parameter(name = "since", description = "起始ID（返回ID大于此值的通知）", in = ParameterIn.QUERY)
    public Result<List<SysAlertVO>> activeSince(@RequestParam(required = false) Long since) {
        if (since == null) {
            List<SysAlertVO> list = sysAlertService.getActiveAlerts();
            return new Result<List<SysAlertVO>>().ok(list);
        }
        List<SysAlertVO> list = sysAlertService.getActiveAlertsSince(since);
        return new Result<List<SysAlertVO>>().ok(list);
    }

    @GetMapping("stream")
    @Operation(summary = "通知SSE实时推送")
    public SseEmitter stream() {
        return sseAlertService.createEmitter();
    }

    // ===== 管理后台接口 =====

    @GetMapping("page")
    @Operation(summary = "分页")
    @Parameters({
            @Parameter(name = Constant.PAGE, description = "当前页码，从1开始", in = ParameterIn.QUERY, required = true, ref = "int"),
            @Parameter(name = Constant.LIMIT, description = "每页显示记录数", in = ParameterIn.QUERY, required = true, ref = "int"),
            @Parameter(name = Constant.ORDER_FIELD, description = "排序字段", in = ParameterIn.QUERY, ref = "String"),
            @Parameter(name = Constant.ORDER, description = "排序方式，可选值(asc、desc)", in = ParameterIn.QUERY, ref = "String"),
            @Parameter(name = "level", description = "级别", in = ParameterIn.QUERY, ref = "String"),
            @Parameter(name = "title", description = "标题", in = ParameterIn.QUERY, ref = "String"),
            @Parameter(name = "sourceType", description = "来源类型", in = ParameterIn.QUERY, ref = "String")
    })
    @RequiresPermissions("sys:alert:page")
    public Result<PageData<SysAlertVO>> page(@Parameter(hidden = true) @RequestParam Map<String, Object> params) {
        PageData<SysAlertVO> page = sysAlertService.pageAlerts(params);
        return new Result<PageData<SysAlertVO>>().ok(page);
    }

    @GetMapping("{id}")
    @Operation(summary = "信息")
    @RequiresPermissions("sys:alert:info")
    public Result<SysAlertVO> get(@PathVariable("id") Long id) {
        SysAlertVO data = sysAlertService.get(id);
        return new Result<SysAlertVO>().ok(data);
    }

    @PostMapping
    @Operation(summary = "保存")
    @LogOperation("发布通知")
    @RequiresPermissions("sys:alert:save")
    public Result save(@RequestBody SysAlertDTO dto) {
        ValidatorUtils.validateEntity(dto, AddGroup.class, DefaultGroup.class);
        sysAlertService.save(dto);
        return new Result();
    }

    @PutMapping
    @Operation(summary = "修改")
    @LogOperation("修改通知")
    @RequiresPermissions("sys:alert:update")
    public Result update(@RequestBody SysAlertDTO dto) {
        ValidatorUtils.validateEntity(dto, UpdateGroup.class, DefaultGroup.class);
        sysAlertService.update(dto);
        return new Result();
    }

    @DeleteMapping
    @Operation(summary = "删除")
    @LogOperation("删除通知")
    @RequiresPermissions("sys:alert:delete")
    public Result delete(@RequestBody Long[] ids) {
        AssertUtils.isArrayEmpty(ids, "id");
        sysAlertService.delete(ids);
        return new Result();
    }

    @PutMapping("{id}/withdraw")
    @Operation(summary = "撤回通知")
    @LogOperation("撤回通知")
    @RequiresPermissions("sys:alert:retract")
    public Result withdraw(@PathVariable Long id) {
        sysAlertService.withdraw(id);
        return new Result();
    }
}
