package com.rj.controller.biz;

import com.rj.dto.TopSalesScoreRequestDto;
import com.rj.service.biz.ITopSalesScoreResultService;
import io.swagger.v3.oas.annotations.Operation;
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 com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rj.entity.bz.TopSalesScoreResult;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/api/topsales")
@Tag(name = "TopSales评分工作流", description = "调用【AI】topsales 所有维度-只打分")
public class TopSalesController {

    @Autowired
    private ITopSalesScoreResultService topSalesScoreResultService;

    @PostMapping("/score")
    @Operation(summary = "调用TopSales评分工作流")
    public ResponseEntity<Map<String, Object>> score(@Valid @RequestBody TopSalesScoreRequestDto requestDto) {
        Map<String, Object> result = new HashMap<>();
        try {
            result.put("success", true);
            result.put("message", "TopSales评分成功");
            result.put("data", topSalesScoreResultService.callAndSave(requestDto));
            return ResponseEntity.ok(result);

        } catch (Exception e) {
            String ss ="TopSales评分工作流调用失败: " + e.getMessage() ;
            result.put("success", true);
            result.put("message", ss);
            log.error("调用TopSales评分工作流失败", e);
            return ResponseEntity.status(500).body(result );
        }
    }

    @GetMapping("/page")
    @Operation(summary = "分页查询TopSales评分结果")
    public ResponseEntity<Object> page(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String workflowId,
            @RequestParam(required = false) String status,
            @RequestParam(required = false) String salespersonName,
            @RequestParam(required = false) String salespersonPhone,
            @RequestParam(required = false) String dealerName,
            @RequestParam(required = false) String dealerPhone
    ) {
        Page<TopSalesScoreResult> page = new Page<>(current, size);
        LambdaQueryWrapper<TopSalesScoreResult> wrapper = new LambdaQueryWrapper<>();
        Map<String, Object> result = new HashMap<>();
        if (workflowId != null && !workflowId.trim().isEmpty()) {
            wrapper.like(TopSalesScoreResult::getWorkflowId, workflowId);
        }
        if (status != null && !status.trim().isEmpty()) {
            wrapper.eq(TopSalesScoreResult::getStatus, status);
        }
        if (salespersonName != null && !salespersonName.trim().isEmpty()) {
            wrapper.like(TopSalesScoreResult::getSalespersonName, salespersonName);
        }
        if (salespersonPhone != null && !salespersonPhone.trim().isEmpty()) {
            wrapper.like(TopSalesScoreResult::getSalespersonPhone, salespersonPhone);
        }
        if (dealerName != null && !dealerName.trim().isEmpty()) {
            wrapper.like(TopSalesScoreResult::getDealerName, dealerName);
        }
        if (dealerPhone != null && !dealerPhone.trim().isEmpty()) {
            wrapper.like(TopSalesScoreResult::getDealerPhone, dealerPhone);
        }
        wrapper.orderByDesc(TopSalesScoreResult::getCreatedAt);
        Page<TopSalesScoreResult> data = topSalesScoreResultService.page(page, wrapper);

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

    }

    @GetMapping("/by-workflow/{workflowId}")
    @Operation(summary = "按workflowId查询TopSales评分结果")
    public ResponseEntity<TopSalesScoreResult> getByWorkflowId(@PathVariable String workflowId) {
        return ResponseEntity.ok(topSalesScoreResultService.getByWorkflowId(workflowId));
    }

    @PostMapping("/save-mock-data")
    @Operation(summary = "保存TopSales模拟评分数据")
    public ResponseEntity<Map<String, Object>> saveMockData(@RequestBody TopSalesScoreRequestDto requestDto) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 创建模拟的评分结果
            TopSalesScoreResult mockResult = createMockScoreResult(requestDto);
            
            // 直接保存到数据库
            boolean saved = topSalesScoreResultService.save(mockResult);
            
            if (saved) {
                result.put("success", true);
                result.put("message", "模拟数据保存成功");
                result.put("data", mockResult);
                return ResponseEntity.ok(result);
            } else {
                result.put("success", false);
                result.put("message", "模拟数据保存失败");
                return ResponseEntity.status(500).body(result);
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "保存模拟数据失败: " + e.getMessage());
            log.error("保存TopSales模拟数据失败", e);
            return ResponseEntity.status(500).body(result);
        }
    }

    /**
     * 创建模拟的评分结果
     */
    private TopSalesScoreResult createMockScoreResult(TopSalesScoreRequestDto requestDto) {
        TopSalesScoreResult result = new TopSalesScoreResult();
        
        // 基本信息
        result.setWorkflowId("mock_workflow_" + System.currentTimeMillis());
        result.setSalespersonName(requestDto.getSalespersonName());
        result.setSalespersonPhone(requestDto.getSalespersonPhone());
        result.setDealerName(requestDto.getDealerName());
        result.setDealerPhone(requestDto.getDealerPhone());
        result.setSrcContent(requestDto.getSrcContent());
        result.setSrcId(requestDto.getSrcId());
        result.setSrcDesc(requestDto.getSrcDesc());
        result.setStatus("success");
        result.setCreatedAt(LocalDateTime.now());
        result.setUpdatedAt(LocalDateTime.now());
        
        // 生成模拟的15个维度评分 (1-10分)
        result.setNaturalnessScore(generateRandomScore());
        result.setCoherenceScore(generateRandomScore());
        result.setFluencyScore(generateRandomScore());
        result.setAdvisorAggressivenessScore(generateRandomScore());
        result.setAdvisorConsistencyScore(generateRandomScore());
        result.setGreetingReceptionScore(generateRandomScore());
        result.setBrandIntroductionScore(generateRandomScore());
        result.setCustomerNeedsUnderstandingScore(generateRandomScore());
        result.setBudgetUnderstandingScore(generateRandomScore());
        result.setRecommendationScore(generateRandomScore());
        result.setSafetyIntroductionScore(generateRandomScore());
        result.setHealthEnvironmentIntroductionScore(generateRandomScore());
        result.setTechnologyIntroductionScore(generateRandomScore());
        result.setTestDriveInvitationScore(generateRandomScore());
        result.setNegotiationDealScore(generateRandomScore());
        
        // 模拟其他字段
        result.setTotalTokens(1000 + (int)(Math.random() * 2000));
        result.setElapsedTime(new BigDecimal(String.format("%.2f", 1.0 + Math.random() * 5.0)));
        
        return result;
    }
    
    /**
     * 生成1-10分的随机评分
     */
    private Integer generateRandomScore() {
        return 1 + (int)(Math.random() * 10);
    }
}


