package com.test.bijihoudaun.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.test.bijihoudaun.entity.Grouping;
import com.test.bijihoudaun.entity.MarkdownFile;
import com.test.bijihoudaun.mapper.GroupingMapper;
import com.test.bijihoudaun.mapper.MarkdownFileMapper;
import com.test.bijihoudaun.service.GroupingService;
import com.test.bijihoudaun.util.SnowflakeIdGenerator;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class GroupingServiceImpl
        extends ServiceImpl<GroupingMapper, Grouping>
        implements GroupingService {

    @Resource
    private GroupingMapper groupingMapper;
    @Resource
    private MarkdownFileMapper markdownFileMapper;
    @Resource
    private SnowflakeIdGenerator snowflakeIdGenerator;


    @Override
    public Grouping createGrouping(Grouping grouping) {
        long id = snowflakeIdGenerator.nextId();
        grouping.setId(id);
        this.save(grouping);
        return grouping;
    }

    @Override
    public List<Grouping> getAllGroupings(Long parentId) {
        LambdaQueryWrapper<Grouping> queryWrapper = new LambdaQueryWrapper<>();
        // 只查询未删除的分组
        queryWrapper.eq(Grouping::getIsDeleted, 0);
        if (ObjectUtil.isNotNull(parentId)){
            queryWrapper.eq(Grouping::getParentId, parentId);
        }
        // 限制最大返回数量，防止内存溢出
        queryWrapper.last("LIMIT 1000");
        return groupingMapper.selectList(queryWrapper);
    }

    @Override
    public Grouping updateGrouping(Grouping grouping) {
        this.updateById(grouping);
        return grouping;
    }

    @Override
    public void deleteGrouping(Long id) {
        // 1. 使用 LambdaUpdateWrapper 软删除分组本身，确保 isDeleted 和 deletedAt 都被更新
        LambdaUpdateWrapper<Grouping> groupingUpdateWrapper = new LambdaUpdateWrapper<>();
        groupingUpdateWrapper.eq(Grouping::getId, id)
                .set(Grouping::getIsDeleted, 1)
                .set(Grouping::getDeletedAt, new java.util.Date());
        this.update(groupingUpdateWrapper);

        // 2. 将该分组下的所有笔记也一并软删除
        LambdaUpdateWrapper<MarkdownFile> markdownFileUpdateWrapper = new LambdaUpdateWrapper<>();
        markdownFileUpdateWrapper.eq(MarkdownFile::getGroupingId, id)
                .set(MarkdownFile::getIsDeleted, 1)
                .set(MarkdownFile::getDeletedAt, new java.util.Date());
        markdownFileMapper.update(null, markdownFileUpdateWrapper);
    }

    @Override
    public void saveOrUpdateBatch(List<Grouping> groupings) {
        super.saveOrUpdateBatch(groupings);
    }
}
