package com.dxhy.oss.service.impl;

import cn.hutool.core.io.FileUtil;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.GeneratePresignedUrlRequest;
import com.amazonaws.services.s3.model.S3Object;
import com.amazonaws.services.s3.model.S3ObjectInputStream;
import com.dxhy.oss.config.OssConfig;
import com.dxhy.oss.config.OssReturnConfig;
import com.dxhy.oss.model.FileModel;
import com.dxhy.oss.service.JdOssService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.Date;

/**
 * @author jiaohongyang
 */
@Service("jdOssService")
@Slf4j
public class JdOssServiceImpl implements JdOssService {
    private final OssConfig ossConfig;

    @Autowired
    public JdOssServiceImpl(OssConfig ossConfig) {
        this.ossConfig = ossConfig;
    }

    /**
     * 京东云OSS文件存储
     *
     * @param filePath 文件
     * @return 返回
     */
    @Override
    public FileModel uploadFile(String fileName, String filePath) {
        FileModel fileModel;
        AmazonS3 jdInstance = null;

        log.info("文件存储京东OSS，存储目录：{} , 存储文件名：{} ", ossConfig.getBucketName(), fileName);
        try {
            // 创建连接
            jdInstance = OssClientFactory.getJdInstance(ossConfig.getEndpointUrl(), ossConfig.getAccessKeyId(),
                    ossConfig.getAccessKeySecret(), ossConfig.getRegion());
            if (jdInstance == null) {
                fileModel = new FileModel();
                fileModel.setCode(OssReturnConfig.ERROR_09);
                return fileModel;
            }

            // 进行文件上传
            jdInstance.putObject(ossConfig.getBucketName(), fileName, new File(filePath));
            fileModel = new FileModel();
            fileModel.setCode(OssReturnConfig.SUCCESS);
            fileModel.setFilePath(fileName);
            return fileModel;
        } catch (Exception e) {
            log.error("文件存储京东OSS失败,异常：{}", e.getMessage());
            e.printStackTrace();
            fileModel = new FileModel();
            fileModel.setCode(OssReturnConfig.ERROR_09);
            return fileModel;
        } finally {
            if (jdInstance != null) {
                jdInstance.shutdown();
            }
            FileUtil.del(filePath);
        }
    }

    /**
     * 下载
     *
     * @param fileName 文件名称
     * @param filePath 本地文件存储地址
     * @return 返回
     */
    @Override
    public FileModel downloadFile(String fileName, String filePath) {
        log.info("下载文件京东OSS，存储目录：{} , 存储文件名：{} ", ossConfig.getBucketName(), fileName);
        AmazonS3 jdInstance = null;
        S3ObjectInputStream s3is = null;
        FileOutputStream fos = null;
        FileModel fileModel;
        try {
            // 创建连接
            jdInstance = OssClientFactory.getJdInstance(ossConfig.getEndpointUrl(), ossConfig.getAccessKeyId(),
                    ossConfig.getAccessKeySecret(), ossConfig.getRegion());
            if (jdInstance == null) {
                fileModel = new FileModel();
                fileModel.setCode(OssReturnConfig.ERROR_09);
                return fileModel;
            }
            // 下载OSS文件到本地文件。如果指定的本地文件存在会覆盖，不存在则新建。
            S3Object object = jdInstance.getObject(ossConfig.getBucketName(), fileName);
            s3is = object.getObjectContent();
            fos = new FileOutputStream(filePath);
            byte[] readBuf = new byte[1024];
            int readLen = 0;
            while ((readLen = s3is.read(readBuf)) > 0) {
                fos.write(readBuf, 0, readLen);
            }
            fileModel = new FileModel();
            fileModel.setCode(OssReturnConfig.SUCCESS);
            fileModel.setFilePath(filePath);
            return fileModel;
        } catch (Exception e) {
            e.printStackTrace();
            fileModel = new FileModel();
            fileModel.setCode(OssReturnConfig.ERROR_09);
            return fileModel;
        } finally {
            try {
                if (s3is != null) {
                    s3is.close();
                }
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

            if (jdInstance != null) {
                jdInstance.shutdown();
            }
        }
    }

    @Override
    public FileModel getUrl(String key) {
        log.info("生成文件下载地址京东OSS，存储目录：{} , 存储文件名：{} ", ossConfig.getBucketName(), key);
        AmazonS3 jdInstance = null;
        FileModel fileModel;
        try {
            // 创建连接
            jdInstance = OssClientFactory.getJdInstance(ossConfig.getEndpointUrl(), ossConfig.getAccessKeyId(),
                    ossConfig.getAccessKeySecret(), ossConfig.getRegion());
            if (jdInstance == null) {
                fileModel = new FileModel();
                fileModel.setCode(OssReturnConfig.ERROR_09);
                return fileModel;
            }
            // 设置URL过期时间为10年 3600l* 1000*24*365*10
            Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 2);
            GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(ossConfig.getBucketName(), key);
            request.setExpiration(expiration);
            URL url = jdInstance.generatePresignedUrl(request);
            if (url != null) {
                fileModel = new FileModel();
                fileModel.setCode(OssReturnConfig.SUCCESS);
                fileModel.setFilePath(url.toString());
                return fileModel;
            }

        } catch (Exception e) {
            e.printStackTrace();
            log.error("文件下载京东OSS失败，异常：{}", e.getMessage());
        } finally {
            if (jdInstance != null) {
                jdInstance.shutdown();
            }
        }
        fileModel = new FileModel();
        fileModel.setCode(OssReturnConfig.ERROR_09);
        return fileModel;

    }

    /**
     * 删除文件
     *
     * @param file 文件名
     * @return 返回
     */
    @Override
    public FileModel deleteFile(String file) {
        log.info("文件删除京东云OSS，存储目录：{} , 存储文件名：{} ", ossConfig.getBucketName(), file);
        AmazonS3 jdInstance = null;
        FileModel fileModel;
        try {
            // 创建连接
            // 创建连接
            jdInstance = OssClientFactory.getJdInstance(ossConfig.getEndpointUrl(), ossConfig.getAccessKeyId(),
                    ossConfig.getAccessKeySecret(), ossConfig.getRegion());
            if (jdInstance == null) {
                fileModel = new FileModel();
                fileModel.setCode(OssReturnConfig.ERROR_09);
                return fileModel;
            }
            jdInstance.deleteObject(ossConfig.getBucketName(), file);
            fileModel = new FileModel();
            fileModel.setCode(OssReturnConfig.SUCCESS);
            return fileModel;
        } catch (Exception e) {
            log.error("文件删除京东云OSS失败，异常：{}", e.getMessage());
            e.printStackTrace();
            fileModel = new FileModel();
            fileModel.setCode(OssReturnConfig.ERROR_09);
            return fileModel;
        } finally {
            if (jdInstance != null) {
                jdInstance.shutdown();
            }
        }
    }
}
