package com.zksy.web.controller.WaterSupply.MonitorAlarm;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zksy.WaterSupply.MonitorAlarm.dto.in.AlarmAuditInDTO;
import com.zksy.WaterSupply.MonitorAlarm.dto.in.AlarmDispatchInDTO;
import com.zksy.WaterSupply.MonitorAlarm.dto.out.AlarmAuditOutDTO;
import com.zksy.WaterSupply.MonitorAlarm.dto.out.AlarmFlowOutDTO;
import com.zksy.WaterSupply.MonitorAlarm.dto.out.AlarmMapPointOutDTO;
import com.zksy.WaterSupply.MonitorAlarm.dto.out.AlarmStatsOutDTO;
import com.zksy.WaterSupply.MonitorAlarm.dto.out.WaterAlarmOutDTO;
import com.zksy.WaterSupply.MonitorAlarm.service.IWaterSupplyAlarmService;
import com.zksy.common.annotation.Log;
import com.zksy.common.core.domain.AjaxResult;
import com.zksy.common.enums.BusinessType;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 供水管网-监测报警接口
 * 包含：报警管理（统计/实时/历史/详情/标记处理/派发工单）、报警审核、全流程跟踪、监测报警一张图
 */
@Slf4j
@RestController
@RequestMapping("/waterSupply/alarm")
@Api(tags = "供水管网-监测报警")
public class WaterSupplyAlarmController {

    @Autowired
    private IWaterSupplyAlarmService waterSupplyAlarmService;

    @GetMapping("/stats")
    @ApiOperation("监测报警统计（实时报警数/今日报警总数/设备异常率/平均响应时间）")
    @PreAuthorize("@ss.hasPermi('waterSupply:alarm:list')")
    public AjaxResult getAlarmStats() {
        AlarmStatsOutDTO stats = waterSupplyAlarmService.getAlarmStats();
        return AjaxResult.success(stats);
    }

    @GetMapping("/realtime")
    @ApiOperation("设备实时异常列表（未处理报警，信息卡片）")
    @PreAuthorize("@ss.hasPermi('waterSupply:alarm:list')")
    public AjaxResult getRealtimeAlarmList() {
        List<WaterAlarmOutDTO> list = waterSupplyAlarmService.getRealtimeAlarmList();
        return AjaxResult.success(list);
    }

    @GetMapping("/history")
    @ApiOperation("历史异常信息分页查询（支持按时间、设备、预警类型、等级、状态查询）")
    @PreAuthorize("@ss.hasPermi('waterSupply:alarm:list')")
    public AjaxResult getHistoryAlarmPage(
            @ApiParam(value = "页码", defaultValue = "1") @RequestParam(defaultValue = "1") long pageNum,
            @ApiParam(value = "每页数量", defaultValue = "10") @RequestParam(defaultValue = "10") long pageSize,
            @ApiParam(value = "设备编码") @RequestParam(required = false) String deviceCode,
            @ApiParam(value = "预警类型") @RequestParam(required = false) String warningType,
            @ApiParam(value = "报警等级 1-4") @RequestParam(required = false) Integer alarmLevel,
            @ApiParam(value = "报警状态 0-未处理 1-已处理") @RequestParam(required = false) Integer alarmStatus,
            @ApiParam(value = "开始时间（yyyy-MM-dd HH:mm:ss）") @RequestParam(required = false)
            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
            @ApiParam(value = "结束时间（yyyy-MM-dd HH:mm:ss）") @RequestParam(required = false)
            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime,
            @ApiParam(value = "关键字（设备编码/预警类型/预警编码）") @RequestParam(required = false) String keyword) {
        Page<WaterAlarmOutDTO> page = waterSupplyAlarmService.getHistoryAlarmPage(
                pageNum, pageSize, deviceCode, warningType, alarmLevel, alarmStatus, startTime, endTime, keyword);
        return AjaxResult.success(page);
    }

