package com.rj.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.rj.entity.bz.DifyWorkflowAnalysis;
import com.rj.entity.CustomerProfileAnalysis;
import com.rj.service.biz.ICustomerProfileAnalysisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

/**
 * Dify工作流服务类
 * 用于调用Dify平台的工作流API
 * 
 * @author 李中华
 * @date 2025/1/3
 */
@Slf4j
@Service
public class DifyWorkflowService {

    @Value("${dify.api.base-url}")
    private String difyBaseUrl;

    @Value("${dify.api.workflow-endpoint-consultingScenar}")
    private String workflowEndpoint;

    @Value("${dify.api.summary-qiwei-token}")// 企微（一句话+分类别） app-WPuiaYg0iVLc2ws0iOfsAUC6
    private String summaryQiweiToken;
    @Value("${dify.api.summary-ddc-token}")// DDC（一句话+分类别）  app-rgaQbIir7vrVb1473Z3Puz6w
    private String summaryddcToken;
    @Value("${dify.api.summary-nameplate-token}")// 铭牌（一句话+分类别） //app-cv5glaYrY4zgjq0XIidSoJea
    private String summaryNameplateToken;

    @Value("${dify.api.portrait-3in1-token}")// 客户画像 app-Tpz9ByHyj5X6QCNpPX53QoBt
    private String portraitAllInToken;

    @Value("${dify.api.ai-feed-token}")
    private String aiFeedToken; // AI-Feed流（社区优质内容评估）

    @Value("${dify.api.top-sales-alldim-token}")
    private String topSalesAllDimToken; // 【AI】topsales 所有维度-只打分



    private final RestTemplate restTemplate;

    @Autowired
    private ICustomerProfileAnalysisService customerProfileAnalysisService;

    public DifyWorkflowService() {
        this.restTemplate = new RestTemplate();
    }

    /**
     * 调用企微对话分析工作流
     * 
     * @param request 工作流请求参数
     * @return 工作流响应结果
     */
    public DifyWorkflowResponse callConsultingScenarioWorkflow(DifyWorkflowRequest request) {
        try {
            String url = difyBaseUrl + workflowEndpoint;
            
            // 构建请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set("Authorization", "Bearer " + summaryQiweiToken);
            
            // 构建请求体
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("inputs", request.getInputs());
            requestBody.put("response_mode", "blocking");
            requestBody.put("user", request.getUserId());
            
            HttpEntity<Map<String, Object>> entity = new HttpEntity<>(requestBody, headers);
            
            log.info("调用Dify工作流API: {}", url);
            log.info("请求参数: {}", JSON.toJSONString(requestBody));
            
            ResponseEntity<String> response = restTemplate.exchange(
                url, 
                HttpMethod.POST, 
                entity, 
                String.class
            );
            
            log.info("Dify工作流响应状态: {}", response.getStatusCode());
            log.info("Dify工作流响应内容: {}", response.getBody());
            
            if (response.getStatusCode() == HttpStatus.OK) {
                JSONObject responseJson = JSON.parseObject(response.getBody());
                return parseAndSaveWorkflowResponse(responseJson, request);
            } else {
                throw new RuntimeException("Dify工作流调用失败，状态码: " + response.getStatusCode());
            }
            
        } catch (Exception e) {
            log.error("调用Dify工作流异常", e);
            throw new RuntimeException("调用Dify工作流异常: " + e.getMessage(), e);
        }
    }

