package com.amms.controller;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.URLEncoder;
import java.util.UUID;

/**
 * 文件处理controller
 */
@Controller
@RequestMapping("/files")
public class FilesController {

    private static Logger logger = LoggerFactory.getLogger(FilesController.class);

    @Value("${files.path}")
    private String path;

    /**
     * 文件上传
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/upload")
    @ResponseBody
    public String upload(@RequestParam("file") MultipartFile file ,@RequestParam(name = "filePath" ,required = false) String filePath) throws IOException {
        logger.info("上传文件：{}", file.getName());
        File fileUploadPath = null;
        // 创建目标路径
        if (!filePath.equals("") && filePath != null) {
            fileUploadPath =  new File(path, filePath);
        } else {
            fileUploadPath = new File(path);
        }
        if (!fileUploadPath.exists()) {
            fileUploadPath.mkdirs();
        }
        // 新文件名
        String newFileName = UUID.randomUUID().toString().replace("-", "") + "-" +  file.getOriginalFilename();
        file.transferTo(new File(fileUploadPath, newFileName));
        // 判断参数中filePath时候为null 不为空则拼接到新文件名前
        if (!filePath.equals("") && filePath != null) {
            if (filePath.endsWith("/")) {
                newFileName =  filePath + newFileName;
            } else {
                newFileName = filePath + "/" + newFileName;
            }
        }
        return newFileName;
    }

    byte[] buffer = new byte[1024];
    BufferedInputStream bis = null;
    OutputStream os = null;

    /**
     * 获取文件（图片）
     * @param fileName
     * @param response
     * @throws UnsupportedEncodingException
     */
    @GetMapping("/get")
    public void getImage(@RequestParam("fileName") String fileName, HttpServletResponse response) throws UnsupportedEncodingException {
        logger.debug("加载图片，文件名：" + fileName);
        File file = new File(path, fileName);
        // 判断文件是否存在
        if (!file.exists()) {
            logger.error("文件【" + file.getAbsolutePath() + "】不存在！");
            response.setStatus(404);
            return;
        }
        response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8") );
        response.setContentType("image/jpeg");
        response.setContentLength((int)file.length());
        FileInputStream is = null;
        OutputStream os = null;
        try {
            is = new FileInputStream(file);
            os = response.getOutputStream();

            byte[] buf = new byte[8192];
            int rd;
            while ((rd = is.read(buf)) > 0)
                os.write(buf, 0, rd);

        } catch (IOException e) {
            logger.error(e.getMessage());
        } finally {
            try {
                if (is!=null) is.close();
                if (os!=null) {
                    os.flush();
                    os.close();
                }
            } catch (IOException e) {
                logger.error(e.getMessage());
            }
        }
    }


    /**
     * 删除文件
     * @param fileName
     * @param response
     * @throws UnsupportedEncodingException
     */
    @GetMapping("/delete")
    public void delete(@RequestParam("fileName") String fileName, HttpServletResponse response) throws UnsupportedEncodingException {
        logger.error("删除文件，文件名：" + fileName);
        File file = new File(path + fileName);
        if (!file.exists()) {
            logger.error("文件【" + fileName + "】不存在！");
            response.setStatus(404);
            return;
        }
        try {
            file.delete();
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
    }


    /**
     * 下载文件
     * @param fileName
     * @param request
     * @param response
     * @throws IOException
     */
    @GetMapping("/download")
    public void download(String fileName, HttpServletRequest request, HttpServletResponse response) throws IOException {
        logger.info("下载文件：{}", fileName);
        File fileUploadPathFile = new File(path);
        if (!fileUploadPathFile.exists()) {
            fileUploadPathFile.mkdir();
        }
        File file = new File(fileUploadPathFile, fileName);

        response.setContentType("application/octet-stream;charset=UTF-8");
        response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
        response.setHeader("Content-Disposition","attachment;filename="+fileName);
        response.setCharacterEncoding("UTF-8");
        os = response.getOutputStream();
        bis = new BufferedInputStream(new FileInputStream(file));
        while(bis.read(buffer) != -1){
            os.write(buffer);
        }
    }
}
