package com.zksy.web.controller.warning;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zksy.base.warning.domain.EarlyWarning;
import com.zksy.base.warning.domain.WarningArchive;
import com.zksy.base.warning.domain.WarningDisposal;
import com.zksy.base.warning.domain.WarningSaveDTO;
import com.zksy.base.warning.service.EarlyWarningService;
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 org.springframework.web.multipart.MultipartFile;

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

@Slf4j
@RestController
@RequestMapping("/warning")
@Api(tags = "预警管理")
public class EarlyWarningController {

    @Autowired
    private EarlyWarningService earlyWarningService;

    @GetMapping("/list")
    @ApiOperation("分页查询预警列表")
    @PreAuthorize("@ss.hasPermi('warning:warning:list')")
    public AjaxResult getWarningList(
            @ApiParam("页码") @RequestParam(defaultValue = "1") Integer pageNum,
            @ApiParam("每页数量") @RequestParam(defaultValue = "10") Integer pageSize,
            @ApiParam("预警名称") @RequestParam(required = false) String warningName,
            @ApiParam("预警类型") @RequestParam(required = false) String warningType,
            @ApiParam("预警级别") @RequestParam(required = false) String warningLevel,
            @ApiParam("状态") @RequestParam(required = false) String status) {
        Page<?> page = new Page<>(pageNum, pageSize);
        IPage<Map<String, Object>> result = earlyWarningService.getWarningList(page, warningName, warningType, warningLevel, status);
        return AjaxResult.success(result);
    }

    @GetMapping("/todo/list")
    @ApiOperation("待办预警列表")
    @PreAuthorize("@ss.hasPermi('warning:warning:list')")
    public AjaxResult getTodoList(
            @ApiParam("页码") @RequestParam(defaultValue = "1") Integer pageNum,
            @ApiParam("每页数量") @RequestParam(defaultValue = "10") Integer pageSize,
            @ApiParam("用户名") @RequestParam String userName,
            @ApiParam("待办类型") @RequestParam(required = false) String todoType,
            @ApiParam("预警名称") @RequestParam(required = false) String warningName) {
        Page<?> page = new Page<>(pageNum, pageSize);
        IPage<Map<String, Object>> result = earlyWarningService.getTodoList(page, userName, todoType, warningName);
        return AjaxResult.success(result);
    }

    @GetMapping("/detail/{warningId}")
    @ApiOperation("预警详情")
    @PreAuthorize("@ss.hasPermi('warning:warning:query')")
    public AjaxResult getWarningDetail(@PathVariable String warningId) {
        Map<String, Object> detail = earlyWarningService.getWarningDetail(warningId);
        if (detail == null) {
            return AjaxResult.error("预警信息不存在");
        }
        return AjaxResult.success(detail);
    }

    @PostMapping("/save")
    @ApiOperation("保存预警信息")
    @Log(title = "保存预警信息", businessType = BusinessType.INSERT)
    @PreAuthorize("@ss.hasPermi('warning:warning:add')")
    public AjaxResult saveWarning(
            @RequestPart("warning") String warningJson,
            @RequestPart(value = "alarmIds", required = false) String alarmIdsJson,
            @RequestPart(value = "files", required = false) List<MultipartFile> files) {
        try {
            EarlyWarning warning = JSON.parseObject(warningJson, EarlyWarning.class);
List<String> alarmIds = alarmIdsJson != null && !alarmIdsJson.isEmpty()
                    ? JSON.parseArray(alarmIdsJson, String.class)
                    : new ArrayList<>();

            boolean result = earlyWarningService.saveWarning(warning, alarmIds, files);
            return result ? AjaxResult.success("保存成功", warning.getWarningId()) : AjaxResult.error("保存失败");
        } catch (Exception e) {
            log.error("保存预警信息失败", e);
            return AjaxResult.error("保存失败：" + e.getMessage());
        }
    }