    /**
     * 调用DCC对话分析工作流
     * 
     * @param request 工作流请求参数
     * @return 工作流响应结果
     */
    public DifyWorkflowResponse callDCCScenarioWorkflow(DifyWorkflowRequest request) {
        try {
            String url = difyBaseUrl + workflowEndpoint;
            
            // 构建请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set("Authorization", "Bearer " + summaryddcToken);
            
            // 构建请求体
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("inputs", request.getInputs());
            requestBody.put("response_mode", "blocking");
            requestBody.put("user", request.getUserId());
            
            HttpEntity<Map<String, Object>> entity = new HttpEntity<>(requestBody, headers);
            
            log.info("调用DCC Dify工作流API: {}", url);
            log.info("DCC请求参数: {}", JSON.toJSONString(requestBody));
            
            ResponseEntity<String> response = restTemplate.exchange(
                url, 
                HttpMethod.POST, 
                entity, 
                String.class
            );
            
            log.info("DCC Dify工作流响应状态: {}", response.getStatusCode());
            log.info("DCC Dify工作流响应内容: {}", response.getBody());
            
            if (response.getStatusCode() == HttpStatus.OK) {
                JSONObject responseJson = JSON.parseObject(response.getBody());
                return parseAndSaveWorkflowResponse(responseJson, request);
            } else {
                throw new RuntimeException("DCC Dify工作流调用失败，状态码: " + response.getStatusCode());
            }
            
        } catch (Exception e) {
            log.error("调用DCC Dify工作流异常", e);
            throw new RuntimeException("调用DCC Dify工作流异常: " + e.getMessage(), e);
        }
    }

    /**
     * 调用客户画像分析工作流
     * 
     * @param request 工作流请求参数
     * @return 工作流响应结果
     */
    public DifyWorkflowResponse callCustomerProfileAnalysisWorkflow(DifyWorkflowRequest request) {
        try {
            String url = difyBaseUrl + workflowEndpoint;
            
            // 构建请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set("Authorization", "Bearer " + portraitAllInToken);
            
            // 构建请求体
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("inputs", request.getInputs());
            requestBody.put("response_mode", "blocking");
            requestBody.put("user", request.getUserId());
            
            HttpEntity<Map<String, Object>> entity = new HttpEntity<>(requestBody, headers);
            
            log.info("调用客户画像分析Dify工作流API: {}", url);
            log.info("客户画像分析请求参数: {}", JSON.toJSONString(requestBody));
            
            ResponseEntity<String> response = restTemplate.exchange(
                url, 
                HttpMethod.POST, 
                entity, 
                String.class
            );
            
            log.info("客户画像分析Dify工作流响应状态: {}", response.getStatusCode());
            log.info("客户画像分析Dify工作流响应内容: {}", response.getBody());
            
            if (response.getStatusCode() == HttpStatus.OK) {
                JSONObject responseJson = JSON.parseObject(response.getBody());
                return parseAndSaveCustomerProfileAnalysisResponse(responseJson, request);
            } else {
                throw new RuntimeException("客户画像分析Dify工作流调用失败，状态码: " + response.getStatusCode());
            }
            
        } catch (Exception e) {
            log.error("调用客户画像分析Dify工作流异常", e);
            throw new RuntimeException("调用客户画像分析Dify工作流异常: " + e.getMessage(), e);
        }
    }

    /**
     * 调用 AI-Feed 流（社区Feed流优质内容）工作流
     * 期望 inputs 参数包含：targetContent、targetId、targetType
     */
    public DifyWorkflowResponse callAiFeedWorkflow(DifyWorkflowRequest request) {
        try {
            String url = difyBaseUrl + workflowEndpoint;

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set("Authorization", "Bearer " + aiFeedToken);

            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("inputs", request.getInputs());
            requestBody.put("response_mode", "blocking");
            requestBody.put("user", request.getUserId());

            HttpEntity<Map<String, Object>> entity = new HttpEntity<>(requestBody, headers);

            log.info("调用AI-Feed Dify工作流API: {}", url);
            log.info("AI-Feed请求参数: {}", JSON.toJSONString(requestBody));

            ResponseEntity<String> response = restTemplate.exchange(
                url,
                HttpMethod.POST,
                entity,
                String.class
            );

            log.info("AI-Feed Dify工作流响应状态: {}", response.getStatusCode());
            log.info("AI-Feed Dify工作流响应内容: {}", response.getBody());

            if (response.getStatusCode() == HttpStatus.OK) {
                JSONObject responseJson = JSON.parseObject(response.getBody());
                // AI-Feed 暂不做入库，直接返回
                DifyWorkflowResponse result = new DifyWorkflowResponse();
                if (responseJson.containsKey("data")) {
                    JSONObject data = responseJson.getJSONObject("data");
                    result.setWorkflowRunId(data.getString("workflow_run_id"));
                    result.setTaskId(data.getString("task_id"));
                    result.setData(data);
                }
                if (responseJson.containsKey("metadata")) {
                    result.setMetadata(responseJson.getJSONObject("metadata"));
                }
                return result;
            } else {
                throw new RuntimeException("AI-Feed Dify工作流调用失败，状态码: " + response.getStatusCode());
            }

        } catch (Exception e) {
            log.error("调用AI-Feed Dify工作流异常", e);
            throw new RuntimeException("调用AI-Feed Dify工作流异常: " + e.getMessage(), e);
        }
    }

