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.AiPaintingFavorite;
import org.dromara.ai.domain.bo.AiPaintingFavoriteBo;
import org.dromara.ai.domain.vo.AiPaintingFavoriteVo;
import org.dromara.ai.domain.vo.AiPaintingRecordVo;
import org.dromara.ai.mapper.AiPaintingFavoriteMapper;
import org.dromara.ai.service.AiPaintingFavoriteService;
import org.dromara.ai.service.AiPaintingRecordService;
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 AiPaintingFavoriteServiceImpl implements AiPaintingFavoriteService {

    private final AiPaintingFavoriteMapper baseMapper;
    private final AiPaintingRecordService paintingRecordService;

    /**
     * 查询AI绘画作品收藏
     */
    @Override
    public AiPaintingFavoriteVo queryById(Long id) {
        AiPaintingFavoriteVo vo = baseMapper.selectVoById(id);
        if (vo != null) {
            enrichPaintingRecord(vo);
        }
        return vo;
    }

    /**
     * 查询AI绘画作品收藏列表
     */
    @Override
    public TableDataInfo<AiPaintingFavoriteVo> queryPageList(AiPaintingFavoriteBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<AiPaintingFavorite> lqw = buildQueryWrapper(bo);
        Page<AiPaintingFavoriteVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        result.getRecords().forEach(this::enrichPaintingRecord);
        return TableDataInfo.build(result);
    }

    /**
     * 查询AI绘画作品收藏列表
     */
    @Override
    public List<AiPaintingFavoriteVo> queryList(AiPaintingFavoriteBo bo) {
        LambdaQueryWrapper<AiPaintingFavorite> lqw = buildQueryWrapper(bo);
        List<AiPaintingFavoriteVo> list = baseMapper.selectVoList(lqw);
        list.forEach(this::enrichPaintingRecord);
        return list;
    }

    /**
     * 构建查询条件
     */
    private LambdaQueryWrapper<AiPaintingFavorite> buildQueryWrapper(AiPaintingFavoriteBo bo) {
        LambdaQueryWrapper<AiPaintingFavorite> lqw = new LambdaQueryWrapper<>();
        lqw.eq(bo.getUserId() != null, AiPaintingFavorite::getUserId, bo.getUserId());
        lqw.eq(bo.getPaintingRecordId() != null, AiPaintingFavorite::getPaintingRecordId, bo.getPaintingRecordId());
        lqw.eq(StringUtils.isNotBlank(bo.getTaskId()), AiPaintingFavorite::getTaskId, bo.getTaskId());
        // 时间范围查询
        lqw.ge(bo.getCreateTimeStart() != null, AiPaintingFavorite::getCreateTime, bo.getCreateTimeStart());
        lqw.le(bo.getCreateTimeEnd() != null, AiPaintingFavorite::getCreateTime, bo.getCreateTimeEnd());
        // 按收藏时间倒序排序
        lqw.orderByDesc(AiPaintingFavorite::getCreateTime);
        return lqw;
    }

    /**
     * 丰富绘画记录信息
     */
    private void enrichPaintingRecord(AiPaintingFavoriteVo vo) {
        if (vo.getPaintingRecordId() != null) {
            AiPaintingRecordVo record = paintingRecordService.queryById(vo.getPaintingRecordId());
            vo.setPaintingRecord(record);
        }
    }

    /**
     * 新增AI绘画作品收藏
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertByBo(AiPaintingFavoriteBo bo) {
        // 检查是否已收藏
        if (bo.getUserId() != null && bo.getPaintingRecordId() != null) {
            Boolean favorited = isFavorited(bo.getUserId(), bo.getPaintingRecordId());
            if (favorited) {
                throw new ServiceException("该作品已被收藏");
            }
        }

        AiPaintingFavorite add = MapstructUtils.convert(bo, AiPaintingFavorite.class);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改AI绘画作品收藏
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateByBo(AiPaintingFavoriteBo bo) {
        AiPaintingFavorite update = MapstructUtils.convert(bo, AiPaintingFavorite.class);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 批量删除AI绘画作品收藏
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            // 可以添加业务校验逻辑
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    /**
     * 检查用户是否已收藏该绘画作品
     */
    @Override
    public Boolean isFavorited(Long userId, Long paintingRecordId) {
        LambdaQueryWrapper<AiPaintingFavorite> lqw = new LambdaQueryWrapper<>();
        lqw.eq(AiPaintingFavorite::getUserId, userId);
        lqw.eq(AiPaintingFavorite::getPaintingRecordId, paintingRecordId);
        return baseMapper.selectCount(lqw) > 0;
    }

    /**
     * 取消收藏
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean cancelFavorite(Long userId, Long paintingRecordId) {
        LambdaQueryWrapper<AiPaintingFavorite> lqw = new LambdaQueryWrapper<>();
        lqw.eq(AiPaintingFavorite::getUserId, userId);
        lqw.eq(AiPaintingFavorite::getPaintingRecordId, paintingRecordId);
        return baseMapper.delete(lqw) > 0;
    }

    /**
     * 根据用户ID查询收藏列表
     */
    @Override
    public List<AiPaintingFavoriteVo> queryByUserId(Long userId) {
        LambdaQueryWrapper<AiPaintingFavorite> lqw = new LambdaQueryWrapper<>();
        lqw.eq(AiPaintingFavorite::getUserId, userId);
        lqw.orderByDesc(AiPaintingFavorite::getCreateTime);
        List<AiPaintingFavoriteVo> list = baseMapper.selectVoList(lqw);
        list.forEach(this::enrichPaintingRecord);
        return list;
    }

}
