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: renmanyi
 * @LastEditTime: 2026-02-03 15:28:25
 * @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
       if (signInfo.vendorType === 'TENCENT_COS') {
        return this.uploadBlobToNewOSSTx(Blob, name, signInfo.signatureVO || signInfo).then(() => {
           return dataType === 'url' ? fileUrl : signInfo
        })
      } else {
        return this.uploadBlobToNewOSS(
          Blob,
          name,
          signInfo.signatureVO || signInfo
        ).then(() => {
          return dataType === 'url' ? fileUrl : signInfo
        });
      }
    })
  };

  static getVideoParseRoute(videoUrl) {
    return Service.Sales('anon/resource/parseVideo', { videoUrl }).then((res) => {
      return res.result.sdUrl || videoUrl;
    })
  }

  static uploadBlobToNewOSS(Blob, name, 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);
      if(signInfo.securityToken) {
        fd.append("x-oss-security-token", signInfo.securityToken);
      }
      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 uploadBlobToNewOSSTx(Blob, name, signInfo={}) {
    return new Promise(function (resolve, reject) {
      var xhr = new XMLHttpRequest();
      var fd = new FormData();
      let timeVal = JSON.parse(signInfo.extAttrs)['q-key-time'];
      fd.append('q-sign-algorithm', 'sha1');
      fd.append('key', signInfo.key);
      fd.append('q-ak', signInfo.accessKeyId);
      fd.append('policy', signInfo.policy);
      fd.append('q-signature', signInfo.signature);
      fd.append('success_action_status', '200');
      fd.append('x-cos-callback', signInfo.callback);
      signInfo.securityToken && fd.append("x-cos-security-token", signInfo.securityToken);
      fd.append('q-key-time', timeVal);
      fd.append('Filename', name);
      fd.append('file', Blob);
      xhr.open('POST', signInfo.host, true);
      xhr.onload = () => {
        if (xhr.readyState === 4) {
          if (xhr.status === 200) {
            const res = JSON.parse(xhr.responseText);
            resolve(res.result.url);
          } else {
            console.error('Error: ' + xhr.status);
          }
        }
      };
      xhr.send(fd);
    });
  };

  static uploadTextToOSS(string, name, success, error) {
    if (!string) return success();
    const params = {
      accessTypeEnum: "PUBLIC",
      bizCode: 'CLOUD_CLASS_COURSE',
      instId: User.getStoreId(),
      resourceName: name,
    }
    Service.Hades('/public/hades/ossAuthority', params).then((res) => {
      const signInfo = res.result;
      const { resourceId } = res.result;
      if (signInfo.vendorType === 'TENCENT_COS') {
        // 腾讯云 COS 上传
        this.uploadBlobToNewOSSTx(new Blob([string]), name, signInfo.signatureVO || signInfo).then(() => {
          success(resourceId);
        }).catch(() => {
          error();
        });
      } else {
        // 阿里云 OSS 上传
        const { accessId, policy, callback, signature, key, host } = signInfo;
        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);
        if(signInfo.securityToken) {
          formData.append("x-oss-security-token", signInfo.securityToken);
        }
        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);
      }
    }).catch(() => {
      error();
    });
  }
}

export default Upload;