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.ChatUsageToken;
import org.dromara.chat.domain.bo.ChatUsageTokenBo;
import org.dromara.chat.domain.vo.ChatUsageTokenVo;
import org.dromara.chat.mapper.ChatUsageTokenMapper;
import org.dromara.chat.service.ChatUsageTokenService;
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;

/**
 * 聊天Token使用记录Service业务层处理
 *
 * @author pengles
 */
@RequiredArgsConstructor
@Service
public class ChatUsageTokenServiceImpl extends ServiceImpl<ChatUsageTokenMapper, ChatUsageToken> implements ChatUsageTokenService {

    /**
     * 查询聊天Token使用记录
     */
    @Override
    public ChatUsageTokenVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询聊天Token使用记录列表
     */
    @Override
    public TableDataInfo<ChatUsageTokenVo> queryPageList(ChatUsageTokenBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<ChatUsageToken> lqw = buildQueryWrapper(bo);
        Page<ChatUsageTokenVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询聊天Token使用记录列表
     */
    @Override
    public List<ChatUsageTokenVo> queryList(ChatUsageTokenBo bo) {
        LambdaQueryWrapper<ChatUsageToken> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<ChatUsageToken> buildQueryWrapper(ChatUsageTokenBo bo) {
        LambdaQueryWrapper<ChatUsageToken> lqw = Wrappers.lambdaQuery();
        lqw.eq(ObjectUtil.isNotNull(bo.getUserId()), ChatUsageToken::getUserId, bo.getUserId());
        lqw.eq(StringUtils.isNotBlank(bo.getModelName()), ChatUsageToken::getModelName, bo.getModelName());
        return lqw;
    }

    /**
     * 新增聊天Token使用记录
     */
    @Override
    public Boolean insertByBo(ChatUsageTokenBo bo) {
        ChatUsageToken add = MapstructUtils.convert(bo, ChatUsageToken.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改聊天Token使用记录
     */
    @Override
    public Boolean updateByBo(ChatUsageTokenBo bo) {
        ChatUsageToken update = MapstructUtils.convert(bo, ChatUsageToken.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

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

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

    /**
     * 根据用户ID查询Token使用记录列表
     */
    @Override
    public List<ChatUsageTokenVo> queryListByUserId(Long userId) {
        LambdaQueryWrapper<ChatUsageToken> lqw = Wrappers.lambdaQuery();
        lqw.eq(ChatUsageToken::getUserId, userId);
        return baseMapper.selectVoList(lqw);
    }

    /**
     * 根据模型名称查询Token使用记录列表
     */
    @Override
    public List<ChatUsageTokenVo> queryListByModelName(String modelName) {
        LambdaQueryWrapper<ChatUsageToken> lqw = Wrappers.lambdaQuery();
        lqw.eq(ChatUsageToken::getModelName, modelName);
        return baseMapper.selectVoList(lqw);
    }

    /**
     * 统计用户总Token使用量
     */
    @Override
    public Long getTotalTokenByUserId(Long userId) {
        LambdaQueryWrapper<ChatUsageToken> lqw = Wrappers.lambdaQuery();
        lqw.eq(ChatUsageToken::getUserId, userId);
        lqw.select(ChatUsageToken::getToken);
        List<ChatUsageToken> list = baseMapper.selectList(lqw);
        return list.stream().mapToLong(ChatUsageToken::getToken).sum();
    }

    /**
     * 统计模型总Token使用量
     */
    @Override
    public Long getTotalTokenByModelName(String modelName) {
        LambdaQueryWrapper<ChatUsageToken> lqw = Wrappers.lambdaQuery();
        lqw.eq(ChatUsageToken::getModelName, modelName);
        lqw.select(ChatUsageToken::getToken);
        List<ChatUsageToken> list = baseMapper.selectList(lqw);
        return list.stream().mapToLong(ChatUsageToken::getToken).sum();
    }

}