/*
 * 文 件 名:  AlarmController
 * 版    权:  华设设计集团股份有限公司
 * 描    述:  <描述>
 * 修 改 人:  lvwenbin
 * 修改时间:  2026/2/3
 * 跟踪单号:  <跟踪单号>
 * 修改单号:  <修改单号>
 * 修改内容:  <修改内容>
 */
package com.ruoyi.ems.controller;

import com.huashe.common.domain.AjaxResult;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.ems.domain.Alarm;
import com.ruoyi.ems.domain.AlarmHandle;
import com.ruoyi.ems.service.IAlarmService;
import com.ruoyi.ems.service.alarm.AlarmProcessService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 告警管理Controller
 */
@RestController
@RequestMapping("/alarm")
@Api(value = "AlarmController", description = "告警管理")
public class AlarmController extends BaseController {

    @Autowired
    private IAlarmService alarmService;

    @Autowired
    private AlarmProcessService processService;

    /**
     * 查询告警列表
     */
    @RequiresPermissions("ems:alarm:list")
    @GetMapping("/list")
    @ApiOperation("查询告警列表")
    public TableDataInfo list(Alarm alarm) {
        startPage();
        List<Alarm> list = alarmService.selectList(alarm);
        return getDataTable(list);
    }

    /**
     * 查询活动告警
     */
    @RequiresPermissions("ems:alarm:list")
    @GetMapping("/active")
    @ApiOperation("查询活动告警")
    public AjaxResult listActive(@RequestParam(value = "areaCode", required = false) String areaCode) {
        return success(alarmService.selectActiveAlarms(areaCode));
    }

    /**
     * 导出告警列表
     */
    @RequiresPermissions("ems:alarm:export")
    @Log(title = "告警管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ApiOperation("导出告警")
    public void export(HttpServletResponse response, Alarm alarm) {
        List<Alarm> list = alarmService.selectList(alarm);
        ExcelUtil<Alarm> util = new ExcelUtil<>(Alarm.class);
        util.exportExcel(response, list, "告警数据");
    }

    /**
     * 获取告警详情
     */
    @RequiresPermissions("ems:alarm:query")
    @GetMapping("/{id}")
    @ApiOperation("获取告警详情")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        Alarm alarm = alarmService.selectById(id);
        if (alarm != null) {
            // 加载处置记录
            alarm.setHandleList(alarmService.selectHandlesByAlarmId(alarm.getAlarmId()));
        }
        return success(alarm);
    }

    /**
     * 根据告警ID获取详情
     */
    @RequiresPermissions("ems:alarm:query")
    @GetMapping("/detail/{alarmId}")
    @ApiOperation("根据告警ID获取详情")
    public AjaxResult getByAlarmId(@PathVariable("alarmId") String alarmId) {
        Alarm alarm = alarmService.selectByAlarmId(alarmId);
        if (alarm != null) {
            alarm.setHandleList(alarmService.selectHandlesByAlarmId(alarmId));
        }
        return success(alarm);
    }

    /**
     * 手动上报告警
     */
    @RequiresPermissions("ems:alarm:add")
    @Log(title = "告警管理", businessType = BusinessType.INSERT)
    @PostMapping("/report")
    @ApiOperation("手动上报告警")
    public AjaxResult report(@RequestBody Alarm alarm) {
        String reporter = SecurityUtils.getUsername();
        Alarm result = processService.reportAlarm(alarm, reporter);
        return success(result);
    }

    /**
     * 确认告警
     */
    @RequiresPermissions("ems:alarm:handle")
    @Log(title = "告警管理", businessType = BusinessType.UPDATE)
    @PutMapping("/confirm/{alarmId}")
    @ApiOperation("确认告警")
    public AjaxResult confirm(@PathVariable("alarmId") String alarmId,
        @RequestBody AlarmHandle handle) {
        String operator = SecurityUtils.getUsername();
        processService.confirmAlarm(alarmId, operator, handle.getRemark());
        return success();
    }

