package ink.wgink.mongo.module.file.service;

import ink.wgink.common.base.DefaultBaseService;
import ink.wgink.interfaces.file.IMongoFileService;
import ink.wgink.pojo.ListPage;
import ink.wgink.pojo.pos.FilePO;
import ink.wgink.pojo.result.SuccessResultList;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.regex.Pattern;

/**
 * @ClassName: MongoFileService
 * @Description:
 * @Author: wanggeng
 * @Date: 2021/12/12 6:18 PM
 * @Version: 1.0
 */
@Service
public class MongoFileService extends DefaultBaseService implements IMongoFileService {

    @Autowired(required = false)
    private MongoTemplate mongoTemplate;

    @Override
    public void saveByUserId(String userId, FilePO filePO) {
        filePO.setCreator(userId);
        filePO.setModifier(userId);
        mongoTemplate.insert(filePO, UPLOAD_FILE_COLLECTION_NAME);
    }

    @Override
    public void delete(List<String> fileIds) {
        mongoTemplate.remove(Query.query(Criteria.where("fileId").in(fileIds)), UPLOAD_FILE_COLLECTION_NAME);
    }

    @Override
    public FilePO getPO(String fileId) {
        return mongoTemplate.findOne(Query.query(Criteria.where("fileId").is(fileId)), FilePO.class, UPLOAD_FILE_COLLECTION_NAME);
    }

    @Override
    public SuccessResultList<List<FilePO>> listPage(ListPage page) {
        Query query = new Query();
        String keywords = getKeywords(page.getParams());
        if (!StringUtils.isBlank(keywords)) {
            Pattern pattern = Pattern.compile("^.*" + keywords + ".*$", Pattern.CASE_INSENSITIVE);
            query.addCriteria(Criteria.where("fileName").regex(pattern));
        }
        long total = mongoTemplate.count(query, UPLOAD_FILE_COLLECTION_NAME);
        query.with(Pageable.ofSize(page.getRows()).withPage(page.getPage() - 1));
        List<FilePO> dataDTOs = mongoTemplate.find(query, FilePO.class, UPLOAD_FILE_COLLECTION_NAME);
        return new SuccessResultList<>(dataDTOs, page.getPage(), total);
    }

    @Override
    public List<FilePO> listByIds(List<String> fileIds) {
        return mongoTemplate.find(Query.query(Criteria.where("fileId").in(fileIds)), FilePO.class, UPLOAD_FILE_COLLECTION_NAME);
    }

    @Override
    public List<FilePO> listByUrl(String fileUrl) {
        Pattern pattern = Pattern.compile("^.*" + fileUrl + ".*$", Pattern.CASE_INSENSITIVE);
        return mongoTemplate.find(Query.query(Criteria.where("fileUrl").regex(pattern)), FilePO.class, UPLOAD_FILE_COLLECTION_NAME);
    }


}
