package org.xyzh.workcase.service;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;

import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import org.xyzh.api.ai.dto.ChatPrepareData;
import org.xyzh.api.ai.dto.TbChat;
import org.xyzh.api.ai.dto.TbChatMessage;
import org.xyzh.api.ai.service.AgentChatService;
import org.xyzh.api.workcase.dto.TbWordCloudDTO;
import org.xyzh.api.workcase.dto.TbWorkcaseDTO;
import org.xyzh.api.workcase.service.WorkcaseChatService;
import org.xyzh.common.core.domain.ResultDomain;
import org.xyzh.common.core.page.PageDomain;
import org.xyzh.common.core.page.PageParam;
import org.xyzh.common.core.page.PageRequest;
import org.xyzh.common.redis.service.RedisService;
import org.xyzh.common.utils.id.IdUtil;
import org.xyzh.workcase.mapper.TbWordCloudMapper;

@DubboService(version = "1.0.0",group = "workcase",timeout = 30000,retries = 0)
public class WorkcaseChatServiceImpl implements WorkcaseChatService{

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

    private static final String CHAT_COUNT_KEY_PREFIX = "workcase:chat:count:";
    private static final int TRANSFER_HUMAN_THRESHOLD = 3;

    @DubboReference(version = "1.0.0", group = "ai", check = false)
    private AgentChatService agentChatService;

    @Autowired
    private TbWordCloudMapper wordCloudMapper;

    @Autowired
    private RedisService redisService;

    // ========================= 聊天管理 ==========================

    @Override
    public ResultDomain<TbChat> createChat(TbChat chat) {
        logger.info("创建对话: userId={}", chat.getUserId());
        ResultDomain<TbChat> result = agentChatService.createChat(chat);
        if (result.getSuccess() && result.getData() != null) {
            redisService.set(CHAT_COUNT_KEY_PREFIX + result.getData().getChatId(), 0);
        }
        return result;
    }

    @Override
    public ResultDomain<TbChat> updateChat(TbChat chat) {
        logger.info("更新对话: chatId={}", chat.getChatId());
        return agentChatService.updateChat(chat);
    }

    @Override
    public ResultDomain<TbChat> getChatList(TbChat filter) {
        return agentChatService.getChatList(filter);
    }

    // ========================= 聊天信息管理 ======================

    @Override
    public ResultDomain<TbChatMessage> getChatMessageList(TbChat filter) {
        return agentChatService.getChatMessageList(filter);
    }

    @Override
    public ResultDomain<String> prepareChatMessageSession(ChatPrepareData prepareData) {
        logger.info("准备对话会话: chatId={}, query={}", prepareData.getChatId(), prepareData.getQuery());
        
        String chatId = prepareData.getChatId();
        Object countObj = redisService.get(CHAT_COUNT_KEY_PREFIX + chatId);
        int chatCount = (countObj != null) ? (Integer) countObj : 0;
        chatCount++;
        redisService.set(CHAT_COUNT_KEY_PREFIX + chatId, chatCount);
        
        ResultDomain<String> result = agentChatService.prepareChatMessageSession(prepareData);
        
        if (result.getSuccess() && chatCount >= TRANSFER_HUMAN_THRESHOLD) {
            logger.info("已达到{}次AI对话，建议转人工: chatId={}", TRANSFER_HUMAN_THRESHOLD, chatId);
        }
        
        return result;
    }

    @Override
    public SseEmitter streamChatMessageWithSse(String sessionId) {
        return agentChatService.streamChatMessageWithSse(sessionId);
    }

    @Override
    public ResultDomain<Boolean> stopChatMessageByTaskId(TbChat filter, String taskId) {
        return agentChatService.stopChatMessageByTaskId(filter, taskId);
    }

    @Override
    public ResultDomain<Boolean> commentChatMessage(TbChat filter, String messageId, String comment) {
        return agentChatService.commentChatMessage(filter, messageId, comment);
    }

    // =============================== 对话分析 ==========================

