<template>
  <el-drawer
    :model-value="modelValue"
    title="選擇 / 上傳圖片"
    direction="ltr"
    size="50%"
    @update:model-value="$emit('update:modelValue', $event)"
  >
    <template #default>
      <section class="-tw-my-5 tw-space-y-7 tw-h-full">
        <el-upload drag :http-request="onImageUpload" :show-file-list="false">
          <el-icon class="el-icon--upload">
            <upload-filled />
          </el-icon>
          <div class="el-upload__text">拖移檔案至此 或 <em>點擊上傳</em></div>
        </el-upload>
        <el-card style="height: 73%" :body-style="{ height: '100%' }">
          <div class="tw-grid tw-grid-cols-4 tw-gap-4 tw-h-full tw-overflow-auto">
            <div
              v-for="item in images"
              :key="item.url"
              style="height: 150px"
            >
              <el-image
                :src="item.url"
                fit="fill"
                :class="[
                  normalizeImageUrl(item.url) === selectedImageUrl ? 'tw-border-4 tw-border-blue-500' : '',
                  'tw-h-full tw-w-full tw-rounded-md',
                ]"
                loading="lazy"
                @click="$emit('select', normalizeImageUrl(item.url))"
              />
            </div>
          </div>
        </el-card>
      </section>
    </template>
  </el-drawer>
</template>

<script setup>
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false,
  },
  images: {
    type: Array,
    default: () => [],
  },
  selectedImageUrl: {
    type: String,
    default: "",
  },
  onImageUpload: {
    type: Function,
    required: true,
  },
})

defineEmits(["update:modelValue", "select"])

const normalizeImageUrl = (url) => url.replace("adapi", "pass")
</script>
