package org.dromara.system.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
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.dromara.system.domain.GameEvent;
import org.dromara.system.domain.bo.GameEventBo;
import org.dromara.system.domain.vo.GameEventVo;
import org.dromara.system.service.IGameEventService;
import org.springframework.stereotype.Service;
import org.dromara.system.domain.bo.ArticleBo;
import org.dromara.system.domain.vo.ArticleVo;
import org.dromara.system.domain.Article;
import org.dromara.system.mapper.ArticleMapper;
import org.dromara.system.service.IArticleService;

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

/**
 * 文章(可用于活动预热)Service业务层处理
 *
 * @author Lion Li
 * @date 2025-08-08
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class ArticleServiceImpl implements IArticleService {

    private final ArticleMapper baseMapper;

    private final IGameEventService gameEventService;

    /**
     * 查询文章(可用于活动预热)
     *
     * @param id 主键
     * @return 文章(可用于活动预热)
     */
    @Override
    public ArticleVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询文章(可用于活动预热)列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 文章(可用于活动预热)分页列表
     */
    @Override
    public TableDataInfo<ArticleVo> queryPageList(ArticleBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<Article> lqw = buildQueryWrapper(bo);
        Page<ArticleVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        // 查询赛事相关信息
        result.getRecords().stream()
            .filter(articleVo -> ObjectUtil.isNotNull(articleVo.getEventId()))
            .map(vo -> {
                GameEventVo gameEventVo = gameEventService.queryById(vo.getEventId());
                if (ObjectUtil.isNotNull(gameEventVo)) {
                    vo.setEventName(gameEventVo.getEventName());
                }
                return vo;
            }).collect(Collectors.toList());
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的文章(可用于活动预热)列表
     *
     * @param bo 查询条件
     * @return 文章(可用于活动预热)列表
     */
    @Override
    public List<ArticleVo> queryList(ArticleBo bo) {
        LambdaQueryWrapper<Article> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<Article> buildQueryWrapper(ArticleBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<Article> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(Article::getId);
        lqw.eq(bo.getEventId() != null, Article::getEventId, bo.getEventId());

        // 通过名称模糊查询
        if (StringUtils.isNotBlank(bo.getEventName())) {
            GameEventBo gameEventBo = new GameEventBo();
            gameEventBo.setEventName(bo.getEventName());
            List<GameEventVo> vos = gameEventService.queryList(gameEventBo);
            List<Long> ids = vos.stream()
                .map(GameEventVo::getEventId)
                .collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(ids)) {
                lqw.in(Article::getEventId, ids);
            } else {
                lqw.apply("1=0");
            }
        }

        lqw.eq(StringUtils.isNotBlank(bo.getTitle()), Article::getTitle, bo.getTitle());
        lqw.eq(StringUtils.isNotBlank(bo.getContent()), Article::getContent, bo.getContent());
        lqw.eq(bo.getType() != null, Article::getType, bo.getType());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), Article::getStatus, bo.getStatus());
        return lqw;
    }

    /**
     * 新增文章(可用于活动预热)
     *
     * @param bo 文章(可用于活动预热)
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(ArticleBo bo) {
        Article add = MapstructUtils.convert(bo, Article.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改文章(可用于活动预热)
     *
     * @param bo 文章(可用于活动预热)
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(ArticleBo bo) {
        Article update = MapstructUtils.convert(bo, Article.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

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

    /**
     * 校验并批量删除文章(可用于活动预热)信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    /**
     * 查询文章数量
     *
     * @return
     */
    @Override
    public Long countArticle() {
        return this.baseMapper.selectCount(
            Wrappers.lambdaQuery(Article.class)
        );
    }
}
