package com.ruoyi.project.common;

import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.file.MimeTypeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.framework.config.RuoYiConfig;
import com.ruoyi.framework.config.ServerConfig;
import com.ruoyi.framework.web.domain.AjaxResult;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.List;

/**
 * 通用请求处理
 *
 * @author zdd
 */
@RestController
@CrossOrigin
public class CommonController {
    @Autowired
    private ServerConfig serverConfig;

    /**
     * 通用上传请求
     */
    @PostMapping("/common/upload")
    public AjaxResult uploadFile(MultipartFile file) throws Exception {
        try {
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = serverConfig.getUrl() + fileName;
            AjaxResult ajax = AjaxResult.success();
            ajax.put("fileName", fileName);
            ajax.put("url", url);
            return ajax;
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 通用上传请求
     */
    @PostMapping("/common/uploadac")
    public AjaxResult uploadac(MultipartFile file) throws Exception {
        try {
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            fileName = fileName.substring(15);
            String url = serverConfig.getUrl() + "/common/download?fileName=" + fileName;
            AjaxResult ajax = AjaxResult.success();
            ajax.put("fileName", fileName);
            ajax.put("url", url);
            return ajax;
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 通用下载请求
     */
    @GetMapping("/common/download")
    public void download(@RequestParam("fileName") String fileName, HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 上传文件路径
        String filePath = RuoYiConfig.getUploadPath() + "/" + fileName;
        //获取文件的绝对路径
        String realPath = request.getSession().getServletContext().getRealPath("upload");
        //获取输入流对象（用于读文件）
        FileInputStream fis = new FileInputStream(new File(filePath));
        //输出刘
        ServletOutputStream out = response.getOutputStream();
        //获取文件后缀（.txt）
        String extendFileName = fileName.substring(fileName.lastIndexOf('.'));
        //去掉第一个字符
        String replace = extendFileName.substring(1);
        String[] imageExtension = MimeTypeUtils.IMAGE_EXTENSION;
        List<String> strings = Arrays.asList(imageExtension);
        download(fileName, request, response, fis, extendFileName);
        /*if (strings.contains(replace)) {
            showimg(response, fis);
        } else {

        }*/
    }

    private void showimg(HttpServletResponse response, FileInputStream fis) throws IOException {
        //创建输出流
        try {

            response.setContentType("image/gif");
            OutputStream out = response.getOutputStream();
            byte[] b = new byte[fis.available()];
            fis.read(b);
            out.write(b);
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void download(@RequestParam("fileName") String fileName, HttpServletRequest request, HttpServletResponse response, FileInputStream fis, String extendFileName) throws IOException {
        //动态设置响应类型，根据前台传递文件类型设置响应类型
        response.setContentType(request.getSession().getServletContext().getMimeType(extendFileName));
        //设置响应头,attachment表示以附件的形式下载，inline表示在线打开
        response.setHeader("content-disposition", "attachment;fileName=" + URLEncoder.encode(fileName, "UTF-8"));
        //获取输出流对象（用于写文件）
        ServletOutputStream os = response.getOutputStream();
        //下载文件,使用spring框架中的FileCopyUtils工具
        FileCopyUtils.copy(fis, os);
    }
}
