package com.zksy.web.controller.drainage;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zksy.common.annotation.Anonymous;
import com.zksy.common.annotation.Log;
import com.zksy.common.core.domain.AjaxResult;
import com.zksy.common.enums.BusinessType;
import com.zksy.drainage.domain.DrainageWarning;
import com.zksy.drainage.domain.WarningPublishRequest;
import com.zksy.drainage.domain.WarningScopeUser;
import com.zksy.drainage.service.DrainageWarningService;
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.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 排水预警信息管理
 */
@Slf4j
@RestController
@RequestMapping("/api/drainage/warning")
@Api(tags = "排水预警信息管理")
public class DrainageWarningController {

    @Autowired
    private DrainageWarningService service;

    @Anonymous
    @GetMapping("/page")
    @ApiOperation(value = "分页查询预警信息")
    public Page<DrainageWarning> page(
            @ApiParam("页码") @RequestParam(defaultValue = "1") long pageNum,
            @ApiParam("每页数量") @RequestParam(defaultValue = "10") long pageSize,
            @ApiParam("预警级别(1严重,2重要,3一般)") @RequestParam(required = false) Integer warningLevel,
            @ApiParam("预警类型") @RequestParam(required = false) String warningType,
            @ApiParam("状态(DRAFT/PENDING/PROCESSING/RELEASED/HANDLED/CLOSED)") @RequestParam(required = false) String status,
            @ApiParam("开始时间(yyyy-MM-dd HH:mm:ss)") @RequestParam(required = false) String startTime,
            @ApiParam("结束时间(yyyy-MM-dd HH:mm:ss)") @RequestParam(required = false) String endTime) {
        return service.findByPage(pageNum, pageSize, warningLevel, warningType, status, startTime, endTime);
    }

    @Anonymous
    @GetMapping("/current/page")
    @ApiOperation(value = "查询当前预警（按用户可见性过滤）")
    public Page<DrainageWarning> currentPage(
            @ApiParam("页码") @RequestParam(defaultValue = "1") long pageNum,
            @ApiParam("每页数量") @RequestParam(defaultValue = "10") long pageSize,
            @ApiParam("预警级别(1严重,2重要,3一般)") @RequestParam(required = false) Integer warningLevel,
            @ApiParam("预警类型") @RequestParam(required = false) String warningType,
            @ApiParam("当前用户ID") @RequestParam(required = false) Long userId,
            @ApiParam("当前用户部门ID") @RequestParam(required = false) Long deptId,
            @ApiParam("是否管理员") @RequestParam(defaultValue = "false") boolean isAdmin,
            @ApiParam("状态筛选(DRAFT/PENDING/PROCESSING/RELEASED)，不传则返回所有当前状态") @RequestParam(required = false) String status,
            @ApiParam("是否只返回当前预警") @RequestParam(defaultValue = "false") boolean currentOnly,
            @ApiParam("设备名称") @RequestParam(required = false) String equipmentName,
            @ApiParam("开始时间(yyyy-MM-dd HH:mm:ss)") @RequestParam(required = false) String startTime,
            @ApiParam("结束时间(yyyy-MM-dd HH:mm:ss)") @RequestParam(required = false) String endTime) {
        return service.findVisibleCurrentPage(pageNum, pageSize, userId, deptId, isAdmin, warningLevel, warningType, status, currentOnly, equipmentName, startTime, endTime);
    }

    @Anonymous
    @GetMapping("/history/page")
    @ApiOperation(value = "查询历史预警（status IN HANDLED/CLOSED）")
    public Page<DrainageWarning> historyPage(
            @ApiParam("页码") @RequestParam(defaultValue = "1") long pageNum,
            @ApiParam("每页数量") @RequestParam(defaultValue = "10") long pageSize,
            @ApiParam("预警级别(1严重,2重要,3一般)") @RequestParam(required = false) Integer warningLevel,
            @ApiParam("预警类型") @RequestParam(required = false) String warningType,
            @ApiParam("状态(HANDLED/CLOSED)") @RequestParam(required = false) String status,
            @ApiParam("开始时间(yyyy-MM-dd HH:mm:ss)") @RequestParam(required = false) String startTime,
            @ApiParam("结束时间(yyyy-MM-dd HH:mm:ss)") @RequestParam(required = false) String endTime,
            @ApiParam("是否只返回历史预警") @RequestParam(defaultValue = "false") boolean historyOnly,
            @ApiParam("设备名称") @RequestParam(required = false) String equipmentName) {
        return service.findHistoryPage(pageNum, pageSize, warningLevel, warningType, status, startTime, endTime, historyOnly, equipmentName);
    }

