package com.rj.controller.biz;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rj.dto.CommunityFeedDTO;
import com.rj.dto.DifyWorkflowResponseDto;
import com.rj.entity.bz.CommunityFeedAnalysisResult;
import com.rj.service.biz.ICommunityFeedAnalysisResultService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/api/community-feed")
@Tag(name = "社区Feed分析", description = "社区Feed分析结果API")
public class CommunityFeedAnalysisResultController {


    
    @Autowired
    private ICommunityFeedAnalysisResultService resultService;

    /**
     * AI-Feed 流（社区Feed流优质内容）
     */
    @PostMapping("/callAIFeedWorkflow")
    @Operation(summary = "AI-Feed 工作流", description = "调用Dify AI-Feed 工作流（社区优质内容评估）")
    public ResponseEntity<DifyWorkflowResponseDto> aiFeedWorkflow(
            @Valid @RequestBody CommunityFeedDTO requestDto) {
        try {
            log.info("开始调用AI-Feed工作流，参数： {}", requestDto);
            return ResponseEntity.ok(resultService.callAiFeedWorkflow(requestDto));

        } catch (Exception e) {
            log.error("调用AI-Feed工作流失败", e);

            DifyWorkflowResponseDto errorResult = DifyWorkflowResponseDto.failure(
                    "AI-Feed 工作流调用失败: " + e.getMessage(),
                    e.getClass().getSimpleName()
            );

            return ResponseEntity.status(500).body(errorResult);
        }
    }

    

    @PostMapping("/save")
    @Operation(summary = "保存分析结果")
    public boolean save(@RequestBody CommunityFeedAnalysisResult result) {
        return resultService.saveResult(result);
    }

    @GetMapping("/by-workflow/{workflowId}")
    @Operation(summary = "按workflowId查询")
    public CommunityFeedAnalysisResult getByWorkflowId(@PathVariable String workflowId) {
        return resultService.getByWorkflowId(workflowId);
    }

    @GetMapping("/page")
    @Operation(summary = "分页查询Feed分析结果")
    public ResponseEntity<Map<String, Object>> page(
            @Parameter(description = "页码", example = "1")
            @RequestParam(defaultValue = "1") Integer current,
            @Parameter(description = "每页大小", example = "10")
            @RequestParam(defaultValue = "10") Integer size,
            @Parameter(description = "工作流ID（模糊查询）")
            @RequestParam(required = false) String workflowId,
            @Parameter(description = "状态（精确匹配）")
            @RequestParam(required = false) String status
    ) {
        Map<String, Object> result = new HashMap<>();
        try {
            Page<CommunityFeedAnalysisResult> page = new Page<>(current, size);
            LambdaQueryWrapper<CommunityFeedAnalysisResult> wrapper = new LambdaQueryWrapper<>();

            if (workflowId != null && !workflowId.trim().isEmpty()) {
                wrapper.like(CommunityFeedAnalysisResult::getWorkflowId, workflowId);
            }
            if (status != null && !status.trim().isEmpty()) {
                wrapper.eq(CommunityFeedAnalysisResult::getStatus, status);
            }

            wrapper.orderByDesc(CommunityFeedAnalysisResult::getCreatedAt);

            Page<CommunityFeedAnalysisResult> dataPage = resultService.page(page, wrapper);

            result.put("success", true);
            result.put("message", "查询成功");
            result.put("data", dataPage.getRecords());
            result.put("total", dataPage.getTotal());
            result.put("current", dataPage.getCurrent());
            result.put("size", dataPage.getSize());
            result.put("pages", dataPage.getPages());

            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("分页查询Feed分析结果失败", e);
            result.put("success", false);
            result.put("message", "查询失败: " + e.getMessage());
            return ResponseEntity.status(500).body(result);
        }
    }
}