    @PutMapping("/update")
    @ApiOperation("修改预警信息")
    @Log(title = "修改预警信息", businessType = BusinessType.UPDATE)
    @PreAuthorize("@ss.hasPermi('warning:warning:edit')")
    public AjaxResult updateWarning(
            @RequestPart("warning") String warningJson,
            @RequestPart(value = "alarmIds", required = false) String alarmIdsJson,
            @RequestPart(value = "files", required = false) List<MultipartFile> files) {
        try {
            EarlyWarning warning = JSON.parseObject(warningJson, EarlyWarning.class);
            List<String> alarmIds = alarmIdsJson != null && !alarmIdsJson.isEmpty() 
                ? JSON.parseArray(alarmIdsJson, String.class) 
                : new ArrayList<>();
            
            boolean result = earlyWarningService.updateWarning(warning, alarmIds, files);
            return result ? AjaxResult.success("修改成功") : AjaxResult.error("修改失败");
        } catch (Exception e) {
            log.error("修改预警信息失败", e);
            return AjaxResult.error("修改失败：" + e.getMessage());
        }
    }

    @DeleteMapping("/delete")
    @ApiOperation("删除预警信息")
    @Log(title = "删除预警信息", businessType = BusinessType.DELETE)
    @PreAuthorize("@ss.hasPermi('warning:warning:remove')")
    public AjaxResult deleteWarning(@RequestParam String warningId) {
        boolean result = earlyWarningService.deleteWarning(warningId);
        return result ? AjaxResult.success("删除成功") : AjaxResult.error("删除失败");
    }

    @DeleteMapping("/delete/batch")
    @ApiOperation("批量删除预警信息")
    @Log(title = "批量删除预警信息", businessType = BusinessType.DELETE)
    @PreAuthorize("@ss.hasPermi('warning:warning:remove')")
    public AjaxResult deleteBatchWarning(@RequestParam List<String> warningIds) {
        boolean result = earlyWarningService.deleteBatchWarning(warningIds);
        return result ? AjaxResult.success("批量删除成功") : AjaxResult.error("批量删除失败");
    }

    @PostMapping("/publish/{warningId}")
    @ApiOperation("发布预警")
    @Log(title = "发布预警", businessType = BusinessType.UPDATE)
    @PreAuthorize("@ss.hasPermi('warning:warning:publish')")
    public AjaxResult publishWarning(@PathVariable String warningId) {
        boolean result = earlyWarningService.publishWarning(warningId);
        return result ? AjaxResult.success("发布成功") : AjaxResult.error("发布失败");
    }

    @PostMapping("/upgrade")
    @ApiOperation("预警升级")
    @Log(title = "预警升级", businessType = BusinessType.UPDATE)
    @PreAuthorize("@ss.hasPermi('warning:warning:handle')")
    public AjaxResult upgradeWarning(
            @ApiParam("预警ID") @RequestParam String warningId,
            @ApiParam("新预警级别") @RequestParam String newLevel,
            @ApiParam("处置说明") @RequestParam String disposalContent) {
        boolean result = earlyWarningService.upgradeWarning(warningId, newLevel, disposalContent);
        return result ? AjaxResult.success("升级成功") : AjaxResult.error("升级失败");
    }

    @PostMapping("/resolve")
    @ApiOperation("解除预警")
    @Log(title = "解除预警", businessType = BusinessType.UPDATE)
    @PreAuthorize("@ss.hasPermi('warning:warning:handle')")
    public AjaxResult resolveWarning(
            @ApiParam("预警ID") @RequestParam String warningId,
            @ApiParam("处置说明") @RequestParam String disposalContent) {
        boolean result = earlyWarningService.resolveWarning(warningId, disposalContent);
        return result ? AjaxResult.success("解除成功") : AjaxResult.error("解除失败");
    }

