package com.trs.project.utils;

import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.jcraft.jsch.*;
import com.jcraft.jsch.ChannelSftp.LsEntry;
import com.trs.project.entity.BusinessInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;

/**
 * 
 * @author 邹许红
 * @date 2018-11-06
 */
public class SFTPUtils {

	private static final Logger LOGGER = LoggerFactory.getLogger(SFTPUtils.class);
	public static ChannelSftp sftp = null;
	public static Session sshSession = null;
	public static Channel channel = null;
	/**
	 * 连接sftp服务器
	 * @param host
	 *            主机
	 * @param port
	 *            端口
	 * @param username
	 *            用户名
	 * @param password
	 *            密码
	 */
	public SFTPUtils(String host, int port, String username,
					 String password){

		sftp = null;
		try {
			JSch jsch = new JSch();
			jsch.getSession(username, host, port);
			sshSession = jsch.getSession(username, host, port);
			LOGGER.debug("Session created.");
			sshSession.setPassword(password);
			Properties sshConfig = new Properties();
			sshConfig.put("StrictHostKeyChecking", "no");
			sshSession.setConfig(sshConfig);
			sshSession.setTimeout(1000*60*30);
			sshSession.connect();
			LOGGER.debug("Session connected.");
			LOGGER.debug("Opening Channel.");
			channel = sshSession.openChannel("sftp");
			channel.connect();
			sftp = (ChannelSftp) channel;
		} catch (Exception e) {
			e.printStackTrace();
			LOGGER.error("创建SFTP通道出现异常");
		}
	}
	/**
	 * 连接sftp服务器
	 * @param host
	 *            主机
	 * @param port
	 *            端口
	 * @param username
	 *            用户名
	 * @param password
	 *            密码
	 * @return
	 */
	public ChannelSftp connect(String host, int port, String username,
							   String password) {
		ChannelSftp sftp = null;
		try {
			JSch jsch = new JSch();
			jsch.getSession(username, host, port);
			Session sshSession = jsch.getSession(username, host, port);
			LOGGER.debug("Session created.");
			sshSession.setPassword(password);
			Properties sshConfig = new Properties();
			sshConfig.put("StrictHostKeyChecking", "no");
			sshSession.setConfig(sshConfig);
			sshSession.setTimeout(1000*60*30);
			sshSession.connect();
			LOGGER.debug("Session connected.");
			LOGGER.debug("Opening Channel.");

			Channel channel = sshSession.openChannel("sftp");
			channel.connect();
			sftp = (ChannelSftp) channel;
		} catch (Exception e) {
			LOGGER.error("创建SFTP通道出现异常");
		}
		return sftp;
	}

