<template>
  <div class="attachment-view">
    <div v-if="attachments.images.length" class="attachment-image-list">
      <t-space :size="8">
        <t-image
          v-for="(img, index) in attachments.images"
          :key="index"
          :src="img"
          fit="scale-down"
          :style="imgStyle"
          overlay-trigger="hover"
          @click="openView(index)"
        >
          <template #overlayContent>
            <div
              :style="{
                background: 'rgba(0,0,0,.4)',
                color: '#fff',
                height: '100%',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
              }"
              >预览</div
            >
          </template>
        </t-image>
      </t-space>
      <t-image-viewer
        v-model:visible="imgVisible"
        :default-index="imgIndex"
        :images="attachments.images"
      >
      </t-image-viewer>
    </div>
    <div v-if="attachments.files.length" class="attachment-link-list">
      <t-link
        v-for="url in attachments.files"
        :key="url"
        theme="primary"
        download
        :href="url"
        target="_block"
      >
        {{ url.split('/').slice(-1)[0] }}
      </t-link>
    </div>
  </div>
</template>

<script setup name="AttachmentView">
import { computed, reactive, ref, watch } from 'vue';
import { objTypeOf } from '@/utils/tool';
import { getAttachmentList } from '@/api/user';

const props = defineProps({
  ids: {
    type: [String, Array],
    default: '',
  },
  imgSize: {
    type: Number,
    default: 80,
  },
  imageList: {
    type: Array,
    default() {
      return [];
    },
  },
  fileList: {
    type: Array,
    default() {
      return [];
    },
  },
});

const imgVisible = ref(false);
const imgIndex = ref(0);

const openView = (index) => {
  imgIndex.value = index;
  imgVisible.value = true;
};

const imgStyle = computed(() => {
  return {
    width: `${props.imgSize}px`,
    height: `${props.imgSize}px`,
  };
});

const attachmentIds = computed(() => {
  let data = [];
  if (objTypeOf(props.ids) === 'string') {
    data = props.ids.split(',');
  } else if (objTypeOf(props.ids) === 'array') {
    data = props.ids;
  }

  data = data.filter((item) => !!item);

  return data;
});

const attachments = reactive({ images: [], files: [] });
const getAttachments = async () => {
  attachments.images = [];
  attachments.files = [];

  // 直接传图片数据时，直接展示
  if (props.imageList && props.imageList.length) {
    attachments.images = [...props.imageList];
  }
  // 直接传图片数据时，直接展示
  if (props.fileList && props.fileList.length) {
    attachments.files = [...props.fileList];
  }

  if (!attachmentIds.value.length) return;

  const res = await getAttachmentList(attachmentIds.value);
  const data = res || [];
  data.forEach((item) => {
    const type = checkFileType(item.url);
    if (type === 'image') {
      attachments.images.push(item.url);
    } else {
      attachments.files.push(item.url);
    }
  });
};

function checkFileType(filepath) {
  const fileFormat = filepath.split('.').pop().toLocaleLowerCase();
  const imgTypes = ['jpg', 'jpeg', 'png'];
  return imgTypes.includes(fileFormat) ? 'image' : 'file';
}

watch(
  [() => attachmentIds, () => props.imageList, () => props.fileList],
  () => {
    getAttachments();
  },
  { immediate: true }
);
</script>

<style lang="less" scoped>
.attachment-view {
  :deep(.t-link) {
    word-break: break-all;
  }
}
</style>
