package com.rj.service.biz.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rj.dto.DifyWorkflowResponseDto;
import com.rj.dto.TopSalesScoreRequestDto;
import com.rj.entity.bz.TopSalesScoreResult;
import com.rj.mapper.TopSalesScoreResultMapper;
import com.rj.service.DifyWorkflowService;
import com.rj.service.biz.ITopSalesScoreResultService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;

@Slf4j
@Service
public class TopSalesScoreResultServiceImpl
        extends ServiceImpl<TopSalesScoreResultMapper, TopSalesScoreResult>
        implements ITopSalesScoreResultService {

    @Autowired
    private DifyWorkflowService difyWorkflowService;

    @Override
    public TopSalesScoreResult callAndSave(TopSalesScoreRequestDto requestDto) {
        DifyWorkflowService.DifyWorkflowResponse response = null;
        TopSalesScoreResult entity = new TopSalesScoreResult();
        try {
            log.info("[TopSales] 开始调用工作流，chat长度={}", requestDto.getChat() == null ? 0 : requestDto.getChat().length());
            JSONObject inputs = new JSONObject();
            inputs.put("chat", requestDto.getChat());
            DifyWorkflowService.DifyWorkflowRequest req = new DifyWorkflowService.DifyWorkflowRequest(inputs, "topsales_user");
            response = difyWorkflowService.callTopSalesScoringWorkflow(req);

            JSONObject data = response.getData();
            if (data != null) {
                log.info("[TopSales] 响应data: {}", data);

                entity.setWorkflowId(data.getString("workflow_id"));
                entity.setStatus(data.getString("status"));
                entity.setTotalTokens(data.getInteger("total_tokens"));
                try {
                    entity.setElapsedTime(data.getBigDecimal("elapsed_time"));
                } catch (Exception ex) {
                    Object et = data.get("elapsed_time");
                    if (et != null) {
                        entity.setElapsedTime(new BigDecimal(String.valueOf(et)));
                    }
                }

                // 输出在 data.outputs.text
                JSONObject outputs = data.getJSONObject("outputs");
                if (outputs != null) {
                    String text = outputs.getString("text");
                    if (text != null) {
                        String cleaned = text.trim();
                        if (cleaned.startsWith("```json")) cleaned = cleaned.substring(7).trim();
                        if (cleaned.startsWith("```")) cleaned = cleaned.substring(3).trim();
                        if (cleaned.endsWith("```")) cleaned = cleaned.substring(0, cleaned.length() - 3).trim();
                        log.info("[TopSales] 清理后的text: {}", cleaned);
                        try {
                            JSONObject score = JSON.parseObject(cleaned);
                            // 同时兼容中文与英文snake_case键
                            entity.setNaturalnessScore(firstInt(score, "自然度分数", "naturalness_score"));
                            entity.setCoherenceScore(firstInt(score, "连贯性分数", "coherence_score"));
                            entity.setFluencyScore(firstInt(score, "流畅度分数", "fluency_score"));
                            entity.setAdvisorAggressivenessScore(firstInt(score, "顾问攻击性分数", "advisor_aggressiveness_score"));
                            entity.setAdvisorConsistencyScore(firstInt(score, "顾问一致性分数", "advisor_consistency_score"));
                            entity.setGreetingReceptionScore(firstInt(score, "欢迎接待分数", "greeting_reception_score"));
                            entity.setBrandIntroductionScore(firstInt(score, "品牌介绍分数", "brand_introduction_score"));
                            entity.setCustomerNeedsUnderstandingScore(firstInt(score, "了解客户用车需求分数", "customer_needs_understanding_score"));
                            entity.setBudgetUnderstandingScore(firstInt(score, "了解客户经济预算分数", "budget_understanding_score"));
                            entity.setRecommendationScore(firstInt(score, "推荐配置或车型分数", "recommendation_score"));
                            entity.setSafetyIntroductionScore(firstInt(score, "重点介绍安全性分数", "safety_introduction_score"));
                            entity.setHealthEnvironmentIntroductionScore(firstInt(score, "重点介绍健康环保分数", "health_environment_introduction_score"));
                            entity.setTechnologyIntroductionScore(firstInt(score, "重点介绍科技性分数", "technology_introduction_score"));
                            entity.setTestDriveInvitationScore(firstInt(score, "邀请试驾分数", "test_drive_invitation_score"));
                            entity.setNegotiationDealScore(firstInt(score, "商谈成交分数", "negotiation_deal_score"));
                        } catch (Exception ex) {
                            log.warn("TopSales 输出解析失败，text= {}", text);
                        }
                    }
                    // 回填源内容字段（允许外部覆盖）
                    String srcContent = requestDto.getSrcContent() == null || requestDto.getSrcContent().trim().isEmpty()
                            ? requestDto.getChat()
                            : requestDto.getSrcContent();
                    entity.setSrcContent(srcContent);
                    entity.setSrcId(requestDto.getSrcId() != null ? requestDto.getSrcId() : data.getString("id"));
                    entity.setSrcDesc(requestDto.getSrcDesc() != null ? requestDto.getSrcDesc() : "topsales_all_dim_score");
                    
                    // 设置销售人员和经销商信息
                    entity.setSalespersonName(requestDto.getSalespersonName());
                    entity.setSalespersonPhone(requestDto.getSalespersonPhone());
                    entity.setDealerName(requestDto.getDealerName());
                    entity.setDealerPhone(requestDto.getDealerPhone());
                }

                LocalDateTime now = LocalDateTime.now();
                entity.setCreatedAt(now);
                entity.setUpdatedAt(now);
                boolean saved = this.save(entity);
                log.info("TopSales评分结果保存{}: {}", saved ? "成功" : "失败", entity);
            }
        } catch (Exception e) {
            log.error("调用并保存TopSales评分结果异常", e);
        }

        return entity ;
    }

    private Integer parseInt(String s) {
        try {
            if (s == null) return null;
            return Integer.parseInt(s.trim());
        } catch (Exception e) {
            return null;
        }
    }

    private Integer firstInt(JSONObject obj, String... keys) {
        for (String k : keys) {
            String v = obj.getString(k);
            Integer parsed = parseInt(v);
            if (parsed != null) return parsed;
        }
        return null;
    }

    @Override
    public TopSalesScoreResult getByWorkflowId(String workflowId) {
        return this.getOne(new LambdaQueryWrapper<TopSalesScoreResult>()
                .eq(TopSalesScoreResult::getWorkflowId, workflowId)
                .last("limit 1"));
    }
}


