import { commonFileUploadApi } from "@/api/staffApi.js";
import {obsConfig} from '@/utils/obsConfig'

/**
 * OBS文件上传
 * @param {Object} file - 文件对象
 * @param {Object} options - 配置选项
 * @param {Function} options.onSuccess - 上传成功回调
 * @param {Object} options.context - 上下文对象，用于在回调中访问组件实例
 * @param {String} options.domainId - 企业ID
 * @returns {void}
 */
export function obsFileUpload(file, options) {
  const { onSuccess, context, domainId = "default" } = options;
  
  let now = new Date();
  let y = now.getFullYear();
  let m = now.getMonth() + 1 < 10 ? '0' + (now.getMonth() + 1) : now.getMonth() + 1;
  let d = now.getDate() < 10 ? '0' + now.getDate() : now.getDate();
  let md = m + '-' + d;
  
  // 处理文件名，去掉+号
  let fileName = file.name.replace(/\+/g, '');
  let objectKey = `uploads/${y}/${md}/${domainId}/${now.getTime()}/${fileName}`;
  
  var obs = new ObsClient({
    access_key_id: obsConfig.ak,
    secret_access_key: obsConfig.sk,
    server: obsConfig.urlserver,
    timeout: 60 * 5,
  });
  
  obs.putObject({
    Bucket: BucketName,
    Key: objectKey,
    SourceFile: file // 获取file文件
  }).then(function(result) {
    console.log(result);

    if (result.CommonMsg.Status < 300) {
      context.$message({ type: 'success', message: "上传成功" });
      console.log('Create object:' + objectKey + ' successfully!\n');
      var httpurl = `https://${BucketName}.${urlserver}/${objectKey}`;
      httpurl = convertCdnPath(httpurl);
      
      if (typeof onSuccess === 'function') {
        onSuccess.call(context, httpurl);
      }
    }
  });
}

/**
 * 内网文件上传
 * @param {Object} file - 文件对象
 * @param {Object} options - 配置选项
 * @param {Function} options.onSuccess - 上传成功回调
 * @param {Object} options.context - 上下文对象，用于在回调中访问组件实例
 * @returns {void}
 */
export function internalFileUpload(file, options) {
  const { onSuccess, context } = options;
  
  let fd = new FormData();
  // 处理文件名，去掉+号
  let fileName = file.name.replace(/\+/g, '');
  // 创建一个新的File对象，使用处理后的文件名
  let newFile = new File([file], fileName, { type: file.type });
  fd.append("file", newFile);
  
  commonFileUploadApi(fd).then(response => {
    let blobReader = new Response(response).json();
    blobReader.then((res) => {
      console.log(res.data);
      if (res.data) {
        let path = window.location.origin + "/obpm" + res.data;
        
        if (typeof onSuccess === 'function') {
          onSuccess.call(context, path);
        }
      }
    });
  });
}

/**
 * 文件上传统一入口
 * @param {Object} e - 上传事件对象
 * @param {Object} options - 配置选项
 * @param {Function} options.onSuccess - 上传成功回调
 * @param {Object} options.context - 上下文对象，用于在回调中访问组件实例
 * @param {String} options.domainId - 企业ID
 * @returns {void}
 */
export function uploadFile(e, options) {
  if (__network__ && process.env.NODE_ENV === "production") {
    obsFileUpload(e.file, options); // obs文件上传
  } else {
    internalFileUpload(e.file, options); // 内网文件上传
  }
}