package com.pjilisense.flxai.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Repository;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

@Repository
public class FileUtil {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Value("${file.common.uploadWindow}")
    private String diskPath;
    @Value("${file.common.uploadLinux}")
    private String uploadLinux;

    @Value("${file.common.uploadUrl}")
    private String uploadUrl;

    public String uploadFile(MultipartFile multipartFile){
        String relPath="uploads/";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
        relPath = relPath+sdf.format(new Date()).substring(0,6)+"/";
        //⽂件的完整名称,如spring.jpeg
        String filename = multipartFile.getOriginalFilename();
        //⽂件后缀,如.jpeg
        assert filename != null;
        String suffix = filename.substring(filename.lastIndexOf("."));
        relPath =relPath+UUID.randomUUID().toString().replace("-","")+suffix;
        //⽬标⽂件
        File descFile = new File(getFilepath(relPath));
        //判断⽬标⽂件所在的⽬录是否存在
        if (!descFile.getParentFile().exists()) {
            descFile.getParentFile().mkdirs();
        }
        //multipartFile.transferTo(descFile);
        try (InputStream is = multipartFile.getInputStream();
             BufferedInputStream bis = new BufferedInputStream(is);
             BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(descFile))) {
            int num = 0;
            while ((num = bis.read()) != -1) {
                bos.write(num);
            }
        } catch (Exception e) {
            //log.error(e.getMessage());
            throw new RuntimeException("文件上传错误,请联系管理员");
        }
        return relPath;
    }

    /**
     *
     * @return int 删除结果  1  已删除  0 未删除
     */
    public int delFile(String filepath, String fileName) {
        String rootPath = getFilepath (filepath);
        File file = new File(rootPath);
        if (file.exists()) {
            if(file.isDirectory()) {
                File filex = new File(rootPath+"/"+fileName);
                if(filex.exists()) {
                    filex.delete();
                }
                return 1;
            } else {
                file.delete();
                return 1;
            }
        }
        return 0;
    }

    public void downLoadFile(String filepath, String filename, HttpServletResponse response){
        String rootPath = getFilepath (filepath);
        File file  = new File(rootPath);
        if(file.exists()){
            InputStream inputStream = null;
            OutputStream outputStream = null;
            try {
                // 读到流中
                if(file.isDirectory()) {
                    filename = rootPath +"/"+ filename;
                    filename = filename.replace("//","/");
                    inputStream = new FileInputStream(filename);// 文件的存放路径
                } else {
                    filename=rootPath;
                    inputStream = new FileInputStream(filename);//filepath可能包含文件名
                }
                filename =filename.substring(filename.lastIndexOf("/")+1);
                response.reset();
                response.setContentType("application/octet-stream");
                response.addHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(filename, "UTF-8"));
                outputStream = response.getOutputStream();
                byte[] b = new byte[1024];
                int len;
                //从输入流中读取一定数量的字节，并将其存储在缓冲区字节数组中，读到末尾返回-1
                while ((len = inputStream.read(b)) > 0) {
                    outputStream.write(b, 0, len);
                }
            } catch (IOException e) {
                System.out.println(e.getMessage());
                //log.error(e.getMessage(), e);
            }finally {
                try {
                    inputStream.close();
                    inputStream.close();
                } catch (IOException e) {
                    //log.error(e.getMessage(), e);
                }
            }
        }
        //
    }

    public String getFilepath (final String filepath) {//filepath可能包含文件名
        String rootPath = getRootpath();
        rootPath = rootPath +"/"+ filepath;
        rootPath =rootPath.replace("//","/");
        if(rootPath.endsWith("/")){
            rootPath=rootPath.substring(0,rootPath.length()-1);
        }
        return rootPath;
    }

    public String getRootpath () {//filepath可能包含文件名
        String rootPath = null;
        if (System.getProperty("os.name").startsWith("Windows")) {
            rootPath = diskPath;
        } else if (System.getProperty("os.name").startsWith("Linux")) {
            rootPath = uploadLinux;
        }
        rootPath =rootPath.replace("//","/");
        if(rootPath.endsWith("/")){
            rootPath=rootPath.substring(0,rootPath.length()-1);
        }
        return rootPath;
    }


}
