package org.dromara.talk.service.impl;

import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.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 lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.dromara.talk.domain.bo.TalkSessionBo;
import org.dromara.talk.domain.vo.TalkSessionVo;
import org.dromara.talk.domain.TalkSession;
import org.dromara.talk.mapper.TalkSessionMapper;
import org.dromara.talk.service.ITalkSessionService;

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

/**
 * 对话会话Service业务层处理
 *
 * @author Lion Li
 *  2026-01-27
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class TalkSessionServiceImpl implements ITalkSessionService {

    private final TalkSessionMapper baseMapper;

    /**
     * 查询对话会话
     *
     * @param id 主键
     * @return 对话会话
     */
    @Override
    public TalkSessionVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询对话会话列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 对话会话分页列表
     */
    @Override
    public TableDataInfo<TalkSessionVo> queryPageList(TalkSessionBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<TalkSession> lqw = buildQueryWrapper(bo);
        Page<TalkSessionVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的对话会话列表
     *
     * @param bo 查询条件
     * @return 对话会话列表
     */
    @Override
    public List<TalkSessionVo> queryList(TalkSessionBo bo) {
        LambdaQueryWrapper<TalkSession> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<TalkSession> buildQueryWrapper(TalkSessionBo bo) {
        LambdaQueryWrapper<TalkSession> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(TalkSession::getId);
        lqw.eq(StringUtils.isNotBlank(bo.getSessionId()), TalkSession::getSessionId, bo.getSessionId());
        lqw.eq(bo.getAgentId() != null, TalkSession::getAgentId, bo.getAgentId());
        lqw.eq(StringUtils.isNotBlank(bo.getCustomerPhone()), TalkSession::getCustomerPhone, bo.getCustomerPhone());
        lqw.eq(StringUtils.isNotBlank(bo.getConversationJson()), TalkSession::getConversationJson, bo.getConversationJson());
        lqw.eq(bo.getStartTime() != null, TalkSession::getStartTime, bo.getStartTime());
        lqw.eq(bo.getEndTime() != null, TalkSession::getEndTime, bo.getEndTime());
        return lqw;
    }

    /**
     * 新增对话会话
     *
     * @param bo 对话会话
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(TalkSessionBo bo) {
        TalkSession add = MapstructUtils.convert(bo, TalkSession.class);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改对话会话
     *
     * @param bo 对话会话
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(TalkSessionBo bo) {
        TalkSession update = MapstructUtils.convert(bo, TalkSession.class);
        return baseMapper.updateById(update) > 0;
    }


    /**
     * 校验并批量删除对话会话信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        return baseMapper.deleteByIds(ids) > 0;
    }

    /**
     * 根据会话ID查询会话
     *
     * @param sessionId 会话唯一标识
     * @return 对话会话
     */
    @Override
    public TalkSessionVo queryBySessionId(String sessionId) {
        LambdaQueryWrapper<TalkSession> lqw = Wrappers.lambdaQuery();
        lqw.eq(TalkSession::getSessionId, sessionId);
        return baseMapper.selectVoOne(lqw);
    }

    /**
     * 保存或更新对话内容
     *
     * @param sessionId 会话唯一标识
     * @param agentId 客服ID
     * @param conversationJson 对话内容JSON
     * @param customerPhone 客户手机号
     * @param createBy 创建人ID
     * @return 是否成功
     */
    @Override
    public Boolean saveOrUpdateConversation(String sessionId, Long agentId, String conversationJson, String customerPhone, Long createBy) {
        LambdaQueryWrapper<TalkSession> lqw = Wrappers.lambdaQuery();
        lqw.eq(TalkSession::getSessionId, sessionId);
        TalkSession existingSession = baseMapper.selectOne(lqw);

        if (existingSession != null) {
            // 更新现有会话
            existingSession.setConversationJson(conversationJson);
            existingSession.setEndTime(new Date());
            if (customerPhone != null) {
                existingSession.setCustomerPhone(customerPhone);
            }
            return baseMapper.updateById(existingSession) > 0;
        } else {
            log.warn("会话不存在，sessionId: {}，跳过创建新会话", sessionId);
            return false;
        }
    }

    /**
     * 更新会话的sessionId
     * 用于将临时sessionId替换为Dify的conversationId
     *
     * @param oldSessionId 旧的sessionId
     * @param newSessionId 新的sessionId
     * @return 是否成功
     */
    @Override
    public Boolean updateSessionId(String oldSessionId, String newSessionId) {
        LambdaQueryWrapper<TalkSession> lqw = Wrappers.lambdaQuery();
        lqw.eq(TalkSession::getSessionId, oldSessionId);
        TalkSession session = baseMapper.selectOne(lqw);

        if (session != null) {
            session.setSessionId(newSessionId);
            return baseMapper.updateById(session) > 0;
        }
        return false;
    }

    /**
     * 更新会话结束时间
     * 用于挂断电话时更新结束时间
     *
     * @param sessionId 会话唯一标识
     * @return 是否成功
     */
    @Override
    public Boolean updateEndTime(String sessionId) {
        LambdaQueryWrapper<TalkSession> lqw = Wrappers.lambdaQuery();
        lqw.eq(TalkSession::getSessionId, sessionId);
        TalkSession session = baseMapper.selectOne(lqw);

        if (session != null) {
            session.setEndTime(new Date());
            return baseMapper.updateById(session) > 0;
        }
        return false;
    }
}
