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

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.jeecg.modules.database.entity.DocumentLibrary;
import org.jeecg.modules.database.entity.DocumentVisitHistory;
import org.jeecg.modules.database.mapper.DocumentVisitHistoryMapper;
import org.jeecg.modules.database.service.IDocumentLibraryService;
import org.jeecg.modules.database.service.IDocumentVisitHistoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Description: 文档访问历史
 * @Author: jeecg-boot
 * @Date: 2024-11-14
 * @Version: V1.0
 */
@Service
public class DocumentVisitHistoryServiceImpl extends ServiceImpl<DocumentVisitHistoryMapper, DocumentVisitHistory>
        implements IDocumentVisitHistoryService {
    @Autowired
    private IDocumentLibraryService documentLibraryService;

    @Override
    public DocumentVisitHistory findByUserAndDocId(String userId, String documentId) {
        DocumentVisitHistory one = getOne(new LambdaQueryWrapper<DocumentVisitHistory>().eq(DocumentVisitHistory::getUserId, userId)
                .eq(DocumentVisitHistory::getDocumentId, documentId), false);
        if (Objects.isNull(one)) {
            DocumentVisitHistory documentVisitHistory = new DocumentVisitHistory();
            documentVisitHistory.setUserId(userId);
            documentVisitHistory.setDocumentId(documentId);
            documentVisitHistory.setVisitCount(1);
            return documentVisitHistory;
        }
        return one;
    }

    @Override
    public List<DocumentLibrary> getRecently(String userId) {
        LambdaQueryWrapper<DocumentVisitHistory> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DocumentVisitHistory::getUserId, userId);
        queryWrapper.orderByDesc(DocumentVisitHistory::getVisitCount);
        List<DocumentVisitHistory> list = list(new Page<>(1, 5), queryWrapper);
        List<DocumentLibrary> result = list.stream().map(visitHistory -> documentLibraryService.getById(visitHistory.getDocumentId()))
                .filter(Objects::nonNull).collect(Collectors.toList());
        return result;
    }

    @Override
    public void removeByDocId(String documentId) {
        LambdaQueryWrapper<DocumentVisitHistory> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DocumentVisitHistory::getDocumentId, documentId);
        remove(queryWrapper);
    }
}
