package com.yn.bftl.thirdparty.modules.qiniu.util;

import com.qiniu.cdn.CdnManager;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.FileInfo;
import com.qiniu.util.Auth;
import com.yn.bftl.common.modules.configuration.entity.ThirdPartyPaySet;
import com.yn.bftl.thirdparty.modules.configuration.service.ThirdPartyPaySetService;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * 七牛云工具类
 *
 * @author huabiao
 * @create 2022/12/8  10:47
 **/
@Component
public class QiniuFileUtils {

    private static final Log log = LogFactory.getLog(QiniuFileUtils.class);

    @Resource
    private ThirdPartyPaySetService thirdPartyPaySetService;

    private static String accessKey;

    @Value("${qiniu.accessKey}")
    public void setAccessKey(String accessKey) {
        QiniuFileUtils.accessKey = accessKey;
    }

    public static String secretKey;

    @Value("${qiniu.secretKey}")
    public void setSecretKey(String secretKey) {
        QiniuFileUtils.secretKey = secretKey;
    }

    private static String bucketName;

    @Value("${qiniu.bucketName}")
    public void setBucketName(String bucketName) {
        QiniuFileUtils.bucketName = bucketName;
    }

    private static String domainImage;

    @Value("${qiniu.domain.image}")
    public void setDomain(String domain) {
        QiniuFileUtils.domainImage = domain;
    }

    private static String domainVideo;

    @Value("${qiniu.domain.video}")
    public void setDomainVideo(String domainVideo) {
        QiniuFileUtils.domainVideo = domainVideo;
    }

    private static String proxyHost;

    @Value("${proxy.host}")
    public void setProxyHostAddress(String proxyHostAddress) {
        QiniuFileUtils.proxyHost = proxyHostAddress;
    }

    private static Integer proxyPort;

    @Value("${proxy.port}")
    public void setProxyPort(Integer proxyPort) {
        QiniuFileUtils.proxyPort = proxyPort;
    }

    //密钥配置
    private static Auth auth = null;

    //密钥配置
    private static CdnManager cdnManager = null;

    //创建上传对象
    private static UploadManager uploadManager = null;

    // 空间资源管理器
    private static BucketManager bucketManager = null;

    private final static String FILE_TYPE_IMAGE = "image";
    private final static String FILE_TYPE_VIDEO = "video";
    private final static String FILE_TYPE_APK = "apk";
    private final static String EXPECT_KEY = "你好?&=\r\n";

    //简单上传，使用默认策略，只需要设置上传的空间名就可以了
    private String getUpToken() {
        String token;
        ThirdPartyPaySet thirdPartyPaySet = thirdPartyPaySetService.getUploadThirdPartyPaySet();
        if (thirdPartyPaySet != null) {
            token = getAuth().uploadToken(thirdPartyPaySet.getQiniuBucket());
        } else {
            token = getAuth().uploadToken(bucketName);
        }
        return token;
    }

    private Auth getAuth() {
        ThirdPartyPaySet thirdPartyPaySet = thirdPartyPaySetService.getUploadThirdPartyPaySet();
        if (thirdPartyPaySet != null) {
            return Auth.create(thirdPartyPaySet.getQiniuAccessKey(), thirdPartyPaySet.getQiniuSecretKey());
        }
        if (auth == null) {
            auth = Auth.create(accessKey, secretKey);
        }
        return auth;
    }

    private static UploadManager getUploadManager() {
        if (uploadManager == null) {
            Configuration configuration = new Configuration(Region.autoRegion());
            uploadManager = new UploadManager(configuration);
        }
        if (StringUtils.isNotBlank(proxyHost) && proxyPort != null) {
            System.setProperty("http.proxyHost", proxyHost);
            System.setProperty("http.proxyPort", proxyPort.toString());
            System.setProperty("https.proxyHost", proxyHost);
            System.setProperty("https.proxyPort", proxyPort.toString());
        }
        return uploadManager;
    }

    private BucketManager getBucketManager() {
        if (bucketManager == null) {
            Configuration configuration = new Configuration(Region.autoRegion());
            bucketManager = new BucketManager(getAuth(), configuration);
        }
        if (StringUtils.isNotBlank(proxyHost) && proxyPort != null) {
            System.setProperty("http.proxyHost", proxyHost);
            System.setProperty("http.proxyPort", proxyPort.toString());
            System.setProperty("https.proxyHost", proxyHost);
            System.setProperty("https.proxyPort", proxyPort.toString());
        }
        return bucketManager;
    }

    public String uploadVideo(MultipartFile file) {
        return upload(file, FILE_TYPE_VIDEO);
    }

    public String uploadImage(MultipartFile file) {
        return upload(file, FILE_TYPE_IMAGE);
    }

    public String uploadImage(File file) {
        return upload(file, FILE_TYPE_IMAGE);
    }

