package org.jeecg.modules.database.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.database.entity.DocumentLibrary;
import org.jeecg.modules.database.mapper.DocumentLibraryMapper;
import org.jeecg.modules.database.service.IDocumentLibraryService;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @Description: 知识库
 * @Author: jeecg-boot
 * @Date: 2024-08-21
 * @Version: V1.0
 */
@Service
public class DocumentLibraryServiceImpl extends ServiceImpl<DocumentLibraryMapper, DocumentLibrary> implements IDocumentLibraryService {

    @Override
    public List<DocumentLibrary> getLatest() {
        LambdaQueryWrapper<DocumentLibrary> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DocumentLibrary::getType, "DOCUMENT");
        queryWrapper.orderByDesc(DocumentLibrary::getCreateTime);
        Page<DocumentLibrary> page = new Page<>(1, 5);
        return list(page, queryWrapper);
    }

    @Override
    public Long getTotal() {
        return count();
    }

    @Override
    public Long getToday() {
        QueryWrapper<DocumentLibrary> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("type", "DOCUMENT");
        queryWrapper.eq("DATE_FORMAT (create_time,'%Y-%m-%d')",
                DateUtils.formatDate(new Date(), "yyyy-MM-dd"));
        return count(queryWrapper);
    }

    @Override
    public Map<String, List<DocumentLibrary>> getCategory() {
        LambdaQueryWrapper<DocumentLibrary> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.isNull(DocumentLibrary::getParentId);
        queryWrapper.eq(DocumentLibrary::getType, "FOLDER");
        List<DocumentLibrary> folderList = list(queryWrapper);
        Map<String, List<DocumentLibrary>> map = new HashMap<>();
        folderList.forEach(folder -> {
            LambdaQueryWrapper<DocumentLibrary> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(DocumentLibrary::getParentId, folder.getId());
            queryWrapper1.eq(DocumentLibrary::getType, "DOCUMENT");
            queryWrapper1.orderByDesc(DocumentLibrary::getCreateTime);
            map.put(folder.getTitle(), list(queryWrapper1));
        });
        return map;
    }
}
