<template>
  <div>{{ $t('recentProject') }}</div>
  <el-scrollbar>
    <ul class="p0">
      <li
        class="flex gap-12px items-center hover:bg-bg-secondary cursor-pointer px-4px py-6px"
        v-for="item in recentStore.recentProjects || []"
        :key="item.id"
        @dblclick="openProject(item)"
      >
        <div>
          <FcOpenedFolder size="32px" />
        </div>
        <div :title="item.projectPath">
          <div class="text-12px text-text-primary mb-4px">{{ item.projectName }}</div>
          <div class="text-10px">
            <p class="m0 p0 flex gap-8px">
              <span class="shrkin-0">{{ $t('createTime') }}</span>
              <span class="truncate">{{ item.createTime }}</span>
            </p>
            <p class="m0 p0 flex gap-8px">
              <span>{{ $t('modifyTime') }}</span>
              <span>{{ item.modifyTime }}</span>
            </p>
          </div>
        </div>
      </li>
    </ul>
    <el-empty v-if="!recentStore.recentProjects?.length" :image-size="120"> </el-empty>
  </el-scrollbar>
</template>

<script setup lang="ts">
import { FcOpenedFolder } from 'vue-icons-plus/fc'
import { useRecentProject } from '@/store/modules/recentProject'
import { ElMessage } from 'element-plus'
import { useI18n } from 'vue-i18n'
import { useProjectStore } from '@/store/modules/project'

const recentStore = useRecentProject()
const projectStore = useProjectStore()
const { t } = useI18n()

const emit = defineEmits(['opened'])

const openProject = async (project) => {
  const projectPath = project.projectPath + '//project.ui'
  const globalStylePath = project.projectPath + '//style.ui'
  // 检查项目是否存在
  const res = await window.electron.ipcRenderer.invoke('check-file-path', projectPath)
  if (res) {
    // 存在 打开项目
    const result = await window.electron.ipcRenderer.invoke('read-file', projectPath, 'utf-8')
    const style = await window.electron.ipcRenderer.invoke('read-file', globalStylePath, 'utf-8')
    if (result) {
      projectStore.loadProject(JSON.parse(result), project.projectPath, JSON.parse(style))
      emit('opened')
    } else {
      // 读取失败 删除项目
      ElMessage.error(t('readProjectError'))
    }
  } else {
    // 不存在 删除项目
    ElMessage.error(t('noFoundProject'))
    recentStore.deleteProject(project.id)
  }
}
</script>

<style scoped></style>
