<template>
  <SplitterCollapse>
    <SplitterCollapseItem title="图片">
      <template #header-right>
        <div class="flex items-center">
          <el-tooltip content="清除未使用图片">
            <span @click.stop>
              <el-popconfirm class="box-item" title="确认清除?" @confirm="handleClearUnusedImage">
                <template #reference>
                  <el-button type="danger" link class="mr-12px">
                    <LuTrash2 size="14px" />
                  </el-button>
                </template>
              </el-popconfirm>
            </span>
          </el-tooltip>
          <el-tooltip content="添加">
            <el-button type="text" class="mr-12px" @click.capture.stop="handleAddImage">
              <LuPlus size="14px" />
            </el-button>
          </el-tooltip>
        </div>
      </template>
      <div class="w-full h-full flex flex-col">
        <div class="p-12px flex gap-8px shrink-0">
          <el-input spellcheck="false" v-model="imageSearch" size="small" placeholder="输入搜索..." />
        </div>
        <el-scrollbar class="flex-1">
          <ResourceItem v-for="item in getImages || []" :key="item.id" :data="item" type="image"
            @delete="deleteResource(item, 'images')" />
          <div v-if="!getImages?.length" class="text-center text-text-secondary">暂无图片~</div>
        </el-scrollbar>
      </div>
    </SplitterCollapseItem>
    <SplitterCollapseItem title="字体">
      <template #header-right>
        <el-tooltip content="添加">
          <el-button type="text" class="mr-12px" @click.capture.stop="handleAddFont">
            <LuPlus size="14px" />
          </el-button>
        </el-tooltip>
      </template>
      <div class="w-full h-full flex flex-col">
        <div class="p-12px flex gap-8px shrink-0">
          <el-input spellcheck="false" v-model="fontSearch" size="small" placeholder="输入搜索..." />
        </div>
        <el-scrollbar class="flex-1">
          <ResourceItem v-for="item in getFonts || []" :key="item.id" :data="item" type="font"
            @delete="deleteResource(item, 'fonts')" />
          <div v-if="!getFonts?.length" class="text-center text-text-secondary">暂无字体~</div>
        </el-scrollbar>
      </div>
    </SplitterCollapseItem>
    <SplitterCollapseItem title="其他资源">
      <template #header-right>
        <el-tooltip content="添加">
          <el-button type="text" class="mr-12px" @click.capture.stop="handleAddOther">
            <LuPlus size="14px" />
          </el-button>
        </el-tooltip>
      </template>
      <div class="w-full h-full flex flex-col">
        <div class="p-12px flex gap-8px shrink-0">
          <el-input spellcheck="false" v-model="otherSearch" size="small" placeholder="输入搜索..." />
        </div>
        <el-scrollbar class="flex-1">
          <ResourceItem v-for="item in getOthers || []" :key="item.id" :data="item" type="other"
            @delete="deleteResource(item, 'others')" />
          <div v-if="!getOthers?.length" class="text-center text-text-secondary">暂无资源~</div>
        </el-scrollbar>
      </div>
    </SplitterCollapseItem>
  </SplitterCollapse>
</template>

<script setup lang="ts">
import type { FontResource, ImageResource, OtherResource, Resource } from '@/types/resource'

import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { SplitterCollapse, SplitterCollapseItem } from '@/components/SplitterCollapse'
import { LuPlus, LuTrash2 } from 'vue-icons-plus/lu'
import { useProjectStore } from '@/store/modules/project'
import { createFileResource } from '@/model'
import ResourceItem from './components/ResourceItem.vue'

const projectStore = useProjectStore()
const imageSearch = ref('')
const fontSearch = ref('')
const otherSearch = ref('')
type ResourceListKey = 'images' | 'fonts' | 'others'
type ResourceType = 'image' | 'font' | 'other'

const normalizeResourcePath = (path: string) => path.replaceAll('/', '\\').toLowerCase()

