package com.ruoyi.system.service.impl;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.system.service.FileService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;


import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

/**
 * <pre>
 * - 文件存储的本地存储实现
 * Author : J.L.Zhou
 * E-Mail : 2233875735@qq.com
 * Tel : 151 1104 7708
 * Date : 2021-09-16 14:17
 * Version : 1.0
 * Copyright 2021 jlzhou.top Inc. All rights reserved.
 * Warning: this content is only for internal circulation of the company.
 *          It is forbidden to divulge it or use it for other commercial purposes.
 * </pre>
 **/
@Service("upload")
@RequiredArgsConstructor
@Slf4j
public class FileServiceImpl implements FileService {

    public final RuoYiConfig config;

    @Override
    public void delete(String filename) {
        if (StrUtil.isEmpty(filename)) {
            throw new RuntimeException("文件名不能为空");
        }
        try {
            if (filename.startsWith(config.upload.pre)) {
                filename = filename.substring(config.upload.pre.length());
            }
            if (filename.indexOf("?") > -1) {
                filename = filename.substring(0, filename.indexOf("?"));
            }
            File file = new File(config.upload.savePath, filename);
            log.debug("file:"+file.exists());
            file.delete();
            log.info("删除:{}",file.getAbsolutePath());
        } catch (Exception e) {
            throw new RuntimeException("删除错误", e);
        }
    }

    @Override
    public File getFile(String filename) {
        if (StrUtil.isEmpty(filename)) {
            throw new RuntimeException("文件名不能为空");
        }

        if (filename.startsWith(config.upload.pre)) {
            filename = filename.substring(config.upload.pre.length());
        }
        if (filename.indexOf("?") > -1) {
            filename = filename.substring(0, filename.indexOf("?"));
        }
        return new File(config.upload.savePath, filename);
    }

    @Override
    public String save(InputStream in, String filename) {
        File file = new File(config.upload.savePath, filename);
        file.getParentFile().mkdirs();
        try(
          FileOutputStream out = new FileOutputStream(file);
          ) {
            IoUtil.copy(in, out);
            return config.upload.pre + "/" + filename;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
