<template>
  <a-upload-dragger
    :file-list="fileList"
    :maxCount="maxNumber"
    :accpet="accpet"
    :name="name"
    :disabled="disabled"
    :multiple="multiple"
    :beforeUpload="beforeUpload"
    listType="picture"
    :show-upload-list="{ showDownloadIcon, showPreviewIcon, showRemoveIcon }"
    @remove="handleRemove"
    @download="handleDownload"
    @preview="handlePreview"
    @drop="handleClick"
    @click="handleClick"
    class="list-upload dragger-upload"
    :style="{ width: '200px' }"
  >
    <div class="dragger-text">
      <Icon icon="ep:upload-filled" color="#5e95ff" :size="24" />
      <div class="mt-2 text-xs">点击或将文件拖拽到这里上传</div>
    </div>
    <div class="dragger-tip">支持扩展名：.doc .docx .pdf .jpg ...</div>
  </a-upload-dragger>
  <a-modal :visible="previewVisible" :title="previewTitle" :footer="null" @cancel="handleCancel">
    <img alt="example" style="width: 100%" :src="previewImage" />
  </a-modal>
</template>
<script lang="ts" setup>
  import { ref, watch } from 'vue';
  import { Upload } from 'ant-design-vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { deleteSingleFile, getFileList } from '/@/api/system/file';
  import { downloadByUrl } from '/@/utils/file/download';
  import { uploadMultiApi } from '/@/api/sys/upload';
  import Icon from '/@/components/Icon/index';
  import { getFileUrl } from '/@/utils/event/design';

  const props = defineProps({
    value: String,
    maxNumber: Number,
    accpet: String,
    name: String,
    disabled: Boolean,
    multiple: Boolean,
    maxSize: Number,
    api: Function,
    listType: {
      type: String,
      default: 'text',
    },
    tip: String,
    showPreviewIcon: {
      type: Boolean,
      default: true,
    },
    showRemoveIcon: {
      type: Boolean,
      default: true,
    },
    showDownloadIcon: {
      type: Boolean,
      default: true,
    },
  });

  const fileList = ref<any[]>([]);
  const list = ref<any[]>([]);
  const { notification } = useMessage();
  const folderId = ref<string>('');
  const deleteFlag = ref(false);
  const emit = defineEmits(['update:value', 'change', 'click']);
  const loading = ref(false);

  const previewVisible = ref(false);
  const previewImage = ref('');
  const previewTitle = ref('');

  watch(
    () => props.value,
    async (val) => {
      if (val) {
        fileList.value = await getFileList({ folderId: props.value });
        if (fileList.value.length) {
          fileList.value.forEach((x) => {
            x.name = x.fileName;
            x.thumbUrl = getFileUrl(x);
            x.status = 'done'; //没有则不会展示下载按钮
          });
          folderId.value = fileList.value[0].folderId;
        }
      }
      if (!val) {
        fileList.value = [];
      }
    },
    {
      immediate: true,
    },
  );
  watch(
    () => list.value,
    async (val) => {
      if (deleteFlag.value) return;
      if (val.length) {
        let arr: any[] = val.filter((o) => {
          return !o.status;
        });
        if (arr.length <= 0) return;
        try {
          let res = await uploadMultiApi(
            {
              name: 'file',
              file: arr,
            },
            folderId.value,
          );
          folderId.value = res[0].folderId;
          fileList.value.forEach((x) => {
            x.status = 'done'; //没有则不会展示下载按钮
            x.thumbUrl = getFileUrl(x);
          });
          emit('update:value', folderId.value);
          emit('change');
          loading.value = false;
        } catch (error) {
          loading.value = false;
        }
      }
    },
  );

  const beforeUpload = (file) => {
    if (props.maxSize && file.size / 1024 / 1024 > props.maxSize) {
      notification.error({
        message: 'Tip',
        description: `文件大小不能超过${props.maxSize}MB！`,
      });
      return false || Upload.LIST_IGNORE;
    }
    if (props.maxNumber && fileList.value.length + list.value.length === props.maxNumber!) {
      notification.error({
        message: 'Tip',
        description: `文件数量不能超过${props.maxNumber}个！`,
      });
      return false;
    }
    list.value = [...list.value, file];
    deleteFlag.value = false;
    loading.value = true;
    return Upload.LIST_IGNORE;
  };
  function handleClick() {
    list.value = [];
  }
  const handleRemove = async (info) => {
    const id = info.response ? info.response.data.id : info.id;

    const newFolderId = await deleteSingleFile(id);

    folderId.value = newFolderId;

    deleteFlag.value = true;

    const index = fileList.value.findIndex((x) => x.id === id);
    fileList.value.splice(index, 1);

    fileList.value.forEach((x) => {
      x.folderId = newFolderId;
    });

    emit('update:value', folderId.value);
    emit('change');
    notification.success({
      message: 'Tip',
      description: '删除成功！',
    });
  };

  const handleDownload = (info) => {
    const url = info.response ? getFileUrl(info.response.data) : info.url;
    downloadByUrl({ url: url });
  };

  const handlePreview = async (file) => {
    previewImage.value = getFileUrl(file?.response?.data) || file.url;
    previewVisible.value = true;
    previewTitle.value = file.name || file.fileName;
  };

  const handleCancel = () => {
    previewVisible.value = false;
    previewTitle.value = '';
  };
</script>
<style lang="less" scoped>
  .list-upload {
    :deep(.ant-upload) {
      display: flex;
      justify-content: center;
      align-items: center;
      flex-direction: column;
      width: 128px;
      height: 128px;
      background: #fafafa;
      border: 1px dashed #d9d9d9;
    }

    :deep(.anticon-plus) {
      font-size: 20px;
      color: #999;
    }

    .dragger-tip {
      background: rgb(0 0 0 / 60%);
      color: #fff;
      height: 100%;
      border-radius: 2px;
      display: none;
      padding: 8px 5px;
      width: 100%;
    }

    .dragger-text {
      padding: 16px 0;
    }

    &:hover .dragger-tip {
      display: block;
    }

    &:hover .dragger-text {
      display: none;
    }
  }

  :deep(.ant-upload) {
    padding: 0 !important;
  }
</style>