const isResourceExists = (type: ResourceListKey, resourcePath: string) => {
  const normalizedPath = normalizeResourcePath(resourcePath)
  return (
    projectStore.project?.resources[type].some(
      (item) => normalizeResourcePath(item.path) === normalizedPath
    ) ?? false
  )
}

const addResourceFile = async (
  sourcePath: string,
  type: ResourceType,
  resourceListKey: ResourceListKey
) => {
  const fileName = sourcePath.split(/[\\/]/).pop()
  if (!fileName) return

  const resourcePath = `\\src\\assets\\${resourceListKey}\\${fileName}`
  if (isResourceExists(resourceListKey, resourcePath)) {
    ElMessage.warning(
      `\u8d44\u6e90 ${fileName} \u5df2\u7ecf\u5b58\u5728\uff0c\u4e0d\u80fd\u91cd\u590d\u6dfb\u52a0`
    )
    return
  }

  await window.electron.ipcRenderer.invoke(
    'copy-file',
    sourcePath,
    `${projectStore.projectPath}\\src\\assets\\${resourceListKey}\\${fileName}`
  )

  const resource = createFileResource(resourcePath, type)
  if (resourceListKey === 'images') {
    projectStore.project?.resources.images.push(resource as ImageResource)
  } else if (resourceListKey === 'fonts') {
    projectStore.project?.resources.fonts.push(resource as FontResource)
  } else {
    projectStore.project?.resources.others.push(resource as OtherResource)
  }
}

const addResourceFiles = async (
  paths: string[] | undefined,
  type: ResourceType,
  resourceListKey: ResourceListKey
) => {
  for (const path of paths || []) {
    await addResourceFile(path, type, resourceListKey)
  }
}

const getImages = computed(() => {
  return projectStore.project?.resources.images.filter((item) =>
    item.fileName.includes(imageSearch.value)
  )
})

const getFonts = computed(() => {
  return projectStore.project?.resources.fonts.filter((item) =>
    item.fileName.includes(fontSearch.value)
  )
})

const getOthers = computed(() => {
  return projectStore.project?.resources.others.filter((item) =>
    item.fileName.includes(otherSearch.value)
  )
})

// 添加图片
const handleAddImage = async () => {
  const paths = await window.electron.ipcRenderer.invoke('get-file', {
    title: '选择文件',
    buttonLabel: '添加',
    properties: ['openFile', 'multiSelections'],
    filters: [
      {
        name: 'Images',
        extensions: ['png', 'jpg', 'bmp']
      }
    ]
  })

  await addResourceFiles(paths, 'image', 'images')
}

// 添加字体
const handleAddFont = async () => {
  const paths = await window.electron.ipcRenderer.invoke('get-file', {
    title: '选择文件',
    buttonLabel: '添加',
    properties: ['openFile', 'multiSelections'],
    filters: [
      {
        name: 'Fonts',
        extensions: ['ttf', 'woff']
      }
    ]
  })

  await addResourceFiles(paths, 'font', 'fonts')
}

// 添加其他资源
const handleAddOther = async () => {
  const paths = await window.electron.ipcRenderer.invoke('get-file', {
    title: '选择文件',
    buttonLabel: '添加',
    properties: ['openFile', 'multiSelections']
  })

  await addResourceFiles(paths, 'other', 'others')
}

// 删除资源
const deleteResource = async (resource: Resource, type: 'images' | 'fonts' | 'others') => {
  await window.electron.ipcRenderer.invoke('delete-file', projectStore.projectPath + resource.path)
  const index =
    projectStore.project?.resources[type].findIndex((item) => item.id === resource.id) ?? -1
  if (index > -1) {
    projectStore.project?.resources[type].splice(index, 1)
  }
}

// 清除未使用图片
const handleClearUnusedImage = () => {
  projectStore.project?.resources.images.forEach((item) => {
    const str = JSON.stringify(projectStore.project?.screens ?? [])
    const count = str.split(item.id).length - 1
    if (count === 0) {
      deleteResource(item, 'images')
    }
  })
}
</script>

<style scoped></style>
