package cn.qinys.platform.mobile.service.impl;

import cn.qinys.platform.base.security.utils.CurrentUtils;
import cn.qinys.platform.entity.wishing.ChatMessage;
import cn.qinys.platform.mobile.constants.MsgTypeEnum;
import cn.qinys.platform.mobile.mapper.ChatMessageMapper;
import cn.qinys.platform.mobile.req.ChatHistoryReq;
import cn.qinys.platform.mobile.req.ChatReq;
import cn.qinys.platform.mobile.resp.ChatHistoryResp;
import cn.qinys.platform.mobile.service.ChatService;
import cn.qinys.platform.mobile.tool.DateTimeTools;
import cn.qinys.platform.mobile.tool.WeatherTools;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;

import org.springframework.stereotype.Service;

@Slf4j
@Service
public class ChatServiceImpl implements ChatService {

    @Resource
    private ChatClient chatClient;

    @Resource
    private ChatMessageMapper chatMessageMapper;


    @Override
    public String chat(ChatReq req) {
        String userId = getUserId();
        if (!"0".equals(userId)) {
            req.setConversationId(userId);
        }
        // 保存用户消息
        saveMessage(userId, req.getTreeId(), "user", req.getMessage(), MsgTypeEnum.TEXT.getValue());
        String reply;
        try {
            reply = chatClient.prompt()
                    .user(req.getMessage())
                    .tools(new DateTimeTools(), new WeatherTools(req.getTreeId()))
                    .advisors(a -> a.param("chat_memory_conversation_id", req.getConversationId()))
                    .call()
                    .content();
        } catch (Exception e) {
            log.error("AI chat error", e);
            reply = "抱歉，我暂时无法回复，请稍后再试～";
        }

        // 保存 AI 回复
        saveMessage(userId, req.getTreeId(), "ai", reply, MsgTypeEnum.TEXT.getValue());

        return reply;
    }

    // ...existing code...

    @Override
    public Page<ChatHistoryResp> getHistory(ChatHistoryReq req) {
        String userId = getUserId();
        if ("0".equals(userId)) {
            return new Page<>(0, 0);
        }
        Page<ChatMessage> page = new Page<>(req.getPage(), req.getPageSize());
        QueryWrapper<ChatMessage> wrapper = new QueryWrapper<>();
        wrapper.eq("tree_id", req.getTreeId());
        wrapper.eq("user_id", userId);
        wrapper.orderByDesc("created_at");
        return chatMessageMapper.getChatHistoryPage(page, wrapper);
    }

    private void saveMessage(String userId, Integer treeId, String role, String content, String type) {
        ChatMessage msg = new ChatMessage();
        msg.setUserId(userId);
        msg.setTreeId(treeId);
        msg.setRole(role);
        msg.setContent(content);
        msg.setType(type);
        chatMessageMapper.insert(msg);
    }

    private String getUserId() {
        return CurrentUtils.getCurrentUserId();
    }
}
