package com.xydl.cac.util;

import com.jcraft.jsch.JSchException;
import com.xydl.cac.entity.IedDlRecord;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class JkpgFtp {
    @Value("${cac.jkpg.ip:}")
    private String ip;
    @Value("${cac.jkpg.port:22}")
    private Integer port;
    @Value("${cac.jkpg.user:}")
    private String user;
    @Value("${cac.jkpg.pass:}")
    private String pass;
    @Value("${cac.jkpg.pass:}")
    private String path;

    SFTPTool sftpTool = new SFTPTool();
    boolean connected = false;

    public void connect() {
        if (StringUtils.isBlank(ip)) {
            log.error("健康评估的IP未配置");
            return;
        }
        if (StringUtils.isBlank(user)) {
            log.error("健康评估的user未配置");
            return;
        }
        try {
            sftpTool.connect(ip, port, user, pass);
            sftpTool.cdmkdir(path);
            connected = true;
        } catch (Exception e) {
            log.error("SFTP连接健康评估失败", e);
            connected = false;
        }
    }

    public void upload(IedDlRecord record) {
        if (!connected) {
            this.connect();
        }
        if (connected) {
            try {
                sftpTool.upload(record.getLocalFullPath(), record.getFilename());
                log.info("SFTP上传健康评估成功, " + record.getFilename());
            } catch (Exception e) {
                log.error("SFTP上传健康评估失败, " + record.getFilename(), e);
            }
        }
    }
}
