package org.dromara.chat.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.dromara.chat.domain.ChatMessage;
import org.dromara.chat.domain.bo.ChatMessageBo;
import org.dromara.chat.domain.vo.ChatMessageVo;
import org.dromara.chat.mapper.ChatMessageMapper;
import org.dromara.chat.service.ChatMessageService;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.springframework.stereotype.Service;

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

/**
 * 聊天消息Service业务层处理
 *
 * @author pengles
 */
@RequiredArgsConstructor
@Service
public class ChatMessageServiceImpl extends ServiceImpl<ChatMessageMapper, ChatMessage> implements ChatMessageService {

    /**
     * 查询聊天消息
     */
    @Override
    public ChatMessageVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询聊天消息列表
     */
    @Override
    public TableDataInfo<ChatMessageVo> queryPageList(ChatMessageBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<ChatMessage> lqw = buildQueryWrapper(bo);
        Page<ChatMessageVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询聊天消息列表
     */
    @Override
    public List<ChatMessageVo> queryList(ChatMessageBo bo) {
        LambdaQueryWrapper<ChatMessage> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<ChatMessage> buildQueryWrapper(ChatMessageBo bo) {
        LambdaQueryWrapper<ChatMessage> lqw = Wrappers.lambdaQuery();
        lqw.eq(ObjectUtil.isNotNull(bo.getSessionId()), ChatMessage::getSessionId, bo.getSessionId());
        lqw.eq(ObjectUtil.isNotNull(bo.getUserId()), ChatMessage::getUserId, bo.getUserId());
        lqw.like(StringUtils.isNotBlank(bo.getContent()), ChatMessage::getContent, bo.getContent());
        lqw.eq(StringUtils.isNotBlank(bo.getRole()), ChatMessage::getRole, bo.getRole());
        lqw.eq(StringUtils.isNotBlank(bo.getModelName()), ChatMessage::getModelName, bo.getModelName());
        lqw.orderByDesc(ChatMessage::getCreateTime);
        return lqw;
    }

    /**
     * 新增聊天消息
     */
    @Override
    public Boolean insertByBo(ChatMessageBo bo) {
        ChatMessage add = MapstructUtils.convert(bo, ChatMessage.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改聊天消息
     */
    @Override
    public Boolean updateByBo(ChatMessageBo bo) {
        ChatMessage update = MapstructUtils.convert(bo, ChatMessage.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(ChatMessage entity) {
        if (StringUtils.isBlank(entity.getContent())) {
            throw new IllegalArgumentException("消息内容不能为空");
        }
        if (StringUtils.isBlank(entity.getRole())) {
            entity.setRole("user");
        }
    }

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

    /**
     * 根据会话ID查询消息列表
     */
    @Override
    public List<ChatMessageVo> queryListBySessionId(Long sessionId) {
        LambdaQueryWrapper<ChatMessage> lqw = Wrappers.lambdaQuery();
        lqw.eq(ChatMessage::getSessionId, sessionId);
        lqw.orderByAsc(ChatMessage::getCreateTime);
        return baseMapper.selectVoList(lqw);
    }

    /**
     * 根据用户ID查询消息列表
     */
    @Override
    public List<ChatMessageVo> queryListByUserId(Long userId) {
        LambdaQueryWrapper<ChatMessage> lqw = Wrappers.lambdaQuery();
        lqw.eq(ChatMessage::getUserId, userId);
        lqw.orderByDesc(ChatMessage::getCreateTime);
        return baseMapper.selectVoList(lqw);
    }

    /**
     * 根据会话ID和用户ID查询消息列表
     */
    @Override
    public List<ChatMessageVo> queryListBySessionIdAndUserId(Long sessionId, Long userId) {
        LambdaQueryWrapper<ChatMessage> lqw = Wrappers.lambdaQuery();
        lqw.eq(ChatMessage::getSessionId, sessionId);
        lqw.eq(ChatMessage::getUserId, userId);
        lqw.orderByAsc(ChatMessage::getCreateTime);
        return baseMapper.selectVoList(lqw);
    }

}