    @PostMapping("/return")
    @ApiOperation("退回重办")
    @Log(title = "退回重办", businessType = BusinessType.UPDATE)
    @PreAuthorize("@ss.hasPermi('warning:warning:handle')")
    public AjaxResult returnWarning(
            @ApiParam("预警ID") @RequestParam String warningId,
            @ApiParam("退回说明") @RequestParam String disposalContent) {
        boolean result = earlyWarningService.returnWarning(warningId, disposalContent);
        return result ? AjaxResult.success("退回成功") : AjaxResult.error("退回失败");
    }

    @PostMapping("/supervision")
    @ApiOperation("预警督办")
    @Log(title = "预警督办", businessType = BusinessType.OTHER)
    @PreAuthorize("@ss.hasPermi('warning:warning:supervision')")
    public AjaxResult supervisionWarning(
            @ApiParam("预警ID") @RequestParam String warningId,
            @ApiParam("督办人员") @RequestParam String supervisionUser,
            @ApiParam("督办意见") @RequestParam String supervisionContent,
            @ApiParam("通知方式") @RequestParam String notificationType,
            @ApiParam("通知内容") @RequestParam(required = false) String notificationContent,
            @ApiParam("附件地址") @RequestParam(required = false) String attachmentUrl) {
        boolean result = earlyWarningService.supervisionWarning(warningId, supervisionUser, supervisionContent, notificationType, notificationContent, attachmentUrl);
        return result ? AjaxResult.success("督办成功") : AjaxResult.error("督办失败");
    }

    @PostMapping("/instruction")
    @ApiOperation("领导批示")
    @Log(title = "领导批示", businessType = BusinessType.OTHER)
    @PreAuthorize("@ss.hasPermi('warning:warning:instruction')")
    public AjaxResult addLeaderInstruction(
            @ApiParam("预警ID") @RequestParam String warningId,
            @ApiParam("领导姓名") @RequestParam String leaderName,
            @ApiParam("批示内容") @RequestParam String instructionContent,
            @ApiParam("短信接收人") @RequestParam(required = false) String smsReceivers) {
        boolean result = earlyWarningService.addLeaderInstruction(warningId, leaderName, instructionContent, smsReceivers);
        return result ? AjaxResult.success("批示成功") : AjaxResult.error("批示失败");
    }

    @PostMapping("/link/alarms")
    @ApiOperation("关联报警信息")
    @PreAuthorize("@ss.hasPermi('warning:warning:edit')")
    public AjaxResult linkAlarms(
            @ApiParam("预警ID") @RequestParam String warningId,
            @ApiParam("报警ID列表") @RequestParam List<String> alarmIds) {
        boolean result = earlyWarningService.linkAlarms(warningId, alarmIds);
        return result ? AjaxResult.success("关联成功") : AjaxResult.error("关联失败");
    }

    @GetMapping("/link/alarms/{warningId}")
    @ApiOperation("获取关联的报警列表")
    @PreAuthorize("@ss.hasPermi('warning:warning:query')")
    public AjaxResult getLinkedAlarms(@PathVariable String warningId) {
        List<Map<String, Object>> result = earlyWarningService.getLinkedAlarms(warningId);
        return AjaxResult.success(result);
    }

    @GetMapping("/disposal/{warningId}")
    @ApiOperation("获取处置记录列表")
    @PreAuthorize("@ss.hasPermi('warning:warning:query')")
    public AjaxResult getDisposalList(@PathVariable String warningId) {
        List<Map<String, Object>> result = earlyWarningService.getDisposalList(warningId);
        return AjaxResult.success(result);
    }

    @GetMapping("/statistics")
    @ApiOperation("获取统计数据")
    @PreAuthorize("@ss.hasPermi('warning:warning:query')")
    public AjaxResult getStatistics() {
        Map<String, Object> result = earlyWarningService.getStatistics();
        return AjaxResult.success(result);
    }

    /*@GetMapping("/config/types")
    @ApiOperation("获取预警类型配置")
    public AjaxResult getTypeConfigList() {
        List<Map<String, Object>> result = earlyWarningService.getTypeConfigList();
        return AjaxResult.success(result);
    }*/