    @Override
    public ResultDomain<TbWorkcaseDTO> analyzeChat(String chatId) {
        logger.info("分析对话内容，生成工单预填信息: chatId={}", chatId);
        
        TbChat filter = new TbChat();
        filter.setChatId(chatId);
        ResultDomain<TbChatMessage> msgResult = agentChatService.getChatMessageList(filter);
        
        if (!msgResult.getSuccess() || msgResult.getDataList() == null || msgResult.getDataList().isEmpty()) {
            return ResultDomain.failure("获取对话消息失败或消息为空");
        }
        
        List<TbChatMessage> messages = msgResult.getDataList();
        
        // ============== 伪代码：调用AI分析对话，自动生成工单预填信息 ==============
        // 步骤5：AI根据聊天对话，自动生成部分工单信息，预填入小程序的工单创建表单
        // 
        // 1. 构建对话上下文
        // StringBuilder conversationContext = new StringBuilder();
        // for (TbChatMessage msg : messages) {
        //     conversationContext.append(msg.getRole()).append(": ").append(msg.getContent()).append("\n");
        // }
        // 
        // 2. 调用Dify工作流或Agent进行对话分析
        // DifyWorkflowRequest request = new DifyWorkflowRequest();
        // request.setWorkflowId("workcase-analysis-workflow");
        // request.setInputs(Map.of("conversation", conversationContext.toString()));
        // DifyWorkflowResponse response = difyService.runWorkflow(request);
        // 
        // 3. 解析AI分析结果，提取工单预填信息
        // JSONObject analysisResult = JSON.parseObject(response.getOutputs());
        // TbWorkcaseDTO workcase = new TbWorkcaseDTO();
        // workcase.setType(analysisResult.getString("type"));           // 问题类型：如"设备故障"、"维修申请"
        // workcase.setDevice(analysisResult.getString("device"));       // 设备名称：如"燃气管道"、"电梯"
        // workcase.setDeviceCode(analysisResult.getString("deviceCode")); // 设备编号（如果用户提到）
        // workcase.setEmergency(analysisResult.getString("emergency")); // 紧急程度：normal/urgent/critical
        // workcase.setRemark(analysisResult.getString("description"));  // 问题描述摘要
        // ============== 伪代码结束 ==============
        
        // 模拟AI分析结果（实际应由AI返回）
        TbWorkcaseDTO workcase = new TbWorkcaseDTO();
        workcase.setType("设备故障");
        workcase.setDevice("待用户确认");
        workcase.setDeviceCode("");
        workcase.setEmergency("normal");
        workcase.setRemark("对话ID:" + chatId + " | " + buildConversationSummary(messages));
        
        logger.info("对话分析完成，工单预填信息已生成: chatId={}", chatId);
        return ResultDomain.success("对话分析完成", workcase);
    }
    
    private String buildConversationSummary(List<TbChatMessage> messages) {
        StringBuilder summary = new StringBuilder();
        for (TbChatMessage msg : messages) {
            if ("user".equals(msg.getRole())) {
                summary.append(msg.getContent()).append(" ");
            }
        }
        String result = summary.toString().trim();
        return result.length() > 200 ? result.substring(0, 200) + "..." : result;
    }

    @Override
    public ResultDomain<TbWorkcaseDTO> summaryChat(String chatId) {
        logger.info("总结对话: chatId={}", chatId);
        
        TbChat filter = new TbChat();
        filter.setChatId(chatId);
        ResultDomain<TbChatMessage> msgResult = agentChatService.getChatMessageList(filter);
        
        if (!msgResult.getSuccess() || msgResult.getDataList() == null) {
            return ResultDomain.failure("获取对话消息失败");
        }
        
        List<TbChatMessage> messages = msgResult.getDataList();
        
        // TODO: 调用AI进行对话总结，提取关键词更新词云
        // 伪代码：
        // String summary = aiService.summarize(messages);
        // List<String> keywords = aiService.extractKeywords(messages);
        // updateWordCloud(keywords);
        
        extractAndUpdateWordCloud(messages);
        
        TbWorkcaseDTO summary = new TbWorkcaseDTO();
        logger.info("对话总结完成: chatId={}", chatId);
        return ResultDomain.success("对话总结完成", summary);
    }

