import { defineComponent, ref, useModel, computed, watch, reactive, resolveComponent, openBlock, createBlock, unref, withCtx, createVNode, createElementVNode, createElementBlock, Fragment, renderList, toDisplayString, createTextVNode, createCommentVNode, renderSlot, mergeModels } from 'vue';
import { ElMessage, ElUpload, ElTable, ElTableColumn, ElImage, ElTag, ElProgress, ElButton } from 'element-plus';
import { VueDraggable } from 'vue-draggable-plus';
import FileUploadRule from '../../utils/upload/FileUploadRule.mjs';
import { MeMessage } from '../../message/index.mjs';
import { uuid } from '../../utils/uuid.mjs';
import { MeFlexBox } from '../../flex-box/index.mjs';
import { MeDialog } from '../../dialog/index.mjs';
import { MeSvgIcon } from '../../svg-icon/index.mjs';
import { formatBytes, getFileThumbByFileName } from '../../utils/file.mjs';

"use strict";
const _hoisted_1 = { class: "el-upload__text" };
const _hoisted_2 = { class: "text-sm" };
const _hoisted_3 = { key: 0 };
const _hoisted_4 = { key: 1 };
const _hoisted_5 = { key: 2 };
const _hoisted_6 = { key: 3 };
const _hoisted_7 = { key: 4 };
const _hoisted_8 = { style: { "cursor": "move" } };
const _hoisted_9 = { class: "me-upload-button" };
const __default__ = defineComponent({
  name: "me-upload"
});
var script = /* @__PURE__ */ defineComponent({
  ...__default__,
  props: /* @__PURE__ */ mergeModels({
    modelValue: { type: Boolean, required: true },
    uploadRequest: { type: Function, required: false, default: (data) => Promise.resolve() },
    showFullscreen: { type: Boolean, required: false },
    showClose: { type: Boolean, required: false, default: true },
    url: { type: String, required: true },
    params: { type: null, required: false, default: {} },
    title: { type: String, required: false, default: "\u4E0A\u4F20" },
    maxCount: { type: Number, required: false, default: 0 },
    multiple: { type: Boolean, required: false, default: true },
    rules: { type: Array, required: true, default: [] },
    closeEvent: { type: Function, required: false, default: () => {
    } },
    uploadCompleteEvent: { type: Function, required: false, default: (data) => {
    } },
    uploadType: { type: String, required: false }
  }, {
    "modelValue": { type: Boolean, ...{ default: false } },
    "modelModifiers": {}
  }),
  emits: /* @__PURE__ */ mergeModels(["update:modelValue", "close"], ["update:modelValue"]),
  setup(__props, { emit: __emit }) {
    const props = __props;
    const emits = __emit;
    const dragDisabled = ref(true);
    const visible = useModel(__props, "modelValue");
    let disabled = ref(false);
    const tips = ref();
    const accept = ref();
    let title = computed(() => {
      if (props.maxCount > 0) {
        return `${props.title}(\u9650\u5236${props.maxCount}\u4E2A\u6587\u4EF6)`;
      }
      return props.title;
    });
    let multiple = computed(() => {
      if (props.maxCount == 1) {
        return false;
      }
      return true;
    });
    const fileList = ref([]);
    let uploadResultList = [];
    const fileUploadRule = new FileUploadRule();
    const cellMouseEnter = (row, column, cell, event) => {
      if (column.label == "") {
        dragDisabled.value = false;
      }
    };
    fileUploadRule.setChangeHandler(() => {
      tips.value = fileUploadRule.getUploadTips();
      accept.value = fileUploadRule.getAccept();
    });
    props.rules.forEach((item) => {
      fileUploadRule.add(item.name, item.size);
    });
    watch(
      () => props.rules,
      (newVal, oldVal) => {
        fileUploadRule.clear();
        newVal.forEach((item) => {
          fileUploadRule.add(item.name, item.size);
        });
      }
    );
    const removeItemHandler = (item) => {
      for (let i = 0; i < fileList.value.length; i++) {
        if (fileList.value[i].file?.uid == item.file.uid) {
          fileList.value.splice(i, 1);
          disabled.value = false;
          break;
        }
      }
    };
    const onChangeHandler = (uploadFile2, uploadFiles) => {
      if (fileList.value.length >= props.maxCount && props.maxCount > 0) {
        return;
      }
      if (!fileUploadRule.check(uploadFile2)) {
        ElMessage.error(fileUploadRule.getErrorMessage());
      } else {
        let data = {
          file: uploadFile2.raw,
          name: uploadFile2.name,
          size: formatBytes(uploadFile2.size),
          progress: 0,
          status: "ready",
          error: "",
          image: ""
        };
        const reader = new FileReader();
        reader.onload = function(e) {
          if (data?.file?.type.startsWith("image/")) {
            data.image = e.target != null ? e.target.result : "";
          } else {
            data.image = getFileThumbByFileName(data.name);
          }
          if (props.maxCount == 0) {
            fileList.value.push(data);
          } else {
            if (fileList.value.length < props.maxCount) {
              fileList.value.push(data);
            }
            if (fileList.value.length >= props.maxCount) {
              disabled.value = true;
            }
          }
        };
        reader.readAsDataURL(uploadFile2.raw);
      }
    };
    const handleReUpload = (row) => {
      uploadFile(row);
    };
    let uploadQueue = () => {
      let data = reactive({
        normal: {
          title: "\u63D0\u793A",
          message: "\u8BF7\u6DFB\u52A0\u8981\u4E0A\u4F20\u7684\u6587\u4EF6",
          loading: false,
          type: "primary"
        }
      });
      if (!hasReadyFile()) {
        MeMessage(data);
        return;
      }
      if (!props?.uploadRequest) {
        data.normal.message = "\u8BF7\u914D\u7F6E\u4E0A\u4F20\u8BF7\u6C42\u65B9\u6CD5";
        MeMessage(data);
        return;
      }
      fileList.value.forEach((item) => {
        if (item.status == "ready" || item.status == "canceled") {
          uploadFile(item);
        }
      });
    };
    function uploadFile(item) {
      const formData = new FormData();
      if (item.file) {
        formData.append("file", item.file);
      }
      item.status = "uploading";
      item.progress = 0;
      const controller = new AbortController();
      item.controller = controller;
      props.uploadRequest({
        url: props.url,
        params: props.params,
        data: formData,
        signal: controller.signal,
        onUploadProgress: function(progressEvent) {
          item.progress = Math.round(progressEvent.loaded / progressEvent.total * 100);
        }
      }).then((res) => {
        item.status = "success";
        res.data.domuuid = uuid();
        uploadResultList.push(res.data);
      }).catch((error) => {
        if (error.name == "AbortError" || error.name == "CanceledError") {
          item.status = "canceled";
          item.error = "\u53D6\u6D88\u4E0A\u4F20";
        } else {
          item.status = "fail";
          item.error = error.message;
        }
        return Promise.reject(error);
      }).finally(() => {
        if (isComplete()) {
          props.uploadCompleteEvent(uploadResultList);
          closeUploadDialog();
        }
      });
    }
    let isUploading = () => {
      for (let i = 0; i < fileList.value.length; i++) {
        if (fileList.value[i].status == "uploading") {
          return true;
        }
      }
      return false;
    };
    let isComplete = () => {
      for (let i = 0; i < fileList.value.length; i++) {
        const status = fileList.value[i].status;
        if (status == "uploading" || status == "ready" || status == "fail" || status == "canceled") {
          return false;
        }
      }
      return true;
    };
    let hasReadyFile = () => {
      for (let i = 0; i < fileList.value.length; i++) {
        const status = fileList.value[i].status;
        if (status == "ready" || status == "canceled") {
          return true;
        }
      }
      return false;
    };
    let closeEventHandler = () => {
      if (fileList.value.length == 0) {
        closeUploadDialog();
        return;
      }
      if (isUploading()) {
        const msg = reactive({
          normal: {
            title: "\u63D0\u793A",
            message: "\u6587\u4EF6\u6B63\u5728\u4E0A\u4F20\u4E2D\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5",
            loading: false,
            type: "primary"
          }
        });
        MeMessage(msg);
        return;
      } else {
        closeUploadDialog();
      }
    };
    let closeUploadDialog = () => {
      visible.value = false;
      fileList.value.length = 0;
      uploadResultList = [];
      disabled.value = false;
      emits("close");
    };
    return (_ctx, _cache) => {
      const _component_el_text = resolveComponent("el-text");
      return openBlock(), createBlock(unref(MeDialog), {
        modelValue: visible.value,
        "onUpdate:modelValue": _cache[2] || (_cache[2] = ($event) => visible.value = $event),
        "show-close": true,
        onCloseEvent: unref(closeEventHandler),
        title: unref(title),
        width: "800"
      }, {
        "me-dialog-footer": withCtx(() => [
          createVNode(unref(MeFlexBox), {
            end: true,
            style: { "justify-content": "space-between" }
          }, {
            default: withCtx(() => [
              renderSlot(_ctx.$slots, "footer"),
              createElementVNode("div", _hoisted_9, [
                createVNode(unref(ElButton), {
                  loading: fileList.value.some((item) => item.status == "uploading"),
                  type: "primary",
                  onClick: unref(uploadQueue)
                }, {
                  default: withCtx(() => [..._cache[8] || (_cache[8] = [
                    createTextVNode(
                      "\u4E0A\u4F20",
                      -1
                      /* CACHED */
                    )
                  ])]),
                  _: 1
                  /* STABLE */
                }, 8, ["loading", "onClick"])
              ])
            ]),
            _: 3
            /* FORWARDED */
          })
        ]),
        default: withCtx(() => [
          createVNode(unref(ElUpload), {
            ref: "uploadRef",
            class: "upload-demo",
            drag: "",
            disabled: unref(disabled),
            multiple: unref(multiple),
            maxCount: props.maxCount,
            accept: accept.value,
            "auto-upload": false,
            "show-file-list": false,
            "on-change": onChangeHandler
          }, {
            default: withCtx(() => [
              createVNode(unref(MeSvgIcon), {
                name: "ri-upload-cloud-line",
                style: { "font-size": "50px" }
              }),
              createElementVNode("div", _hoisted_1, [
                _cache[3] || (_cache[3] = createElementVNode(
                  "div",
                  { class: "text-sm mt-4 font-bold" },
                  "\u70B9\u51FB\u6216\u62D6\u52A8\u6587\u4EF6\u5230\u6B64\u5904\u4E0A\u4F20",
                  -1
                  /* CACHED */
                )),
                (openBlock(true), createElementBlock(
                  Fragment,
                  null,
                  renderList(tips.value, (item) => {
                    return openBlock(), createElementBlock(
                      "div",
                      {
                        class: "text-xs mt-4",
                        key: item.name
                      },
                      " \u4E0A\u4F20\u6587\u4EF6\u652F\u6301 " + toDisplayString(item.name) + " \u683C\u5F0F\uFF0C \u5E76\u4E14\u6587\u4EF6\u5927\u5C0F\u4E0D\u80FD\u5927\u4E8E " + toDisplayString(item.size),
                      1
                      /* TEXT */
                    );
                  }),
                  128
                  /* KEYED_FRAGMENT */
                ))
              ])
            ]),
            _: 1
            /* STABLE */
          }, 8, ["disabled", "multiple", "maxCount", "accept"]),
          createVNode(unref(VueDraggable), {
            disabled: dragDisabled.value,
            modelValue: fileList.value,
            "onUpdate:modelValue": _cache[1] || (_cache[1] = ($event) => fileList.value = $event),
            target: "tbody",
            animation: 150
          }, {
            default: withCtx(() => [
              createVNode(unref(ElTable), {
                onCellMouseEnter: cellMouseEnter,
                onCellMouseLeave: _cache[0] || (_cache[0] = ($event) => dragDisabled.value = true),
                data: fileList.value,
                class: "me-table mt-4"
              }, {
                default: withCtx(() => [
                  createVNode(unref(ElTableColumn), {
                    prop: "image",
                    label: "\u7F29\u7565\u56FE",
                    width: "80"
                  }, {
                    default: withCtx((scope) => [
                      createVNode(unref(ElImage), {
                        shape: "square",
                        style: { "vertical-align": "middle", "width": "50px", "height": "50px" },
                        src: scope.row.image
                      }, null, 8, ["src"])
                    ]),
                    _: 1
                    /* STABLE */
                  }),
                  createVNode(unref(ElTableColumn), {
                    prop: "name",
                    label: "\u6587\u4EF6\u540D"
                  }, {
                    default: withCtx((scope) => [
                      createVNode(
                        _component_el_text,
                        { truncated: "" },
                        {
                          default: withCtx(() => [
                            createTextVNode(
                              toDisplayString(scope.row.name),
                              1
                              /* TEXT */
                            )
                          ]),
                          _: 2
                          /* DYNAMIC */
                        },
                        1024
                        /* DYNAMIC_SLOTS */
                      )
                    ]),
                    _: 1
                    /* STABLE */
                  }),
                  createVNode(unref(ElTableColumn), {
                    prop: "size",
                    label: "\u5927\u5C0F",
                    width: "100"
                  }, {
                    default: withCtx((scope) => [
                      createElementVNode(
                        "span",
                        _hoisted_2,
                        toDisplayString(scope.row.size),
                        1
                        /* TEXT */
                      )
                    ]),
                    _: 1
                    /* STABLE */
                  }),
                  createVNode(unref(ElTableColumn), {
                    prop: "status",
                    label: "\u72B6\u6001",
                    width: "150"
                  }, {
                    default: withCtx((scope) => [
                      scope.row.status == "ready" ? (openBlock(), createElementBlock("div", _hoisted_3, [
                        createVNode(unref(ElTag), {
                          type: "primary",
                          effect: "plain"
                        }, {
                          default: withCtx(() => [..._cache[4] || (_cache[4] = [
                            createTextVNode(
                              "\u5F85\u4E0A\u4F20 ",
                              -1
                              /* CACHED */
                            )
                          ])]),
                          _: 1
                          /* STABLE */
                        })
                      ])) : createCommentVNode("v-if", true),
                      createCommentVNode(" \u4E0A\u4F20\u8FDB\u5EA6\u6761 "),
                      scope.row.status == "uploading" ? (openBlock(), createElementBlock("div", _hoisted_4, [
                        createVNode(unref(ElProgress), {
                          percentage: scope.row.progress,
                          "stroke-width": 15,
                          striped: "",
                          "striped-flow": "",
                          "text-inside": true
                        }, null, 8, ["percentage"])
                      ])) : createCommentVNode("v-if", true),
                      scope.row.status == "success" ? (openBlock(), createElementBlock("div", _hoisted_5, [
                        createVNode(unref(ElTag), { type: "success" }, {
                          default: withCtx(() => [..._cache[5] || (_cache[5] = [
                            createTextVNode(
                              "\u4E0A\u4F20\u6210\u529F ",
                              -1
                              /* CACHED */
                            )
                          ])]),
                          _: 1
                          /* STABLE */
                        })
                      ])) : createCommentVNode("v-if", true),
                      scope.row.status == "fail" ? (openBlock(), createElementBlock("div", _hoisted_6, [
                        createVNode(unref(ElTag), { type: "danger" }, {
                          default: withCtx(() => [..._cache[6] || (_cache[6] = [
                            createTextVNode(
                              "\u4E0A\u4F20\u5931\u8D25 ",
                              -1
                              /* CACHED */
                            )
                          ])]),
                          _: 1
                          /* STABLE */
                        })
                      ])) : createCommentVNode("v-if", true),
                      scope.row.status == "canceled" ? (openBlock(), createElementBlock("div", _hoisted_7, [
                        createVNode(unref(ElTag), { type: "danger" }, {
                          default: withCtx(() => [..._cache[7] || (_cache[7] = [
                            createTextVNode(
                              "\u5DF2\u53D6\u6D88",
                              -1
                              /* CACHED */
                            )
                          ])]),
                          _: 1
                          /* STABLE */
                        })
                      ])) : createCommentVNode("v-if", true)
                    ]),
                    _: 1
                    /* STABLE */
                  }),
                  createVNode(unref(ElTableColumn), {
                    prop: "",
                    label: "\u64CD\u4F5C",
                    width: "80"
                  }, {
                    default: withCtx(({ row }) => [
                      row.status !== "uploading" ? (openBlock(), createBlock(unref(ElButton), {
                        key: 0,
                        link: "",
                        onClick: ($event) => removeItemHandler(row)
                      }, {
                        default: withCtx(() => [
                          createVNode(unref(MeSvgIcon), { name: "ri-delete-bin-line" })
                        ]),
                        _: 1
                        /* STABLE */
                      }, 8, ["onClick"])) : createCommentVNode("v-if", true),
                      row.status === "uploading" ? (openBlock(), createBlock(unref(ElButton), {
                        key: 1,
                        link: "",
                        type: "danger",
                        onClick: ($event) => row.controller.abort()
                      }, {
                        default: withCtx(() => [
                          createVNode(unref(MeSvgIcon), { name: "ri-close-line" })
                        ]),
                        _: 1
                        /* STABLE */
                      }, 8, ["onClick"])) : createCommentVNode("v-if", true),
                      row.status === "canceled" ? (openBlock(), createBlock(unref(ElButton), {
                        key: 2,
                        link: "",
                        type: "primary",
                        onClick: ($event) => handleReUpload(row)
                      }, {
                        default: withCtx(() => [
                          createVNode(unref(MeSvgIcon), { name: "ri-reset-right-line" })
                        ]),
                        _: 1
                        /* STABLE */
                      }, 8, ["onClick"])) : createCommentVNode("v-if", true)
                    ]),
                    _: 1
                    /* STABLE */
                  }),
                  createVNode(unref(ElTableColumn), {
                    width: "50px",
                    label: ""
                  }, {
                    default: withCtx(() => [
                      createElementVNode("div", _hoisted_8, [
                        createVNode(unref(MeSvgIcon), { name: "ri-draggable" })
                      ])
                    ]),
                    _: 1
                    /* STABLE */
                  })
                ]),
                _: 1
                /* STABLE */
              }, 8, ["data"])
            ]),
            _: 1
            /* STABLE */
          }, 8, ["disabled", "modelValue"])
        ]),
        _: 3
        /* FORWARDED */
      }, 8, ["modelValue", "onCloseEvent", "title"]);
    };
  }
});

export { script as default };
//# sourceMappingURL=upload.vue2.mjs.map
