package com.nantian.cloud.jljc.tools;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.jcraft.jsch.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Properties;

@Component
public class FtpUtil {
    private static Logger logger = LoggerFactory.getLogger(FtpUtil.class);

    /**
     * ftp服务器ip地址
     */
    private static String host;

    @Value("${ftp.host}")
    public void setHost(String val){
        FtpUtil.host = val;
    }

    /**
     * 端口
     */
    private static int port;

    @Value("${ftp.port}")
    public void setPort(int val){
        FtpUtil.port = val;
    }

    /**
     * 用户名
     */
    private static String userName;

    @Value("${ftp.userName}")
    public void setUserName(String val){
        FtpUtil.userName = val;
    }

    /**
     * 密码
     */
    private static String password;

    @Value("${ftp.password}")
    public void setPassword(String val){
        FtpUtil.password = val;
    }

    /**
     * 存放文件的根目录
     */
    private static String rootPath;

    @Value("${ftp.rootPath}")
    public void setRootPath(String val){
        FtpUtil.rootPath = val;
    }

    /**
     * 存放文件的路径
     */
    private static String imgUrl;

    @Value("${ftp.img.url}")
    public void setImgUrl(String val){
        FtpUtil.imgUrl = val;
    }

    /**
     * 获取连接
     */
    private static ChannelSftp getChannel() throws Exception{
        JSch jsch = new JSch();

        //->ssh root@host:port
        Session sshSession = jsch.getSession(userName,host,port);
        //密码
        sshSession.setPassword(password);

        Properties sshConfig = new Properties();
        sshConfig.put("StrictHostKeyChecking", "no");
        sshSession.setConfig(sshConfig);
        sshSession.connect();

        Channel channel = sshSession.openChannel("sftp");
        channel.connect();

        return (ChannelSftp) channel;
    }

    /**
     * ftp上传文件
     * @param inputStream 文件io流
     * @param imagePath 路径，不存在就创建目录
     * @param imagesName 文件名称
     * @return urlStr 文件的存放路径
     */
    public static String putImages(InputStream inputStream, String imagePath, String imagesName){
        try {
            ChannelSftp sftp = getChannel();
            String path = rootPath + imagePath + "/";
            createDir(path,sftp);

            //上传文件
            sftp.put(inputStream, path + imagesName);
            logger.info("ftp上传文件成功！");
            sftp.quit();
            sftp.exit();

            //处理返回的路径
            String resultFile;
            resultFile = imgUrl + imagePath + imagesName;

            return resultFile;

        } catch (Exception e) {
            logger.error("ftp上传文件失败：" + e);
        }
        return "";
    }

    /**
     * ftp下载文件
     * imagePath 文件的访问路径，如http://220.163.102.62:18900/20210926/15comTraining.mp4
     * outfileName 文件重命名，无后缀
     */
    public static boolean getImages(String imagePath, String outfileName, HttpServletResponse response) throws IOException {
        try {
            ChannelSftp sftp = getChannel();

            //String[] split = imagePath.split(imgUrl+"/");
            String[] split = imagePath.split("/");
            if(split.length<2){
                logger.error("下载失败：路径错误！");
            }
            //String path = rootPath + split[1];
            String path =  split[split.length-2];
            String fileNmae =  split[split.length-1];
            // 切换到文件目录
            sftp.cd(rootPath);
            sftp.cd(path);
            //下载文件
            InputStream inputStream = sftp.get(fileNmae);
            if (inputStream == null){
                logger.info("ftp下载文件失败，获取的文件流为空！");
                return false;
            }

            byte[] buf = new byte[1024 * 8];
            int length = 0;
            String newFileName = (StringUtils.isEmpty(outfileName) ? IDUtils.genImageName() : outfileName) + imagePath.substring(imagePath.lastIndexOf("."));

            response.reset();
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(newFileName, "UTF-8"));
            response.setContentType("application/octet-stream");
            response.setCharacterEncoding("UTF-8");
            OutputStream outputStream = response.getOutputStream();
            while ((length = inputStream.read(buf)) > 0) {
                outputStream.write(buf, 0, length);
            }
            sftp.quit();
            sftp.exit();
            inputStream.close();
            outputStream.close();
            logger.info("ftp下载文件成功！");
        } catch (Exception e) {
            logger.error("ftp下载文件失败：" + e);
            return false;
        }
        return true;
    }

    /**
     * 创建目录
     */
    private static void createDir(String path,ChannelSftp sftp) throws SftpException {
        String[] folders = path.split("/");
        sftp.cd("/");
        for ( String folder : folders ) {
            if ( folder.length() > 0 ) {
                try {
                    sftp.cd( folder );
                }catch ( SftpException e ) {
                    sftp.mkdir( folder );
                    sftp.cd( folder );
                }
            }
        }
    }

    /**
     * 删除文件
     */
    public static void delImages(String imagesName){
        try {
            ChannelSftp sftp = getChannel();
            String path = rootPath + imagesName;
            sftp.rm(path);
            sftp.quit();
            sftp.exit();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}