import { defineStore } from 'pinia'
import { ref } from 'vue'
import { openDB } from 'idb'
import dayjs from 'dayjs'

type ProjectRecord = {
  id: string
  projectName: string
  projectPath: string
  createTime: string
  modifyTime: string
}

export const useRecentProject = defineStore('recentProject', () => {
  const recentProjects = ref<ProjectRecord[]>()
  const currentRecord = ref<ProjectRecord>()

  // 获取数据库
  const getDB = async () => {
    const db = await openDB('projects', 1, {
      upgrade(db) {
        db.createObjectStore('projects', { keyPath: 'id' })
      }
    })
    return db
  }

  // 获取所有项目
  const getAllProjects = async () => {
    const db = await getDB()
    const projects = await db.getAll('projects')
    recentProjects.value = projects.sort((a, b) =>
      dayjs(a.modifyTime).isAfter(dayjs(b.modifyTime)) ? -1 : 1
    )
  }

  // 添加项目
  const addProject = async (project: ProjectRecord) => {
    currentRecord.value = project
    const db = await getDB()
    // 1、查找是否是存在的项目
    const existProject = recentProjects.value?.find(
      (item) => item.projectName === project.projectName && item.projectPath === project.projectPath
    )
    if (existProject) {
      currentRecord.value.id = existProject.id
      return
    } else {
      const result = await db.add('projects', project)
      getAllProjects()
      return result
    }
  }

  // 删除项目
  const deleteProject = async (id: string) => {
    const db = await getDB()
    const result = await db.delete('projects', id)
    getAllProjects()
    return result
  }

  // 修改项目
  const updateProject = async (project: ProjectRecord) => {
    const db = await getDB()
    const result = await db.put('projects', project)
    return result
  }

  getAllProjects()

  return {
    recentProjects,
    currentRecord,
    addProject,
    deleteProject,
    updateProject
  }
})