    @Anonymous
    @GetMapping("/{id}")
    @ApiOperation(value = "查询预警详情")
    public AjaxResult getById(@PathVariable String id) {
        DrainageWarning entity = service.getById(id);
        if (entity == null) {
            return AjaxResult.error("该预警信息不存在");
        }
        return AjaxResult.success(entity);
    }

    @Anonymous
    @PostMapping
    @ApiOperation(value = "发布新预警")
    @Log(title = "发布新预警", businessType = BusinessType.INSERT)
    @Transactional
    public AjaxResult save(@RequestBody DrainageWarning entity) {
        boolean saved = service.saveWithCheck(entity);
        return saved ? AjaxResult.success("发布成功") : AjaxResult.error("发布失败");
    }

    @Anonymous
    @PutMapping
    @ApiOperation(value = "修改预警")
    @Log(title = "修改预警", businessType = BusinessType.UPDATE)
    @Transactional
    public AjaxResult update(@RequestBody DrainageWarning entity) {
        boolean updated = service.updateWithCheck(entity);
        return updated ? AjaxResult.success("修改成功") : AjaxResult.error("修改失败");
    }

    @Anonymous
    @PutMapping("/{id}/status")
    @ApiOperation(value = "更新预警状态")
    @Log(title = "更新预警状态", businessType = BusinessType.UPDATE)
    @Transactional
    public AjaxResult updateStatus(
            @PathVariable String id,
            @ApiParam("新状态(DRAFT/PENDING/PROCESSING/RELEASED/HANDLED/CLOSED)") @RequestParam String status,
            @ApiParam("处理人") @RequestParam(required = false) String processor) {
        boolean updated = service.updateStatus(id, status, processor);
        return updated ? AjaxResult.success("状态更新成功") : AjaxResult.error("状态更新失败");
    }

    @Anonymous
    @PostMapping("/publish")
    @ApiOperation(value = "发布预警（带接收人员列表）")
    @Log(title = "发布预警", businessType = BusinessType.INSERT)
    @Transactional
    public AjaxResult publish(@RequestBody WarningPublishRequest request) {
        service.publishWarning(request.getWarning(), request.getUserIds());
        return AjaxResult.success("发布成功");
    }

    @Anonymous
    @PutMapping("/{id}/firstApprove")
    @ApiOperation(value = "处理（指定人员处理）")
    @Log(title = "预警处理", businessType = BusinessType.UPDATE)
    @Transactional
    public AjaxResult firstApprove(
            @PathVariable String id,
            @ApiParam("处理人ID") @RequestParam Long userId,
            @ApiParam("处理人名称") @RequestParam(required = false) String userName) {
        service.firstApprove(id, userId, userName);
        return AjaxResult.success("处理成功");
    }

    @Anonymous
    @PutMapping("/{id}/finalApprove")
    @ApiOperation(value = "审批（管理员审批）")
    @Log(title = "预警审批", businessType = BusinessType.UPDATE)
    @Transactional
    public AjaxResult finalApprove(
            @PathVariable String id,
            @ApiParam("审批人ID(管理员)") @RequestParam Long userId,
            @ApiParam("审批人名称") @RequestParam(required = false) String userName) {
        service.finalApprove(id, userId, userName);
        return AjaxResult.success("审批成功");
    }

    @Anonymous
    @GetMapping("/scopeUsers/{warningId}")
    @ApiOperation(value = "获取某预警的接收人员列表")
    public AjaxResult scopeUsers(@PathVariable String warningId) {
        List<WarningScopeUser> list = service.findScopeUsers(warningId);
        return AjaxResult.success(list);
    }

    @Anonymous
    @DeleteMapping("/{id}")
    @ApiOperation(value = "删除预警")
    @Log(title = "删除预警", businessType = BusinessType.DELETE)
    @Transactional
    public AjaxResult deleteById(@PathVariable String id) {
        boolean deleted = service.removeWithCheck(id);
        return deleted ? AjaxResult.success("删除成功") : AjaxResult.error("删除失败");
    }
}
