package com.test.bijihoudaun.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
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
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) {
        if (parentId == null){
            return groupingMapper.selectList(null);
        }
        return groupingMapper.selectList(new LambdaQueryWrapper<Grouping>()
                .eq(Grouping::getParentId, parentId));
    }

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

    @Override
    @Transactional
    public void deleteGrouping(Long id) {
        LambdaUpdateWrapper<MarkdownFile> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(MarkdownFile::getGroupingId, id)
                .set(MarkdownFile::getGroupingId, 999L);
        markdownFileMapper.update(null, updateWrapper);

        this.removeById(id);
    }

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