package cc.smtweb.system.bpm.spring.file.attach;

import cc.smtweb.framework.core.util.StringUtil;
import cc.smtweb.system.bpm.spring.config.FileConfigProperties;
import cc.smtweb.system.bpm.util.UtilDownloadFile;
import cc.smtweb.system.bpm.util.UtilFile;
import cc.smtweb.system.bpm.util.ftp.FtpTask;
import cc.smtweb.system.bpm.util.ftp.FtpTaskManager;
import cc.smtweb.system.bpm.util.ftp.IFtpServerConfig;
import cc.smtweb.system.bpm.util.ftp.IFtpUtil;
import cc.smtweb.system.bpm.web.sys.base.attach.AttachInfo;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.InputStream;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by AKmm at 2011-2-23 16:35:49
 * ftp工作服务
 */
@Component
public final class AttachFtpWork implements IAttachWorkIntf {
    Logger logger = LoggerFactory.getLogger(AttachFtpWork.class);
    @Autowired
    private FileConfigProperties properties;

    private String getPath(String remoteFolderPath) {
        String path = properties.getAttachPath();
        if (StringUtil.isNotEmpty(remoteFolderPath) && !path.endsWith("/") && !remoteFolderPath.startsWith("/"))
            path = path + "/" + remoteFolderPath;
        else path = path + remoteFolderPath;
        path = path.replaceAll("-", "");
        UtilFile.makeDir(path);
        if (!path.endsWith("/")) path = path + "/";
        logger.info("远程附件路径：" + path);
        return path;
    }

    public FtpTaskManager getFtpManager() {
        return FtpTaskManager.getInstance("ATTACH_FTP", new IFtpServerConfig() {
            @Override
            public boolean isSFTP() {
                return "sftp".equalsIgnoreCase(properties.getAttachType());
            }

            @Override
            public String getServerIp() {
                return properties.getAttachFtpIp();
            }

            @Override
            public Integer getPort() {
                return properties.getAttachFtpPort();
            }

            @Override
            public String getUserName() {
                return properties.getAttachFtpUser();
            }

            @Override
            public String getPassword() {
                return properties.getAttachFtpPwd();
            }
        });
    }

    public void saveAttach(String remoteAttachName, String remoteFolderPath, String localAttach, boolean isDelLocal) throws Exception {
        getFtpManager().uploadToFtp(remoteAttachName, getPath(remoteFolderPath), localAttach, isDelLocal);
    }

    @Override
    public void copyAttach(String srcFileName, String desFileName, String remoteFolderPath, boolean isDelSrc) throws Exception {
        getFtpManager().execute(new FtpTask() {
            public Object execute(IFtpUtil ftp) throws Exception {
                if (!ftp.existsFile(srcFileName, getPath(remoteFolderPath))) return null;
                ftp.setRemoteDir("/");
                ftp.mkdir(remoteFolderPath);
                ftp.rename(remoteFolderPath, srcFileName, desFileName);
                return null;
            }
        });
    }


    public void deletePath(final String remotePath) throws Exception {
        getFtpManager().execute(new FtpTask() {
            public Object execute(IFtpUtil ftp) throws Exception {
                ftp.deleteFolder(remotePath);
                return null;
            }
        });
    }

    public void deleteAttach(final String remotePath, final String remoteName) throws Exception {
        getFtpManager().execute(new FtpTask() {
            public Object execute(IFtpUtil ftp) throws Exception {
                ftp.deleteFile(getPath(remotePath), remoteName);
                return null;
            }
        });
    }

    public void downloadAttach(final String remotePath, final String remoteName, final String fileName, final HttpServletResponse response) throws Exception {
        getFtpManager().execute(new FtpTask() {
            public Object execute(IFtpUtil ftp) throws Exception {
                InputStream in;
                in = ftp.downloadFile(getPath(remotePath), remoteName);

                if (in == null) return null;
                try {
                    UtilDownloadFile.downfileStream(response, fileName, 0, in);
                } finally {
                    IOUtils.closeQuietly(in);
                    ftp.completePendingCommand();
                }

                return null;
            }
        });
    }

    @Override
    public void showAttachImg(final String remotePath, final String remoteName, final HttpServletResponse response) throws Exception {
        getFtpManager().execute(new FtpTask() {
            public Object execute(IFtpUtil ftp) throws Exception {
                InputStream in = null;
                try {
                    in = ftp.downloadFile(getPath(remotePath), remoteName);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (in == null) return null;
                try {
                    UtilDownloadFile.sendImgStream(response, in);
                } finally {
                    IOUtils.closeQuietly(in);
                    ftp.completePendingCommand();
                }

                return null;
            }
        });
    }


    public void downloadAttach(final String remotePath, final String remoteName, final String localPath) throws Exception {
        getFtpManager().execute(new FtpTask() {
            public Object execute(IFtpUtil ftp) throws Exception {
                try {
                    ftp.downloadFile(getPath(remotePath), remoteName, localPath);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return null;
            }
        });
    }

    @Override
    public void downloadAttach(String remotePath, String remoteName, String localPath, String localName) throws Exception {
        getFtpManager().execute(new FtpTask() {
            public Object execute(IFtpUtil ftp) throws Exception {
                try {
                    ftp.downloadFileEx(getPath(remotePath), remoteName, localPath + File.separator + localName);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return null;
            }
        });
    }

    public List<String> getAttachListFromFtp(final List<AttachInfo> attachlist, final String ownerType, final String localRoot) throws Exception {
        final List<String> files = new ArrayList<String>();
        getFtpManager().execute(new FtpTask() {
            public Object execute(IFtpUtil ftp) throws Exception {
                String localPath = localRoot + UtilFile.FSChar + ownerType + UtilFile.FSChar;
                File file = new File(localPath);
                if (!file.exists()) {
                    file.mkdirs();
                }
                String fileName;
                for (AttachInfo attach : attachlist) {
                    fileName = localPath + attach.getName();
                    file = new File(fileName);
                    if (!file.exists())
                        try {
                            ftp.downloadFileEx(getPath(attach.getPath()), attach.getName(), fileName);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    files.add(fileName);
                }

                return null;
            }
        });
        return files;
    }

    public void makeRemoteDir(final String path) throws Exception {
        getFtpManager().execute(new FtpTask() {
            public Object execute(IFtpUtil ftp) throws Exception {
                ftp.setRemoteDir(path);
                return null;
            }
        });
    }

    @Override
    public Path getAttachPath(String remotePath, String remoteName) {
        throw new UnsupportedOperationException("FTP的还没用到，没开发，暂不支持");
    }
}
