var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/upload/index.tsx
var upload_exports = {};
__export(upload_exports, {
  default: () => upload_default
});
module.exports = __toCommonJS(upload_exports);
var import_react = __toESM(require("react"));
var import_antd = require("antd");
var import_icons = require("@ant-design/icons");
var import_core = __toESM(require("jquery/src/core"));
var import_ajax = require("jquery/src/ajax");
var import_xhr = require("jquery/src/ajax/xhr");
var import_md5 = __toESM(require("crypto-js/md5"));
var import_hooks = require("../_util/hooks");
var import_constants = require("../_util/constants");
var import_preview = require("../preview");
var import_nos_js_sdk = __toESM(require("./nos-js-sdk"));
var import_vcloud_js_sdk = __toESM(require("./vcloud-js-sdk"));
var import_context = require("../config-provider/context");
var MAX_SIZE = 5 * 1024 * 1024 * 1024;
var TRUNK_SIZE = 4 * 1024 * 1024;
var kmType = ["pdf", "ppt", "pptx", "doc", "docx"];
var videoType = ["wmv", "asf", "asx", "rm", "rmvb", "mp4", "3gp", "mov", "m4v", "avi", "dat", "mkv", "flv", "vob"];
var audioType = ["wav", "flac", "ape", "alac", "wv", "mp3", "aac", "ogg", "vorbis", "opusdeng"];
var formatData = (data) => {
  if (!data)
    return [];
  return Array.isArray(data) ? data.map(
    (item) => item = {
      uid: item.nosKey || item.uid,
      ...item
    }
  ) : [
    {
      uid: data.nosKey || data.uid,
      ...data
    }
  ];
};
var getFileType = (fileName) => {
  var _a;
  return ((_a = fileName.split(".").pop()) == null ? void 0 : _a.toLowerCase()) || "";
};
var getEncryptType = (transformType = ["KM", "YX"], fileType, encrypt) => {
  if (encrypt) {
    if (videoType.includes(fileType) && transformType.includes("YX")) {
      return "YX_VIDEO";
    }
    if (audioType.includes(fileType) && transformType.includes("YX")) {
      return "YX_AUDIO";
    }
  }
  if (kmType.includes(fileType) && transformType.includes("KM")) {
    return "KM";
  }
  return "NONE";
};
var upload_default = (props) => {
  const componentContext = (0, import_react.useContext)(import_context.ConfigContext);
  const { uiLocale } = componentContext;
  const {
    encrypt = false,
    validFileType,
    filterErrorFile = true,
    maxSize = MAX_SIZE,
    bucketName = "rms",
    // 桶名
    AppKey = "765c863df7ec8f8e2f545a4cf2633fcf",
    // 云信-应用的AppKey，https://app.yunxin.163.com/overview
    trunkSize = TRUNK_SIZE,
    maxCount = Infinity,
    transformType,
    // 转码类型
    onChange,
    getInstance,
    fileList,
    extra,
    dragger = false,
    canRepeat = false,
    text = uiLocale.Upload.text,
    children,
    ...rest
  } = props;
  const isImg = ["picture-card", "picture"].includes(rest.listType || "");
  let prefixCls = "ehr-ui";
  let [value, setValue] = (0, import_react.useState)(fileList);
  let tempTransformType = (0, import_react.useRef)();
  let uploaderRef = (0, import_react.useRef)({});
  (0, import_react.useEffect)(() => {
    setValue(fileList);
  }, [fileList]);
  const formatValue = (0, import_react.useMemo)(() => formatData(value), [value]);
  (0, import_react.useEffect)(() => {
    return () => {
      Object.keys(uploaderRef.current).map((uid) => {
        uploaderRef.current[uid].pauseUpload();
      });
    };
  }, []);
  const beforeUpload = (file, fileList2) => {
    const fileType = getFileType(file.name);
    tempTransformType.current = getEncryptType(transformType, fileType, encrypt);
    if (file.name.length > 100) {
      import_antd.message.error(uiLocale.Upload.fileNameLongError);
      return false;
    }
    if (validFileType && (!fileType || !validFileType.map((item) => item.toLocaleLowerCase()).includes(fileType))) {
      import_antd.message.error(uiLocale.Upload.fileTypeError);
      return false;
    }
    if (file.size > maxSize) {
      import_antd.message.error(uiLocale.Upload.maxSizeError);
      return false;
    }
    if (!canRepeat && formatValue.some((item) => item.name === file.name)) {
      import_antd.message.warning(uiLocale.Upload.repeatError);
      return false;
    }
    if (rest.beforeUpload)
      return rest.beforeUpload(file, fileList2);
    return true;
  };
  const KMTransform = (nosKey, fileName, url) => new Promise((resolve, reject) => {
    import_core.default.ajax({
      type: "post",
      url: import_constants.EHR_SERVICE + "/api/office/km/file/convert",
      data: JSON.stringify({
        dataId: nosKey,
        fileName,
        fileUrl: url
      }),
      dataType: "json",
      contentType: "application/json;charset=utf-8",
      // 数据必须转换为字符串
      success: (res) => {
        var _a;
        return resolve((_a = res == null ? void 0 : res.data) == null ? void 0 : _a.fileId);
      },
      error: () => {
        import_antd.message.error(uiLocale.Upload.convertError);
        reject();
      }
    });
  });
  const getNosUrl = (nosKey, bucketName2, fileName) => new Promise((resolve, reject) => {
    import_core.default.ajax({
      type: "get",
      url: import_constants.EHR_SERVICE + "/api/file/nos/url",
      data: { nosKey, bucketName: bucketName2, fileName: encodeURIComponent(fileName), fileNameEncode: "URL_ENCODE" },
      // 数据必须转换为字符串
      success: (res) => res.code === 200 ? resolve(res.data) : reject(),
      error: reject
    });
  });
  const nosUpload = (option) => {
    const { file, onProgress, onError, onSuccess } = option;
    const { name, size, uid } = file;
    if (file) {
      const uploader = (0, import_nos_js_sdk.default)({
        onProgress: (curFile) => {
          onProgress && onProgress({ percent: +curFile.progress });
        },
        onError: (errObj) => {
          import_antd.message.error(uiLocale.Upload.commonError);
          onError && onError(errObj);
        }
      });
      uploader.addFile(file, function() {
        let nosKey = (0, import_md5.default)(name + ":" + size + ":" + new Date().getTime()).toString();
        import_core.default.ajax({
          type: "get",
          url: import_constants.EHR_SERVICE + "/api/file/nos/token",
          // 获取上传凭证接口
          data: { nosKey, bucketName },
          dataType: "json",
          success: ({ data: token = "" }) => {
            let param = {
              bucketName,
              // 桶名
              objectName: nosKey,
              // 存储在NOS的对象名(前端生成一个唯一索引)
              token,
              // 上传凭证
              trunkSize
            };
            uploader.upload(param, function(curFile) {
              getNosUrl(nosKey, bucketName, curFile.fileName).then((url) => {
                let rep = { nosKey, url };
                if (tempTransformType.current === "KM") {
                  KMTransform(nosKey, curFile.fileName, url).then(
                    (transformId) => onSuccess && onSuccess({ ...rep, transformType: "KM", transformId }, new XMLHttpRequest())
                  ).catch(() => {
                    onError && onError(new Error());
                  });
                } else {
                  onSuccess && onSuccess({ ...rep, transformType: tempTransformType.current }, new XMLHttpRequest());
                }
              }).catch((errObj) => {
                import_antd.message.error(uiLocale.Upload.commonError);
                onError && onError(errObj);
              });
            });
          },
          error: (errObj) => {
            import_antd.message.error(uiLocale.Upload.commonError);
            onError && onError(errObj);
          }
        });
      });
      uploaderRef.current = { ...uploaderRef.current, [uid]: uploader };
    }
  };
  const yxUpload = (option) => {
    const { file, onProgress, onError, onSuccess } = option;
    if (file) {
      import_core.default.ajax({
        type: "get",
        url: import_constants.EHR_SERVICE + "/api/yunxin/yunxin/checkSum",
        dataType: "json",
        success: (res) => {
          const data = res.data || {};
          const uploader = (0, import_vcloud_js_sdk.default)({
            AppKey,
            nonce: data.nonce,
            curTime: data.curTime,
            checkSum: data.checkSum,
            onProgress: (curFile) => {
              onProgress && onProgress({ percent: +curFile.progress });
            },
            onSuccess: (res2) => {
              const url = res2.downloadOrigUrl.replace("http://", "https://");
              onSuccess && onSuccess(
                {
                  yxInfo: res2,
                  transformType: tempTransformType.current,
                  nosKey: "yx-" + res2.vid,
                  transformId: res2.vid,
                  url
                },
                new XMLHttpRequest()
              );
            },
            onError: (errObj) => {
              import_antd.message.error(uiLocale.Upload.commonError);
              onError && onError(errObj);
            }
          });
          uploader.initCustom(file);
        },
        error: (errObj) => {
          import_antd.message.error(uiLocale.Upload.commonError);
          onError && onError(errObj);
        }
      });
    }
  };
  const customRequest = (e) => {
    if (tempTransformType.current === "YX_VIDEO") {
      yxUpload(e);
    } else {
      nosUpload(e);
    }
  };
  const onChangeFile = (info) => {
    let { file, fileList: fileList2 } = info;
    if (file.status === void 0)
      return;
    if (filterErrorFile) {
      fileList2 = fileList2.filter((item) => item.status !== "error");
    }
    fileList2 = fileList2.map((item) => ({
      canDownload: !encrypt,
      ...item,
      ...item.response || {}
    }));
    file = { canDownload: !encrypt, ...file, ...file.response || {} };
    setValue(fileList2);
    onChange && onChange(maxCount === 1 ? fileList2[0] : fileList2, file);
  };
  const onRemove = (file) => {
    uploaderRef.current[file.uid] && uploaderRef.current[file.uid].pauseUpload();
    rest.onRemove && rest.onRemove(file);
  };
  const [currFile, setFile] = (0, import_react.useState)({});
  const onPreview = (file) => {
    if (!(file.transformType === "KM" || isImg)) {
      import_antd.message.warning(uiLocale.Upload.notSupportPreview);
      return;
    }
    setFile({ ...file });
  };
  (0, import_react.useEffect)(() => {
    getInstance == null ? void 0 : getInstance({ nosUpload, yxUpload });
  }, []);
  const params = {
    progress: {
      size: "small",
      format: (percent) => percent && `${parseFloat(percent.toFixed(1))}%`
    },
    fileList: formatValue,
    onRemove,
    onPreview,
    showUploadList: {
      showPreviewIcon: true,
      showRemoveIcon: true,
      showDownloadIcon: true,
      downloadIcon: () => /* @__PURE__ */ import_react.default.createElement(import_icons.DownloadOutlined, null),
      removeIcon: () => /* @__PURE__ */ import_react.default.createElement(import_icons.DeleteOutlined, { style: { color: "#ff4d4f" } })
    },
    iconRender: (file) => !file.canDownload ? /* @__PURE__ */ import_react.default.createElement(import_antd.Tooltip, { title: uiLocale.Upload.lockTooltip }, /* @__PURE__ */ import_react.default.createElement(import_icons.LockOutlined, null)) : /* @__PURE__ */ import_react.default.createElement(import_icons.PaperClipOutlined, null),
    ...rest,
    beforeUpload,
    onChange: onChangeFile,
    customRequest
  };
  return (0, import_hooks.useConfig)(
    /* @__PURE__ */ import_react.default.createElement(import_react.default.Fragment, null, dragger ? /* @__PURE__ */ import_react.default.createElement(import_antd.Upload.Dragger, { ...params, style: { display: formatValue.length < maxCount ? "block" : "none" } }, children ? children : /* @__PURE__ */ import_react.default.createElement(import_react.default.Fragment, null, /* @__PURE__ */ import_react.default.createElement("p", { className: `${prefixCls}-upload-drag-icon` }, /* @__PURE__ */ import_react.default.createElement(import_icons.InboxOutlined, null)), /* @__PURE__ */ import_react.default.createElement("p", { className: `${prefixCls}-upload-text` }, uiLocale.Upload.dragUploadText), extra && /* @__PURE__ */ import_react.default.createElement("p", { className: `${prefixCls}-upload-hint` }, props.extra))) : /* @__PURE__ */ import_react.default.createElement(import_antd.Upload, { ...params }, formatValue.length < maxCount && (children ? children : /* @__PURE__ */ import_react.default.createElement(import_react.default.Fragment, null, /* @__PURE__ */ import_react.default.createElement(import_antd.Button, { type: "primary" }, /* @__PURE__ */ import_react.default.createElement(import_icons.UploadOutlined, null), " ", text), extra && /* @__PURE__ */ import_react.default.createElement("p", { className: `${prefixCls}-upload-hint` }, extra)))), isImg && /* @__PURE__ */ import_react.default.createElement(import_antd.Image, { width: 0, src: currFile.url, preview: { visible: !!currFile.url, onVisibleChange: () => setFile({}) } }), currFile.transformType === "KM" && /* @__PURE__ */ import_react.default.createElement(import_antd.Modal, { destroyOnClose: true, footer: null, open: !!currFile.url, width: 1e3, onCancel: () => setFile({}) }, /* @__PURE__ */ import_react.default.createElement(import_preview.FilePreview, { file: currFile })))
  );
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {});
