package com.YuyeTech.HeartRate.utils;

import com.YuyeTech.HeartRate.config.AliyunConfig;
import com.aliyun.oss.*;
import com.aliyun.oss.model.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author:slambb
 * @date:2019/12/16
 */
@Service
@Slf4j
public class AliyunOSSUtil {

    @Autowired
    private AliyunConfig aliyunConfig;
    private static SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

    /**
     * 上传
     *
     * @param file
     * @return
     */
    public String upload(File file, String fileType) {
        log.info("=========>OSS文件上传开始：" + file.getName());
        String endpoint = aliyunConfig.getEndpoint();
        String accessKeyId = aliyunConfig.getAccessKeyId();
        String accessKeySecret = aliyunConfig.getAccessKeySecret();
        String bucketName = aliyunConfig.getBucketName();
        String fileHost = aliyunConfig.getFileHost();
        if (fileType.equals("avatar")) {
            //如果是头像，保存到头像文件夹里面
            fileHost = aliyunConfig.getFileAvatar();
        } else if (fileType.equals("gameIcon")) {
            fileHost = aliyunConfig.getFileGameIcon();
        } else if (fileType.equals("pictures")) {
            fileHost = aliyunConfig.getFilePictures();
        } else if (fileType.equals("publicAvatar")) {
            //公共头像库，
            fileHost = aliyunConfig.getFilePublicAvatar();
        }
        log.info(endpoint + "=========>OSS文件上传开始 fileHost：" + fileHost);

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String dateStr = format.format(new Date());

        if (null == file) {
            return null;
        }

        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            //容器不存在，就创建
            if (!ossClient.doesBucketExist(bucketName)) {
                ossClient.createBucket(bucketName);
                CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName);
                createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
                ossClient.createBucket(createBucketRequest);
            }
            //创建文件路径
            String fileUrl = fileHost + "/" + (dateStr + "/" + UUID.randomUUID().toString().replace("-", "") + "-" + file.getName());
            //上传文件
            PutObjectResult result = ossClient.putObject(new PutObjectRequest(bucketName, fileUrl, file));
            //设置权限 这里是公开读
            ossClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
            if (null != result) {
                log.info("==========>OSS文件上传成功,OSS地址：" + fileUrl);
                return fileUrl;
            }
        } catch (OSSException oe) {
            log.error(oe.getMessage());
        } catch (ClientException ce) {
            log.error(ce.getMessage());
        } finally {
            //关闭
            ossClient.shutdown();
        }
        return null;
    }


    /**
     * 删除
     *
     * @param fileKey
     * @return
     */
    @Transactional
    public Boolean deleteBlog(String fileKey) {
        log.info("=========>OSS文件删除开始");
        String endpoint = aliyunConfig.getEndpoint();
        String accessKeyId = aliyunConfig.getAccessKeyId();
        String accessKeySecret = aliyunConfig.getAccessKeySecret();
        String bucketName = aliyunConfig.getBucketName();
        String fileHost = aliyunConfig.getFileHost();
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            if (!ossClient.doesBucketExist(bucketName)) {
                log.info("==============>您的Bucket不存在");
                return false;
            } else {
                log.info("==============>开始删除Object");
                ossClient.deleteObject(bucketName, fileKey);
                log.info("==============>Object删除成功：" + fileKey);
                return true;
            }
        } catch (Exception ex) {
            log.info("删除Object失败", ex);
            return false;
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

    /**
     * 拼接并，返回oss 默认域名
     *
     * @param fileKey
     * @return
     */
    public String addDomainName(String fileKey) {
        if (StringUtils.isEmpty(fileKey)) return fileKey;
        Boolean bAdd = isHttpUrl(fileKey);
        if (!bAdd) {
            if (aliyunConfig.getUsingDomain()) {
                String url = aliyunConfig.getDomainName()
                        .concat("/")
                        .concat(fileKey);
                return url;
            } else {
                String url = "https://"
                        .concat(aliyunConfig.getBucketName())
                        .concat(".")
                        .concat(aliyunConfig.getEndpoint())
                        .concat("/")
                        .concat(fileKey);
                return url;
            }

        } else {
            return fileKey;
        }

    }


    public String getDomainName() {
        if (aliyunConfig.getUsingDomain()) {
            String url = aliyunConfig.getDomainName()
                    .concat("/");
            return url;
        } else {
            String url = "https://"
                    .concat(aliyunConfig.getBucketName())
                    .concat(".")
                    .concat(aliyunConfig.getEndpoint())
                    .concat("/");
            return url;
        }
    }

    /**
     * 判断字符串是否为URL
     *
     * @param urls 用户头像key
     * @return true:是URL、false:不是URL
     */
    public static boolean isHttpUrl(String urls) {
        boolean isurl = false;
        String regex = "(((https|http)?://)?([a-z0-9]+[.])|(www.))"
                + "\\w+[.|\\/]([a-z0-9]{0,})?[[.]([a-z0-9]{0,})]+((/[\\S&&[^,;\u4E00-\u9FA5]]+)+)?([.][a-z0-9]{0,}+|/?)";//设置正则表达式

        Pattern pat = Pattern.compile(regex.trim());//比对
        Matcher mat = pat.matcher(urls.trim());
        isurl = mat.matches();//判断是否匹配
        if (isurl) {
            isurl = true;
        }
        return isurl;
    }

    /**
     * 查询文件名列表
     *
     * @param bucketName
     * @return
     */
    public List<String> getObjectList(String bucketName) {
        List<String> listRe = new ArrayList<>();
        String endpoint = aliyunConfig.getEndpoint();
        String accessKeyId = aliyunConfig.getAccessKeyId();
        String accessKeySecret = aliyunConfig.getAccessKeySecret();
        try {
            log.info("===========>查询文件名列表");
            OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
            ListObjectsRequest listObjectsRequest = new ListObjectsRequest(bucketName);
            //列出11111目录下今天所有文件
            listObjectsRequest.setPrefix("11111/" + format.format(new Date()) + "/");
            ObjectListing list = ossClient.listObjects(listObjectsRequest);
            for (OSSObjectSummary objectSummary : list.getObjectSummaries()) {
                System.out.println(objectSummary.getKey());
                listRe.add(objectSummary.getKey());
            }
            return listRe;
        } catch (Exception ex) {
            log.info("==========>查询列表失败", ex);
            return new ArrayList<>();
        }
    }
}
