/**
 * Copyright &copy; 2021-2026 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.file.controller;

import cn.hutool.core.util.StrUtil;
import com.jeeplus.file.config.FileProperties;
import com.jeeplus.file.repository.AccessoryRepository;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;

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

/**
 * 文件管理Controller
 *
 * @author liugf
 * @version 2021-01-21
 * 提供了配套的upload/download, uploadFile/downloadFile
 * 区别在于访问文件的方式一个是通过重定向，一个是通过下载文件流
 */

@RestController
@RequestMapping("/file")
public class FileController {

    @Autowired
    private FileProperties fileProperties;

    @Autowired
    private AccessoryRepository accessoryRepository;

    private String FILE_SERVER = "/file";

    /**
     * 获取文件网络地址
     *
     * @return
     * @throws IOException
     * @throws IllegalStateException
     */
    @GetMapping("download")
    public void download(String uploadPath, String name, HttpServletRequest request, HttpServletResponse response) throws Exception {
        String url = accessoryRepository.getURL ( uploadPath, name ,request, response);
        if( StrUtil.isNotEmpty ( url ) ){
            try {
                response.sendRedirect ( url );
            } catch (IOException e) {
                throw new Exception ( "文件不存在!" );
            }
        }
    }

    /**
     * 获取文件网络地址
     *
     * @return
     * @throws IOException
     * @throws IllegalStateException
     */
    @GetMapping("videoDownload")
    public void videoDownload(String uploadPath, String name, HttpServletRequest request, HttpServletResponse response) throws Exception {
        String url = "";
        if(null == uploadPath || "".equals(uploadPath)){
            if(System.getProperty("os.name").toLowerCase().contains("win")){
                uploadPath = "D:/java_project/wdt_ERP_new/wdt_ERP_process_vue/public/img/video/";;
            }else{
                uploadPath = "/etc/nginx/html/img/video/";
            }
            url = accessoryRepository.getVideoURL ( uploadPath, name ,request, response);
        }else{
            url = accessoryRepository.getURL ( uploadPath, name ,request, response);
        }
        if( StrUtil.isNotEmpty ( url ) ){
            try {
                response.sendRedirect ( url );
            } catch (IOException e) {
                throw new Exception ( "文件不存在!" );
            }
        }
    }

    /**
     * 上传文件
     *
     * @return
     * @throws IOException
     */
    @RequestMapping("upload")
    public ResponseEntity upload(HttpServletRequest request, MultipartFile file) {

        Calendar cal = Calendar.getInstance ( );
        int year = cal.get ( Calendar.YEAR );
        int month = cal.get ( Calendar.MONTH ) + 1;
        String uploadPath = request.getParameter ( "uploadPath" ) + "/" + year + "/" + month + "/";
        // 判断文件是否为空
        if ( !file.isEmpty ( ) ) {
            String name = file.getOriginalFilename ( );
            if ( fileProperties.isAvailable ( name ) ) {
                // 文件保存路径
                // 转存文件
                //accessoryRepository.save ( file, uploadPath, name );
                return ResponseEntity.ok ( FILE_SERVER + "/download?uploadPath=" + uploadPath + "&name=" + name );

            } else {
                return ResponseEntity.badRequest ( ).body ( "请勿上传非法文件!" );
            }
        } else {
            return ResponseEntity.badRequest ( ).body ( "文件不存在!" );
        }
    }

    /**
     * 上传文件
     *
     * @return
     * @throws IOException
     */
    @RequestMapping("videoUpload")
    public ResponseEntity videoUpload(HttpServletRequest request, MultipartFile file, String uploadPath) {

        Calendar cal = Calendar.getInstance ( );
        int year = cal.get ( Calendar.YEAR );
        int month = cal.get ( Calendar.MONTH ) + 1;
        String path = "";
        if(System.getProperty("os.name").toLowerCase().contains("win")){
            path = "D:/java_project/wdt_ERP_new/wdt_ERP_process_vue/public/img/video/";;
        }else{
            path = "/etc/nginx/html/img/video/";
        }
        // 判断文件是否为空
        if ( !file.isEmpty ( ) ) {
            String name = file.getOriginalFilename ( );
            if ( fileProperties.isVideoAvailable ( name ) ) {
                saveMultipartFile(file,path);
                // 文件保存路径
                // 转存文件
                //accessoryRepository.save ( file, path, name );
                return ResponseEntity.ok ( FILE_SERVER + "/videoDownload?path=" + path + "&name=" + name );

            } else {
                return ResponseEntity.badRequest ( ).body ( "请勿上传非法文件!" );
            }
        } else {
            return ResponseEntity.badRequest ( ).body ( "文件不存在!" );
        }
    }

