package com.ruoyi.novel.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.novel.domain.NovelChapter;
import com.ruoyi.novel.domain.NovelContent;
import com.ruoyi.novel.mapper.NovelChapterMapper;
import com.ruoyi.novel.mapper.NovelContentMapper;
import com.ruoyi.novel.service.ChapterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

// ChapterServiceImpl.java
@Service
public class ChapterServiceImpl implements ChapterService {

    @Autowired
    private NovelChapterMapper chapterMapper;

    @Autowired
    private NovelContentMapper contentMapper;

    @Override
    public List<NovelChapter> selectChapterListByNovelId(Long novelId) {
        return chapterMapper.selectList(
                new QueryWrapper<NovelChapter>()
                        .eq("novel_id", novelId)
                        .orderByAsc("chapter_order")
        );
    }

    @Override
    @Transactional
    public int saveChapter(NovelChapter chapter, String content) {
        if (chapter.getId() == null) {
            // 新增章节
            chapter.setCreateTime(new Date());
            chapterMapper.insert(chapter);

            NovelContent novelContent = new NovelContent();
            novelContent.setChapterId(chapter.getId());
            novelContent.setContent(content);
            return contentMapper.insert(novelContent);
        } else {
            // 更新章节
            chapter.setUpdateTime(new Date());
            chapterMapper.updateById(chapter);

            NovelContent novelContent = new NovelContent();
            novelContent.setChapterId(chapter.getId());
            novelContent.setContent(content);
            return contentMapper.updateById(novelContent);
        }
    }

    @Override
    public NovelChapter getChapterById(Long chapterId) {
        return chapterMapper.selectById(chapterId);
    }

    @Override
    @Transactional
    public int deleteChapters(Long[] ids) {
        // 删除章节内容
        contentMapper.deleteBatchIds(Arrays.asList(ids));
        // 删除章节
        return chapterMapper.deleteBatchIds(Arrays.asList(ids));
    }
}