    @GetMapping("/search")
    @ApiOperation("综合搜索预警信息")
    @PreAuthorize("@ss.hasPermi('warning:warning:list')")
    public AjaxResult searchWarnings(
            @ApiParam("页码") @RequestParam(defaultValue = "1") Integer pageNum,
            @ApiParam("每页数量") @RequestParam(defaultValue = "10") Integer pageSize,
            @ApiParam("预警名称") @RequestParam(required = false) String warningName,
            @ApiParam("预警编号") @RequestParam(required = false) String warningNo,
            @ApiParam("预警类型") @RequestParam(required = false) String warningType,
            @ApiParam("预警级别") @RequestParam(required = false) String warningLevel,
            @ApiParam("状态") @RequestParam(required = false) String status,
            @ApiParam("预警位置") @RequestParam(required = false) String location,
            @ApiParam("发布人") @RequestParam(required = false) String publisher,
            @ApiParam("权属单位") @RequestParam(required = false) String ownershipUnit,
            @ApiParam("开始时间") @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
            @ApiParam("结束时间") @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime) {
        Page<?> page = new Page<>(pageNum, pageSize);
        IPage<Map<String, Object>> result = earlyWarningService.searchWarnings(page, warningName, warningNo, warningType, warningLevel, status, location, publisher, ownershipUnit, startTime, endTime);
        return AjaxResult.success(result);
    }

    @GetMapping("/detail/full/{warningId}")
    @ApiOperation("获取预警完整详情(含GIS定位和电子存档)")
    @PreAuthorize("@ss.hasPermi('warning:warning:query')")
    public AjaxResult getWarningFullDetail(@PathVariable String warningId) {
        Map<String, Object> detail = earlyWarningService.getWarningFullDetail(warningId);
        if (detail == null) {
            return AjaxResult.error("预警信息不存在");
        }
        return AjaxResult.success(detail);
    }

    @GetMapping("/processing/list")
    @ApiOperation("获取处置过程跟踪 - 进行中的预警")
    @PreAuthorize("@ss.hasPermi('warning:warning:list')")
    public AjaxResult getProcessingWarnings(
            @ApiParam("页码") @RequestParam(defaultValue = "1") Integer pageNum,
            @ApiParam("每页数量") @RequestParam(defaultValue = "10") Integer pageSize,
            @ApiParam("预警类型") @RequestParam(required = false) String warningType,
            @ApiParam("预警级别") @RequestParam(required = false) String warningLevel) {
        Page<?> page = new Page<>(pageNum, pageSize);
        IPage<Map<String, Object>> result = earlyWarningService.getProcessingWarnings(page, warningType, warningLevel);
        return AjaxResult.success(result);
    }

    @GetMapping("/completed/list")
    @ApiOperation("获取处置过程跟踪 - 已完成的预警")
    @PreAuthorize("@ss.hasPermi('warning:warning:list')")
    public AjaxResult getCompletedWarnings(
            @ApiParam("页码") @RequestParam(defaultValue = "1") Integer pageNum,
            @ApiParam("每页数量") @RequestParam(defaultValue = "10") Integer pageSize,
            @ApiParam("预警类型") @RequestParam(required = false) String warningType,
            @ApiParam("预警级别") @RequestParam(required = false) String warningLevel,
            @ApiParam("开始时间") @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
            @ApiParam("结束时间") @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime) {
        Page<?> page = new Page<>(pageNum, pageSize);
        IPage<Map<String, Object>> result = earlyWarningService.getCompletedWarnings(page, warningType, warningLevel, startTime, endTime);
        return AjaxResult.success(result);
    }

    @GetMapping("/disposal/history/{warningId}")
    @ApiOperation("获取预警处置历史记录")
    @PreAuthorize("@ss.hasPermi('warning:warning:query')")
    public AjaxResult getDisposalHistory(@PathVariable String warningId) {
        List<Map<String, Object>> result = earlyWarningService.getDisposalHistory(warningId);
        return AjaxResult.success(result);
    }

