package com.gxwebsoft.ai.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gxwebsoft.ai.constants.AuditContent3DecisionConstants;
import com.gxwebsoft.ai.service.AuditContent3DecisionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import cn.hutool.core.util.StrUtil;

import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class AuditContent3DecisionServiceImpl extends AbstractAuditContentService implements AuditContent3DecisionService {

    // 工作流配置
    private static final String DIFY_WORKFLOW_TOKEN = "Bearer app-yN7Q8GEN9E7SCMkhI6HaAagW";

    @Override
    public JSONObject generateDecisionTableData(String kbIds, String libraryKbIds, String projectLibrary, 
                                               String userName, String history, String suggestion, Object data) {
        log.info("开始生成重大经济决策调查表数据 - 用户: {}", userName);
        
        JSONObject result = new JSONObject();
        long startTime = System.currentTimeMillis();
        
        try {
            // 1. 解析三重一大数据
            JSONArray tripleOneData = parseTripleOneData(data);
            
            if (tripleOneData == null || tripleOneData.isEmpty()) {
                log.warn("未传入三重一大数据，无法生成重大经济决策调查表");
                result.put("success", false);
                result.put("error", "需要三重一大数据作为生成依据");
                return result;
            }
            
            // 2. 检索相关知识库内容
            Map<String, List<String>> knowledgeSources = retrieveKnowledge(kbIds, libraryKbIds, projectLibrary, tripleOneData);
            
            // 3. 构建上下文并调用工作流
            String knowledgeContext = buildKnowledgeContext(tripleOneData, knowledgeSources, history, suggestion);
            JSONObject requestBody = buildWorkflowRequest(knowledgeContext, userName);
            JSONArray decisionTableData = callWorkflow(DIFY_WORKFLOW_URL, DIFY_WORKFLOW_TOKEN, requestBody, "重大经济决策调查表");
            
            // 4. 构建返回结果
            return buildSuccessResponse(decisionTableData, startTime, "triple_one_primary");
            
        } catch (Exception e) {
            log.error("生成重大经济决策调查表失败", e);
            return buildErrorResponse("生成重大经济决策调查表失败: " + e.getMessage());
        }
    }

    /**
     * 检索相关知识
     */
    private Map<String, List<String>> retrieveKnowledge(String kbIds, String libraryKbIds, String projectLibrary, JSONArray tripleOneData) {
        Map<String, List<String>> knowledgeSources = new HashMap<>();
        knowledgeSources.put("enterprise", new ArrayList<>());
        knowledgeSources.put("regulation", new ArrayList<>());
        knowledgeSources.put("auditCase", new ArrayList<>());
        
        // 企业单位知识检索
        if (StrUtil.isNotBlank(kbIds)) {
            List<String> enterpriseQueries = buildEnterpriseQueries(tripleOneData);
            Arrays.stream(kbIds.split(","))
                .map(String::trim)
                .filter(StrUtil::isNotBlank)
                .forEach(kbId -> knowledgeSources.get("enterprise")
                    .addAll(queryKnowledgeBase(kbId, enterpriseQueries, 20)));
        }
        
        // 法律法规知识检索
        if (StrUtil.isNotBlank(libraryKbIds)) {
            List<String> regulationQueries = buildRegulationQueries(tripleOneData);
            Arrays.stream(libraryKbIds.split(","))
                .map(String::trim)
                .filter(StrUtil::isNotBlank)
                .forEach(libId -> knowledgeSources.get("regulation")
                    .addAll(queryKnowledgeBase(libId, regulationQueries, 100)));
        }
        
        // 审计案例知识检索
        if (StrUtil.isNotBlank(projectLibrary)) {
            List<String> auditCaseQueries = buildAuditCaseQueries(tripleOneData);
            knowledgeSources.get("auditCase").addAll(
                queryKnowledgeBase(projectLibrary, auditCaseQueries, 50));
        }
        
        // 智能去重
        knowledgeSources.forEach((sourceType, knowledgeList) -> {
            List<String> distinctList = knowledgeList.stream().distinct().collect(Collectors.toList());
            knowledgeSources.put(sourceType, distinctList);
        });
        
        log.info("知识库检索完成 - 企业单位: {}条, 法律法规: {}条, 审计案例: {}条", 
                knowledgeSources.get("enterprise").size(),
                knowledgeSources.get("regulation").size(),
                knowledgeSources.get("auditCase").size());
        
        return knowledgeSources;
    }

    /**
     * 构建企业单位查询
     */
    private List<String> buildEnterpriseQueries(JSONArray tripleOneData) {
        List<String> queries = new ArrayList<>();
        
        for (int i = 0; i < tripleOneData.size(); i++) {
            JSONObject item = tripleOneData.getJSONObject(i);
            if (item != null) {
                String category = item.getString("category");
                if (StrUtil.isNotBlank(category)) {
                    queries.add(category + " 会议记录 决策事项");
                    queries.add(category + " 经济决策 程序");
                }
                
                String policyContent = item.getString("policyContent");
                if (StrUtil.isNotBlank(policyContent)) {
                    if (policyContent.contains("投资")) queries.add("投资项目 决策");
                    if (policyContent.contains("采购")) queries.add("采购项目 决策");
                    if (policyContent.contains("资产")) queries.add("资产处置 决策");
                }
            }
        }
        
        return queries;
    }

    /**
     * 构建法律法规查询
     */
    private List<String> buildRegulationQueries(JSONArray tripleOneData) {
        List<String> queries = new ArrayList<>(Arrays.asList(AuditContent3DecisionConstants.GLOBAL_REGULATION_QUERIES));
        
        // 提取分类信息
        Set<String> categories = new HashSet<>();
        for (int i = 0; i < tripleOneData.size(); i++) {
            JSONObject item = tripleOneData.getJSONObject(i);
            if (item != null) {
                String category = item.getString("category");
                if (StrUtil.isNotBlank(category)) {
                    categories.add(category);
                }
            }
        }
        
        // 添加分类相关查询
        for (String category : categories) {
            queries.add(category + " 法律法规");
        }
        
        return queries;
    }

    /**
     * 构建审计案例查询
     */
    private List<String> buildAuditCaseQueries(JSONArray tripleOneData) {
        List<String> queries = new ArrayList<>(Arrays.asList(AuditContent3DecisionConstants.GLOBAL_AUDIT_CASE_QUERIES));
        
        // 提取分类信息
        Set<String> categories = new HashSet<>();
        for (int i = 0; i < tripleOneData.size(); i++) {
            JSONObject item = tripleOneData.getJSONObject(i);
            if (item != null) {
                String category = item.getString("category");
                if (StrUtil.isNotBlank(category)) {
                    categories.add(category);
                }
            }
        }
        
        // 添加分类相关查询
        for (String category : categories) {
            queries.add(category + " 审计案例");
        }
        
        return queries;
    }

    /**
     * 构建知识上下文
     */
    private String buildKnowledgeContext(JSONArray tripleOneData, Map<String, List<String>> knowledgeSources,
                                       String history, String suggestion) {
        StringBuilder context = new StringBuilder();
        
        // 1. 核心指令
        context.append("## 核心生成指令\n");
        context.append("请基于三重一大制度对比分析数据生成重大经济决策调查表。\n\n");
        context.append(AuditContent3DecisionConstants.AUDIT_FOCUS_AND_METHODS).append("\n\n");
        
        // 2. 三重一大数据
        context.append("## 三重一大制度对比分析数据\n");
        for (int i = 0; i < tripleOneData.size(); i++) {
            JSONObject item = tripleOneData.getJSONObject(i);
            if (item != null) {
                context.append("### 三重一大事项 ").append(i + 1).append("\n");
                context.append(JSONObject.toJSONString(item, true)).append("\n\n");
            }
        }
        
        // 3. 知识库内容
        context.append("## 相关知识库内容\n");
        
        if (!knowledgeSources.get("enterprise").isEmpty()) {
            context.append("### 企业单位知识\n");
            knowledgeSources.get("enterprise").forEach(knowledge -> 
                context.append("- ").append(knowledge).append("\n"));
        }
        
        if (!knowledgeSources.get("regulation").isEmpty()) {
            context.append("### 法律法规知识\n");
            knowledgeSources.get("regulation").forEach(knowledge -> 
                context.append("- ").append(knowledge).append("\n"));
        }
        
        if (!knowledgeSources.get("auditCase").isEmpty()) {
            context.append("### 审计案例知识\n");
            knowledgeSources.get("auditCase").forEach(knowledge -> 
                context.append("- ").append(knowledge).append("\n"));
        }
        
        // 4. 历史内容和用户建议
        if (StrUtil.isNotBlank(history)) {
            context.append("## 历史生成内容\n").append(history).append("\n");
        }
        
        if (StrUtil.isNotBlank(suggestion)) {
            context.append("## 用户优化建议\n").append(suggestion).append("\n");
        }

        context.append("\n\n重要要求：\n");
        context.append("1. 除了本次说明中提供的数据知识等依据，不能从其他地方读取数据，不能凭空捏造数据\n");
        
        return context.toString();
    }

    /**
     * 解析三重一大数据
     */
    private JSONArray parseTripleOneData(Object data) {
        if (data == null) {
            return null;
        }
        
        try {
            JSONArray tripleData;
            if (data instanceof JSONArray) {
                tripleData = (JSONArray) data;
            } else if (data instanceof List) {
                tripleData = JSONArray.parseArray(JSONObject.toJSONString(data));
            } else {
                JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(data));
                if (jsonObject.containsKey("data") && jsonObject.get("data") instanceof JSONArray) {
                    tripleData = jsonObject.getJSONArray("data");
                } else {
                    tripleData = new JSONArray();
                    tripleData.add(jsonObject);
                }
            }
            
            log.info("解析三重一大数据成功，条数: {}", tripleData.size());
            return tripleData;
            
        } catch (Exception e) {
            log.error("解析三重一大数据失败", e);
            return null;
        }
    }
}