package com.ruoyi.oa.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.ruoyi.oa.domain.bo.SysOaAiMessageBo;
import com.ruoyi.oa.domain.vo.SysOaAiMessageVo;
import com.ruoyi.oa.domain.SysOaAiMessage;
import com.ruoyi.oa.mapper.SysOaAiMessageMapper;
import com.ruoyi.oa.service.ISysOaAiMessageService;

import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * AI对话详情Service业务层处理
 *
 * @author ruoyi
 * @date 2024-12-19
 */
@RequiredArgsConstructor
@Service
public class SysOaAiMessageServiceImpl implements ISysOaAiMessageService {

    private final SysOaAiMessageMapper baseMapper;

    /**
     * 查询AI对话详情
     */
    @Override
    public SysOaAiMessageVo queryById(Long messageId) {
        return baseMapper.selectVoById(messageId);
    }

    /**
     * 查询AI对话详情列表
     */
    @Override
    public TableDataInfo<SysOaAiMessageVo> queryPageList(SysOaAiMessageBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<SysOaAiMessage> lqw = buildQueryWrapper(bo);
        Page<SysOaAiMessageVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询AI对话详情列表
     */
    @Override
    public List<SysOaAiMessageVo> queryList(SysOaAiMessageBo bo) {
        LambdaQueryWrapper<SysOaAiMessage> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<SysOaAiMessage> buildQueryWrapper(SysOaAiMessageBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<SysOaAiMessage> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getConversationId() != null, SysOaAiMessage::getConversationId, bo.getConversationId());
        lqw.eq(StringUtils.isNotBlank(bo.getRole()), SysOaAiMessage::getRole, bo.getRole());
        lqw.like(StringUtils.isNotBlank(bo.getContent()), SysOaAiMessage::getContent, bo.getContent());
        lqw.eq(bo.getTokens() != null, SysOaAiMessage::getTokens, bo.getTokens());
        lqw.eq(bo.getCost() != null, SysOaAiMessage::getCost, bo.getCost());
        lqw.eq(bo.getMessageOrder() != null, SysOaAiMessage::getMessageOrder, bo.getMessageOrder());
        return lqw;
    }

    /**
     * 新增AI对话详情
     */
    @Override
    public Boolean insertByBo(SysOaAiMessageBo bo) {
        SysOaAiMessage add = BeanUtil.toBean(bo, SysOaAiMessage.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setMessageId(add.getMessageId());
        }
        return flag;
    }

    /**
     * 修改AI对话详情
     */
    @Override
    public Boolean updateByBo(SysOaAiMessageBo bo) {
        SysOaAiMessage update = BeanUtil.toBean(bo, SysOaAiMessage.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(SysOaAiMessage entity) {
        // TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除AI对话详情
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            // TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    /**
     * 根据对话ID查询消息列表
     */
    @Override
    public List<SysOaAiMessageVo> queryByConversationId(Long conversationId) {
        return baseMapper.selectMessagesByConversationId(conversationId);
    }

    /**
     * 添加用户消息
     */
    @Override
    public Boolean addUserMessage(Long conversationId, String content) {
        SysOaAiMessage message = new SysOaAiMessage();
        message.setConversationId(conversationId);
        message.setRole("user");
        message.setContent(content);
        message.setTokens(0);
        message.setCost(java.math.BigDecimal.ZERO);
        
        // 获取当前消息顺序
        LambdaQueryWrapper<SysOaAiMessage> lqw = Wrappers.lambdaQuery();
        lqw.eq(SysOaAiMessage::getConversationId, conversationId);
        lqw.orderByDesc(SysOaAiMessage::getMessageOrder);
        lqw.last("LIMIT 1");
        SysOaAiMessage lastMessage = baseMapper.selectOne(lqw);
        int nextOrder = (lastMessage != null && lastMessage.getMessageOrder() != null) ? 
            lastMessage.getMessageOrder() + 1 : 1;
        message.setMessageOrder(nextOrder);
        
        return baseMapper.insert(message) > 0;
    }

    /**
     * 添加AI回复消息
     */
    @Override
    public Boolean addAiMessage(Long conversationId, String content, Integer tokens, java.math.BigDecimal cost) {
        SysOaAiMessage message = new SysOaAiMessage();
        message.setConversationId(conversationId);
        message.setRole("assistant");
        message.setContent(content);
        message.setTokens(tokens != null ? tokens : 0);
        message.setCost(cost != null ? cost : java.math.BigDecimal.ZERO);
        
        // 获取当前消息顺序
        LambdaQueryWrapper<SysOaAiMessage> lqw = Wrappers.lambdaQuery();
        lqw.eq(SysOaAiMessage::getConversationId, conversationId);
        lqw.orderByDesc(SysOaAiMessage::getMessageOrder);
        lqw.last("LIMIT 1");
        SysOaAiMessage lastMessage = baseMapper.selectOne(lqw);
        int nextOrder = (lastMessage != null && lastMessage.getMessageOrder() != null) ? 
            lastMessage.getMessageOrder() + 1 : 1;
        message.setMessageOrder(nextOrder);
        
        return baseMapper.insert(message) > 0;
    }
} 