<template>
  <div>
    <a-upload
      class="InputUpload w-full"
      accept="image/png, image/jpeg, image/jpg"
      :beforeUpload="beforeUpload"
      listType="text"
      :show-upload-list="false"
      @remove="handleRemove"
      @download="handleDownload"
      @preview="handlePreview"
      @click="handleClick"
    >
      <a-input-group compact class="!flex items-center">
        <a-input :placeholder="placeholder" :value="name">
          <template #suffix>
            <Icon icon="fa-solid:upload" color="#ccc" />
            <CloseCircleFilled
              @click.stop="handleClear"
              style="position: absolute; right: 40px; color: #ccc; cursor: pointer; z-index: 99"
            />
          </template>
        </a-input>
        <a-popover placement="topRight">
          <template #content>
            <a-image
              v-if="tipType == 'img'"
              :width="280"
              :src="tips"
              fallback="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMIAAADDCAYAAADQvc6UAAABRWlDQ1BJQ0MgUHJvZmlsZQAAKJFjYGASSSwoyGFhYGDIzSspCnJ3UoiIjFJgf8LAwSDCIMogwMCcmFxc4BgQ4ANUwgCjUcG3awyMIPqyLsis7PPOq3QdDFcvjV3jOD1boQVTPQrgSkktTgbSf4A4LbmgqISBgTEFyFYuLykAsTuAbJEioKOA7DkgdjqEvQHEToKwj4DVhAQ5A9k3gGyB5IxEoBmML4BsnSQk8XQkNtReEOBxcfXxUQg1Mjc0dyHgXNJBSWpFCYh2zi+oLMpMzyhRcASGUqqCZ16yno6CkYGRAQMDKMwhqj/fAIcloxgHQqxAjIHBEugw5sUIsSQpBobtQPdLciLEVJYzMPBHMDBsayhILEqEO4DxG0txmrERhM29nYGBddr//5/DGRjYNRkY/l7////39v///y4Dmn+LgeHANwDrkl1AuO+pmgAAADhlWElmTU0AKgAAAAgAAYdpAAQAAAABAAAAGgAAAAAAAqACAAQAAAABAAAAwqADAAQAAAABAAAAwwAAAAD9b/HnAAAHlklEQVR4Ae3dP3PTWBSGcbGzM6GCKqlIBRV0dHRJFarQ0eUT8LH4BnRU0NHR0UEFVdIlFRV7TzRksomPY8uykTk/zewQfKw/9znv4yvJynLv4uLiV2dBoDiB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ELNNtScABFyNiqFCBChULMNNSdAhJyNSiECRCjUbEPNCRAhZ6NSiAARCjXbUHMCRMjZqBQiQIRCzTbUnAARcjYqhQgQoVCzDTUnQIScjUohAkQo1GxDzQkQIWejUogAEQo121BzAkTI2agUIkCEQs021JwAEXI2KoUIEKFQsw01J0CEnI1KIQJEKNRsQ80JECFno1KIABEKNdtQcwJEyNmoFCJAhELNNtScABFyNiqFCBChULMNNSdAhJyNSiEC/wGgKKC4YMA4TAAAAABJRU5ErkJggg=="
            />
          </template>
          <QuestionCircleOutlined
            v-if="showTip"
            style="width: 50px; font-size: 20px; color: #ccc; border: 0"
          />
        </a-popover>
      </a-input-group>
    </a-upload>
    <a-modal
      :bodyStyle="bodyStyle"
      :width="800"
      :visible="previewVisible"
      :title="previewTitle"
      :footer="null"
      @cancel="handleCancel"
    >
      <iframe :src="previewFile" class="iframe-box"></iframe>;
    </a-modal>
  </div>
</template>
<script lang="ts" setup>
  import { ref, watch } from 'vue';
  import { Upload } from 'ant-design-vue';
  import { CloseCircleFilled, QuestionCircleOutlined } from '@ant-design/icons-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';
  import { Base64 } from 'js-base64';
  import { getAppEnvConfig } from '/@/utils/env';
  import { getFileUrl } from '/@/utils/event/design';

  const props = defineProps({
    value: String,
    showTip: { type: Boolean, default: true },
    placeholder: String,
    tipType: String,
    tips: String,
    maxSize: Number,
  });

  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 name = ref();
  const previewVisible = ref(false);
  const previewFile = 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.url = getFileUrl(x);
            x.thumbUrl = getFileUrl(x, 'thUrl');
            x.status = 'done'; //没有则不会展示下载按钮
          });
          folderId.value = fileList.value[0].folderId;
          name.value = fileList.value[0].name + fileList.value[0].fileType;
        }
      }
      if (!val) {
        fileList.value = [];
        name.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.url = getFileUrl(x);
            x.thumbUrl = getFileUrl(x, 'thUrl');
          });
          name.value = res[0].fileName + res[0].fileType;
          emit('update:value', folderId.value);
          emit('change');
          loading.value = false;
        } catch (error) {
          console.error(error);
          loading.value = false;
        }
      }
    },
  );

  const bodyStyle = { height: '500px' };

  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;
    }

    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;
    const fileName = info.response ? info.response.data.fileName : info.fileName;

    downloadByUrl({ url, fileName });
  };

  const handlePreview = async (file) => {
    const fileUrl = getFileUrl(file?.response?.data) || file.url;
    previewFile.value =
      getAppEnvConfig().VITE_GLOB_UPLOAD_PREVIEW +
      encodeURIComponent(
        Base64.encode(
          fileUrl.includes('http://') || fileUrl.includes('https://')
            ? fileUrl
            : getAppEnvConfig().VITE_GLOB_API_URL + fileUrl,
        ),
      );

    previewVisible.value = true;
    previewTitle.value = file.name || file.fileName;
  };

  const handleCancel = () => {
    previewVisible.value = false;
    previewTitle.value = '';
  };

  function handleClear() {
    name.value = '';
    folderId.value = '';
    emit('update:value', folderId.value);
    emit('change');
  }
</script>
<style lang="less" scoped>
  .InputUpload {
    :deep(.ant-upload) {
      width: 100%;
    }

    :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;
  }

  .iframe-box {
    width: 100%;
    height: 100%;
  }
</style>
