package com.tuoheng.common.controller;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.tuoheng.common.config.CommonConfig;
import com.tuoheng.common.config.UploadFileConfig;
import com.tuoheng.common.utils.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

@RestController
@RequestMapping("/common")
public class CommonController {

    private static final Logger log = LoggerFactory.getLogger(CommonController.class);

    /**
     * 下载文件
     *
     * @param fileName 文件名
     * @param isDelete 是否下载后删除
     * @param request  网络请求
     * @param response
     */
    @GetMapping("/download")
    public void downloadFile(String fileName, boolean isDelete, HttpServletRequest request, HttpServletResponse response) {
        try {
            if (!FileUtils.isValidFilename(fileName)) {
                throw new Exception(StringUtils.format("文件名称({})非法，不允许下载。 ", fileName));
            }
            String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
            String filePath = UploadFileConfig.uploadFolder + fileName;
            response.setCharacterEncoding("utf-8");
            response.setContentType("multipart/form-data");
            response.setHeader("Content-Disposition", "attachment;fileName=" + FileUtils.setFileDownloadHeader(request, realFileName));
            FileUtils.writeBytes(filePath, response.getOutputStream());
            if (isDelete) {
                // 删除文件
                FileUtils.deleteFile(filePath);
            }
        } catch (Exception e) {
            log.error("下载文件失败", e);
        }
    }

    /**
     * 下载文件
     *
     * @param fileName 文件名
     * @param response
     * @return
     */
    @GetMapping("/downloadFile/{fileName}")
    public OutputStream downloadFile(@PathVariable("fileName") String fileName, HttpServletResponse response) {
        // 替换域名
        if (fileName.contains(CommonConfig.imageURL)) {
            fileName = fileName.replaceAll(CommonConfig.imageURL, "");
        }
        // 文件地址
        String filePath = UploadFileConfig.uploadFolder + fileName;
        if (fileName != null) {
            //设置文件路径
            File file = new File(filePath);
            if (file.exists()) {
                byte[] buffer = new byte[1024];
                FileInputStream fis = null;
                BufferedInputStream bis = null;
                try {
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                    OutputStream os = response.getOutputStream();
                    int i = bis.read(buffer);
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }
                    return os;
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (bis != null) {
                        try {
                            bis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        return null;
    }

}
