package org.dromara.ai.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
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.dromara.ai.domain.AiChatRecord;
import org.dromara.ai.domain.bo.AiChatRecordBo;
import org.dromara.ai.domain.vo.AiChatRecordVo;
import org.dromara.ai.mapper.AiChatRecordMapper;
import org.dromara.ai.service.AiChatRecordService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * AI聊天记录Service业务层处理
 *
 * @author pengles
 */
@RequiredArgsConstructor
@Service
public class AiChatRecordServiceImpl implements AiChatRecordService {

    private final AiChatRecordMapper baseMapper;

    /**
     * 查询AI聊天记录
     */
    @Override
    public AiChatRecordVo queryById(Long id) {
        AiChatRecordVo vo = baseMapper.selectVoById(id);
        if (vo != null) {
            // 转换流式字段
            vo.setIsStreamStr(vo.getIsStream() != null && vo.getIsStream() == 1 ? "是" : "否");
        }
        return vo;
    }

    /**
     * 查询AI聊天记录列表
     */
    @Override
    public TableDataInfo<AiChatRecordVo> queryPageList(AiChatRecordBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<AiChatRecord> lqw = buildQueryWrapper(bo);
        Page<AiChatRecordVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        // 转换流式字段
        result.getRecords().forEach(vo -> {
            vo.setIsStreamStr(vo.getIsStream() != null && vo.getIsStream() == 1 ? "是" : "否");
        });
        return TableDataInfo.build(result);
    }

    /**
     * 查询AI聊天记录列表
     */
    @Override
    public List<AiChatRecordVo> queryList(AiChatRecordBo bo) {
        LambdaQueryWrapper<AiChatRecord> lqw = buildQueryWrapper(bo);
        List<AiChatRecordVo> list = baseMapper.selectVoList(lqw);
        // 转换流式字段
        list.forEach(vo -> {
            vo.setIsStreamStr(vo.getIsStream() != null && vo.getIsStream() == 1 ? "是" : "否");
        });
        return list;
    }

    /**
     * 构建查询条件
     */
    private LambdaQueryWrapper<AiChatRecord> buildQueryWrapper(AiChatRecordBo bo) {
        LambdaQueryWrapper<AiChatRecord> lqw = new LambdaQueryWrapper<>();
        lqw.eq(StringUtils.isNotBlank(bo.getSessionId()), AiChatRecord::getSessionId, bo.getSessionId());
        lqw.eq(bo.getUserId() != null, AiChatRecord::getUserId, bo.getUserId());
        lqw.like(StringUtils.isNotBlank(bo.getProviderName()), AiChatRecord::getProviderName, bo.getProviderName());
        lqw.like(StringUtils.isNotBlank(bo.getModelName()), AiChatRecord::getModelName, bo.getModelName());
        lqw.eq(StringUtils.isNotBlank(bo.getMessageType()), AiChatRecord::getMessageType, bo.getMessageType());
        // 内容搜索（模糊查询）
        lqw.like(StringUtils.isNotBlank(bo.getContent()), AiChatRecord::getContent, bo.getContent());
        lqw.eq(bo.getIsStream() != null, AiChatRecord::getIsStream, bo.getIsStream());
        // 时间范围查询
        lqw.ge(bo.getCreateTimeStart() != null, AiChatRecord::getCreateTime, bo.getCreateTimeStart());
        lqw.le(bo.getCreateTimeEnd() != null, AiChatRecord::getCreateTime, bo.getCreateTimeEnd());
        // 按创建时间倒序
        lqw.orderByDesc(AiChatRecord::getCreateTime);
        return lqw;
    }

    /**
     * 新增AI聊天记录
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertByBo(AiChatRecordBo bo) {
        AiChatRecord add = MapstructUtils.convert(bo, AiChatRecord.class);
        // 设置默认值
        if (add.getIsStream() == null) {
            add.setIsStream(0);
        }
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 批量新增AI聊天记录
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertBatch(List<AiChatRecordBo> boList) {
        if (boList == null || boList.isEmpty()) {
            return true;
        }
        List<AiChatRecord> recordList = boList.stream()
                .map(bo -> {
                    AiChatRecord record = MapstructUtils.convert(bo, AiChatRecord.class);
                    if (record.getIsStream() == null) {
                        record.setIsStream(0);
                    }
                    return record;
                })
                .collect(Collectors.toList());
        return baseMapper.insertBatch(recordList);
    }

    /**
     * 批量删除AI聊天记录信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        return baseMapper.deleteByIds(ids) > 0;
    }

    /**
     * 归档聊天记录（删除指定日期之前的记录）
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer archiveChatRecords(java.util.Date beforeDate) {
        if (beforeDate == null) {
            return 0;
        }
        LambdaQueryWrapper<AiChatRecord> lqw = new LambdaQueryWrapper<>();
        lqw.lt(AiChatRecord::getCreateTime, beforeDate);
        return baseMapper.delete(lqw);
    }

}