    @GetMapping("/detail/{alarmId}")
    @ApiOperation("异常详情（报警数据 + 设备数据 + 关联工单）")
    @PreAuthorize("@ss.hasPermi('waterSupply:alarm:list')")
    public AjaxResult getAlarmDetail(@PathVariable String alarmId) {
        WaterAlarmOutDTO detail = waterSupplyAlarmService.getAlarmDetail(alarmId);
        return detail != null ? AjaxResult.success(detail) : AjaxResult.error("报警信息不存在");
    }

    @PutMapping("/resolve/{alarmId}")
    @ApiOperation("一键标记已处理")
    @Log(title = "供水报警标记已处理", businessType = BusinessType.UPDATE)
    @PreAuthorize("@ss.hasPermi('waterSupply:alarm:handle')")
    public AjaxResult resolveAlarm(@PathVariable String alarmId,
                                   @ApiParam(value = "处理备注") @RequestParam(required = false) String handleRemark) {
        try {
            boolean result = waterSupplyAlarmService.resolveAlarm(alarmId, handleRemark);
            return result ? AjaxResult.success("处理成功") : AjaxResult.error("处理失败");
        } catch (Exception e) {
            log.error("标记报警已处理失败：alarmId={}", alarmId, e);
            return AjaxResult.error("处理失败：" + e.getMessage());
        }
    }

    @PostMapping("/dispatch")
    @ApiOperation("将报警派发为运维工单")
    @Log(title = "供水报警派发工单", businessType = BusinessType.INSERT)
    @PreAuthorize("@ss.hasPermi('waterSupply:alarm:dispatch')")
    public AjaxResult dispatchToWorkOrder(@RequestBody AlarmDispatchInDTO inDTO) {
        try {
            boolean result = waterSupplyAlarmService.dispatchToWorkOrder(inDTO);
            return result ? AjaxResult.success("工单派发成功") : AjaxResult.error("工单派发失败");
        } catch (Exception e) {
            log.error("供水报警派发工单失败：alarmId={}", inDTO != null ? inDTO.getAlarmId() : null, e);
            return AjaxResult.error("工单派发失败：" + e.getMessage());
        }
    }

    @PostMapping("/audit")
    @ApiOperation("报警审核/解除（支持意见录入与附件上传）")
    @Log(title = "供水报警审核", businessType = BusinessType.UPDATE)
    @PreAuthorize("@ss.hasPermi('waterSupply:alarm:audit')")
    public AjaxResult auditAlarm(@RequestBody AlarmAuditInDTO inDTO) {
        try {
            AlarmAuditOutDTO audit = waterSupplyAlarmService.auditAlarm(inDTO);
            return AjaxResult.success("审核操作成功", audit);
        } catch (Exception e) {
            log.error("供水报警审核失败：alarmId={}", inDTO != null ? inDTO.getAlarmId() : null, e);
            return AjaxResult.error("审核操作失败：" + e.getMessage());
        }
    }

    @GetMapping("/audit/list")
    @ApiOperation("查询报警审核记录列表")
    @PreAuthorize("@ss.hasPermi('waterSupply:alarm:list')")
    public AjaxResult getAuditList(@ApiParam(value = "报警ID", required = true) @RequestParam String alarmId) {
        return AjaxResult.success(waterSupplyAlarmService.getAuditList(alarmId));
    }

    @GetMapping("/flow/{alarmId}")
    @ApiOperation("报警处置全流程跟踪（报警+审核记录+工单+工单操作日志）")
    @PreAuthorize("@ss.hasPermi('waterSupply:alarm:list')")
    public AjaxResult getAlarmFlow(@PathVariable String alarmId) {
        AlarmFlowOutDTO flow = waterSupplyAlarmService.getAlarmFlow(alarmId);
        return flow != null && flow.getAlarm() != null ? AjaxResult.success(flow) : AjaxResult.error("报警信息不存在");
    }

    @GetMapping("/map/points")
    @ApiOperation("监测报警一张图-报警点位（按报警级别着色）")
    @PreAuthorize("@ss.hasPermi('waterSupply:alarm:list')")
    public AjaxResult getAlarmMapPoints() {
        List<AlarmMapPointOutDTO> points = waterSupplyAlarmService.getAlarmMapPoints();
        return AjaxResult.success(points);
    }
}
