package com.wteam.framework.modules.oss.service.impl;


import cn.hutool.core.date.DateTime;
import cn.hutool.json.JSONUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.CannedAccessControlList;
import com.google.gson.Gson;
import com.wteam.framework.modules.oss.OssSetting;
import com.wteam.framework.modules.oss.service.OssService;
import com.wteam.framework.modules.system.entity.dos.Setting;
import com.wteam.framework.modules.system.entity.enums.SettingEnum;
import com.wteam.framework.modules.system.service.SettingService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
@Slf4j
public class OssServiceImpl implements OssService {


    public static final String url = "https://dt-cluture.oss-cn-guangzhou.aliyuncs.com/";

    @Autowired
    private SettingService settingService;

    private String getUrlPrefix() {

        Setting setting = settingService.get(SettingEnum.OSS_SETTING.name());
        OssSetting ossSetting = JSONUtil.toBean(setting.getSettingValue(), OssSetting.class);

        return "https://" + ossSetting.getBucketName() + "." + ossSetting.getEndPoint() + "/";
    }

    /**
     * 阿里云oss文件上传
     *
     * @param inputStream      输入流
     * @param moudle           文件夹名称,上传到那个目录
     * @param originalFileName 原始文件名
     * @return 文件图片在oss服务器上的url
     */
    @Override
    public String upload(InputStream inputStream, String moudle, String originalFileName) {

        Setting setting = settingService.get(SettingEnum.OSS_SETTING.name());
        OssSetting ossSetting = new Gson().fromJson(setting.getSettingValue(), OssSetting.class);
        String endPoint = ossSetting.getEndPoint();
        String accessKeyId = ossSetting.getAccessKeyId();
        String accessKeySecret = ossSetting.getAccessKeySecret();
        String bucketName = ossSetting.getBucketName();


        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endPoint, accessKeyId, accessKeySecret);
//        log.info(ossClient.toString()+"------------------------------");
        //先判断 bucketname是否存在
        if (!ossClient.doesBucketExist(bucketName)) {
            // 创建存储空间
            ossClient.createBucket(bucketName);
            //设置 为公共读权限
            ossClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
        }

        //构建一个objectName: 就是在bucket里面的文件路径
        //文件夹文件太多,影响性能,所以就有策略,日期策略,用户策略,随机数策略生成不同的包,放不同的东西
        //这里 使用的日期策略
        //文件路径   testStorage/2022/09/14/mmexport1623393500702.jpg
        //引入jodatime坐标,来把时间格式化成这样
        //文件名如果是原文件名,怕重复,还是用uuid来随机生成吧
        String folder = new DateTime().toString("yyyy/MM/dd");
        String fileName = UUID.randomUUID().toString();
        //加文件拓展名
        String fileExtension = originalFileName.substring(originalFileName.lastIndexOf("."));
        String key = moudle + "/" + folder + "/" + fileName + fileExtension;

        // 创建PutObject请求
        ossClient.putObject(bucketName, key, inputStream);
        //关闭ossClient
        ossClient.shutdown();

        //返回文件路径url https://zdy-123.oss-cn-guangzhou.aliyuncs.com/testStorage/mmexport1623393500702.jpg
        return getUrlPrefix() + key;
    }

    /**
     * 根据文件名删除文件
     *
     * @param objectName
     * @return
     */
    @Override
    public String delete(String objectName) {
        //读取配置信息
        Setting setting = settingService.get(SettingEnum.OSS_SETTING.name());
        OssSetting ossSetting = new Gson().fromJson(setting.getSettingValue(), OssSetting.class);
        String endPoint = ossSetting.getEndPoint();
        String accessKeyId = ossSetting.getAccessKeyId();
        String accessKeySecret = ossSetting.getAccessKeySecret();
        String bucketName = ossSetting.getBucketName();
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endPoint, accessKeyId, accessKeySecret);
        // 删除文件或目录。如果要删除目录，目录必须为空。
        ossClient.deleteObject(bucketName, objectName);
        //关闭ossClient
        ossClient.shutdown();
        return "删除成功";
    }

    @Override
    public List<String> upFiles(String moudle, MultipartFile[] multipartFiles) {
        Setting setting = settingService.get(SettingEnum.OSS_SETTING.name());
        OssSetting ossSetting = new Gson().fromJson(setting.getSettingValue(), OssSetting.class);
        String endPoint = ossSetting.getEndPoint();
        String accessKeyId = ossSetting.getAccessKeyId();
        String accessKeySecret = ossSetting.getAccessKeySecret();
        String bucketName = ossSetting.getBucketName();


        List<String> urlList = new ArrayList<>();
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endPoint, accessKeyId, accessKeySecret);
        for (int i = 0; i < multipartFiles.length; i++) {
            try {
                // 上传文件流
                MultipartFile file = multipartFiles[i];
                InputStream inputStream = file.getInputStream();
                String fileName = file.getOriginalFilename();
                String uuid = cn.hutool.core.lang.UUID.randomUUID().toString().replaceAll("-", "");
                fileName = uuid + fileName;

                //按照当前日期，创建文件夹，上传到创建文件夹里面
                //  2022/03/15/xx.jpg
                //  String timeUrl = new Date().toString("yyyy/MM/dd");
                Date date = new Date();//获取当前日期
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
                String timeUrl = sdf.format(date);//将时间格式化

                fileName = moudle + "/" + timeUrl + "/" + fileName;
                // 调用方法实现上传
                ossClient.putObject(bucketName, fileName, inputStream);

                // 上传之后文件路径
                String path = getUrlPrefix() + fileName;
                urlList.add(path);
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
        }
        // 关闭ossclient
        ossClient.shutdown();
        return urlList;
    }
}