    @GetMapping("/attachments/{warningId}")
    @ApiOperation("获取预警附件列表")
    @PreAuthorize("@ss.hasPermi('warning:warning:query')")
    public AjaxResult getAttachments(@PathVariable String warningId) {
        List<Map<String, Object>> result = earlyWarningService.getAttachments(warningId);
        return AjaxResult.success(result);
    }

    @GetMapping("/dashboard/statistics")
    @ApiOperation("获取仪表盘统计数据")
    @PreAuthorize("@ss.hasPermi('warning:warning:query')")
    public AjaxResult getDashboardStatistics() {
        Map<String, Object> result = earlyWarningService.getDashboardStatistics();
        return AjaxResult.success(result);
    }

    @GetMapping("/archive/{warningId}")
    @ApiOperation("获取预警归档信息")
    @PreAuthorize("@ss.hasPermi('warning:warning:query')")
    public AjaxResult getArchive(@PathVariable String warningId) {
        WarningArchive archive = earlyWarningService.getArchiveByWarningId(warningId);
        if (archive == null) {
            return AjaxResult.error("归档信息不存在");
        }
        return AjaxResult.success(archive);
    }

    @GetMapping("/archive/list")
    @ApiOperation("获取归档列表")
    @PreAuthorize("@ss.hasPermi('warning:warning:list')")
    public AjaxResult getArchiveList(
            @ApiParam("页码") @RequestParam(defaultValue = "1") Integer pageNum,
            @ApiParam("每页数量") @RequestParam(defaultValue = "10") Integer pageSize,
            @ApiParam("预警名称") @RequestParam(required = false) String warningName,
            @ApiParam("预警类型") @RequestParam(required = false) String warningType,
            @ApiParam("预警级别") @RequestParam(required = false) String warningLevel,
            @ApiParam("开始时间") @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
            @ApiParam("结束时间") @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime) {
        Page<WarningArchive> page = new Page<>(pageNum, pageSize);
        IPage<WarningArchive> result = earlyWarningService.getArchiveList(page, warningName, warningType, warningLevel, startTime, endTime);
        return AjaxResult.success(result);
    }

    @GetMapping("/process/{warningId}")
    @ApiOperation("获取预警处置过程记录（完整流程）")
    @PreAuthorize("@ss.hasPermi('warning:warning:query')")
    public AjaxResult getDisposalProcess(@PathVariable String warningId) {
        List<WarningDisposal> result = earlyWarningService.getDisposalProcess(warningId);
        return AjaxResult.success(result);
    }

    @GetMapping("/diagram/{warningId}")
    @ApiOperation("获取预警流程可视化数据（路线图）")
    @PreAuthorize("@ss.hasPermi('warning:warning:query')")
    public AjaxResult getProcessDiagram(@PathVariable String warningId) {
        Map<String, Object> result = earlyWarningService.getProcessDiagram(warningId);
        if (result != null && result.containsKey("error")) {
            return AjaxResult.error(result.get("error").toString());
        }
        return AjaxResult.success(result);
    }

    @GetMapping("/disposal/detail/{disposalId}")
    @ApiOperation("获取预警处置详情")
    @PreAuthorize("@ss.hasPermi('warning:warning:query')")
    public AjaxResult getDisposalDetail(@PathVariable String disposalId) {
        Map<String, Object> result = earlyWarningService.getDisposalDetail(disposalId);
        if (result == null) {
            return AjaxResult.error("处置记录不存在");
        }
        return AjaxResult.success(result);
    }

    @GetMapping("/process/statistics/{warningId}")
    @ApiOperation("获取预警流程统计信息")
    @PreAuthorize("@ss.hasPermi('warning:warning:query')")
    public AjaxResult getProcessStatistics(@PathVariable String warningId) {
        Map<String, Object> result = earlyWarningService.getProcessStatistics(warningId);
        return AjaxResult.success(result);
    }
}