    /**
     * 文件上传
     *
     * @param file
     * @return
     */
    private String upload(MultipartFile file, String type) {
        String fileName = getQiniuFileName(file.getOriginalFilename());
        try {
            Response response = getUploadManager().put(file.getBytes(), fileName, getUpToken());
            //打印返回的信息
            log.info(response.bodyString());
            log.info(response.getInfo());
        } catch (QiniuException qiniuException) {
            Response response = qiniuException.response;
            // 请求失败时打印的异常的信息
            log.info(response.toString());
            try {
                //响应的文本信息
                log.info(response.bodyString());
            } catch (QiniuException e1) {
                //ignore
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        String domain = getDomain(type);
        if (!domain.endsWith("/")) {
            domain += "/";
        }
        removeProxy();
        return domain + fileName;
    }

    /**
     * 文件上传
     *
     * @param file
     * @return
     */
    public String upload(File file, String type) {
        String fileName = getQiniuFileName(file.getName());
        try {
            //调用put方法上传
            Response res = getUploadManager().put(file, fileName, getUpToken());
            //打印返回的信息
            log.info(res.bodyString());
            log.info(res.getInfo());
        } catch (QiniuException e) {
            Response r = e.response;
            // 请求失败时打印的异常的信息
            log.info(r.toString());
            try {
                //响应的文本信息
                log.info(r.bodyString());
            } catch (QiniuException e1) {
                //ignore
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        String domain = getDomain(type);
        if (!domain.endsWith("/")) {
            domain += "/";
        }
        removeProxy();
        return domain + fileName;
    }

    /**
     * 七牛云-文件重命名
     *
     * @param oldFileName:旧文件名称
     * @param newFileName:新文件名称
     * @return
     * @description
     * @author huabiao
     * @create 2022/8/11  19:41
     */
    public Boolean rename(String oldFileName, String newFileName) {
        Response response = null;
        try {
            ThirdPartyPaySet thirdPartyPaySet = thirdPartyPaySetService.getUploadThirdPartyPaySet();
            if (thirdPartyPaySet != null) {
                response = getBucketManager().rename(thirdPartyPaySet.getQiniuBucket(), oldFileName, newFileName, false);
            } else {
                response = getBucketManager().rename(bucketName, oldFileName, newFileName, false);
            }
        } catch (QiniuException e) {
            Response r = e.response;
            // 请求失败时打印的异常的信息
            log.info(r.toString());
            try {
                //响应的文本信息
                log.info(r.bodyString());
            } catch (QiniuException e1) {
                //ignore
            }
        }
        removeProxy();
        return response.isOK();
    }


    /**
     * 七牛云-查询
     *
     * @param fileKsy:文件key
     * @return
     * @description
     * @author huabiao
     * @create 2022/8/11  19:41
     */
    public Boolean findByKey(String fileKsy) {
        FileInfo fileInfo = null;
        try {
            ThirdPartyPaySet thirdPartyPaySet = thirdPartyPaySetService.getUploadThirdPartyPaySet();
            if (thirdPartyPaySet != null) {
                fileInfo = getBucketManager().stat(thirdPartyPaySet.getQiniuBucket(), fileKsy);
            } else {
                fileInfo = getBucketManager().stat(bucketName, fileKsy);
            }
        } catch (QiniuException e) {
            Response r = e.response;
            // 请求失败时打印的异常的信息
            log.info(r.toString());
            try {
                //响应的文本信息
                log.info(r.bodyString());
            } catch (QiniuException e1) {
                //ignore
            }
        }
        removeProxy();
        return fileInfo != null;
    }

    /**
     * 获取CDN域名（视频和图片分不同域名）
     *
     * @param type
     * @return
     */
    private String getDomain(String type) {
        ThirdPartyPaySet thirdPartyPaySet = thirdPartyPaySetService.getUploadThirdPartyPaySet();

        if (FILE_TYPE_VIDEO.equals(type)) {
            if (thirdPartyPaySet != null) {
                return thirdPartyPaySet.getQiniuDomainFile();
            } else {
                return domainVideo;
            }
        }
        if (thirdPartyPaySet != null) {
            return thirdPartyPaySet.getQiniuDomainImage();
        } else {
            return domainImage;
        }
    }

    /**
     * 取消代理
     */
    private static void removeProxy() {
        System.getProperties().remove("http.proxyHost");
        System.getProperties().remove("http.proxyPort");
        System.getProperties().remove("https.proxyHost");
        System.getProperties().remove("https.proxyPort");
    }

    /**
     * 七牛云-获取生成的七牛云名称
     *
     * @param fileName:文件名称
     * @return 七牛云文件名称
     * @author huabiao
     * @create 2022/8/26  9:21
     */
    private static String getQiniuFileName(String fileName) {
        return UUID.randomUUID().toString() + fileName.substring(fileName.lastIndexOf("."));
    }
}
