<template>
  <div>
    <div
      class="px-2 pb-2 pt-1 grid grid-cols-[repeat(auto-fill,minmax(70px,1fr))] gap-row-2 gap-10px"
    >
      <CompLibaryItem
        v-for="item in components"
        :key="item.key"
        :comp="item.value"
        @click="handleAdd(item.value)"
      />
    </div>
    <el-empty
      v-if="!components.length"
      description="暂无数据，右键选择自定义组件创建"
      :image-size="80"
    ></el-empty>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { useEventBus } from '@vueuse/core'
import { getAllIDBData } from '@/utils/database'
import { useProjectStore } from '@/store/modules/project'
import { createWidget } from '@/model'

import CompLibaryItem from './CompLibaryItem.vue'

import type { ICustomWidget } from '@/types'

const components = ref<{ key: string; value: ICustomWidget }[]>([])
const addedCustomCompBus = useEventBus('created-custom-comp')
const projectStore = useProjectStore()

const getAllData = async () => {
  const data = await getAllIDBData()
  components.value = data || []
}

const handleAdd = (item: ICustomWidget) => {
  const newWidget = createWidget(item.widget, 1, true)
  const page = projectStore.activePage
  // 查找当前screen
  const screen = projectStore.project?.screens.find(
    (screen) => !!screen.pages.find((p) => page?.id === p.id)
  )
  // 随机位置
  const r = Math.floor(Math.random() * 100)
  const width = newWidget.props?.width || 0
  const height = newWidget.props?.height || 0
  if (screen) {
    newWidget.props.x = Math.round(screen.width / 2 - width / 2 + r)
    newWidget.props.y = Math.round(screen.height / 2 - height / 2 + r)
  }

  projectStore.activePage?.children?.push(newWidget)
  projectStore.setSelectWidgets([newWidget])
}

const unsubscribe = addedCustomCompBus.on(() => {})

onMounted(() => {
  getAllData()
})
onBeforeUnmount(() => {
  unsubscribe()
})
</script>

<style scoped></style>