    /**
     * 调用【AI】TopSales 所有维度-只打分 工作流
     * 输入：chat
     * 输出：data.outputs.text（可能是纯文本或JSON字符串）
     */
    public DifyWorkflowResponse callTopSalesScoringWorkflow(DifyWorkflowRequest request) {
        try {
            String url = difyBaseUrl + workflowEndpoint;

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set("Authorization", "Bearer " + topSalesAllDimToken);

            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("inputs", request.getInputs());
            requestBody.put("response_mode", "blocking");
            requestBody.put("user", request.getUserId());

            HttpEntity<Map<String, Object>> entity = new HttpEntity<>(requestBody, headers);

            log.info("调用TopSales评分工作流API: {}", url);
            log.info("TopSales评分请求参数: {}", JSON.toJSONString(requestBody));

            ResponseEntity<String> response = restTemplate.exchange(
                    url,
                    HttpMethod.POST,
                    entity,
                    String.class
            );

            log.info("TopSales评分工作流响应状态: {}", response.getStatusCode());
            log.info("TopSales评分工作流响应内容: {}", response.getBody());

            if (response.getStatusCode() == HttpStatus.OK) {
                JSONObject responseJson = JSON.parseObject(response.getBody());
                DifyWorkflowResponse result = new DifyWorkflowResponse();
                if (responseJson.containsKey("data")) {
                    JSONObject data = responseJson.getJSONObject("data");
                    result.setWorkflowRunId(data.getString("workflow_run_id"));
                    result.setTaskId(data.getString("task_id"));
                    result.setData(data);
                }
                if (responseJson.containsKey("metadata")) {
                    result.setMetadata(responseJson.getJSONObject("metadata"));
                }
                return result;
            } else {
                throw new RuntimeException("TopSales评分工作流调用失败，状态码: " + response.getStatusCode());
            }
        } catch (Exception e) {
            log.error("调用TopSales评分工作流异常", e);
            throw new RuntimeException("调用TopSales评分工作流异常: " + e.getMessage(), e);
        }
    }

    /**
     * 解析工作流响应并保存数据
     */
    private DifyWorkflowResponse parseAndSaveWorkflowResponse(JSONObject responseJson, DifyWorkflowRequest request) {
        DifyWorkflowResponse response = new DifyWorkflowResponse();
        
        if (responseJson.containsKey("data")) {
            JSONObject data = responseJson.getJSONObject("data");
            response.setWorkflowRunId(data.getString("workflow_run_id"));
            response.setTaskId(data.getString("task_id"));
            response.setData(data);
            
            // 解析并保存分析结果到数据库
            if (data.containsKey("outputs")) {
                JSONObject outputs = data.getJSONObject("outputs");
                log.info("Dify工作流响应数据 outputs : {}", outputs);
                
                // 保存分析结果到数据库
                saveAnalysisResultToDatabase(outputs, request);
            }
        }
        
        if (responseJson.containsKey("metadata")) {
            response.setMetadata(responseJson.getJSONObject("metadata"));
        }
        
        return response;
    }

