import { func } from "prop-types";
import Service from '@/common/js/service';
import User from '@/common/js/user';
import { message } from 'antd';
/*
 * @Author: 吴文洁
 * @Date: 2020-08-11 11:47:14
 * @LastEditors: wufan
 * @LastEditTime: 2021-01-03 21:04:30
 * @Description: 
 * @Copyright: 杭州杰竞科技有限公司 版权所有
 */
class Upload {
  static uploadBlobToOSS(Blob, name, dir, dataType = 'url') {
    // 上传图片和视频
    const param = {
      accessTypeEnum:"PUBLIC",
      bizCode:'CLOUD_CLASS_COMMON',
      instId:User.getStoreId(),
      resourceName:name
    }
    return Service.Hades('public/hades/commonOssAuthority', param).then((res) => {
      const signInfo = res.result;
      const { fileUrl } = res.result
      return this.uploadBlobToNewOSS(Blob, name, dir, signInfo.signatureVO || signInfo).then(() => {
        console.log('url2222222',fileUrl);
        return dataType === 'url' ? fileUrl : signInfo
      });
    })
  };

  static asyncUploadVideoToOSS(Blob, name, complete, dir, needSize) {
    name = window.encodeURI(name.toLowerCase());
    let ossSignServerAddress = UPLOAD + 'xm/oss/web/token?bucket=v';
    const xhr = new XMLHttpRequest();
    xhr.open('GET', ossSignServerAddress, true);
    xhr.onload = () => {
      const signInfo = JSON.parse(xhr.responseText);
      const fd = new FormData();

      fd.append('Filename', name);
      fd.append('callback', signInfo.callback);
      fd.append('expire', signInfo.expire);
      fd.append('policy', signInfo.policy);
      fd.append('signature', signInfo.signature);
      fd.append('OSSAccessKeyId', signInfo.accessid);
      fd.append('success_action_status', 200);
      if (!dir) {
        dir = Blob.type == 'text/html' ? 'html/' : '';
      }
      fd.append('key', signInfo.dir + dir + name);
      fd.append('file', Blob);

      xhr.open('POST', signInfo.host, true);
      xhr.onload = () => {
        const result = JSON.parse(xhr.responseText);

        if (needSize) {
          complete(result);
        } else {
          complete((result.url || false).replace(/http:/, "https:"));
        }
      };
      xhr.send(fd);
    };
    xhr.onerror = () => {
      complete(false);
    }
    xhr.send(null);
    return xhr;
  }

  static getVideoParseRoute(videoUrl) {
    return Service.MFS('anon/video/parse', { videoUrl }).then((res) => {
      return res.result.sdUrl || videoUrl;
    })
  }

  // mfs上传文件

  static uploadBlobToMFSOSS(signInfoUrl, signInfoParams, Blob, name, dir) {
    return Service.post(signInfoUrl, signInfoParams).then(res => {
      var signInfo = res.result;
      return this.uploadBlobToNewOSS(Blob, name, dir, signInfo.signatureVO || signInfo).then((res) => {
        return signInfo;
      });

    })
  }

  static uploadBlobToNewOSS(Blob, name, dir, signInfo) {
    return new Promise(function (resolve, reject) {
      var xhr = new XMLHttpRequest();
      var fd = new FormData();
      fd.append('OSSAccessKeyId', signInfo.accessId);
      fd.append('policy', signInfo.policy);
      fd.append('callback', signInfo.callback);
      fd.append('Filename', name);
      fd.append('expire', signInfo.expire);
      fd.append('signature', signInfo.signature);
      // if (!dir) {
      //   dir = Blob.type == 'text/html' ? 'html/' : '';
      // }
      fd.append('key', signInfo.key);
      fd.append('file', Blob);
      fd.append('success_action_status', 200);
      xhr.open('POST', signInfo.host.replace(/http:/, "https:"), true);
      xhr.onload = () => {
        const result = JSON.parse(xhr.responseText);
        if(!result.success){
          message.error('上传失败');
          reject();
        }else{
          resolve(result.url);
        }
      }
      xhr.send(fd);
    });


  };

  // 监听多媒体上传进度
  static uploadToOSSEvent(Blob, name, onInit=()=>{}, onProgress=()=>{}, onLoad=()=>{}, onError=()=>{}) {
    Service.MFS('anon/mfs/webTokenWithAccessUrl', { resourceName: name, instId: (!!window.currentUserInstInfo && window.currentUserInstInfo.instId) || LS.get('instId') || '' }).then((res) => {
      const signInfo = res.result;
      const { url } = res.result;
      const xhr = new XMLHttpRequest();
      const fd = new FormData();

      fd.append('OSSAccessKeyId', signInfo.accessId);
      fd.append('policy', signInfo.policy);
      fd.append('callback', signInfo.callback);
      fd.append('Filename', name);
      fd.append('expire', signInfo.expire);
      fd.append('signature', signInfo.signature);
      fd.append('key', signInfo.key);
      fd.append('file', Blob);
      fd.append('success_action_status', 200);
      
      onInit(url,xhr,signInfo)
      xhr.open('POST', signInfo.host);
      xhr.upload.addEventListener("progress", onProgress, false);
      xhr.onload = onLoad;
      xhr.onerror = onError;
      xhr.send(fd);
    })
  }

  static uploadTextToOSS(string, name, success, error) {
    if (!string) return success();
    const params = {
      accessTypeEnum: "PUBLIC",
      bizCode: 'CLOUD_CLASS_COMMON',
      instId: User.getStoreId(),
      resourceName: name,
    }
    Service.Hades('/public/hades/ossAuthority', params).then((res) => {
      const { resourceId, accessId, policy, callback, signature,key, host } = res.result;
      const xhr = new XMLHttpRequest();
      const formData = new FormData();
      formData.append("OSSAccessKeyId", accessId);
      formData.append("policy", policy);
      formData.append("callback", callback);
      formData.append("Signature", signature);
      formData.append("key", key);
      formData.append("file", new Blob([string]));
      formData.append("success_action_status", 200);
      xhr.open("POST", host);
      xhr.onload = () => {
        success(resourceId);
      };
      xhr.onerror = () => {
        error();
      }
      xhr.send(formData);
    })
  }
}

export default Upload;