<template>
  <el-dialog draggable append-to-body title="图片选择" v-model="visible" width="800px">
    <div class="flex h-320px overflow-y-auto gap-8px flex-wrap">
      <div
        class="w-100px h-100px border-solid border-border cursor-pointer flex flex-col"
        v-for="item in imageList"
        :key="item.id"
        :class="item.id === selected ? 'border-accent-blue!' : ''"
        @click="handleClick(item.id)"
        :title="item.fileName"
      >
        <LocalImage class="h-70px" :src="projectStore.projectPath + item.path" />
        <div class="h-20px leading-30px text-12px text-text-secondary px-2px truncate">
          {{ item.fileName }}
        </div>
      </div>
      <el-empty class="mx-auto" v-if="!imageList.length" description="暂无资源" />
    </div>
    <template #footer>
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" :disabled="!selected" @click="handleConfirm">确定</el-button>
    </template>
  </el-dialog>
  <el-input spellcheck="false" :model-value="selectedFile?.fileName" readonly>
    <template #suffix>
      <LuX v-if="selectedFile" class="cursor-pointer" size="16px" @click="handleClear" />
    </template>
    <template #append>
      <LocalImage
        v-if="selectedFile"
        class="h-20px cursor-pointer"
        :src="projectStore.projectPath + selectedFile.path"
        @click="visible = true"
      />
      <LuFileImage v-else class="cursor-pointer" size="20px" @click="visible = true" />
    </template>
  </el-input>
</template>

<script setup lang="ts">
import { computed, ref } from 'vue'
import { useProjectStore } from '@/store/modules/project'
import { LocalImage } from '@/components'
import { LuFileImage, LuX } from 'vue-icons-plus/lu'

const modelValue = defineModel('modelValue')
const projectStore = useProjectStore()
const visible = ref(false)
const selected = ref(modelValue.value)
// 图片列表
const imageList = computed(() => {
  return projectStore.project?.resources.images || []
})
// 选中资源
const selectedFile = computed(() => {
  return imageList.value.find((item) => item.id === modelValue.value)
})

const handleClick = (val: string) => {
  if (selected.value === val) {
    selected.value = ''
  } else {
    selected.value = val
  }
}

// 取消
const handleCancel = () => {
  visible.value = false
}

// 确定
const handleConfirm = () => {
  visible.value = false
  modelValue.value = selected.value
}

// 清除
const handleClear = () => {
  selected.value = ''
  modelValue.value = ''
}
</script>

<style scoped></style>
