<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 fileList"
        :key="item.id"
        :class="item.id === selected ? 'border-accent-blue!' : ''"
        @click="handleClick(item.id)"
        :title="item.fileName"
      >
        <div class="w-100px h-70px flex items-center justify-center">
          <component :is="icon || GrDocumentVideo" size="45px" />
        </div>

        <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="!fileList.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>
      <component
        :is="appendIcon || GrDocumentVideo"
        size="20px"
        class="cursor-pointer"
        @click="visible = true"
      />
    </template>
  </el-input>
</template>

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

type FileSelectProps = {
  // 扩展名列表
  extensionNames: string[]
  // input插槽图标
  appendIcon?: IconType
  // 选择插槽图标
  icon?: IconType
}

const modelValue = defineModel('modelValue')

const props = defineProps<FileSelectProps>()

const projectStore = useProjectStore()
const visible = ref(false)
const selected = ref(modelValue.value)
// 资源列表
const fileList = computed(() => {
  // 文件扩展名：['mp4']
  const extensionNames = (props.extensionNames || []).map((item) => item.toLowerCase())
  return (projectStore.project?.resources.others || []).filter((item) =>
    extensionNames.includes((item.fileType || '').toLowerCase())
  )
})
// 选中资源
const selectedFile = computed(() => {
  return fileList.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>
