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

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.modules.system.entity.FileInfo;
import org.jeecg.modules.system.mapper.FileInfoMapper;
import org.jeecg.modules.system.service.IFileInfoService;
import org.jeecg.modules.system.util.HttpDownUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.List;
import java.util.Objects;

/**
 * @Description: 文件信息表
 * @Author: jeecg-boot
 * @Date: 2023-02-21
 * @Version: V1.0
 */
@Slf4j
@Service
public class FileInfoServiceImpl extends ServiceImpl<FileInfoMapper, FileInfo> implements IFileInfoService {


    /**
     * 从minio下载文件
     *
     * @return
     */
    @Override
    public void downloadFile(String fileSaveId, HttpServletResponse response) {
        FileInfo fileInfo = listByFileSaveId(fileSaveId);
        if (!Objects.isNull(fileInfo)) {
            HttpDownUtils.downLoadFromMinio(fileSaveId, fileInfo.getFileName(), response);
        } else {
            log.info("数据库中没有找到文件记录：" + fileSaveId);
        }
    }


    /**
     * 保存文件
     *
     * @param fileName
     * @return
     */
    @Override
    public FileInfo saveFile(String fileSaveId, String fileName, Long videoDuration) {
        FileInfo fileInfo = new FileInfo();
        fileInfo.setFileSaveId(fileSaveId);
        fileInfo.setFileName(fileName);
        fileInfo.setVideoDuration(videoDuration);
        save(fileInfo);
        return fileInfo;
    }


    /**
     * 根据文件保存id查询
     *
     * @param fileSaveId
     * @return
     */
    @Override
    public FileInfo listByFileSaveId(String fileSaveId) {
        List<FileInfo> list = query().eq("file_save_id", fileSaveId).list();
        if (!CollectionUtils.isEmpty(list)) {
            return list.get(0);
        } else {
            return null;
        }
    }
}