    /**
     * @param file
     * @param targetDirPath 存储MultipartFile文件的目标文件夹
     * @return 文件的存储的绝对路径
     */
    public static String saveMultipartFile(MultipartFile file, String targetDirPath) {

        File toFile = null;
        if (file.equals("") || file.getSize() <= 0) {
            return null;
        } else {

            /*获取文件原名称*/
            String originalFilename = file.getOriginalFilename();
            /*获取文件格式*/
            String fileFormat = originalFilename.substring(originalFilename.lastIndexOf("."));

            toFile = new File(targetDirPath + File.separator + originalFilename);

            String absolutePath = null;
            try {
                absolutePath = toFile.getCanonicalPath();

                /*判断路径中的文件夹是否存在，如果不存在，先创建文件夹*/
                String dirPath = absolutePath.substring(0, absolutePath.lastIndexOf(File.separator));
                File dir = new File(dirPath);
                if (!dir.exists()) {
                    dir.mkdirs();
                }

                InputStream ins = file.getInputStream();

                inputStreamToFile(ins, toFile);
                ins.close();

            } catch (IOException e) {
                e.printStackTrace();
            }
            return absolutePath;
        }

    }

    //获取流文件
    private static void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除本地临时文件
     *
     * @param file
     */
    public static void deleteTempFile(File file) {
        if (file != null) {
            File del = new File(file.toURI());
            del.delete();
        }
    }


    /**
     * 下载文件流
     *
     * @return
     * @throws IOException
     * @throws IllegalStateException
     */
    @GetMapping(value ="downloadFile", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
    public ResponseEntity<StreamingResponseBody> downloadFile(String uploadPath, String name) throws Exception {
        File file =  accessoryRepository.get ( uploadPath, name );
        return ResponseEntity.ok()
                .contentType( MediaType.APPLICATION_OCTET_STREAM)
                .header("Content-disposition", "attachment; filename="+name)
                .body(outputStream -> {
                    try (InputStream inputStream = new FileInputStream(file)) {
                        StreamUtils.copy(inputStream, outputStream);
                    } catch (IOException e) {

                    }
                });
    }

    /**
     * 上传文件
     *
     * @return
     * @throws IOException
     */
    @RequestMapping("uploadFile")
    public ResponseEntity uploadFile(HttpServletRequest request, MultipartFile file) {

        Calendar cal = Calendar.getInstance ( );
        int year = cal.get ( Calendar.YEAR );
        int month = cal.get ( Calendar.MONTH ) + 1;

        String path = "";
        if(System.getProperty("os.name").toLowerCase().contains("win")){
            path = "D:/java_project/wdt_ERP_new/wdt_ERP_process_vue/public/img/video/";;
        }else{
            path = "/etc/nginx/html/img/video/";
        }

        //String uploadPath = request.getParameter ( "uploadPath" ) + "/" + year + "/" + month + "/";

        // 判断文件是否为空
        if ( !file.isEmpty ( ) ) {
            String name = file.getOriginalFilename ( );
            if ( fileProperties.isAvailable ( name ) ) {
                saveMultipartFile(file,path);
                // 文件保存路径
                // 转存文件
                //accessoryRepository.save ( file, uploadPath, name );
                //return ResponseEntity.ok ( FILE_SERVER + "/downloadFile?uploadPath=" + uploadPath + "&name=" + name );
                return ResponseEntity.ok ( FILE_SERVER + "/downloadFile?path=" + path + "&name=" + name );

            } else {
                return ResponseEntity.badRequest ( ).body ( "请勿上传非法文件!" );
            }
        } else {
            return ResponseEntity.badRequest ( ).body ( "文件不存在!" );
        }
    }

}
