package com.ruoyi.cs.service.impl;

import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.cs.service.ISysFileService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * 本地文件存储
 *
 * @author xiaoniu
 */
@Service
public class LocalSysFileServiceImpl implements ISysFileService {


    /**
     * 域名或本机访问地址
     */
    @Value("${ruoyi.domain}")
    public String domain;

    /**
     * 上传文件存储在本地的根路径
     */
    @Value("${ruoyi.profile}")
    private String localFilePath;



    @Override
    public void downloadFile(HttpServletResponse response, String fileUrl) {
        try {

            String name = fileUrl.substring(fileUrl.lastIndexOf('/') + 1);
            response.setCharacterEncoding("utf-8");
            response.setHeader("content-type", "application/octet-stream");
            response.setHeader("Content-disposition",
                    "attachment;filename=" + URLEncoder.encode(name, String.valueOf(StandardCharsets.UTF_8)));
            // new String(name.getBytes("gbk"), "iso8859-1"));
            String file = fileUrl.replaceAll(domain, localFilePath);
            // 将文件转为文件输入流
            InputStream inStream = new FileInputStream(file);
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            // 创建一个Buffer字符串
            byte[] buffer = new byte[4096];
            // 每次读取的字符串长度，如果为-1，代表全部读取完毕
            int len = 0;
            // 使用一个输入流从buffer里把数据读取出来
            while ((len = inStream.read(buffer)) != -1) {
                // 用输出流往buffer里写入数据，中间参数代表从哪个位置开始读，len代表读取的长度
                byteArrayOutputStream.write(buffer, 0, len);
            }
            // 把outStream里的数据写入内存
            // 输出数据
            OutputStream outStream = response.getOutputStream();
            // 写入数据
            outStream.write(byteArrayOutputStream.toByteArray());
            outStream.flush();
            // 关闭输入流
            inStream.close();
            // 关闭输出流
            outStream.close();
        } catch (Exception e) {
            throw new ServiceException(e.getMessage());
        }
    }
}
