package com.dxhy.oss.service.impl;

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

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

/**
 * @author jiaohongyang
 */
@Service("aliOssService")
@Slf4j
public class AliOssServiceImpl implements AliOssService {

    private final OssConfig ossConfig;

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

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

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

            // 进行文件上传

            ossClient.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 (ossClient != null) {
                ossClient.shutdown();
            }
            FileUtil.del(filePath);
        }
    }

    @Override
    public FileModel getUrl(String key) {
        OSS ossClient = null;
        FileModel fileModel;
        try {
            ossClient =
                    OssClientFactory.getInstance(ossConfig.getEndpointUrl(), ossConfig.getAccessKeyId(), ossConfig.getAccessKeySecret());
            if (ossClient == 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);
            // 生成URL
            URL url = ossClient.generatePresignedUrl(ossConfig.getBucketName(), key, expiration);
            if (url != null) {
                fileModel = new FileModel();
                fileModel.setCode(OssReturnConfig.SUCCESS);
                fileModel.setFilePath(url.toString());
                return fileModel;
            }
        } catch (Exception e) {
            e.printStackTrace();

        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        fileModel = new FileModel();
        fileModel.setCode(OssReturnConfig.ERROR_09);
        return fileModel;
    }

    /**
     * 下载
     *
     * @param fileName 文件名称
     * @param filePath 本地文件存储地址
     * @return 返回
     */
    @Override
    public FileModel downloadFile(String fileName, String filePath) {
        log.info("下载文件阿里OSS，存储目录：{} , 存储文件名：{} ", ossConfig.getBucketName(), fileName);
        OSS ossClient = null;
        FileModel fileModel;
        try {
            // 创建连接
            ossClient =
                    OssClientFactory.getInstance(ossConfig.getEndpointUrl(), ossConfig.getAccessKeyId(), ossConfig.getAccessKeySecret());
            if (ossClient == null) {
                fileModel = new FileModel();
                fileModel.setCode(OssReturnConfig.ERROR_09);
                return fileModel;
            }
            // 下载OSS文件到本地文件。如果指定的本地文件存在会覆盖，不存在则新建。
            ossClient.getObject(new GetObjectRequest(ossConfig.getBucketName(), fileName), new File(filePath));
            fileModel = new FileModel();
            fileModel.setCode(OssReturnConfig.SUCCESS);
            fileModel.setFilePath(filePath);
            return fileModel;
        } catch (Exception e) {
            log.error("文件下载阿里OSS失败，异常：{}", e.getMessage());
            e.printStackTrace();
            fileModel = new FileModel();
            fileModel.setCode(OssReturnConfig.ERROR_09);
            return fileModel;
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

    /**
     * 删除文件
     *
     * @param file 文件名
     * @return 返回
     */
    @Override
    public FileModel deleteFile(String file) {
        log.info("文件删除阿里OSS，存储目录：{} , 存储文件名：{} ", ossConfig.getBucketName(), file);
        OSS ossClient = null;
        FileModel fileModel;
        try {
            // 创建连接
            ossClient =
                    OssClientFactory.getInstance(ossConfig.getEndpointUrl(), ossConfig.getAccessKeyId(), ossConfig.getAccessKeySecret());
            if (ossClient == null) {
                fileModel = new FileModel();
                fileModel.setCode(OssReturnConfig.ERROR_09);
                return fileModel;
            }
            ossClient.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 (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}
