package com.cusc.nirvana.user.rnr.fp.common.util;

import com.jcraft.jsch.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays;

/**
 * @description： sftp 工具类
 */
@Component
@Slf4j
public class ChinaMobileSftpUtil {
    //ip地址
    @Value("${t1.chinaMobile.sftp.client.host:}")
    private String host;

    //端口号
    @Value("${t1.chinaMobile.sftp.client.port:}")
    private Integer port;

    //用户名
    @Value("${t1.chinaMobile.sftp.client.username:}")
    private String username;

    //密码
    @Value("${t1.chinaMobile.sftp.client.password:}")
    private String password;

    //session链接超时时间
    @Value("${t1.chinaMobile.sftp.client.sessionConnectTimeout:15000}")
    private Integer sessionConnectTimeout = 15000;

    //channel链接超时时间
    @Value("${t1.chinaMobile.sftp.client.channelConnectedTimeout:15000}")
    private Integer channelConnectedTimeout = 15000;

    /**
     * 检查SFTP目录或文件是否存在
     * @param remotePath
     * @return
     */
    public boolean checkFileExist(String remotePath) throws SftpException, JSchException {
        ChannelSftp channelSftp = loginSftp();
        try {
            channelSftp.ls(remotePath);

            return true;
        } catch (SftpException e) {
            throw e;
        }
    }

    /**
     * 文件上传
     * @param localFilePath
     * @param remoteDirPath
     * @return
     */
    public String uploadFile(String localFilePath, String remoteDirPath) throws SftpException, JSchException {
        ChannelSftp channelSftp = loginSftp();
        try {
            boolean dirs = createDirs(remoteDirPath, channelSftp);
            if (!dirs) {
                log.error("Remote path error. path:{}", remoteDirPath);
                return null;
            }
            channelSftp.put(localFilePath, remoteDirPath);

            String remoteFilePath = remoteDirPath+"/"+new File(localFilePath).getName();

            log.info("upload file:::{}", remoteFilePath);

            return remoteFilePath;
        } catch(SftpException ex) {
            log.error("Error upload file", ex);
            throw ex;
        } finally {
            logoutSftp(channelSftp);
        }
    }


    /**
     * 文件下载
     * @param localDirPath
     * @param remoteFilePath
     * @return
     */
    public String downloadFile(String localDirPath, String remoteFilePath) throws IOException, SftpException, JSchException {
        ChannelSftp channelSftp = loginSftp();
        OutputStream outputStream = null;
        try {
            String fileName = remoteFilePath.substring(remoteFilePath.lastIndexOf("/") + 1);

            if(!new File(localDirPath).exists()){
                new File(localDirPath).mkdirs();
            }

            String localFilePath = localDirPath+"/"+fileName;
            File file = new File(localFilePath);
            outputStream = new FileOutputStream(file);
            channelSftp.get(remoteFilePath, outputStream);

            file.createNewFile();
            return localFilePath;
        } catch(SftpException | IOException ex) {
            ex.printStackTrace();
            throw ex;
        } finally {
            logoutSftp(channelSftp);
            if(outputStream!=null){
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }



    /**
     * 登录SFTP
     * @return
     */
    private ChannelSftp loginSftp() throws JSchException {
        JSch jsch = new JSch();
        try {
            Session sshSession = jsch.getSession(username, host, port);
            sshSession.setPassword(password);
            sshSession.setConfig("StrictHostKeyChecking", "no");
            sshSession.connect(sessionConnectTimeout);
            Channel channel = sshSession.openChannel("sftp");
            channel.connect(channelConnectedTimeout);
            ChannelSftp channelSftp = (ChannelSftp) channel;
            return channelSftp;
        } catch (JSchException e) {
            e.printStackTrace();
            throw e;
        }
    }

    /**
     * 关闭SFTP
     * @param channelSftp
     */
    private void logoutSftp(ChannelSftp channelSftp) throws JSchException {
        try {
            if( channelSftp == null){
                return;
            }
            if(channelSftp.isConnected()){
                channelSftp.disconnect();
            }
            if(channelSftp.getSession() != null){
                channelSftp.getSession().disconnect();
            }
        } catch(Exception ex) {
            ex.printStackTrace();
            throw ex;
        }
    }

    /**
     * 创建SFTP目录，如果目录不存在就创建
     * 加锁，防止创建目录混乱
     * @param dirPath
     * @param sftp
     * @return
     */
    private synchronized boolean createDirs(String dirPath, ChannelSftp sftp) throws SftpException {
        if (StringUtils.isNotBlank(dirPath)) {
            String[] dirs = Arrays.stream(dirPath.split("/")).filter(StringUtils::isNotBlank).toArray(String[]::new);
            //将当前位置定位到/，根目录
            sftp.cd("/");
            for (String dir : dirs) {
                try {
                    sftp.cd(dir);
                    log.info("Change directory {}", dir);
                } catch (Exception e) {
                    try {
                        sftp.mkdir(dir);
                        log.info("Create directory {}", dir);
                    } catch (SftpException e1) {
                        log.error("Create directory failure, directory:{}", dir, e1);
                        e1.printStackTrace();
                        return false;
                    }
                    try {
                        sftp.cd(dir);
                        log.info("Change directory {}", dir);
                    } catch (SftpException e1) {
                        log.error("Change directory failure, directory:{}", dir, e1);
                        e1.printStackTrace();
                        return false;
                    }
                }
            }
            return true;
        }
        return false;
    }

}


