/**
 * @ProjectName: 智慧评标-主观分助手
 * @Package: com.zhpb.gdyd_zhpb_zgf.controller
 * @ClassName: ComparisonController
 * @Description: 供应商对比分析控制器
 * @Author: 张志锋
 * @Date: 2025-11-04
 * @Version: 1.0
 * @Copyright: © 2025 智慧评标-主观分助手
 */
package com.zhpb.gdyd_zhpb_zgf.controller;

import com.zhpb.gdyd_zhpb_zgf.dto.ComparisonRequest;
import com.zhpb.gdyd_zhpb_zgf.dto.ComparisonResponse;
import com.zhpb.gdyd_zhpb_zgf.service.ComparisonService;
import com.zhpb.gdyd_zhpb_zgf.service.UserLogService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import java.util.HashMap;
import java.util.Map;

/**
 * 供应商对比分析控制器
 */
@RestController
@RequestMapping("/api/v1/comparison")
@Tag(name = "供应商对比分析", description = "供应商横向对比分析相关接口")
public class ComparisonController {

    private static final Logger logger = LoggerFactory.getLogger(ComparisonController.class);

    @Autowired
    private ComparisonService comparisonService;

    @Autowired
    private UserLogService userLogService;

    /**
     * 获取指定项目的供应商数据
     */
    @GetMapping("/vendors")
    @Operation(
        summary = "获取项目供应商数据",
        description = "获取指定项目下的所有供应商及其关联文件，用于在对比时选择。"
    )
    @ApiResponses(value = {
        @ApiResponse(
            responseCode = "200",
            description = "获取成功",
            content = @io.swagger.v3.oas.annotations.media.Content(
                mediaType = "application/json",
                schema = @io.swagger.v3.oas.annotations.media.Schema(implementation = ComparisonResponse.VendorsData.class)
            )
        ),
        @ApiResponse(responseCode = "422", description = "参数验证错误")
    })
    public ResponseEntity<Map<String, Object>> getProjectVendors(
        @Parameter(description = "项目ID", required = true, example = "project-001")
        @RequestParam("project_id") String projectId,
        @Parameter(description = "用户ID", required = false, example = "user-001")
        @RequestParam(value = "userId", required = false) String userId,
        @Parameter(description = "用户ID（兼容字段）", required = false, example = "user-001")
        @RequestParam(value = "userld", required = false) String legacyUserId,
        @Parameter(description = "用户名", required = false, example = "张三")
        @RequestParam(value = "userName", required = false) String userName,
        HttpServletRequest request) {

        Map<String, Object> response = new HashMap<>();
        String resolvedUserId = userId != null ? userId : legacyUserId;

        try {
            ComparisonResponse.VendorsData data = comparisonService.getProjectVendors(projectId);

            response.put("code", 0);
            response.put("message", "获取供应商数据成功");
            response.put("data", data);

            userLogService.logUserOperation(resolvedUserId, userName, projectId,
                "VIEW_VENDORS", "获取项目供应商数据", null, request);

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            logger.error("获取项目供应商数据失败", e);
            response.put("code", 500);
            response.put("message", "获取供应商数据失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 启动供应商对比分析任务
     */
    @PostMapping("/start")
    @Operation(
        summary = "启动对比分析任务",
        description = "提交一个异步的横向对比任务。"
    )
    @ApiResponses(value = {
        @ApiResponse(
            responseCode = "201",
            description = "任务启动成功",
            content = @io.swagger.v3.oas.annotations.media.Content(
                mediaType = "application/json",
                schema = @io.swagger.v3.oas.annotations.media.Schema(implementation = ComparisonResponse.StartTaskData.class)
            )
        ),
        @ApiResponse(responseCode = "422", description = "参数验证错误")
    })
    public ResponseEntity<Map<String, Object>> startComparison(
        @Parameter(description = "对比分析请求参数", required = true)
        @Valid @RequestBody ComparisonRequest request) {

        Map<String, Object> response = new HashMap<>();

        try {
            ComparisonResponse.StartTaskData data = comparisonService.startComparison(request);

            response.put("code", 0);
            response.put("message", "对比分析任务已启动");
            response.put("data", data);

            return ResponseEntity.status(201).body(response);

        } catch (Exception e) {
            logger.error("启动对比分析任务失败", e);
            response.put("code", 500);
            response.put("message", "启动对比分析任务失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 获取对比任务历史
     */
    @GetMapping("/history/tasks")
    @Operation(
        summary = "获取对比任务历史",
        description = "获取指定用户在某个项目下的所有历史对比任务列表。"
    )
    @ApiResponses(value = {
        @ApiResponse(
            responseCode = "200",
            description = "获取成功",
            content = @io.swagger.v3.oas.annotations.media.Content(
                mediaType = "application/json",
                schema = @io.swagger.v3.oas.annotations.media.Schema(implementation = ComparisonResponse.TaskHistoryData.class)
            )
        ),
        @ApiResponse(responseCode = "422", description = "参数验证错误")
    })
    public ResponseEntity<Map<String, Object>> getComparisonHistory(
        @Parameter(description = "项目ID", required = true, example = "project-001")
        @RequestParam("project_id") String projectId,
        @Parameter(description = "用户ID", required = true, example = "user-001")
        @RequestParam("user_id") String userId,
        @Parameter(description = "用户名", required = false, example = "张三")
        @RequestParam(value = "userName", required = false) String userName,
        @Parameter(description = "用户名（兼容字段）", required = false, example = "张三")
        @RequestParam(value = "user_name", required = false) String legacyUserName,
        HttpServletRequest request) {

        Map<String, Object> response = new HashMap<>();

        try {
            ComparisonResponse.TaskHistoryData data = comparisonService.getComparisonHistory(projectId, userId);

            response.put("code", 0);
            response.put("message", "获取对比任务历史成功");
            response.put("data", data);

            String resolvedUserName = userName;
            if (resolvedUserName == null || resolvedUserName.isBlank()) {
                resolvedUserName = legacyUserName;
            }
            if ((resolvedUserName == null || resolvedUserName.isBlank()) && request != null) {
                resolvedUserName = request.getHeader("User-Name");
                if (resolvedUserName == null || resolvedUserName.isBlank()) {
                    resolvedUserName = request.getHeader("userName");
                }
            }

            userLogService.logUserOperation(userId, resolvedUserName, projectId,
                "VIEW_COMPARISON_HISTORY", "获取对比任务历史", null, request);

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            logger.error("获取对比任务历史失败", e);
            response.put("code", 500);
            response.put("message", "获取对比任务历史失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 获取对比任务结果
     */
    @GetMapping("/result")
    @Operation(
        summary = "获取对比任务结果",
        description = "根据任务ID，获取对比任务的状态和结果。甲方可通过轮询此接口来获取最终结果。"
    )
    @ApiResponses(value = {
        @ApiResponse(
            responseCode = "200",
            description = "获取成功",
            content = @io.swagger.v3.oas.annotations.media.Content(
                mediaType = "application/json",
                schema = @io.swagger.v3.oas.annotations.media.Schema(implementation = ComparisonResponse.ComparisonResultData.class)
            )
        ),
        @ApiResponse(responseCode = "422", description = "参数验证错误")
    })
    public ResponseEntity<Map<String, Object>> getComparisonResult(
        @Parameter(description = "任务ID", required = true, example = "task-001")
        @RequestParam("task_id") String taskId) {

        Map<String, Object> response = new HashMap<>();

        try {
            ComparisonResponse.ComparisonResultData data = comparisonService.getComparisonResult(taskId);

            response.put("code", 0);
            response.put("message", "获取对比任务结果成功");
            response.put("data", data);

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            logger.error("获取对比任务结果失败", e);
            response.put("code", 500);
            response.put("message", "获取对比任务结果失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }
}
