package com.dxhy.oss.service.impl;

import cn.hutool.core.io.FileUtil;
import com.dxhy.oss.config.OssConfig;
import com.dxhy.oss.config.OssReturnConfig;
import com.dxhy.oss.model.FileModel;
import com.dxhy.oss.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @author jiaohongyang
 */
@Slf4j
@Service("fileService")
public class FileServiceImpl implements FileService {
    private final OssConfig ossConfig;
    private final AliOssService aliOssService;
    private final JdOssService jdOssService;
    private final FtpService ftpService;
    private final SshService sshService;

    @Autowired
    public FileServiceImpl(OssConfig ossConfig, AliOssService aliOssService, JdOssService jdOssService, FtpService ftpService, SshService sshService) {
        this.ossConfig = ossConfig;
        this.aliOssService = aliOssService;
        this.jdOssService = jdOssService;
        this.ftpService = ftpService;
        this.sshService = sshService;
    }

    /**
     * 文件上传
     *
     * @param fileName       上传文件，路径+ 名称
     * @param originFileName 本地文件地址
     * @return 返回
     * @throws Exception 异常
     */
    @Override
    public FileModel uploadFile(String fileName, String originFileName)  {
        log.info("上传文件地址：{} ， 本地存储文件地址：{}", fileName, originFileName);
        FileModel fileModel;
        if (OssReturnConfig.AL.equals(ossConfig.getOssType())) {
            if (fileName.startsWith("/")) {
                fileName = fileName.substring(1);
            }
            fileModel = aliOssService.uploadFile(fileName, originFileName);

        } else if (OssReturnConfig.JD.equals(ossConfig.getOssType())) {
            if (fileName.startsWith("/")) {
                fileName = fileName.substring(1);
            }
            fileModel = jdOssService.uploadFile(fileName, originFileName);

        } else if (OssReturnConfig.SSH.equals(ossConfig.getOssType())){
            if (!fileName.startsWith("/")) {
                fileName = "/" + fileName;
            }
            String directory = fileName.substring(0, fileName.lastIndexOf("/"));
            File directoryFile = new File(fileName);
            String downloadFileName = directoryFile.getName();
            boolean b = sshService.uploadFile(directory, downloadFileName, originFileName);
            fileModel = new FileModel();
            fileModel.setFilePath(fileName);
            if (b) {
                fileModel.setCode(OssReturnConfig.SUCCESS);
            } else {
                fileModel.setCode(OssReturnConfig.ERROR_09);
            }
        }else if (OssReturnConfig.FTP.equals(ossConfig.getOssType())) {
            if (!fileName.startsWith("/")) {
                fileName = "/" + fileName;
            }
            String directory = fileName.substring(0, fileName.lastIndexOf("/"));
            File directoryFile = new File(fileName);
            String downloadFileName = directoryFile.getName();
            boolean b = false;
            try {
                b = ftpService.uploadFile(directory, downloadFileName, originFileName);
            } catch (InterruptedException e) {
                log.error(e.getMessage());
            }
            fileModel = new FileModel();
            fileModel.setFilePath(fileName);
            if (b) {
                fileModel.setCode(OssReturnConfig.SUCCESS);
            } else {
                fileModel.setCode(OssReturnConfig.ERROR_09);
            }
        } else if(OssReturnConfig.LOCAL.equals(ossConfig.getOssType())){
            //创建目录
            boolean b = false;
            FileInputStream fis = null;
            FileOutputStream fos = null;
            try {
                File directory = new File(fileName.substring(0, fileName.lastIndexOf("/")));
                if(!directory.exists()){
                    directory.mkdirs();
                }
                File sourceFile = new File(originFileName);

                File file = new File(fileName);
                if(!file.exists()){
                    file.createNewFile();
                }
                fis = new FileInputStream(sourceFile);
                fos = new FileOutputStream(file);
                //复制文件
                byte[] bytes = new byte[1024];
                while (fis.read(bytes) != -1){
                    fos.write(bytes);
                }
                fos.flush();
                b = true;
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                try {
                    if(fis != null){fis.close();}
                    if(fos != null){fos.close();}
                } catch (IOException e) {
                    log.error("上传文件关闭文件流异常：{}",e.getMessage());
                }
            }
            fileModel = new FileModel();
            fileModel.setFilePath(fileName);
            if (b) {
                fileModel.setCode(OssReturnConfig.SUCCESS);
            } else {
                fileModel.setCode(OssReturnConfig.ERROR_09);
            }

        } else {
            fileModel = new FileModel();
            fileModel.setCode(OssReturnConfig.ERROR_09);
        }
        log.info("文件上传结果编码：{}，地址信息返回：{}", fileModel.getCode(), fileModel.getFilePath());
        return fileModel;
    }

