package com.rj.controller;

import com.rj.dto.CommunityFeedDTO;
import com.rj.dto.DifyWorkflowRequestDto;
import com.rj.dto.DifyWorkflowResponseDto;
import com.rj.dto.CustomerProfileAnalysisRequestDto;
import com.rj.service.DifyWorkflowService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import java.util.HashMap;
import java.util.Map;

/**
 * Dify工作流控制器
 * 
 * @author 李中华
 * @date 2025/1/3
 */
@Slf4j
@RestController
@RequestMapping("/api/aicommunity")
@Tag(name = "Dify工作流", description = "Dify工作流API接口")
public class DifyWorkflowController {

    @Autowired
    private DifyWorkflowService difyWorkflowService;

    /**
     * 企微对话分析工作流
     */
    @PostMapping("/workflow/consulting-scenario")
    @Operation(summary = "企微对话分析工作流", description = "调用Dify企微对话分析工作流")
    public ResponseEntity<DifyWorkflowResponseDto> consultingScenarioWorkflow(
            @Valid @RequestBody DifyWorkflowRequestDto requestDto) {
        
        try {
            log.info("开始调用企微对话分析工作流，  参数： "+requestDto.toString());
            // 构建工作流输入参数
            Map<String, Object> inputs = new HashMap<>();
            inputs.put("unionId", requestDto.getUnionId());
            inputs.put("consultantId", requestDto.getConsultantId());
            inputs.put("communicateDate", requestDto.getCommunicateDate());
            inputs.put("analysisScene", requestDto.getAnalysisScene());
            inputs.put("aiAnalysisRequestId", requestDto.getAiAnalysisRequestId());
            inputs.put("version", requestDto.getVersion());
            inputs.put("chat", requestDto.getChat());

            // 创建请求对象
            DifyWorkflowService.DifyWorkflowRequest request = 
                new DifyWorkflowService.DifyWorkflowRequest(inputs, requestDto.getConsultantId());

            // 调用工作流（Service层会自动保存数据到数据库）
            DifyWorkflowService.DifyWorkflowResponse response = 
                difyWorkflowService.callConsultingScenarioWorkflow(request);

            // 构建返回结果
            DifyWorkflowResponseDto result = DifyWorkflowResponseDto.success(
                response.getWorkflowRunId(),
                response.getTaskId(),
                response.getData(),
                response.getMetadata()
            );

            return ResponseEntity.ok(result);

        } catch (Exception e) {
            log.error("调用企微对话分析工作流失败", e);
            
            DifyWorkflowResponseDto errorResult = DifyWorkflowResponseDto.failure(
                "工作流调用失败: " + e.getMessage(),
                e.getClass().getSimpleName()
            );

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



    /**
     * DCC对话分析工作流
     */
    @PostMapping("/workflow/dcc-scenario")
    @Operation(summary = "DCC对话分析工作流", description = "调用Dify DCC对话分析工作流")
    public ResponseEntity<DifyWorkflowResponseDto> dccScenarioWorkflow(
            @Valid @RequestBody DifyWorkflowRequestDto requestDto) {
        
        try {
            log.info("开始调用DCC对话分析工作流，参数： " + requestDto.toString());
            // 构建工作流输入参数
            Map<String, Object> inputs = new HashMap<>();
            inputs.put("unionId", requestDto.getUnionId());
            inputs.put("consultantId", requestDto.getConsultantId());
            inputs.put("communicateDate", requestDto.getCommunicateDate());
            inputs.put("analysisScene", requestDto.getAnalysisScene());
            inputs.put("aiAnalysisRequestId", requestDto.getAiAnalysisRequestId());
            inputs.put("version", requestDto.getVersion());
            inputs.put("chat", requestDto.getChat());

            // 创建请求对象
            DifyWorkflowService.DifyWorkflowRequest request = 
                new DifyWorkflowService.DifyWorkflowRequest(inputs, requestDto.getConsultantId());

            // 调用DCC工作流（Service层会自动保存数据到数据库）
            DifyWorkflowService.DifyWorkflowResponse response = 
                difyWorkflowService.callDCCScenarioWorkflow(request);

            // 构建返回结果
            DifyWorkflowResponseDto result = DifyWorkflowResponseDto.success(
                response.getWorkflowRunId(),
                response.getTaskId(),
                response.getData(),
                response.getMetadata()
            );

            return ResponseEntity.ok(result);

        } catch (Exception e) {
            log.error("调用DCC对话分析工作流失败", e);
            
            DifyWorkflowResponseDto errorResult = DifyWorkflowResponseDto.failure(
                "DCC工作流调用失败: " + e.getMessage(),
                e.getClass().getSimpleName()
            );

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

    /**
     * 客户画像分析工作流
     */
    @PostMapping("/workflow/customer-profile-analysis")
    @Operation(summary = "客户画像分析工作流", description = "调用Dify客户画像分析工作流")
    public ResponseEntity<DifyWorkflowResponseDto> customerProfileAnalysisWorkflow(
            @Valid @RequestBody CustomerProfileAnalysisRequestDto requestDto) {
        
        try {
            log.info("开始调用客户画像分析工作流，参数： " + requestDto.toString());
            
            // 构建工作流输入参数
            Map<String, Object> inputs = new HashMap<>();
            inputs.put("chat", requestDto.getChat());
            inputs.put("communicateDate", requestDto.getCommunicateDate());
            inputs.put("analysisScene", requestDto.getAnalysisScene());
            inputs.put("aiAnalysisRequestld", requestDto.getAiAnalysisRequestId()); // 注意：Dify工作流期望的参数名是aiAnalysisRequestld
            inputs.put("businessId", requestDto.getBusinessId());
            inputs.put("customerFlowId", requestDto.getCustomerFlowId());
            inputs.put("businessType", requestDto.getBusinessType());

            // 创建请求对象
            DifyWorkflowService.DifyWorkflowRequest request = 
                new DifyWorkflowService.DifyWorkflowRequest(inputs, requestDto.getBusinessId());

            // 调用客户画像分析工作流（Service层会自动保存数据到数据库）
            DifyWorkflowService.DifyWorkflowResponse response = 
                difyWorkflowService.callCustomerProfileAnalysisWorkflow(request);

            // 构建返回结果
            DifyWorkflowResponseDto result = DifyWorkflowResponseDto.success(
                response.getWorkflowRunId(),
                response.getTaskId(),
                response.getData(),
                response.getMetadata()
            );

            return ResponseEntity.ok(result);

        } catch (Exception e) {
            log.error("调用客户画像分析工作流失败", e);
            
            DifyWorkflowResponseDto errorResult = DifyWorkflowResponseDto.failure(
                "客户画像分析工作流调用失败: " + e.getMessage(),
                e.getClass().getSimpleName()
            );

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

}
