package com.ssyf.module.resource;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import org.dromara.x.file.storage.core.FileInfo;
import org.dromara.x.file.storage.core.FileStorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class OssUploadService {

    OSS ossClient;

    OssConfig ossConfig = new OssConfig();

    @Lazy
    @Autowired
    private FileStorageService fileStorageService;
    @Value("${theServer.filesUrl:http://cloud.ssyunfu.com/files/}")
    private String filesUrl;

    @PostConstruct
    private void init(){
        ossClient = ossConfig.getOssClient();
    }


    public Map generatePostSignature() {
        OSS ossClient = ossConfig.getOssClient();
        Map response = new HashMap();
        try {
            long expireEndTime = System.currentTimeMillis() + ossConfig.getExpireTime() * 1000;
            Date expiration = new Date(expireEndTime);
            PolicyConditions policyConds = new PolicyConditions();
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, ossConfig.getDir());
            String postPolicy = ossClient.generatePostPolicy(expiration, policyConds);
            byte[] binaryData = postPolicy.getBytes("utf-8");
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            String postSignature = ossClient.calculatePostSignature(postPolicy);
            response.put("ossAccessKeyId", ossConfig.getAccessKeyId());
            response.put("policy", encodedPolicy);
            response.put("signature", postSignature);
            response.put("dir", ossConfig.getDir());
            response.put("host", ossConfig.getHost());
        } catch (
                OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
//            // 假设此方法存在
            System.out.println("HTTP Status Code: " + oe.getRawResponseError());
            System.out.println("Error Message: " + oe.getErrorMessage());
            System.out.println("Error Code:       " + oe.getErrorCode());
            System.out.println("Request ID:      " + oe.getRequestId());
            System.out.println("Host ID:           " + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message: " + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
            return response;
        }
    }


    public static class OssConfig {

        String endpoint = "oss-cn-hongkong.aliyuncs.com";
        // 从环境变量中获取步骤1.1生成的RAM用户的访问密钥（AccessKey ID和AccessKey Secret）。
        String accessKeyId = "LTAI5t8xBP8YBmUhZdoj5qiX";
        String accessKeySecret = "GQzdDgnaLB3CYMwVOq30XJGVaLNR18";

        /**
         * 将 <YOUR-BUCKET> 替换为 Bucket 名称
         */
        private String bucket = "os--video";
        /**
         * 指定上传到 OSS 的文件前缀
         */
        private String dir = "unified-message/";
        /**
         * 指定过期时间，单位为秒
         */
        private long expireTime = 3600;
        /**
         * 构造 host
         */
        private String host = "http://" + bucket + "." + endpoint;

        private OSS ossClient;

        public OSS getOssClient() {
            ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            return ossClient;
        }

        public String getHost() {
            return host;
        }

        public String getAccessKeyId() {
            return accessKeyId;
        }

        public long getExpireTime() {
            return expireTime;
        }

        public String getDir() {
            return dir;
        }

        public void onDestroy() {
            ossClient.shutdown();
        }
    }
}
