package com.chinaweal.aiccs.common.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.commons.text.StringSubstitutor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;

@Configuration
@Slf4j
public class FtpUtil {

    @Value("${storage.ftp.ip}")
    private String hostName; //= "127.0.0.1" ;FTP IP
    @Value("${storage.ftp..port}")
    private int port;//FTP 端口号
    @Value("${storage.ftp..username}")
    private String username;//FTP 登录账号
    @Value("${storage.ftp..password}")
    private String password; //FTP 登录密码

    public static byte[] downloadfileByte(String hostname,int port,String username,String password,String pathname,String fileName) {
        FTPClient ftpClient = new FTPClient();
        String LOCAL_CHARSET;
        byte[] in2b = new byte[12];
        try{
            //连接FTP服务器
            ftpClient.connect(hostname, port);
            //登录FTP服务器
            ftpClient.login(username, password);
            if (FTPReply.isPositiveCompletion(ftpClient.sendCommand("OPTS UTF8", "ON"))) {// 开启服务器对UTF-8的支持，如果服务器支持就用UTF-8编码，否则就使用本地编码（GBK）.
                LOCAL_CHARSET = "UTF-8";
            }
            ftpClient.enterLocalPassiveMode();// 设置被动模式
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);// 设置传输的模式
            ftpClient.changeWorkingDirectory(pathname);

            InputStream retrieveFileStream = null;
            byte[] input2byte = null;
            retrieveFileStream = ftpClient.retrieveFileStream(new String(fileName.getBytes(),"ISO-8859-1"));
            input2byte = input2byte(retrieveFileStream);


            // 使用流进行操作，例如读取内容或保存到本地
            BufferedReader reader = new BufferedReader(new InputStreamReader(retrieveFileStream));
            reader.close();

            return input2byte;
        } catch (IOException e){
            e.printStackTrace();
        } finally{
            if(ftpClient.isConnected()){
                try {
                    ftpClient.disconnect();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return in2b;
    }

    public static byte[] input2byte(InputStream inStream) throws IOException {
        ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
        byte[] buff = new byte[100];
        int rc = 0;
        while ((rc = inStream.read(buff, 0, 100)) > 0) {
            swapStream.write(buff, 0, rc);
        }
        byte[] in2b = swapStream.toByteArray();
        return in2b;
    }

    public void getFtpFile(HttpServletResponse response,String path){
        HashMap<String, Object> valuesMap = new HashMap<>();
        valuesMap.put("username", username);
        valuesMap.put("password", password);
        valuesMap.put("hostName", hostName);
        valuesMap.put("port", port);
        valuesMap.put("path", path);

        String template = "ftp://${username}:${password}@${hostName}:${port}${path}"; //"ftp://epsuser:1qaz!QAZ@19.15.77.57:8888/NLIQ/upload/440003000049189+20210803.pdf";
        String file = StringSubstitutor.replace(template, valuesMap);

        if(file.indexOf("/")!=-1)
            file = parseFile(file);

        String fileName = null;    //中文解码
        try {
            fileName = new String(file.getBytes("GB2312"), "ISO_8859_1");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }

        fileName = fileName.replace(' ','+');

        HashMap map = new HashMap();
        map.put("mp3","audio/mpeg");
        map.put("gif","image/gif");
        map.put("jpg","image/jpeg");
        map.put("png","image/png");
        map.put("bmp","image/bmp");
        map.put("html","text/html");
        map.put("htm","text/html");
        map.put("txt","text/plain");
        map.put("pdf","application/pdf");
        map.put("doc","application/msword");
        map.put("ppt","application/powerpoint");
        map.put("xls","application/vnd.ms-excel");
        map.put("exe","application/x-msdownload");
        map.put("zip","application/zip");
        map.put("rar","application/rar");
        map.put("chm","application/mshelp");
        map.put("xml","text/xml");

        String fileExt = fileName.substring(file.lastIndexOf(".")+1).toLowerCase();
        String attachMimeDesc = (String)map.get(fileExt);
        if(StringUtils.isEmpty(attachMimeDesc)){
            attachMimeDesc = "text/plain";
        }

        try {
            InputStream inStream = new ByteArrayInputStream(downloadfileByte(hostName,port,username,password,fileName,path));
            response.reset();
            response.setContentType(attachMimeDesc);

            String saveName = fileName.substring(fileName.lastIndexOf(File.separator)+1);

    //        if (".gif.png.jpg.jpeg.bmp.swf".indexOf(fileExt)==-1) { //附件下载  不是图片时采用！
            response.addHeader("Content-Disposition", "filename=\""+saveName + "\""); //用IE打开
            // 不是图片时，不管是本地或数据库上的文件都直接从网页上显示出来。
            byte[] b = new byte[2048];
            int len;
            ServletOutputStream sos = response.getOutputStream();
            while ((len = inStream.read(b)) > 0) {
                sos.write(b, 0, len);
            }
            sos.close();
            sos.flush();
            inStream.close();
        } catch (Exception e) {
            e.printStackTrace();
            String msg = "文件“" + fileName + "”不存在或网络错误，异常信息：" + e.getMessage();
        }
    }

    //修正路径
    String parseFile(String file){
        if(file.indexOf("/")!=-1){
            String[] tmp = file.split("/");
            if(tmp.length>0)
                return StringUtils.join(tmp,"\\");
        }
        return file;
    }
}
