package com.supServer.common.utils;

import com.amazonaws.ClientConfiguration;
import com.amazonaws.Protocol;
import com.amazonaws.auth.PropertiesCredentials;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.S3ClientOptions;
import com.amazonaws.services.s3.internal.Mimetypes;
import com.amazonaws.services.s3.model.GeneratePresignedUrlRequest;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.model.PutObjectRequest;
import com.amazonaws.services.s3.model.PutObjectResult;
import com.supServer.common.utils.file.FileUploadUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @description：
 * @Author: ly
 * @Date: 2022/4/13 11:06
 */
@Component
public class FileUploadUtil {

    private static final Logger logger = LoggerFactory.getLogger(Threads.class);

    private static String accessKey = "L6pr75HLgfpCW2ULNSq9";
    private static String secretKey = "cTNvyScRuCwc03zXlv3ddoec45RwsBIAQhNhDw5m";
    private static String endpoint = "cq4oss.ctyunxs.cn";
    private static String bucket = "cqzx";

//    public static void main(String[] args) {
//        System.out.println(OssConfig.accessKey);
//        System.out.println(OssConfig.getAccessKey());
//    }
    public static AmazonS3 getClient() {
        ClientConfiguration clientConfig = new ClientConfiguration();
        // 设置连接的超时时间，单位毫秒
        clientConfig.setConnectionTimeout(30 * 1000);
        // 设置 socket 超时时间，单位毫秒
        clientConfig.setSocketTimeout(30 * 1000);
        clientConfig.setProtocol(Protocol.HTTP); //设置 http
        // 设置 V4 签名算法中负载是否参与签名，关于签名部分请参看《OOS 开发者文档》
        S3ClientOptions options = new S3ClientOptions();
        options.setPayloadSigningEnabled(true);
        // 创建 client
        AmazonS3 oosClient = new AmazonS3Client(
                new PropertiesCredentials(accessKey,secretKey), clientConfig);
        // 设置 endpoint
        oosClient.setEndpoint(endpoint);
        //设置选项
        oosClient.setS3ClientOptions(options);
        return oosClient;
    }

    public static String uploadFile(MultipartFile file) {
        AmazonS3 ossClient = getClient();
        String fileName = FileUploadUtils.extractFilename(file);
        if (fileName.contains("(") || fileName.contains(")")){
            fileName=fileName.replace("(","").replace(")","");
        }
        try {
            File file1 = multipartFileToFile(file);
            // 创建上传Object的Metadata
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setCacheControl("no-cache");
            objectMetadata.setHeader("Pragma", "no-cache");
            if (objectMetadata.getContentType() == null) {
                objectMetadata.setContentType(Mimetypes.getInstance().getMimetype(fileName));
            }
            // 上传文件
            logger.info("开始上传文件到oos");
            FileInputStream fis = new FileInputStream(file1);
            objectMetadata.setContentLength(fis.available());
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucket, fileName, fis, objectMetadata);
            PutObjectResult putObjectResult = ossClient.putObject(putObjectRequest);
            System.out.println("===================" + putObjectResult);
            //删除临时文件
            File del = new File(file1.toURI());
            del.delete();
            System.out.println(fileName);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("上传文件到oos失败");
        } finally {
            if (ossClient != null) {
                ((AmazonS3Client) ossClient).shutdown();
            }
        }
        return fileName;
    }

    public static String generatePresignedUrl(String fileKey) throws ParseException {
        GeneratePresignedUrlRequest request = new
                GeneratePresignedUrlRequest(bucket, fileKey);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date expireDate = sdf.parse("2099-01-01");
        request.setExpiration(expireDate);
        URL url = getClient().generatePresignedUrl(request);
        return url.toString();
    }


    /**
     * MultipartFile 转 File
     *
     * @param file
     * @throws Exception
     */
    public static File multipartFileToFile(MultipartFile file) throws Exception {

        File toFile = null;
        if (file.equals("") || file.getSize() <= 0) {
            file = null;
        } else {
            InputStream ins = null;
            ins = file.getInputStream();
            toFile = new File(file.getOriginalFilename());
            inputStreamToFile(ins, toFile);
            ins.close();
        }
        return toFile;
    }

    //获取流文件
    private static void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
