<script setup lang="ts">
import type { UploadFileDto } from '@/types/user.js'
import { computed, onMounted, ref, useTemplateRef } from 'vue'
import FileModal from '@/components/file/FileModal.vue'

const { file, size, enableSelect, onSelect, onRemove } = defineProps<{
  file: UploadFileDto
  size: number
  enableSelect?: boolean
  onSelect?: (file: UploadFileDto) => boolean
  onRemove?: (file: UploadFileDto) => boolean
}>()

const th = useTemplateRef('th')

const showModal = ref(false)
const selected = ref(false)

const ALLOWED_EXTENSIONS = ['jpg', 'jpeg', 'png']

onMounted(() => {
  if (ALLOWED_EXTENSIONS.includes(file.safe_name.split('.').at(-1)!.toLowerCase())) {
    th.value?.style.setProperty('background-image', 'url("' + file.download_url + '")')
  }
})

function onClick() {
  if (!enableSelect) {
    showModal.value = true
  }

  if (selected.value && onRemove) {
    if (onRemove(file)) {
      selected.value = false
      th.value?.classList.remove('selected')
      console.log(`选中文件：${file.original_name}`)
    }
  } else if (!selected.value && onSelect) {
    if (onSelect(file)) {
      selected.value = true
      th.value?.classList.add('selected')
      console.log(`取消文件：${file.original_name}`)
    }
  }
}

const size_px = computed(() => `${size}px`)
</script>

<template>
  <div class="file-thumbnail" ref="th" @click="onClick"></div>

  <file-modal :file v-model:show-modal="showModal" />
</template>

<style scoped>
div.file-thumbnail {
  box-sizing: border-box;
  width: v-bind(size_px);
  height: v-bind(size_px);
  border-radius: 3px;
  border: 2px solid rgb(0 0 0 / 0.2);
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;

  transition:
    border-color 0.3s,
    box-shadow 0.3s;
}

div.selected {
  border-color: rgb(74 228 112 / 0.8);
  box-shadow: 0 0 0 2px rgb(104 104 104 / 0.2);
}
</style>
