package com.jiayue.ipfcst.client.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.springframework.stereotype.Component;

import java.io.*;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author bizy
 * @version 1.0
 * @ClassName FtpUtil
 * @Description ftp上传下载工具
 * @date 2018/7/16 10:45 上午
 * @Modified By
 */
@Slf4j
@Component
public class FtpUtil {

    /**
     * 获取FTPClient对象
     *
     * @param ftpHost     FTP主机服务器
     * @param ftpPassword FTP 登录密码
     * @param ftpUserName FTP登录用户名
     * @param ftpPort     FTP端口 默认为21
     * @return
     */
    public static FTPClient getFTPClient(String ftpHost, String ftpUserName,
                                         String ftpPassword, int ftpPort) throws SocketException, IOException {
        log.info("ftp链接时间：" + TimeUtils.getStringDate());
        FTPClient ftpClient = new FTPClient();
        ftpClient.connect(ftpHost, ftpPort);// 连接FTP服务器
        ftpClient.login(ftpUserName, ftpPassword);// 登陆FTP服务器
        ftpClient.setConnectTimeout(500000);// 连接超时时间
        if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
            log.error("未连接到FTP，用户名或密码错误。");
            ftpClient.disconnect();
        } else {
            log.info("FTP连接成功。");
        }

        return ftpClient;
    }

    /**
     * 功能描述: 手动下载rb文件
     *
     * @param: [ftpHost, ftpUserName, ftpPassword, ftpPort, ftpPath, localPath, date]
     * @return: java.util.List<java.lang.String>
     * @auther: bizy
     * @date: 2018/7/24 13:24 下午
     */
    public static void downloadFtpFileDQAndNWP(String ftpHost, String ftpUserName,
                                               String ftpPassword, int ftpPort, String ftpPath, String localPath,
                                               String date, boolean flag) throws Exception {
        FTPClient ftpClient = null;

        ftpClient = getFTPClient(ftpHost, ftpUserName, ftpPassword, ftpPort);
        ftpClient.setControlEncoding("UTF-8"); // 中文支持
        ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
        ftpClient.enterLocalPassiveMode();

//        ftpClient.changeWorkingDirectory(ftpPath);
        String ftpType = Constant.proBean.getFtpType();
        String[] names = ftpType.split(",");
        FTPFile[] files = ftpClient.listFiles();
        for (int i = 0; i < names.length; i++) {
            if(!names[i].isEmpty()){
                names[i] = names[i].trim() + "_" + date;
            }
        }
        String dir = "";
        if (localPath.endsWith(String.valueOf(File.separatorChar))) {
            dir = localPath.substring(0, localPath.length() - 1) + "temp";
        } else {
            dir = localPath + "temp";
        }
        UtilTools.judeDirExists(dir);

        //根据flag区分是否为手动下载，手动下载则全部下载
        if (flag) {
            for (FTPFile ftpFile : files) {
                String fileName = ftpFile.getName();

                for (String name : names) {
                    if (fileName.startsWith(name) && fileName.endsWith(".RB")) {
                        log.info("文件手动下载：" + localPath + File.separatorChar + fileName);
                        File localFile = new File(dir + File.separatorChar + fileName);
                        OutputStream os = new FileOutputStream(localFile);
                        ftpClient.retrieveFile(fileName, os);
                        Constant.filedownLoadList.add(dir + File.separatorChar + fileName);
                        os.close();
                    }
                }
            }
        } else {
            if (!Constant.nowDate.equals(date)) {
                Constant.nowDate = date;
                Constant.alreadyDownFilesList = new ArrayList<String>();
            }

            for (FTPFile ftpFile : files) {
                String fileName = ftpFile.getName();
                for (String name : names) {
                    if (fileName.startsWith(name) && fileName.endsWith(".RB")) {
                        if (!Constant.alreadyDownFilesList.contains(fileName)) {
                            Constant.alreadyDownFilesList.add(fileName);
                            log.info("文件下载路径：" + localPath + File.separatorChar + fileName);
                            File localFile = new File(dir + File.separatorChar + fileName);
                            OutputStream os = new FileOutputStream(localFile);
                            ftpClient.retrieveFile(fileName, os);
                            Constant.filedownLoadList.add(dir + File.separatorChar + fileName);
                            os.close();
                        }
                    }
                }
            }
        }

        ftpClient.logout();
    }


    /*
     * 从FTP服务器下载文件
     *
     * @param ftpHost FTP IP地址
     * @param ftpUserName FTP 用户名
     * @param ftpPassword FTP用户名密码
     * @param ftpPort FTP端口
     * @param ftpPath FTP服务器中文件所在路径 格式： ftptest/aa
     * @param localPath 下载到本地的位置 格式：H:/download
     * @param fileName 文件名称
     */
    public static void downloadFtpFile(String ftpHost, String ftpUserName,
                                       String ftpPassword, int ftpPort, String ftpPath, String localPath,
                                       String fileName) throws FileNotFoundException,SocketException,IOException{

        FTPClient ftpClient = null;

        ftpClient = getFTPClient(ftpHost, ftpUserName, ftpPassword, ftpPort);
        ftpClient.enterRemotePassiveMode();
        ftpClient.setControlEncoding("UTF-8");
        ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
        ftpClient.enterLocalPassiveMode();
        String[] rt=ftpClient.doCommandAsStrings("pwd","");
        Pattern p=Pattern.compile("\"(.*?)\"");
        Matcher m=p.matcher(rt[0]);
        if(m.find()){
            ftpPath = m.group(0).replace("\"","")+ftpPath;
            System.out.println(ftpPath);
        }
        boolean flag = ftpClient.changeWorkingDirectory(new String(ftpPath.getBytes("GBK"),"ISO-8859-1"));
        if(flag){
            log.info("文件下载路径：" + localPath + File.separatorChar + fileName);
            File localFile = new File( localPath + File.separatorChar + fileName);
            OutputStream os = new FileOutputStream(localFile);
            ftpClient.retrieveFile(fileName, os);
            os.close();
        }
        ftpClient.logout();

        try {
            if (UtilTools.osName.indexOf("Windows") <= -1) {
                Runtime.getRuntime().exec("chmod 777 -R " + localPath + File.separatorChar + fileName);
            }
        } catch (IOException e) {
            log.error("系统错误：" + e.getMessage(), e);
        }

    }

}