    /**
     * 保存分析结果到数据库
     */
    private void saveAnalysisResultToDatabase(JSONObject outputs, DifyWorkflowRequest request) {
        try {
            DifyWorkflowAnalysis analysis = new DifyWorkflowAnalysis();
            
            // 从outputs中提取数据
            if (outputs.containsKey("data")) {
                JSONObject analysisData = outputs.getJSONObject("data");
                
                // 提取分析结果摘要
                if (analysisData.containsKey("analysisResult")) {
                    analysis.setAnalysisResult(analysisData.getString("analysisResult"));
                }
                
                // 解析详细分析结果
                if (analysisData.containsKey("analysisDetail")) {
                    JSONObject analysisDetail = analysisData.getJSONObject("analysisDetail");
                    
                    // 解析客户需求
                    if (analysisDetail.containsKey("customerNeeds")) {
                        JSONObject customerNeeds = analysisDetail.getJSONObject("customerNeeds");
                        analysis.setCustomerSource(customerNeeds.getString("customerSource"));
                        analysis.setCustomerOccupation(customerNeeds.getString("customerOccupation"));
                        analysis.setCustomerHobbies(customerNeeds.getString("customerHobbies"));
                        analysis.setHomeAddress(customerNeeds.getString("homeAddress"));
                        analysis.setCarPurchaseNeed(customerNeeds.getString("carPurchase"));
                        analysis.setPurchaseType(customerNeeds.getString("purchaseType"));
                        analysis.setPurchaseBuyer(customerNeeds.getString("purchaseBuyer"));
                        analysis.setCarUser(customerNeeds.getString("carUser"));
                        analysis.setIntendedCarModel(customerNeeds.getString("intendedCarModel"));
                        analysis.setCarQualifications(customerNeeds.getString("carQualifications"));
                        analysis.setCarBudget(customerNeeds.getString("carBudget"));
                        analysis.setFinancialInstallment(customerNeeds.getString("financialInstallment"));
                        analysis.setPurchaseCycle(customerNeeds.getString("purchaseCycle"));
                        analysis.setFocusPoints(customerNeeds.getString("focus"));
                        analysis.setConcerns(customerNeeds.getString("concerns"));
                        analysis.setCarContrast(customerNeeds.getString("carContrast"));
                    }
                    
                    // 解析顾问服务
                    if (analysisDetail.containsKey("customerService")) {
                        JSONObject customerService = analysisDetail.getJSONObject("customerService");
                        analysis.setProductDescription(customerService.getString("productDesc"));
                        analysis.setSolution(customerService.getString("solution"));
                        analysis.setQuotation(customerService.getString("quotation"));
                    }
                    
                    // 解析后续行动和未解决问题
                    analysis.setAgreedFollowUpActions(analysisDetail.getString("agreedFollowUpActions"));
                    analysis.setUnresolvedIssues(analysisDetail.getString("unresolvedIssues"));
                }
            }
            
            // 从outputs中提取其他字段
            if (outputs.containsKey("unionId")) {
                analysis.setUnionId(outputs.getString("unionId"));
            }
            if (outputs.containsKey("consultantId")) {
                analysis.setConsultantId(outputs.getString("consultantId"));
            }
            if (outputs.containsKey("communicateDate")) {
                try {
                    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                    analysis.setCommunicateDate(LocalDateTime.parse(outputs.getString("communicateDate"), formatter));
                } catch (Exception e) {
                    log.warn("解析沟通时间失败: {}", outputs.getString("communicateDate"), e);
                    analysis.setCommunicateDate(LocalDateTime.now());
                }
            }
            if (outputs.containsKey("analysisScene")) {
                analysis.setAnalysisScene(outputs.getString("analysisScene"));
            }
            if (outputs.containsKey("analysisRecordId")) {
                analysis.setAnalysisRecordId(outputs.getString("analysisRecordId"));
            }
            if (outputs.containsKey("version")) {
                analysis.setVersion(outputs.getInteger("version"));
            }
            
            // 从request的inputs中提取原始对话内容
            if (request.getInputs() != null && request.getInputs().containsKey("chat")) {
                analysis.setOriginalCorpus((String) request.getInputs().get("chat"));
            }
            
            // 设置创建时间和更新时间
            LocalDateTime now = LocalDateTime.now();
            analysis.setCreatedAt(now);
            analysis.setUpdatedAt(now);
            
            // 保存到数据库
//            boolean saveResult = difyWorkflowAnalysisService.save(analysis);
//            if (saveResult) {
//                log.info("分析结果保存成功，ID: {}", analysis.getId());
//            } else {
//                log.error("分析结果保存失败");
//            }
            
        } catch (Exception e) {
            log.error("保存分析结果到数据库失败", e);
        }
    }

