// 上传文件到阿里云oss
import OSS from 'ali-oss'
import {apiGetOSSSign} from '@/api/common'
/* const Minio = require('minio')
const stream = require('stream') */
import * as Minio from 'minio-es'
import * as stream from 'stream'
import * as buffer from 'buffer'
const Buffer = buffer.Buffer

/**
 * 上传到oss
 * @param data 文件数据
 * @param fileName 存放在oss中的文件路径包含文件名
 * @param isMultipart 是否分片上传
 * @returns fileUrl 返回文件在阿里云上的地址
 */
export async function useUploadFileToOSS(data,fileName,isMultipart=false){
    const signRes=await apiGetOSSSign({StorageSource:1})
    if(signRes.Ret!==200) return
    const accessKeyId=signRes.Data.AccessKeyId
    const accessKeySecret=signRes.Data.AccessKeySecret
    const stsToken=signRes.Data.SecurityToken

    const ALOSSINS=new OSS({
        // yourRegion填写Bucket所在地域。以华东1（杭州）为例，Region填写为oss-cn-hangzhou。
        region: signRes.Data.RegionId,
        // 从STS服务获取的临时访问密钥（AccessKey ID和AccessKey Secret）。
        accessKeyId: accessKeyId,
        accessKeySecret: accessKeySecret,
        // 从STS服务获取的安全令牌（SecurityToken）。
        stsToken: stsToken,
        // 填写Bucket名称，例如examplebucket。
        bucket: signRes.Data.Bucketname,
        endpoint:signRes.Data.Endpoint,
        cname:true,
        timeout:6000000
    });

    let res=null,resUrl='';
    try {
        if(isMultipart){
            const options = {
                // 获取分片上传进度、断点和返回值。
                progress: (p, cpt, res) => {
                    // console.log(p);
                    // ALOSSAbortCheckpoint=cpt
                    // this.percentage=parseInt(p*100)
                },
                // 设置并发上传的分片数量。
                parallel: 10,
                // 设置分片大小。默认值为1 MB，最小值为100 KB。
                partSize: 1024 * 1024 * 10, // 10MB
            };
            res=await ALOSSINS.multipartUpload(fileName,data,{...options})
        }else{
            res=await ALOSSINS.put(fileName,data)
        }

        if(res.res.status===200){
            resUrl=signRes.Data.Imghost+res.name
        }
    } catch (error) {
        console.log('阿里云上传失败',error);
    }
    

    return resUrl
}

//上传到minio
// minio sdk 文档 https://min.io/docs/minio/linux/developers/javascript/API.html
export async function useUploadToMinIO (file, fileName, options = {}){
    const res = await apiGetOSSSign({StorageSource:2})
    if (res.Ret !== 200) {
        console.log("获取minio临时签名错误,res.Ret=" + res.Ret)
        return
    }
    const minioClient = new Minio.Client({
        endPoint: res.Data.Endpoint.split(':')[0],
        port: Number(res.Data.Port) || undefined,
        useSSL: res.Data.UseSSL.toLocaleLowerCase() == "false" ? false : true,
        accessKey: res.Data.AccessKeyId,
        secretKey: res.Data.SecretKeyId,
    })
    const metaData = {
        ...{
            'Content-Type': file.type || 'application/octet-stream',
            "Content-Length": file.size,
        },
        ...options
    }
    return new Promise((resolve,reject)=>{
        try {
            minioClient.bucketExists(res.Data.Bucketname, function (err, exists) {
                if (err) {
                    return console.log("minio 查看桶是否存在失败" + err)
                }
                if (!exists) {
                    // 不存在桶，创建桶
                    console.log("桶不存在，先创建桶", res.Data.Bucketname);
                    minioClient.makeBucket(res.Data.Bucketname, res.Data.RegionId, function (err) {
                        if (err) {
                            console.log("minio 创建桶失败" + err)
                            return 
                        }
                        let reader = new FileReader();
                        // console.log(reader);
                        reader.readAsArrayBuffer(file);
                        reader.onloadend = function (e) {
                            const dataurl = e.target.result;
                            let bufferStream = new stream.PassThrough();
                            // 转化成数据流  minio接受数据流格式
                            bufferStream.end(Buffer.from(dataurl))
                            minioClient.putObject(res.Data.Bucketname, fileName, bufferStream, file.size, metaData, function (err, etag) {
                                if (err) {
                                    return console.log("上传到minio失败：" + err)
                                }
                                let fileUrl = fileName.startsWith('/') ? res.Data.ImgHost + fileName : res.Data.ImgHost + "/" + fileName
                                resolve(fileUrl)
                            })
                        }
                    })
                }
                if (exists) {
                    // console.log("桶存在",res.Data.Bucketname);
                    let reader = new FileReader();
                    reader.readAsArrayBuffer(file);
                    reader.onloadend = function (e) {
                        const dataurl = e.target.result;
                        let bufferStream = new stream.PassThrough();
                        bufferStream.end(Buffer.from(dataurl))
                        minioClient.putObject(res.Data.Bucketname, fileName, bufferStream, metaData, function (err, etag) {
                            if (err) {
                                console.log("上传到minio失败：" + err)
                                return 
                            }
                            let fileUrl = fileName.startsWith('/') ? res.Data.ImgHost + fileName : res.Data.ImgHost + "/" + fileName
                            //console.log('test',fileUrl)
                            resolve(fileUrl)
                        })
                    }
                }
            })
        } catch (error) {
            console.error(error);
            if (error.name !== "cancel") {
                //不是取消上传的则给错误提示
                console.log("上传失败，请刷新重试");
            }
            reject(error)
        }
    })
}

//上传到s3
export async function useUploadToS3(file,fileName,options={}){
    const res = await apiGetOSSSign({StorageSource:3})
    if(res.Ret!==200){
        console.log("获取s3前面错误,res.Ret="+res.Ret)
        return
    }
    const { 
        Endpoint,
        AccessKeyId,
        AccessKeySecret,
        Port,
        Bucketname,
        RegionId,
        S3ForceStyle,
        S3Protocol
    } = res.Data
    const s3Client = new window.AWS.S3({
        apiVersion: '2006-03-01',
        endpoint:Endpoint,
        region:RegionId,
        s3ForcePathStyle:S3ForceStyle,
        credentials:{
            accessKeyId:AccessKeyId,
            secretAccessKey:AccessKeySecret,
        }
    })
    try {
        let reader = new FileReader();
        reader.readAsArrayBuffer(file);
        reader.onloadend = function (e) {
            const dataurl = e.target.result;
            let bufferStream = new stream.PassThrough();
            bufferStream.end(Buffer.from(dataurl))
            //upload会返回完整路径
            s3Client.upload({
                Bucket: Bucketname,
                ContentType: file.type || 'application/octet-stream',
                Body: file,
                ACL: "public-read",
                Key: fileName
            }, function (err, data) {
                if (err) {
                    console.log("Error! err =====> ", err);
                    throw new Error("上传到s3失败!")
                } else {
                    let url = data['Location'];
                    console.log("Successfully uploaded! URL =====> ", url);
                    return url
                }
            });
        }
      } catch (error) {
        console.error(error);
        if (error.name !== "cancel") {
          //不是取消上传的则给错误提示
          console.log("上传失败，请刷新重试");
        }
      }
}