<template>
  <el-input
    v-model="search"
    placeholder="请输入组件名称"
    class="m-8px"
    style="width: calc(100% - 16px)"
  />
  <el-collapse v-model="activeCollapse">
    <el-collapse-item
      v-for="group in getGroups"
      :key="group.label"
      :title="group.label"
      :name="group.label"
    >
      <div class="px-2 pb-2 pt-1 grid grid-cols-[repeat(auto-fill,minmax(70px,1fr))] gap-row-2">
        <LibaryItem
          v-for="item in group.items"
          :key="item.key"
          :comp="item"
          @click="handleAdd(item)"
        />
      </div>
    </el-collapse-item>
  </el-collapse>
  <el-empty v-if="!getGroups.length" :image-size="80">
    <template #description>
      <div>没有找到组件</div>
    </template>
  </el-empty>
</template>

<script setup lang="ts">
import { computed, ref } from 'vue'
import { ComponentArray } from '@/lvgl-widgets'
import LibaryItem from './LibaryItem.vue'
import { createWidget } from '@/model'
import { getAddWidgetIndex } from '@/utils'
import { useProjectStore } from '@/store/modules/project'

import type { IComponentModelConfig } from '@/lvgl-widgets/type'
import { klona } from 'klona'

const search = ref('')
const activeCollapse = ref<string[]>([])
const projectStore = useProjectStore()

const groupMap = ref<{
  [key: string]: {
    label: string
    items: IComponentModelConfig[]
  }
}>({})

// 变量全部控件
ComponentArray.filter((item) => !item.hideLibary).forEach((item) => {
  if (!groupMap.value[item.group]) {
    groupMap.value[item.group] = {
      label: item.group,
      items: []
    }
  }
  if (!item?.hideLibary) {
    groupMap.value[item.group].items.push(item)
  }

  return item.group
})

// 根据搜索条件获取分组信息
const getGroups = computed(() => {
  const list = klona(
    Object.values(groupMap.value).filter((item) =>
      item.items.some((item) => item.label.includes(search.value))
    )
  )

  list.forEach((item) => {
    item.items = item.items.filter((item) => item.label.includes(search.value))
  })

  activeCollapse.value = list.map((item) => item.label)

  return list
})

// 处理点击添加控件
function handleAdd(item: IComponentModelConfig) {
  const page = projectStore.activePage
  const index = getAddWidgetIndex(page!, item.key)
  const newWidget = createWidget(item, index)
  // 查找当前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])
}
</script>

<style scoped lang="less">
::v-deep(.el-collapse-item__content) {
  padding: 0;
}
</style>