    /**
     * 解析客户画像分析工作流响应并保存数据
     */
    private DifyWorkflowResponse parseAndSaveCustomerProfileAnalysisResponse(JSONObject responseJson, DifyWorkflowRequest request) {
        DifyWorkflowResponse response = new DifyWorkflowResponse();
        
        if (responseJson.containsKey("data")) {
            JSONObject data = responseJson.getJSONObject("data");
            response.setWorkflowRunId(data.getString("workflow_run_id"));
            response.setTaskId(data.getString("task_id"));
            response.setData(data);
            
            // 解析并保存客户画像分析结果到数据库
            if (data.containsKey("outputs")) {
                JSONObject outputs = data.getJSONObject("outputs");
                log.info("客户画像分析Dify工作流响应数据 outputs : {}", outputs);
                
                // 保存客户画像分析结果到数据库
                saveCustomerProfileAnalysisResultToDatabase(outputs, request);
            }
        }
        
        if (responseJson.containsKey("metadata")) {
            response.setMetadata(responseJson.getJSONObject("metadata"));
        }
        
        return response;
    }

    /**
     * 保存客户画像分析结果到数据库
     */
    private void saveCustomerProfileAnalysisResultToDatabase(JSONObject outputs, DifyWorkflowRequest request) {
        try {
            CustomerProfileAnalysis analysis = new CustomerProfileAnalysis();
            
            // 从request的inputs中提取基础信息
            Map<String, Object> inputs = request.getInputs();
            if (inputs != null) {
                // 设置基础字段
                analysis.setProfileAnalysisRecordId((String) inputs.get("aiAnalysisRequestld"));
                analysis.setRelatedBusinessId((String) inputs.get("businessId"));
                analysis.setAnalysisSceneType(parseAnalysisSceneType((String) inputs.get("analysisScene")));
                
                // 解析沟通时间
                if (inputs.containsKey("communicateDate")) {
                    try {
                        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                        analysis.setInteractionDate(LocalDateTime.parse((String) inputs.get("communicateDate"), formatter));
                    } catch (Exception e) {
                        log.warn("解析沟通时间失败: {}", inputs.get("communicateDate"), e);
                        analysis.setInteractionDate(LocalDateTime.now());
                    }
                }
                
                // 设置原始对话内容（用于后续分析）
                if (inputs.containsKey("chat")) {
                    // 这里可以保存原始对话内容，但实体类中没有对应字段，可以扩展
                    log.info("原始对话内容: {}", inputs.get("chat"));
                }
            }
            
            // 从outputs中提取客户画像分析结果字段
            // Dify工作流现在直接输出与MySQL表字段名一致的JSON结构
            if (outputs.containsKey("result")) {
                JSONObject result = outputs.getJSONObject("result");
                
                // 解析info部分（客户基础信息）
                if (result.containsKey("info")) {
                    JSONObject info = result.getJSONObject("info");
                    
                    // 直接使用MySQL表字段名进行赋值
                    if (info.containsKey("dealer_code")) {
                        analysis.setDealerCode(info.getString("dealer_code"));
                    }
                    if (info.containsKey("opportunity_id")) {
                        analysis.setOpportunityId(info.getString("opportunity_id"));
                    }
                    if (info.containsKey("client_id")) {
                        analysis.setClientId(info.getString("client_id"));
                    }
                    if (info.containsKey("client_name")) {
                        analysis.setClientName(info.getString("client_name"));
                    }
                    if (info.containsKey("client_phone")) {
                        analysis.setClientPhone(info.getString("client_phone"));
                    }
                    if (info.containsKey("home_address")) {
                        analysis.setHomeAddress(info.getString("home_address"));
                    }
                    if (info.containsKey("vehicle_usage")) {
                        analysis.setVehicleUsage(info.getString("vehicle_usage"));
                    }
                    if (info.containsKey("primary_driver")) {
                        analysis.setPrimaryDriver(info.getString("primary_driver"));
                    }
                    if (info.containsKey("family_composition")) {
                        analysis.setFamilyComposition(info.getString("family_composition"));
                    }
                    if (info.containsKey("family_size")) {
                        analysis.setFamilySize(info.getString("family_size"));
                    }
                    if (info.containsKey("monthly_income")) {
                        analysis.setMonthlyIncome(info.getString("monthly_income"));
                    }
                    if (info.containsKey("industry_sector")) {
                        analysis.setIndustrySector(info.getString("industry_sector"));
                    }
                    if (info.containsKey("job_title")) {
                        analysis.setJobTitle(info.getString("job_title"));
                    }
                    if (info.containsKey("company_type")) {
                        analysis.setCompanyType(info.getString("company_type"));
                    }
                    if (info.containsKey("hobby")) {
                        analysis.setHobby(info.getString("hobby"));
                    }
                    if (info.containsKey("education_level")) {
                        analysis.setEducationLevel(info.getString("education_level"));
                    }
                    if (info.containsKey("purchase_date")) {
                        analysis.setPurchaseDate(info.getString("purchase_date"));
                    }
                    if (info.containsKey("purchase_type")) {
                        analysis.setPurchaseType(info.getString("purchase_type"));
                    }
                    if (info.containsKey("budget_range")) {
                        analysis.setBudgetRange(info.getString("budget_range"));
                    }
                    if (info.containsKey("payment_way")) {
                        analysis.setPaymentWay(info.getString("payment_way"));
                    }
                    if (info.containsKey("current_brand")) {
                        analysis.setCurrentBrand(info.getString("current_brand"));
                    }
                    if (info.containsKey("competitor_brand")) {
                        analysis.setCompetitorBrand(info.getString("competitor_brand"));
                    }
                    if (info.containsKey("purchase_qualification")) {
                        analysis.setPurchaseQualification(info.getString("purchase_qualification"));
                    }
                    if (info.containsKey("interest_focus")) {
                        analysis.setInterestFocus(info.getString("interest_focus"));
                    }
                    if (info.containsKey("concern_point")) {
                        analysis.setConcernPoint(info.getString("concern_point"));
                    }
                    if (info.containsKey("notes")) {
                        analysis.setNotes(info.getString("notes"));
                    }
                }
                
                // 解析entities部分（情感分析）
                if (result.containsKey("entities")) {
                    JSONObject entities = result.getJSONObject("entities");
                    
                    // 直接使用MySQL表字段名进行赋值
                    if (entities.containsKey("entity_brand")) {
                        analysis.setEntityBrand(entities.getString("entity_brand"));
                    }
                    if (entities.containsKey("entity_brand_reason")) {
                        analysis.setEntityBrandReason(entities.getString("entity_brand_reason"));
                    }
                    if (entities.containsKey("entity_design")) {
                        analysis.setEntityDesign(entities.getString("entity_design"));
                    }
                    if (entities.containsKey("entity_design_reason")) {
                        analysis.setEntityDesignReason(entities.getString("entity_design_reason"));
                    }
                    if (entities.containsKey("entity_color")) {
                        analysis.setEntityColor(entities.getString("entity_color"));
                    }
                    if (entities.containsKey("entity_color_reason")) {
                        analysis.setEntityColorReason(entities.getString("entity_color_reason"));
                    }
                    if (entities.containsKey("entity_size")) {
                        analysis.setEntitySize(entities.getString("entity_size"));
                    }
                    if (entities.containsKey("entity_size_reason")) {
                        analysis.setEntitySizeReason(entities.getString("entity_size_reason"));
                    }
                    if (entities.containsKey("entity_space")) {
                        analysis.setEntitySpace(entities.getString("entity_space"));
                    }
                    if (entities.containsKey("entity_space_reason")) {
                        analysis.setEntitySpaceReason(entities.getString("entity_space_reason"));
                    }
                    if (entities.containsKey("entity_interior")) {
                        analysis.setEntityInterior(entities.getString("entity_interior"));
                    }
                    if (entities.containsKey("entity_interior_reason")) {
                        analysis.setEntityInteriorReason(entities.getString("entity_interior_reason"));
                    }
                    if (entities.containsKey("entity_audio")) {
                        analysis.setEntityAudio(entities.getString("entity_audio"));
                    }
                    if (entities.containsKey("entity_audio_reason")) {
                        analysis.setEntityAudioReason(entities.getString("entity_audio_reason"));
                    }
                    if (entities.containsKey("entity_ivinfo")) {
                        analysis.setEntityIvinfo(entities.getString("entity_ivinfo"));
                    }
                    if (entities.containsKey("entity_ivinfo_reason")) {
                        analysis.setEntityIvinfoReason(entities.getString("entity_ivinfo_reason"));
                    }
                    if (entities.containsKey("entity_fsd")) {
                        analysis.setEntityFsd(entities.getString("entity_fsd"));
                    }
                    if (entities.containsKey("entity_fsd_reason")) {
                        analysis.setEntityFsdReason(entities.getString("entity_fsd_reason"));
                    }
                    if (entities.containsKey("entity_mileage")) {
                        analysis.setEntityMileage(entities.getString("entity_mileage"));
                    }
                    if (entities.containsKey("entity_mileage_reason")) {
                        analysis.setEntityMileageReason(entities.getString("entity_mileage_reason"));
                    }
                    if (entities.containsKey("entity_safety")) {
                        analysis.setEntitySafety(entities.getString("entity_safety"));
                    }
                    if (entities.containsKey("entity_safety_reason")) {
                        analysis.setEntitySafetyReason(entities.getString("entity_safety_reason"));
                    }
                    if (entities.containsKey("entity_eco")) {
                        analysis.setEntityEco(entities.getString("entity_eco"));
                    }
                    if (entities.containsKey("entity_eco_reason")) {
                        analysis.setEntityEcoReason(entities.getString("entity_eco_reason"));
                    }
                    if (entities.containsKey("entity_liscense")) {
                        analysis.setEntityLiscense(entities.getString("entity_liscense"));
                    }
                    if (entities.containsKey("entity_liscense_reason")) {
                        analysis.setEntityLiscenseReason(entities.getString("entity_liscense_reason"));
                    }
                    if (entities.containsKey("entity_price")) {
                        analysis.setEntityPrice(entities.getString("entity_price"));
                    }
                    if (entities.containsKey("entity_price_reason")) {
                        analysis.setEntityPriceReason(entities.getString("entity_price_reason"));
                    }
                    if (entities.containsKey("entity_benefit")) {
                        analysis.setEntityBenefit(entities.getString("entity_benefit"));
                    }
                    if (entities.containsKey("entity_benefit_reason")) {
                        analysis.setEntityBenefitReason(entities.getString("entity_benefit_reason"));
                    }
                    if (entities.containsKey("entity_cost")) {
                        analysis.setEntityCost(entities.getString("entity_cost"));
                    }
                    if (entities.containsKey("entity_cost_reason")) {
                        analysis.setEntityCostReason(entities.getString("entity_cost_reason"));
                    }
                    if (entities.containsKey("entity_value")) {
                        analysis.setEntityValue(entities.getString("entity_value"));
                    }
                    if (entities.containsKey("entity_value_reason")) {
                        analysis.setEntityValueReason(entities.getString("entity_value_reason"));
                    }
                    if (entities.containsKey("entity_power")) {
                        analysis.setEntityPower(entities.getString("entity_power"));
                    }
                    if (entities.containsKey("entity_power_reason")) {
                        analysis.setEntityPowerReason(entities.getString("entity_power_reason"));
                    }
                    if (entities.containsKey("entity_control")) {
                        analysis.setEntityControl(entities.getString("entity_control"));
                    }
                    if (entities.containsKey("entity_control_reason")) {
                        analysis.setEntityControlReason(entities.getString("entity_control_reason"));
                    }
                    if (entities.containsKey("entity_tradein")) {
                        analysis.setEntityTradein(entities.getString("entity_tradein"));
                    }
                    if (entities.containsKey("entity_tradein_reason")) {
                        analysis.setEntityTradeinReason(entities.getString("entity_tradein_reason"));
                    }
                    if (entities.containsKey("entity_finance")) {
                        analysis.setEntityFinance(entities.getString("entity_finance"));
                    }
                    if (entities.containsKey("entity_finance_reason")) {
                        analysis.setEntityFinanceReason(entities.getString("entity_finance_reason"));
                    }
                    if (entities.containsKey("entity_warranty")) {
                        analysis.setEntityWarranty(entities.getString("entity_warranty"));
                    }
                    if (entities.containsKey("entity_warranty_reason")) {
                        analysis.setEntityWarrantyReason(entities.getString("entity_warranty_reason"));
                    }
                    if (entities.containsKey("entity_delivery")) {
                        analysis.setEntityDelivery(entities.getString("entity_delivery"));
                    }
                    if (entities.containsKey("entity_delivery_reason")) {
                        analysis.setEntityDeliveryReason(entities.getString("entity_delivery_reason"));
                    }
                }
            }
            
            // 设置系统字段
            LocalDateTime now = LocalDateTime.now();
            analysis.setCreatedAt(now);
            analysis.setUpdatedAt(now);
            analysis.setRecordVersion(0);
            analysis.setIsDeleted(0);
            
            // 保存到数据库
            boolean saveResult = customerProfileAnalysisService.saveCustomerProfileAnalysis(analysis);
            if (saveResult) {
                log.info("客户画像分析结果保存成功，ID: {}", analysis.getId());
            } else {
                log.error("客户画像分析结果保存失败");
            }
            
        } catch (Exception e) {
            log.error("保存客户画像分析结果到数据库失败", e);
        }
    }

