package com.test.bijihoudaun.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.test.bijihoudaun.entity.MarkdownFile;
import com.test.bijihoudaun.entity.MarkdownFileVO;
import com.test.bijihoudaun.mapper.MarkdownFileMapper;
import com.test.bijihoudaun.service.MarkdownFileService;
import com.test.bijihoudaun.util.SnowflakeIdGenerator;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

@Service
public class MarkdownFileServiceImpl
        extends ServiceImpl<MarkdownFileMapper, MarkdownFile>
        implements MarkdownFileService {

    @Autowired
    MarkdownFileMapper markdownFileMapper;
    @Resource
    SnowflakeIdGenerator snowflakeIdGenerator;


    @Override
    public MarkdownFile updateMarkdownContent(MarkdownFile markdownFile) {
        markdownFile.setUpdatedAt(new Date());
        // 如果ID为空或0，则视为新文件
        if (markdownFile.getId() == null || markdownFile.getId() == 0L) {
            markdownFile.setId(snowflakeIdGenerator.nextId());
            markdownFile.setCreatedAt(new Date());
            this.save(markdownFile); // 使用MyBatis-Plus的save方法
        } else {
            this.updateById(markdownFile); // 使用MyBatis-Plus的updateById方法
        }
        return markdownFile;
    }
    
    @Override
    public MarkdownFile getMarkdownById(Long id) {
        return this.getById(id);
    }

    
    @Override
    public List<MarkdownFileVO> getFilesByGroupingId(String groupingId) {
        return markdownFileMapper.selectByGroupingIdWithGrouping(groupingId);
    }
    
    @Override
    public boolean deleteMarkdownFile(Long id) {
        return this.removeById(id);
    }

    @Override
    public List<MarkdownFile> test() {
        List<MarkdownFile> markdownFiles = markdownFileMapper.selectList(null);
        return markdownFiles;
    }

    @Override
    public List<MarkdownFile> getAllMarkdownFiles() {
        return markdownFileMapper.selectList(null);
    }

    @Override
    public List<MarkdownFile> searchByTitle(String keyword) {
        QueryWrapper<MarkdownFile> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("title", keyword);
        return this.list(queryWrapper);
    }

    @Override
    public MarkdownFile updateMarkdownTitle(Long id, String title) {
        MarkdownFile file = this.getById(id);
        if (file != null) {
            file.setTitle(title);
            file.setUpdatedAt(new Date());
            this.updateById(file);
        }
        return file;
    }

    @Override
    public List<MarkdownFileVO> getRecentFiles(int limit) {
        return markdownFileMapper.selectRecentWithGrouping(limit);
    }
}
