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.ChatSession;
import org.dromara.chat.domain.bo.ChatSessionBo;
import org.dromara.chat.domain.vo.ChatSessionVo;
import org.dromara.chat.mapper.ChatMessageMapper;
import org.dromara.chat.mapper.ChatSessionMapper;
import org.dromara.chat.service.ChatSessionService;
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 org.springframework.transaction.annotation.Transactional;

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

/**
 * 聊天会话Service业务层处理
 *
 * @author pengles
 */
@RequiredArgsConstructor
@Service
public class ChatSessionServiceImpl extends ServiceImpl<ChatSessionMapper, ChatSession> implements ChatSessionService {

    private final ChatMessageMapper chatMessageMapper;

    /**
     * 查询聊天会话
     */
    @Override
    public ChatSessionVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询聊天会话列表
     */
    @Override
    public TableDataInfo<ChatSessionVo> queryPageList(ChatSessionBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<ChatSession> lqw = buildQueryWrapper(bo);
        Page<ChatSessionVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询聊天会话列表
     */
    @Override
    public List<ChatSessionVo> queryList(ChatSessionBo bo) {
        LambdaQueryWrapper<ChatSession> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<ChatSession> buildQueryWrapper(ChatSessionBo bo) {
        LambdaQueryWrapper<ChatSession> lqw = Wrappers.lambdaQuery();
        lqw.eq(ObjectUtil.isNotNull(bo.getUserId()), ChatSession::getUserId, bo.getUserId());
        lqw.like(StringUtils.isNotBlank(bo.getSessionTitle()), ChatSession::getSessionTitle, bo.getSessionTitle());
        lqw.orderByDesc(ChatSession::getUpdateTime);
        return lqw;
    }

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

    /**
     * 修改聊天会话
     */
    @Override
    public Boolean updateByBo(ChatSessionBo bo) {
        ChatSession update = MapstructUtils.convert(bo, ChatSession.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(ChatSession entity) {
        if (StringUtils.isBlank(entity.getSessionTitle())) {
            entity.setSessionTitle("新会话");
        }
        if (entity.getSessionTitle().length() > 50) {
            entity.setSessionTitle(entity.getSessionTitle().substring(0, 50));
        }
    }

    /**
     * 校验并批量删除聊天会话
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            // 删除关联的消息
            LambdaQueryWrapper<ChatMessage> lqw = Wrappers.lambdaQuery();
            lqw.in(ChatMessage::getSessionId, ids);
            chatMessageMapper.delete(lqw);
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    /**
     * 根据用户ID查询会话列表
     */
    @Override
    public List<ChatSessionVo> queryListByUserId(Long userId) {
        LambdaQueryWrapper<ChatSession> lqw = Wrappers.lambdaQuery();
        lqw.eq(ChatSession::getUserId, userId);
        lqw.orderByDesc(ChatSession::getUpdateTime);
        return baseMapper.selectVoList(lqw);
    }

    /**
     * 创建新会话
     */
    @Override
    public ChatSessionVo createNewSession(Long userId, String sessionTitle) {
        ChatSession session = new ChatSession();
        session.setUserId(userId);
        session.setSessionTitle(sessionTitle);
        baseMapper.insert(session);
        return baseMapper.selectVoById(session.getId());
    }

    /**
     * 更新会话标题
     */
    @Override
    public Boolean updateSessionTitle(Long sessionId, String sessionTitle) {
        ChatSession session = new ChatSession();
        session.setId(sessionId);
        session.setSessionTitle(sessionTitle);
        return baseMapper.updateById(session) > 0;
    }

}