package com.cmvr.web.controller.inspection;

import com.cmvr.common.annotation.Log;
import com.cmvr.common.core.controller.BaseController;
import com.cmvr.common.core.domain.AjaxResult;
import com.cmvr.common.core.page.TableDataInfo;
import com.cmvr.common.enums.BusinessType;
import com.cmvr.common.utils.poi.ExcelUtil;
import com.cmvr.inspection.domain.dto.InspectionResultQuery;
import com.cmvr.inspection.domain.dto.InspectionResultReviewRequest;
import com.cmvr.inspection.domain.vo.InspectionResultVo;
import com.cmvr.inspection.service.IInspectionResultService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
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.RestController;

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

/**
 * 巡检结果、人工复核和任务报表接口。
 */
@RestController
@RequestMapping("/inspection/result")
@Api(tags = "智能巡检--巡检结果", description = "巡检结果查询、人工复核、三级告警统计和报表导出")
@ApiResponses({
        @ApiResponse(code = 200, message = "请求处理成功"),
        @ApiResponse(code = 400, message = "请求参数或状态不合法"),
        @ApiResponse(code = 401, message = "未登录或登录已失效"),
        @ApiResponse(code = 403, message = "无接口权限"),
        @ApiResponse(code = 500, message = "系统内部异常")
})
@RequiredArgsConstructor
public class InspectionResultController extends BaseController
{
    private final IInspectionResultService inspectionResultService;

    @ApiOperation(value = "查询巡检结果列表",
            notes = "分页查询PPE、仪表读数和人工判断结果；查询条件均为可选，结果按检测时间倒序。"
                    + "返回rows元素为InspectionResultVo，包含taskName任务名称和evidenceType主要证据类型；"
                    + "完整mediaList仅在详情接口返回")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "页码，从1开始", dataType = "int", paramType = "query", example = "1"),
            @ApiImplicitParam(name = "pageSize", value = "每页数量", dataType = "int", paramType = "query", example = "10"),
            @ApiImplicitParam(name = "taskInstanceId", value = "巡检任务实例数据库ID", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "taskId", value = "巡检任务ID", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "itemId", value = "检测项ID", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "resultType", value = "结果类型：PPE、METER、MANUAL", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "resultStatus", value = "状态：PENDING、NORMAL、ABNORMAL、RECOGNIZE_FAILED", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "alarmLevel", value = "告警级别：1提示、2警告、3严重", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "resultName", value = "检查名称，支持模糊查询", dataType = "string", paramType = "query")
    })
    @PreAuthorize("@ss.hasPermi('inspection:result:list')")
    @GetMapping("/list")
    public TableDataInfo list(@ApiParam("巡检结果查询条件") InspectionResultQuery query)
    {
        startPage();
        return getDataTable(inspectionResultService.selectResultList(query));
    }

    @ApiOperation(value = "查询巡检结果详情",
            notes = "返回结构化巡检结果及按顺序排列的全部图片、视频证据",
            response = InspectionResultVo.class)
    @PreAuthorize("@ss.hasPermi('inspection:result:query')")
    @GetMapping("/{id}")
    public AjaxResult getInfo(@ApiParam(value = "巡检结果ID", required = true)
                              @PathVariable String id)
    {
        return success(inspectionResultService.selectResultById(id));
    }

    @ApiOperation(value = "提交人工复核结果",
            notes = "仅PENDING或RECOGNIZE_FAILED状态可复核。ABNORMAL必须传alarmLevel；reviewVersion用于并发控制")
    @PreAuthorize("@ss.hasPermi('inspection:result:review')")
    @Log(title = "巡检结果人工复核", businessType = BusinessType.UPDATE)
    @PutMapping("/{id}/review")
    public AjaxResult review(@ApiParam(value = "巡检结果ID", required = true)
                             @PathVariable String id,
                             @ApiParam(value = "人工复核内容", required = true)
                             @Validated @RequestBody InspectionResultReviewRequest request)
    {
        return success(inspectionResultService.review(id, request));
    }

    @ApiOperation(value = "查询巡检任务报表汇总",
            notes = "返回summary统计和results明细。reviewCompleted=false表示仍有待复核或识别失败结果")
    @PreAuthorize("@ss.hasPermi('inspection:result:report')")
    @GetMapping("/report/{taskInstanceId}")
    public AjaxResult report(@ApiParam(value = "巡检任务实例数据库ID", required = true)
                             @PathVariable String taskInstanceId)
    {
        AjaxResult result = AjaxResult.success();
        result.put("summary", inspectionResultService.buildReportSummary(taskInstanceId));
        InspectionResultQuery query = new InspectionResultQuery();
        query.setTaskInstanceId(taskInstanceId);
        result.put("results", inspectionResultService.selectResultList(query));
        return result;
    }

    @ApiOperation(value = "导出巡检结果报表",
            notes = "按查询条件导出Excel；不传条件时导出全部巡检结果")
    @PreAuthorize("@ss.hasPermi('inspection:result:export')")
    @Log(title = "巡检结果", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response,
                       @ApiParam("导出筛选条件") InspectionResultQuery query)
    {
        List<InspectionResultVo> list = inspectionResultService.selectResultList(query);
        ExcelUtil<InspectionResultVo> util = new ExcelUtil<>(InspectionResultVo.class);
        util.exportExcel(response, list, "巡检结果数据");
    }
}
