import { ref, computed } from 'vue'
import list from '@/utils/component-list'
import useConfig from './useConfig'

export default function useComponent() {
  const showComponentModal = ref(false) // 展示组件选择框
  const curBox = ref<number | null>(null) // 当前容器下标
  const components = ref<{ [key: number]: string }>({}) // {容器下标: 组件key}

  const config = useConfig() // 获取组件选择配置
  if (config?.components) {
    components.value = config.components
  }

  const openComponentModal = (i: number) => {
    // 点击容器中的新增按钮
    curBox.value = i
    showComponentModal.value = true
  }
  const onSelectComponent = (key: string) => {
    // 选择组件后将key存入
    if (curBox.value === null) return
    components.value[curBox.value] = key
  }
  const onCancelComponent = (i: number) => {
    // 取消组件
    delete components.value[i]
  }
  const componentList = computed(() => list) // key值-组件 对照表

  return {
    components,
    componentList,
    showComponentModal,
    openComponentModal,
    onSelectComponent,
    onCancelComponent,
  }
}