	/**
	 * 上传文件
	 *
	 * @param directory
	 *            上传的目录
	 * @param uploadFile
	 *            要上传的文件
	 * @param sftp
	 *            SFTP通道
	 */
	public boolean upload(String directory, String uploadFile, ChannelSftp sftp) {

		try {
			sftp.cd(directory);
			File file = new File(uploadFile);
			sftp.put(new FileInputStream(file), file.getName());
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}


	/**
	 * 创建一个文件目录
	 */
	public  void createDir(String createpath, ChannelSftp sftp) throws Exception {
		try {
			LOGGER.debug(sftp.pwd());
			if (isDirExist(createpath,sftp)) {

			}else{
				String pathArry[] = createpath.split("/");

				for (String path : pathArry) {
					if (StringUtils.isBlank(path)) {
						continue;
					}

					if (isDirExist(path,sftp)) {
						sftp.cd(path);
					} else {
						// 建立目录
						sftp.mkdir(path);
						// 进入并设置为当前目录
						sftp.cd(path);
					}
				}
			}
			LOGGER.debug(sftp.pwd());
			//sftp.cd(createpath);
		} catch (SftpException e) {
			e.printStackTrace();
			throw new Exception("创建路径错误：" + createpath);
		}

	}


	/**
	 * 判断目录是否存在
	 */
	public  boolean isDirExist(String directory,ChannelSftp sftp) {
		boolean isDirExistFlag = false;
		try {
			SftpATTRS sftpATTRS = sftp.lstat(directory);
			isDirExistFlag = true;
			return sftpATTRS.isDir();
		} catch (Exception e) {
			if (e.getMessage().toLowerCase().equals("no such file")) {
				isDirExistFlag = false;
			}
		}
		return isDirExistFlag;
	}




	/**
	 * 下载文件
	 *
	 * @param directory
	 *            下载目录
	 * @param downloadFile
	 *            下载的文件
	 * @param saveFile
	 *            存在本地的路径
	 * @param sftp
	 */
	public void download(String directory, String downloadFile,
						 String saveFile, ChannelSftp sftp) {
		FileOutputStream outputStream = null;
		try {
			sftp.cd(directory);
			File file = new File(saveFile);
			outputStream = new FileOutputStream(file);
			sftp.get(downloadFile, outputStream);
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			try {
				outputStream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}


	/**
	 * 删除文件
	 *
	 * @param directory
	 *            要删除文件所在目录
	 * @param deleteFile
	 *            要删除的文件
	 * @param sftp
	 */
	public void delete(String directory, String deleteFile, ChannelSftp sftp) {
		try {
			sftp.cd(directory);
			sftp.rm(deleteFile);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 *
	 * @param dataFileprefix
	 *        文件前缀
	 * @param dataFileSuffix
	 *        文件后缀
	 * @param directory
	 *        目录
	 * @param sftp
	 *        SFTP通道
	 * @return
	 */
	public  List<String>  listFiles(String  dataFileprefix,String dataFileSuffix,
									String directory,ChannelSftp sftp){
		List<String>  list=new ArrayList<String>();
		String dataFileRexSufFix="";
		if(dataFileSuffix.startsWith(".")){
			dataFileRexSufFix="/"+dataFileSuffix;
		}else {
			dataFileRexSufFix=dataFileSuffix;
		}
		String dataFileRegex="^"+dataFileprefix+".*"+dataFileRexSufFix;
		try {
			Vector<?> lsList=sftp.ls(directory);
			for (int i = 0; i < lsList.size(); i++) {
				LsEntry lsEntry=(LsEntry) lsList.get(i);
				String  fileName=lsEntry.getFilename();
				if(fileName.matches(dataFileRegex))
					list.add(fileName);
			}

		} catch (SftpException e) {
			e.printStackTrace();
			LOGGER.error("SFTP查询目录出现异常");

		}
		return list;

	}
	/**
	 * 列出目录下的文件及目录
	 * @param directory
	 *        要列出的目录
	 * @param sftp
	 *        SFTP通道
	 * @return
	 * @throws SftpException
	 */
	public Vector<?> listFiles(String directory, ChannelSftp sftp)
			throws SftpException {

		return sftp.ls(directory);
	}

	public Vector<?> listFilesNoEx(String directory, ChannelSftp sftp)
			throws SftpException {
		Vector ls = null;
		try {
			ls = sftp.ls(directory);
		}catch (Exception e){
			e.printStackTrace();
		}
		return ls;
	}

	/**
	 * 关闭连接
	 */
	public void  disconnect(ChannelSftp sftp ,Session sshSession,Channel channel)  {
		try{
			if (sftp!=null&&sftp.isConnected()) {
				sftp.disconnect();
			}
			if (channel!=null&&channel.isConnected()) {
				channel.disconnect();
			}
			if (sshSession!=null&&sshSession.isConnected()) {
				sshSession.disconnect();
			}
		}catch(Exception e){
			LOGGER.error("关闭服务器连接出现异常");
		}
	}

	public void  disconnect()  {
		try{
			if (sftp != null && sftp.isConnected()) {
				sftp.disconnect();
			}
			if (channel != null & channel.isConnected()) {
				channel.disconnect();
			}
			if (sshSession != null && sshSession.isConnected()) {
				sshSession.disconnect();
			}
		}catch(Exception e){
			LOGGER.error("关闭服务器连接出现异常");
		}
	}

	//-------------------------
	public ChannelSftp getSftp() {
		return sftp;
	}

	public void setSftp(ChannelSftp sftp) {
		this.sftp = sftp;
	}

	public Session getSshSession() {
		return sshSession;
	}

	public void setSshSession(Session sshSession) {
		this.sshSession = sshSession;
	}

	public Channel getChannel() {
		return channel;
	}

	public void setChannel(Channel channel) {
		this.channel = channel;
	}


	public static void main(String[] args) throws Exception {
		String  cust="BEA_000004_F_C_20120420182012_ALL.dat";
		String  regex=".*";
		String fileUrl = "C:/Users/ZHENG/Desktop/FTP/file2/";
		System.err.println(cust.matches(regex));
		//tempFileName.matches(dataFileRegex)
		ChannelSftp sftp=new ChannelSftp();
		SFTPUtils sftpUtils   =  new SFTPUtils("119.254.15.195", 22321, "nmgsl", "EtDRPjdSVU");
		Vector<?> objects = sftpUtils.listFiles("/data/trs_cust/data/ENT/20230203", sftpUtils.sftp);
		for (Object object : objects) {
			String[] s = object.toString().split(" ");
			String fileName = s[s.length - 1];
			if(!fileName.equals(".") && !fileName.equals("..")){
				System.out.println(fileName);
				sftpUtils.download("/data/trs_cust/data/ENT/20230203",fileName,fileUrl+fileName, sftpUtils.sftp);
				//Java 解压zip
				String newFilename = ZipUtil.unzipFile(fileUrl+fileName, fileUrl);
				List<Map<String,Object>> list = TRSParser.readFile(
						FileUtil.newFile(fileUrl+newFilename),"GBK");
				for (Map<String, Object> map : list) {
					BusinessInfo businessInfo = new BusinessInfo();
					businessInfo.setId(map.get("eid").toString());
					businessInfo.setFormat_name(map.get("entname").toString());
					businessInfo.setOperName(map.get("legal_person").toString());
					businessInfo.setRegistCapi(map.get("regcap").toString()+" 万人民币");
					businessInfo.setStartDate(map.get("esdate").toString());
					businessInfo.setCreditNo(map.get("credit_code").toString());
					businessInfo.setBusinessType("3");
					businessInfo.setStatus(map.get("entstatus_name").toString());
					businessInfo.setRegNo(map.get("regno").toString());
					businessInfo.setEconKind(map.get("enttype_name_char").toString());
					businessInfo.setCheckDate(map.get("apprdate").toString());
					businessInfo.setIndustryChain(map.get("industryco_name").toString());
					businessInfo.setBelongOrg(map.get("regorg_name").toString());
					businessInfo.setSocialStaffNum(map.get("endo_ins_num").toString());
					businessInfo.setManagementLocation(map.get("dom").toString());
					businessInfo.setSocialStaffNum(map.get("opscope").toString());
					businessInfo.setScope(map.get("opscope").toString());
					businessInfo.setTermStart(map.get("opfrom").toString());
					businessInfo.setTermEnd(map.get("opto").toString());
					System.out.println(businessInfo);
				}
			}
		}
		sftpUtils.disconnect(sftpUtils.sftp, sftpUtils.sshSession, sftpUtils.channel);
	}
}