    /**
     * 处置告警
     */
    @RequiresPermissions("ems:alarm:handle")
    @Log(title = "告警管理", businessType = BusinessType.UPDATE)
    @PutMapping("/handle/{alarmId}")
    @ApiOperation("处置告警")
    public AjaxResult handle(@PathVariable("alarmId") String alarmId,
        @RequestBody AlarmHandle handle) {
        String operator = SecurityUtils.getUsername();
        processService.handleAlarm(alarmId, handle.getHandleContent(), handle.getHandleResult(), operator);
        return success();
    }

    /**
     * 解决告警
     */
    @RequiresPermissions("ems:alarm:handle")
    @Log(title = "告警管理", businessType = BusinessType.UPDATE)
    @PutMapping("/resolve/{alarmId}")
    @ApiOperation("解决告警")
    public AjaxResult resolve(@PathVariable("alarmId") String alarmId,
        @RequestBody Alarm alarm) {
        String operator = SecurityUtils.getUsername();
        processService.resolveAlarm(alarmId, alarm.getResolveRemark(), operator);
        return success();
    }

    /**
     * 关闭告警
     */
    @RequiresPermissions("ems:alarm:handle")
    @Log(title = "告警管理", businessType = BusinessType.UPDATE)
    @PutMapping("/close/{alarmId}")
    @ApiOperation("关闭告警")
    public AjaxResult close(@PathVariable("alarmId") String alarmId, @RequestBody Alarm alarm) {
        String operator = SecurityUtils.getUsername();
        // 从实体中获取 reason
        processService.closeAlarm(alarmId, alarm.getResolveRemark(), operator);
        return success();
    }

    /**
     * 批量确认告警
     */
    @RequiresPermissions("ems:alarm:handle")
    @Log(title = "告警管理", businessType = BusinessType.UPDATE)
    @PutMapping("/batchConfirm")
    @ApiOperation("批量确认告警")
    public AjaxResult batchConfirm(@RequestBody List<String> alarmIds) {
        String operator = SecurityUtils.getUsername();
        int count = processService.batchConfirm(alarmIds, operator);
        return success("成功确认 " + count + " 条告警");
    }

    /**
     * 删除告警
     */
    @RequiresPermissions("ems:alarm:remove")
    @Log(title = "告警管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    @ApiOperation("删除告警")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(alarmService.deleteByIds(ids));
    }

    // ==================== 统计接口 ====================

    /**
     * 告警统计概览
     */
    @RequiresPermissions("ems:alarm:query")
    @GetMapping("/stats/overview")
    @ApiOperation("告警统计概览")
    public AjaxResult statsOverview(Alarm query) {
        return success(alarmService.selectAlarmStats(query));
    }

    /**
     * 按级别统计
     */
    @RequiresPermissions("ems:alarm:query")
    @GetMapping("/stats/byLevel")
    @ApiOperation("按级别统计")
    public AjaxResult countByLevel(Alarm query) {
        return success(alarmService.countByLevel(query));
    }

    /**
     * 按状态统计
     */
    @RequiresPermissions("ems:alarm:query")
    @GetMapping("/stats/byStatus")
    @ApiOperation("按状态统计")
    public AjaxResult countByStatus(Alarm query) {
        return success(alarmService.countByStatus(query));
    }

    /**
     * 按时间趋势统计
     */
    @RequiresPermissions("ems:alarm:query")
    @GetMapping("/stats/trend")
    @ApiOperation("按时间趋势统计")
    public AjaxResult countByTrend(Alarm query,
        @RequestParam(value = "granularity", defaultValue = "day") String granularity) {
        return success(alarmService.countByTimeTrend(query, granularity));
    }

    /**
     * 按子系统统计
     */
    @RequiresPermissions("ems:alarm:query")
    @GetMapping("/stats/bySubsystem")
    @ApiOperation("按子系统统计")
    public AjaxResult countBySubsystem(Alarm query) {
        return success(alarmService.countBySubsystem(query));
    }

    /**
     * 处理率统计
     */
    @RequiresPermissions("ems:alarm:query")
    @GetMapping("/stats/handleRate")
    @ApiOperation("处理率统计")
    public AjaxResult handleRate(Alarm query) {
        return success(alarmService.countHandleRate(query));
    }
}