package com.xydl.cac.task;

import com.jcraft.jsch.ChannelSftp;
import com.xydl.cac.config.BizConfig;
import com.xydl.cac.entity.*;
import com.xydl.cac.entity.constants.Constants;
import com.xydl.cac.model.StaticVariable;
import com.xydl.cac.service.RemoteConfigService;
import com.xydl.cac.service.RemoteDownloadService;
import com.xydl.cac.socket.WebSocketServer;
import com.xydl.cac.util.DingTalkPushUtil;
import com.xydl.cac.util.SFTPTool;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.Vector;

@Service
@Slf4j
public class SftpDownloadTask {

    String folder = "/sftp";

    @Resource
    BizConfig bizConfig;
    @Resource
    RemoteConfigService configService;
    @Resource
    RemoteDownloadService downloadService;
    @Resource
    DingTalkPushUtil dingTalkPushUtil;
    @Resource
    WebSocketServer webSocketServer;

    int shutdown = 0;

    @PreDestroy
    private void preDestroy() {
        shutdown = 1;
    }

    @Scheduled(cron = "0 10 * * * ?")
    public void downloadAll() {
        List<RemoteConfig> configList = configService.listAll();
        if (!CollectionUtils.isEmpty(configList)) {
            log.info("AmpliDownloadTask.downloadAll 开始.");
            for (RemoteConfig config : configList) {
                this.downloadServer(config);
            }
            log.info("AmpliDownloadTask.downloadAll 结束.");
        }
    }

    // 下载一个远端服务器
    private void downloadServer(RemoteConfig config) {
        if (shutdown == 1) {
            return;
        }
        if (config.getActive() == null || config.getActive().intValue() == Constants.FALSE) {
            return;
        }
        config.toList();
        if (config.getPathList() == null) {
            return;
        }
        SFTPTool sftpTool = new SFTPTool();
        try {
            sftpTool.connect(config.getIp(), config.getPort(), config.getUser(), config.getPasswd());

            for (String remotePath : config.getPathList()) {
                this.downloadPath(remotePath, config, sftpTool);
            }
        } catch (Exception e) {
            log.error("AmpliDownloadTask.downloadServer error.", e);
            String str = "SFTP下载文件异常: " + config.getName() + " " +
                    config.getIp() + " " + e.getMessage();
            String key = "sftp" + config.getId();
            if (!StaticVariable.doneWarnMap.containsKey(key)) {
                StaticVariable.doneWarnMap.put(key, "1");
                webSocketServer.sendMessage(str, null);
                dingTalkPushUtil.pushText(str);
            }
        } finally {
            sftpTool.disconnect();
        }
    }

    private void downloadPath(String remotePath, RemoteConfig config, SFTPTool sftpTool) throws Exception {
        if (shutdown == 1) {
            return;
        }
        String str = "abcd" + remotePath.replaceAll("/", "").replaceAll("\\\\", "");
        str = str.substring(str.length() - 4);
        String localPath = folder + "/" + config.getIp() + "/" + str;
        File dir = new File(bizConfig.getDatapath() + localPath);
        dir.mkdirs();

        Vector<ChannelSftp.LsEntry> files = sftpTool.listFiles(remotePath);
        for (ChannelSftp.LsEntry file : files) {
            this.downloadFile(remotePath, file.getFilename(), localPath, config, sftpTool);
        }
    }

    private void downloadFile(String remotePath, String filename,
                              String localPath, RemoteConfig config, SFTPTool sftpTool) throws Exception {
        if (shutdown == 1) {
            return;
        }
        if (StringUtils.isBlank(config.getSuffix()) || filename.toLowerCase().endsWith(config.getSuffix().toLowerCase())) {
            RemoteDownload item = new RemoteDownload();
            item.setConfigId(config.getId());
            item.setRemotePath(remotePath);
            item.setFilename(filename);

            boolean exist = downloadService.exist(item);
            if (!exist) {
                String localFilePath = localPath + "/" + filename;
                sftpTool.download(filename, bizConfig.getDatapath() + localFilePath);
                if (config.getTodel() != null && config.getTodel().intValue() == Constants.TRUE) {
                    sftpTool.delete(filename);
                }
                item.setPath(bizConfig.getDataNginxPath() + localFilePath);
                item.setCreateTime(new Date());
                downloadService.add(item);
            }
        }
    }

}