    private void extractAndUpdateWordCloud(List<TbChatMessage> messages) {
        // TODO: 调用AI提取关键词
        // 伪代码：List<String> keywords = aiService.extractKeywords(messages);
        
        // 模拟提取的关键词
        String[] mockKeywords = {"故障", "维修", "设备"};
        String today = LocalDate.now().format(DateTimeFormatter.ISO_LOCAL_DATE);
        
        for (String keyword : mockKeywords) {
            TbWordCloudDTO queryFilter = new TbWordCloudDTO();
            queryFilter.setWord(keyword);
            queryFilter.setCategory("fault");
            queryFilter.setStatDate(today);
            TbWordCloudDTO existing = wordCloudMapper.selectWordCloudOne(queryFilter);
            if (existing != null) {
                wordCloudMapper.incrementFrequency(existing.getWordId(), 1);
            } else {
                TbWordCloudDTO wordCloud = new TbWordCloudDTO();
                wordCloud.setWordId(IdUtil.generateUUID());
                wordCloud.setWord(keyword);
                wordCloud.setCategory("fault");
                wordCloud.setStatDate(today);
                wordCloud.setFrequency("1");
                wordCloudMapper.insertWordCloud(wordCloud);
            }
        }
    }

    // =============================== 词云管理 ==========================

    @Override
    public ResultDomain<TbWordCloudDTO> addWordCloud(TbWordCloudDTO wordCloud) {
        logger.info("添加词云: word={}", wordCloud.getWord());
        
        if (wordCloud.getWordId() == null || wordCloud.getWordId().isEmpty()) {
            wordCloud.setWordId(IdUtil.generateUUID());
        }
        if (wordCloud.getStatDate() == null || wordCloud.getStatDate().isEmpty()) {
            wordCloud.setStatDate(LocalDate.now().format(DateTimeFormatter.ISO_LOCAL_DATE));
        }
        if (wordCloud.getFrequency() == null) {
            wordCloud.setFrequency("1");
        }
        
        TbWordCloudDTO queryFilter = new TbWordCloudDTO();
        queryFilter.setWord(wordCloud.getWord());
        queryFilter.setCategory(wordCloud.getCategory());
        queryFilter.setStatDate(wordCloud.getStatDate());
        TbWordCloudDTO existing = wordCloudMapper.selectWordCloudOne(queryFilter);
        
        if (existing != null) {
            wordCloudMapper.incrementFrequency(existing.getWordId(), Integer.parseInt(wordCloud.getFrequency()));
            TbWordCloudDTO updated = wordCloudMapper.selectWordCloudById(existing.getWordId());
            return ResultDomain.success("词频更新成功", updated);
        }
        
        int rows = wordCloudMapper.insertWordCloud(wordCloud);
        if (rows > 0) {
            return ResultDomain.success("添加成功", wordCloud);
        }
        return ResultDomain.failure("添加失败");
    }

    @Override
    public ResultDomain<TbWordCloudDTO> updateWordCloud(TbWordCloudDTO wordCloud) {
        logger.info("更新词云: wordId={}", wordCloud.getWordId());
        
        int rows = wordCloudMapper.updateWordCloud(wordCloud);
        if (rows > 0) {
            TbWordCloudDTO updated = wordCloudMapper.selectWordCloudById(wordCloud.getWordId());
            return ResultDomain.success("更新成功", updated);
        }
        return ResultDomain.failure("更新失败");
    }

    @Override
    public ResultDomain<TbWordCloudDTO> getWordCloudList(TbWordCloudDTO filter) {
        List<TbWordCloudDTO> list = wordCloudMapper.selectWordCloudList(filter);
        return ResultDomain.success("查询成功", list);
    }

    @Override
    public ResultDomain<TbWordCloudDTO> getWordCloudPage(PageRequest<TbWordCloudDTO> pageRequest) {
        TbWordCloudDTO filter = pageRequest.getFilter();
        PageParam pageParam = pageRequest.getPageParam();
        
        List<TbWordCloudDTO> list = wordCloudMapper.selectWordCloudPage(filter, pageParam);
        long total = wordCloudMapper.countWordClouds(filter);
        
        pageParam.setTotal((int) total);
        PageDomain<TbWordCloudDTO> pageDomain = new PageDomain<>(pageParam, list);
        return ResultDomain.success("查询成功", pageDomain);
    }

}
