// import  getBrowser from './getBrowser';
// import  getNetworkType from './getNetworkType';
// import  getSystemInfo from './getSystemInfo';

import {Message} from "element-ui"
import{getOSSSign} from "@/api/api.js"
const Minio = require('minio')
const stream = require('stream')

// 根据字节流下载文件
/**
 * @param {Blob} data 流数据
 * @param {String} type 下载的文件类型
 * @param {String} fileName 下载的文件名
 */
export function downloadByFlow(data,type,fileName) {
    let fileTypeMime ='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    switch (type) { // 获取后缀对应的 mimeType
      case 'png': fileTypeMime = 'image/png'; break;
      case 'doc': fileTypeMime = 'application/msword'; break;
      case 'docx': fileTypeMime = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'; break;
      case 'jpg': case 'jpeg': fileTypeMime = 'image/jpeg'; break;
      case 'gif': fileTypeMime = 'image/gif'; break;
      case 'svg': fileTypeMime = 'image/svg+xml'; break;
      case 'tif': case 'tiff': fileTypeMime = 'image/tiff'; break;
      case 'txt': fileTypeMime = 'text/plain'; break;
      case 'ppt': fileTypeMime = 'application/vnd.ms-powerpoint'; break;
      case 'pptx': fileTypeMime = 'application/vnd.openxmlformats-officedocument.presentationml.presentation'; break;
      case 'xls': fileTypeMime = 'application/vnd.ms-excel'; break;
      case 'xlsx': fileTypeMime = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'; break;
      case 'zip': fileTypeMime = 'application/zip'; break;
      case '7z': fileTypeMime = 'application/x-7z-compressed'; break;
    }
    let blob = window.URL.createObjectURL(new Blob([data], {
      'type': fileTypeMime
    }))
    let link = document.createElement('a')
    link.style.display = 'none'
    link.href = blob
    link.setAttribute('download', fileName.indexOf('.')?fileName:`${fileName}.${type}`)
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link) //下载完成移除元素
    window.URL.revokeObjectURL(blob) //释放掉 blob 对象
  }

/* 获取地址栏参数值 */
export function getUrlParams(str=window.location.href,key) {
  let obj = {};
	str.split('?')[1].split('&').map(i => obj[(i.split('=')[0])] = i.split('=')[1]);

  return obj[key]
}

/**
 * 
 * @param {*} objectStorageClient oss-走oss 2-走minio string
 * @param {*} file 上传文件
 * @param {*} temName 文件路径/文件名字
 * @param {*} options 文件路径/文件名字
 * @param {*} options.OSS 上传至阿里云的配置
 * @param {*} options.MINIO 上传至MINIO的配置
 */

// 上传文件 直接走对象存取服务器
export function uploadFileDirect(objectStorageClient,file,temName,options={}){
  const objectStorageType= (objectStorageClient || JSON.parse(localStorage.getItem('dynamicOutLinks')).ObjectStorageClient || 'oss')
  // console.log(objectStorageType,'objectStorageType');
  // return 
  if(!objectStorageType){
    Message.error("ObjectStorageClient参数丢失")
    return new Promise((resolve,reject) => reject("ObjectStorageClient参数丢失"))
  }
  if(!file){
    Message.error("file参数错误")
    return new Promise((resolve,reject) => reject("file参数错误"))
  }
  if(!temName){
    Message.error("temName参数错误")
    return new Promise((resolve,reject) => reject("temName参数错误"))
  }
  // console.log(objectStorageType,file,temName,options,'objectStorageType,file,temName,options');
  switch (objectStorageType) {
    case "oss":
      let ossOptions = {}
      if(options.OSS){
        ossOptions=options.OSS
      }

      return handleUploadToOSS(file,temName,ossOptions)
      // break;
    case "minio":
      let minioOptions = {}
      if(options.MINIO){
        minioOptions=options.MINIO
      }
      return handleUploadToMinIO(file,temName,minioOptions)
      // break;
    default:
      break;
  }
}

const handleUploadToOSS= (file,fileName,options={})=>{
  return new Promise(async (resolve,reject)=>{
    // 获取oss临时签名
    const res=await getOSSSign({StorageSource:1})
    // console.log(res);
    if(res.Ret!==200) reject("获取阿里云oss临时签名错误,res.Ret="+res.Ret)
    try {

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

      const resp=await ALOSSINS.multipartUpload(fileName,file,{...options})
      console.log('上传结果',resp);
      if(resp.res.status===200){
        let url=imgHost+resp.name
        resolve(url)
        console.log('oss文件地址',url);
      }else{
        throw new Error('上传到阿里云失败：res.status'+resp.res.status)
      }
    } catch (error) {
      console.error(error);
      if (error.name !== "cancel") {
        Message.warning('上传失败，请刷新重试')
      }
      reject(error)
    }
  })
}

// minio sdk 文档 https://min.io/docs/minio/linux/developers/javascript/API.html
const handleUploadToMinIO=(file,fileName,options={})=>{
  return new Promise(async (resolve,reject)=>{

    const res=await getOSSSign({StorageSource:2})
    // console.log(res);
    if(res.Ret!==200) reject("获取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,
    })
    console.log(minioClient);
    try {
      var metaData = {...{
        'Content-Type': file.type||'application/octet-stream',
        "Content-Length": file.size,
      },...options}
    
      minioClient.bucketExists(res.Data.Bucketname, function (err, exists) {
          if (err) {
              throw "minio 查看桶是否存在失败"+err
              // return console.log(err);
          }
          if (!exists) {
            // 不存在桶，创建桶
            console.log("桶不存在，先创建桶",res.Data.Bucketname);
            minioClient.makeBucket(res.Data.Bucketname, res.Data.RegionId,function (err) {
              if (err) {
                throw "minio 创建桶失败"+err
              }
            
              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))
                // console.log(bufferStream);
                minioClient.putObject(res.Data.Bucketname, fileName, bufferStream,file.size, metaData, function (err, etag) {
                  if (err){
                    throw "上传到minio失败："+err
                  }
            
                })
              }
            })
          }
          if (exists) {
            // console.log("桶存在",res.Data.Bucketname);
            let reader = new FileReader();
            console.log(reader);
            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){
                  throw "上传到minio失败："+err
                }
                let fileUrl = fileName.startsWith('/')?res.Data.ImgHost+fileName:res.Data.ImgHost+"/"+fileName
                resolve(fileUrl)
              })
            }
          }
      })
    } catch (error) {
      console.error(error);
      if (error.name !== "cancel") {
        //不是取消上传的则给错误提示
        this.$message.warning("上传失败，请刷新重试");
      }
      reject(error)
    }
  })
}