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.exception.ServiceException;
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.AiRatingRecord;
import org.dromara.ai.domain.bo.AiRatingRecordBo;
import org.dromara.ai.domain.vo.AiRatingRecordVo;
import org.dromara.ai.mapper.AiRatingRecordMapper;
import org.dromara.ai.service.AiRatingRecordService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * AI评价记录Service业务层处理
 *
 * @author pengles
 */
@RequiredArgsConstructor
@Service
public class AiRatingRecordServiceImpl implements AiRatingRecordService {

    private final AiRatingRecordMapper baseMapper;

    /**
     * 查询AI评价记录
     */
    @Override
    public AiRatingRecordVo queryById(Long id) {
        AiRatingRecordVo vo = baseMapper.selectVoById(id);
        if (vo != null) {
            // 转换匿名字段
            vo.setAnonymousStr(vo.getAnonymous() != null && vo.getAnonymous() == 1 ? "是" : "否");
        }
        return vo;
    }

    /**
     * 查询AI评价记录列表
     */
    @Override
    public TableDataInfo<AiRatingRecordVo> queryPageList(AiRatingRecordBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<AiRatingRecord> lqw = buildQueryWrapper(bo);
        Page<AiRatingRecordVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        // 转换匿名字段
        result.getRecords().forEach(vo -> {
            vo.setAnonymousStr(vo.getAnonymous() != null && vo.getAnonymous() == 1 ? "是" : "否");
        });
        return TableDataInfo.build(result);
    }

    /**
     * 查询AI评价记录列表
     */
    @Override
    public List<AiRatingRecordVo> queryList(AiRatingRecordBo bo) {
        LambdaQueryWrapper<AiRatingRecord> lqw = buildQueryWrapper(bo);
        List<AiRatingRecordVo> list = baseMapper.selectVoList(lqw);
        // 转换匿名字段
        list.forEach(vo -> {
            vo.setAnonymousStr(vo.getAnonymous() != null && vo.getAnonymous() == 1 ? "是" : "否");
        });
        return list;
    }

    /**
     * 构建查询条件
     */
    private LambdaQueryWrapper<AiRatingRecord> buildQueryWrapper(AiRatingRecordBo bo) {
        LambdaQueryWrapper<AiRatingRecord> lqw = new LambdaQueryWrapper<>();
        lqw.eq(StringUtils.isNotBlank(bo.getMessageId()), AiRatingRecord::getMessageId, bo.getMessageId());
        lqw.eq(bo.getUserId() != null, AiRatingRecord::getUserId, bo.getUserId());
        lqw.like(StringUtils.isNotBlank(bo.getProviderName()), AiRatingRecord::getProviderName, bo.getProviderName());
        lqw.eq(bo.getRating() != null, AiRatingRecord::getRating, bo.getRating());
        lqw.like(StringUtils.isNotBlank(bo.getDimension()), AiRatingRecord::getDimension, bo.getDimension());
        lqw.eq(bo.getAnonymous() != null, AiRatingRecord::getAnonymous, bo.getAnonymous());
        // 时间范围查询
        lqw.ge(bo.getCreateTimeStart() != null, AiRatingRecord::getCreateTime, bo.getCreateTimeStart());
        lqw.le(bo.getCreateTimeEnd() != null, AiRatingRecord::getCreateTime, bo.getCreateTimeEnd());
        // 按创建时间倒序
        lqw.orderByDesc(AiRatingRecord::getCreateTime);
        return lqw;
    }

    /**
     * 新增AI评价记录
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertByBo(AiRatingRecordBo bo) {
        AiRatingRecord add = MapstructUtils.convert(bo, AiRatingRecord.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(AiRatingRecord entity) {
        // 评分必须在1-5之间
        if (entity.getRating() != null && (entity.getRating() < 1 || entity.getRating() > 5)) {
            throw new ServiceException("评分必须在1-5之间");
        }
        // 检查是否已存在相同messageId和userId的评价记录
        if (entity.getMessageId() != null && entity.getUserId() != null) {
            LambdaQueryWrapper<AiRatingRecord> lqw = new LambdaQueryWrapper<>();
            lqw.eq(AiRatingRecord::getMessageId, entity.getMessageId());
            lqw.eq(AiRatingRecord::getUserId, entity.getUserId());
            if (entity.getId() != null) {
                lqw.ne(AiRatingRecord::getId, entity.getId());
            }
            Long count = baseMapper.selectCount(lqw);
            if (count > 0) {
                throw new ServiceException("该消息已评价，不能重复评价");
            }
        }
    }

    /**
     * 批量删除AI评价记录
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            // 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    /**
     * 根据消息ID查询评价记录
     */
    @Override
    public AiRatingRecordVo queryByMessageId(String messageId, Long userId) {
        LambdaQueryWrapper<AiRatingRecord> lqw = new LambdaQueryWrapper<>();
        lqw.eq(StringUtils.isNotBlank(messageId), AiRatingRecord::getMessageId, messageId);
        lqw.eq(userId != null, AiRatingRecord::getUserId, userId);
        AiRatingRecord record = baseMapper.selectOne(lqw);
        if (record != null) {
            AiRatingRecordVo vo = MapstructUtils.convert(record, AiRatingRecordVo.class);
            vo.setAnonymousStr(vo.getAnonymous() != null && vo.getAnonymous() == 1 ? "是" : "否");
            return vo;
        }
        return null;
    }

    /**
     * 获取平均评分
     */
    @Override
    public Double getAverageRating(String providerName) {
        LambdaQueryWrapper<AiRatingRecord> lqw = new LambdaQueryWrapper<>();
        lqw.eq(StringUtils.isNotBlank(providerName), AiRatingRecord::getProviderName, providerName);
        List<AiRatingRecord> list = baseMapper.selectList(lqw);
        if (list.isEmpty()) {
            return 0.0;
        }
        double sum = list.stream().mapToInt(AiRatingRecord::getRating).sum();
        return sum / list.size();
    }

}
