package com.test.bijihoudaun.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.test.bijihoudaun.entity.ImageName;
import com.test.bijihoudaun.entity.MarkdownFile;
import com.test.bijihoudaun.entity.MarkdownFileVO;
import com.test.bijihoudaun.mapper.ImageNameMapper;
import com.test.bijihoudaun.mapper.MarkdownFileMapper;
import com.test.bijihoudaun.service.MarkdownFileService;
import com.test.bijihoudaun.util.MarkdownImageExtractor;
import com.test.bijihoudaun.util.SnowflakeIdGenerator;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

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

    @Autowired
    MarkdownFileMapper markdownFileMapper;
    @Resource
    ImageNameMapper imageNameMapper;
    @Resource
    SnowflakeIdGenerator snowflakeIdGenerator;
    @Resource
    ImageNameSyncService imageNameSyncService;


    @Override
    public MarkdownFile updateMarkdownContent(MarkdownFile markdownFile) {
        long id;
        markdownFile.setUpdatedAt(new Date());
        if (ObjectUtil.isNull(markdownFile.getId()) || markdownFile.getId() == 0L) {
            long l = snowflakeIdGenerator.nextId();
            markdownFile.setId(l);
            markdownFile.setCreatedAt(new Date());
            this.save(markdownFile);
            id=l;
        } else {
            MarkdownFile existingFile = this.getById(markdownFile.getId());
            if (existingFile != null) {
                LambdaUpdateWrapper<MarkdownFile> updateWrapper = new LambdaUpdateWrapper<>();
                updateWrapper.eq(MarkdownFile::getId, markdownFile.getId())
                        .set(MarkdownFile::getUpdatedAt, new Date());
                
                if (markdownFile.getTitle() != null) {
                    updateWrapper.set(MarkdownFile::getTitle, markdownFile.getTitle());
                }
                if (markdownFile.getContent() != null) {
                    updateWrapper.set(MarkdownFile::getContent, markdownFile.getContent());
                }
                if (markdownFile.getGroupingId() != null) {
                    updateWrapper.set(MarkdownFile::getGroupingId, markdownFile.getGroupingId());
                }
                if (markdownFile.getFileName() != null) {
                    updateWrapper.set(MarkdownFile::getFileName, markdownFile.getFileName());
                }
                if (markdownFile.getIsPrivate() != null) {
                    updateWrapper.set(MarkdownFile::getIsPrivate, markdownFile.getIsPrivate());
                }
                
                this.update(updateWrapper);
            } else {
                this.updateById(markdownFile);
            }
            id=markdownFile.getId();
        }

        List<String> strings = MarkdownImageExtractor.extractImageFilenames(markdownFile.getContent());
        // 修复：调用单独的 Service 处理异步逻辑
        imageNameSyncService.syncImageNames(id, strings);
        
        MarkdownFileVO result = markdownFileMapper.selectByIdWithGrouping(id);
        if (result != null) {
            // 确保 groupingId 被正确设置
            if (result.getGroupingId() == null && markdownFile.getGroupingId() != null) {
                result.setGroupingId(markdownFile.getGroupingId());
            }
            return result;
        }
        return markdownFile;
    }
    
    @Override
    public MarkdownFile getMarkdownById(Long id, boolean isAuthenticated) {
        MarkdownFile file = this.getById(id);
        if (file != null && !isAuthenticated && file.getIsPrivate() != null && file.getIsPrivate() == 1) {
            // 对于未认证用户，私密笔记只返回标题，内容置空
            file.setContent("");
            return file;
        }
        return file;
    }

    
    @Override
    public List<MarkdownFileVO> getFilesByGroupingId(String groupingId) {
        return markdownFileMapper.selectByGroupingIdWithGrouping(groupingId);
    }
    
    @Override
    public boolean deleteMarkdownFile(Long id) {
        LambdaUpdateWrapper<MarkdownFile> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(MarkdownFile::getId, id)
                .set(MarkdownFile::getIsDeleted, 1)
                .set(MarkdownFile::getDeletedAt, new Date());
        return this.update(updateWrapper);
    }

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

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

    @Override
    public List<MarkdownFile> searchByTitle(String keyword) {
        // 修复：转义特殊字符防止 SQL 注入
        if (keyword == null || keyword.trim().isEmpty()) {
            return List.of();
        }
        String escapedKeyword = keyword.replace("%", "\\%").replace("_", "\\_");
        QueryWrapper<MarkdownFile> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("title", escapedKeyword);
        return this.list(queryWrapper);
    }

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

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

}