    /**
     * 解析分析场景类型
     */
    private Integer parseAnalysisSceneType(String analysisScene) {
        if (analysisScene == null) {
            return 1; // 默认企微会话
        }
        
        switch (analysisScene.toLowerCase()) {
            case "wechat_chat":
            case "企微会话":
                return 1;
            case "ai_call":
            case "AI通话录音":
                return 2;
            case "ai_nameplate_flow":
            case "AI铭牌(客流)":
                return 3;
            case "ai_nameplate_test_drive":
            case "AI铭牌(试驾)":
                return 4;
            default:
                return 1; // 默认企微会话
        }
    }

    /**
     * Dify工作流请求参数
     */
    public static class DifyWorkflowRequest {
        private Map<String, Object> inputs;
        private String userId;

        public DifyWorkflowRequest() {}

        public DifyWorkflowRequest(Map<String, Object> inputs, String userId) {
            this.inputs = inputs;
            this.userId = userId;
        }

        public Map<String, Object> getInputs() {
            return inputs;
        }

        public void setInputs(Map<String, Object> inputs) {
            this.inputs = inputs;
        }

        public String getUserId() {
            return userId;
        }

        public void setUserId(String userId) {
            this.userId = userId;
        }
    }

    /**
     * Dify工作流响应结果
     */
    public static class DifyWorkflowResponse {
        private String workflowRunId;
        private String taskId;
        private JSONObject data;
        private JSONObject metadata;

        public String getWorkflowRunId() {
            return workflowRunId;
        }

        public void setWorkflowRunId(String workflowRunId) {
            this.workflowRunId = workflowRunId;
        }

        public String getTaskId() {
            return taskId;
        }

        public void setTaskId(String taskId) {
            this.taskId = taskId;
        }

        public JSONObject getData() {
            return data;
        }

        public void setData(JSONObject data) {
            this.data = data;
        }

        public JSONObject getMetadata() {
            return metadata;
        }

        public void setMetadata(JSONObject metadata) {
            this.metadata = metadata;
        }
    }
}
