package com.aegis.web.controller.emergency.event;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
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 com.aegis.common.annotation.Log;
import com.aegis.common.core.controller.BaseController;
import com.aegis.common.core.domain.AjaxResult;
import com.aegis.common.core.page.TableDataInfo;
import com.aegis.common.enums.BusinessType;
import com.aegis.emergency.event.domain.Event;
import com.aegis.emergency.event.domain.EventLog;
import com.aegis.emergency.event.dto.EventReportRequest;
import com.aegis.emergency.event.service.IEventService;
import com.aegis.emergency.event.service.IEventLogService;

/**
 * 事件Controller
 * 
 * @author aegis
 */
@RestController
@RequestMapping("/api/events")
public class EventController extends BaseController {

    @Autowired
    private IEventService eventService;

    @Autowired
    private IEventLogService eventLogService;

    /**
     * 查询事件列表（分页）
     */
    @PreAuthorize("@ss.hasPermi('emergency:event:list')")
    @GetMapping
    public TableDataInfo list(Event condition) {
        startPage();
        List<Event> list = eventService.listByCondition(condition);
        return getDataTable(list);
    }

    /**
     * 根据ID查询事件详情
     */
    @PreAuthorize("@ss.hasPermi('emergency:event:query')")
    @GetMapping("/{id}")
    public AjaxResult getInfo(@PathVariable Long id) {
        Event event = eventService.getById(id);
        if (event == null) {
            return error("事件不存在或已删除");
        }
        return success(event);
    }

    /**
     * 根据事件编号查询事件
     */
    @PreAuthorize("@ss.hasPermi('emergency:event:query')")
    @GetMapping("/no/{eventNo}")
    public AjaxResult getByEventNo(@PathVariable String eventNo) {
        Event event = eventService.getByEventNo(eventNo);
        if (event == null) {
            return error("事件不存在或已删除");
        }
        return success(event);
    }

    /**
     * 新增事件
     */
    @PreAuthorize("@ss.hasPermi('emergency:event:add')")
    @Log(title = "事件管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Event event) {
        return toAjax(eventService.save(event));
    }

    /**
     * 修改事件
     */
    @PreAuthorize("@ss.hasPermi('emergency:event:edit')")
    @Log(title = "事件管理", businessType = BusinessType.UPDATE)
    @PutMapping("/{id}")
    public AjaxResult edit(@PathVariable Long id, @RequestBody Event event) {
        event.setId(id);
        return toAjax(eventService.updateById(event));
    }

    /**
     * 删除事件（支持批量，仅限草稿状态）
     */
    @PreAuthorize("@ss.hasPermi('emergency:event:remove')")
    @Log(title = "事件管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        boolean allSuccess = true;
        for (Long id : ids) {
            allSuccess &= eventService.removeById(id);
        }
        return toAjax(allSuccess);
    }

    /**
     * 开始处理事件（状态从pending变为processing）
     */
    @PreAuthorize("@ss.hasPermi('emergency:event:edit')")
    @Log(title = "事件管理", businessType = BusinessType.UPDATE)
    @PostMapping("/{id}/start-processing")
    public AjaxResult startProcessing(@PathVariable Long id) {
        return toAjax(eventService.startProcessing(id));
    }

    /**
     * 完成事件处理（状态从processing变为completed）
     */
    @PreAuthorize("@ss.hasPermi('emergency:event:edit')")
    @Log(title = "事件管理", businessType = BusinessType.UPDATE)
    @PostMapping("/{id}/complete")
    public AjaxResult complete(@PathVariable Long id) {
        return toAjax(eventService.completeEvent(id));
    }

    /**
     * 归档事件（状态从completed变为archived）
     */
    @PreAuthorize("@ss.hasPermi('emergency:event:edit')")
    @Log(title = "事件管理", businessType = BusinessType.UPDATE)
    @PostMapping("/{id}/archive")
    public AjaxResult archive(@PathVariable Long id) {
        return toAjax(eventService.archiveEvent(id));
    }

    /**
     * 查询事件操作日志（支持按action类型过滤）
     */
    @PreAuthorize("@ss.hasPermi('emergency:event:query')")
    @GetMapping("/{id}/logs")
    public AjaxResult getLogs(@PathVariable Long id, 
                              @RequestParam(required = false) String action) {
        EventLog condition = new EventLog();
        condition.setEventId(id);
        if (action != null && !action.isEmpty()) {
            condition.setAction(action);
        }
        List<EventLog> logs = eventLogService.listByCondition(condition);
        return success(logs);
    }

    /**
     * 上报事件
     */
    @PreAuthorize("@ss.hasPermi('emergency:event:report')")
    @Log(title = "事件管理", businessType = BusinessType.UPDATE)
    @PostMapping("/{id}/report")
    public AjaxResult report(@PathVariable Long id, @RequestBody EventReportRequest request) {
        if (request == null || (request.getReportContent() == null || request.getReportContent().trim().isEmpty())) {
            return error("报告内容不能为空");
        }
        return toAjax(eventService.reportEvent(id, request.getReportContent()));
    }

    /**
     * 续报事件
     */
    @PreAuthorize("@ss.hasPermi('emergency:event:report')")
    @Log(title = "事件管理", businessType = BusinessType.UPDATE)
    @PostMapping("/{id}/follow-up-report")
    public AjaxResult followUpReport(@PathVariable Long id, @RequestBody EventReportRequest request) {
        if (request == null || (request.getReportContent() == null || request.getReportContent().trim().isEmpty())) {
            return error("报告内容不能为空");
        }
        return toAjax(eventService.followUpReport(id, request.getReportContent()));
    }

    /**
     * 标记事件为重点
     */
    @PreAuthorize("@ss.hasPermi('emergency:event:pin')")
    @Log(title = "事件管理", businessType = BusinessType.UPDATE)
    @PostMapping("/{id}/pin")
    public AjaxResult pinEvent(@PathVariable Long id) {
        return toAjax(eventService.markImportant(id, true));
    }

    /**
     * 取消事件重点标记
     */
    @PreAuthorize("@ss.hasPermi('emergency:event:pin')")
    @Log(title = "事件管理", businessType = BusinessType.UPDATE)
    @PostMapping("/{id}/unpin")
    public AjaxResult unpinEvent(@PathVariable Long id) {
        return toAjax(eventService.markImportant(id, false));
    }
}