    /**
     *
     * @param downloadFile 下载文件 服务器路径
     * @param saveFile     保存文件地址 本地路劲
     * @return
     */
    @Override
    public FileModel downFile(String downloadFile, String saveFile) {
        log.info("下载文件地址：{} ， 本地存储文件地址：{}", downloadFile, saveFile);
        // 获取下载文件存储路径 ,路径不存在则创建路径
        File file = new File(saveFile);
        String path = file.getParent();
        FileUtil.mkdir(path);
        FileModel fileModel;
        if (OssReturnConfig.AL.equals(ossConfig.getOssType())) {
            if (downloadFile.startsWith("/")) {
                downloadFile = downloadFile.substring(1);
            }
            fileModel = aliOssService.downloadFile(downloadFile, saveFile);
        } else if (OssReturnConfig.JD.equals(ossConfig.getOssType())) {
            if (downloadFile.startsWith("/")) {
                downloadFile = downloadFile.substring(1);
            }
            fileModel = jdOssService.downloadFile(downloadFile, saveFile);
        } else if(OssReturnConfig.SSH.equals(ossConfig.getOssType())){
            String directory = downloadFile.substring(0, downloadFile.lastIndexOf("/"));
            String downloadFileName = downloadFile.substring(downloadFile.lastIndexOf("/") + 1);
            boolean b = sshService.downloadFile(directory, downloadFileName, path);
            fileModel = new FileModel();
            fileModel.setFilePath(saveFile);
            if (b) {
                fileModel.setCode(OssReturnConfig.SUCCESS);
            } else {
                fileModel.setCode(OssReturnConfig.ERROR_09);
            }
        }else if (OssReturnConfig.FTP.equals(ossConfig.getOssType())) {
            String directory = downloadFile.substring(0, downloadFile.lastIndexOf("/"));
            File directoryFile = new File(downloadFile);
            String downloadFileName = directoryFile.getName();
            boolean b = ftpService.downloadFile(directory, downloadFileName, path);
            fileModel = new FileModel();
            fileModel.setFilePath(saveFile);
            if (b) {
                fileModel.setCode(OssReturnConfig.SUCCESS);
            } else {
                fileModel.setCode(OssReturnConfig.ERROR_09);
            }

        } else if(OssReturnConfig.LOCAL.equals(ossConfig.getOssType())){
            //创建目录
            boolean b = false;
            FileInputStream fis = null;
            FileOutputStream fos = null;
            try {
                File download = new File(downloadFile);
                fis = new FileInputStream(download);
                fos = new FileOutputStream(file);
                //复制文件
                byte[] bytes = new byte[1024];
                while (fis.read(bytes) != -1){
                    fos.write(bytes);
                }
                fos.flush();
                b = true;
            } catch (IOException e) {
                log.error("本地导出异常：{}",e);
            }finally {
                try {
                    if(fis != null){fis.close();}
                    if(fos != null){fos.close();}
                } catch (IOException e) {
                    log.error("上传文件关闭文件流异常：{}",e.getMessage());
                }
            }
            fileModel = new FileModel();
            fileModel.setFilePath(saveFile);
            if (b) {
                fileModel.setCode(OssReturnConfig.SUCCESS);
            } else {
                fileModel.setCode(OssReturnConfig.ERROR_09);
            }
        } else {
            fileModel = new FileModel();
            fileModel.setCode(OssReturnConfig.ERROR_09);
        }
        log.info("文件下载结果编码：{}，地址信息返回：{}", fileModel.getCode(), fileModel.getFilePath());
        return fileModel;
    }


    @Override
    public FileModel getUrl(String key) {
        FileModel fileModel;
        log.info("生成文件下载地址：{} ", key);
        if (OssReturnConfig.AL.equals(ossConfig.getOssType())) {
            fileModel = aliOssService.getUrl(key);
        } else if (OssReturnConfig.JD.equals(ossConfig.getOssType())) {
            fileModel = jdOssService.getUrl(key);
        } else {
            fileModel = new FileModel();
            fileModel.setCode(OssReturnConfig.ERROR_09);
        }
        log.info("生成文件下载地址结果编码：{}，地址链接返回：{}", fileModel.getCode(), fileModel.getFilePath());
        return fileModel;
    }

    @Override
    public FileModel deleteFile(String path) {
        log.info("删除文件信息：{} ", path);
        FileModel fileModel;
        if (OssReturnConfig.AL.equals(ossConfig.getOssType())) {
            if (path.startsWith("/")) {
                path = path.substring(1);
            }
            fileModel = aliOssService.deleteFile(path);
        } else if (OssReturnConfig.JD.equals(ossConfig.getOssType())) {
            if (path.startsWith("/")) {
                path = path.substring(1);
            }
            fileModel = jdOssService.deleteFile(path);
        } else if(OssReturnConfig.SSH.equals(ossConfig.getOssType())){
            File file = new File(path);
            boolean b = sshService.deleteFile(file.getParent(), file.getName());
            if (b) {
                fileModel = new FileModel();
                fileModel.setCode(OssReturnConfig.SUCCESS);
            } else {
                fileModel = new FileModel();
                fileModel.setCode(OssReturnConfig.ERROR_01);
            }
        }else if (OssReturnConfig.FTP.equals(ossConfig.getOssType())) {
            File file = new File(path);
            boolean b = ftpService.deleteFile(file.getParent(), file.getName());
            if (b) {
                fileModel = new FileModel();
                fileModel.setCode(OssReturnConfig.SUCCESS);
            } else {
                fileModel = new FileModel();
                fileModel.setCode(OssReturnConfig.ERROR_01);
            }
        } else if(OssReturnConfig.LOCAL.equals(ossConfig.getOssType())){
            File file = new File(path);
            boolean b = file.delete();
            if (b) {
                fileModel = new FileModel();
                fileModel.setCode(OssReturnConfig.SUCCESS);
            } else {
                fileModel = new FileModel();
                fileModel.setCode(OssReturnConfig.ERROR_01);
            }
        }else{
            fileModel = new FileModel();
            fileModel.setCode(OssReturnConfig.ERROR_09);
        }
        log.info("删除文件信息返回结果编码：{}", fileModel.getCode());
        return fileModel;
    }

    @Override
    public String getPathPrefix() {
        return ossConfig.getPathPrefix();
    }

    @Override
    public String getLocalPathDefault() {
        return ossConfig.getLocalPathDefault();
    }

    @Override
    public String getTempPath() {
        return ossConfig.getTempPath();
    }

    /**
     * PDF 上传文件大小
     */
    @Override
    public String getFtpPdfSize() {
        return ossConfig.getPdfSize();
    }
}
