<template>
  <div v-if="attachments?.length" class="msg-attachments">
    <div v-for="item in attachments" :key="item.id" class="msg-attachments__item" @click="handleClick(item)">
      <el-image
        v-if="item.type === 'image'"
        :src="item.url"
        fit="cover"
        class="msg-attachments__thumb"
        :preview-src-list="imageUrls"
        :initial-index="imageUrls.indexOf(item.url)"
        preview-teleported
      />
      <div v-else class="msg-attachments__file">
        <el-icon :size="20"><Document /></el-icon>
        <span class="msg-attachments__file-name">{{ item.name }}</span>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { computed } from 'vue';
import { Document } from '@element-plus/icons-vue';
import type { ChatAttachment } from '../../types/index';

const props = defineProps<{ attachments: ChatAttachment[] }>();

const imageUrls = computed(() =>
  props.attachments.filter(a => a.type === 'image').map(a => a.url)
);

function handleClick(item: ChatAttachment) {
  if (item.type !== 'image' && item.url) {
    window.open(item.url, '_blank');
  }
}
</script>

<style scoped>
.msg-attachments {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-top: 8px;
}
.msg-attachments__thumb {
  width: 120px;
  height: 120px;
  border-radius: 8px;
  cursor: pointer;
  object-fit: cover;
}
.msg-attachments__file {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 6px 12px;
  border: 1px solid var(--el-border-color-light);
  border-radius: 8px;
  background: var(--el-fill-color-blank);
  cursor: pointer;
  font-size: 13px;
}
.msg-attachments__file-name {
  max-width: 160px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>
