<!-- eslint-disable @typescript-eslint/no-explicit-any -->
<!-- eslint-disable @typescript-eslint/ban-ts-comment -->
<script setup lang="ts">
import { ref, onMounted, nextTick } from 'vue'
import { qiankunWindow } from 'vite-plugin-qiankun/dist/helper'
import type { Config, Handle } from '@form-create/designer'
// import { formCreate } from '@form-create/designer'
import { formConfig } from './form.config.ts'
import FcDesigner from '@form-create/designer'
import { RcSelect } from './plugins/components/rc-select.config.ts'
import { RcRadio } from './plugins/components/rc-radio.config.ts'
import { MenuOptions } from './plugins/menu/options.ts'
import type { FcDesignerInstance } from '@form-create/designer' // 注册组件
import { RcCheckbox } from './plugins/components/rc-checkbox.ts'

/**
 * @see https://view.form-create.com/methods
 */
declare global {
  interface Window {
    __QIANKUN__EVENT__: {
      on: (name: string, fn: (...arg: any[]) => void) => void
      emit: (name: string, ...arg: any[]) => void
    } // 事件中心
    __QIANKUN__REQUSET__: () => void // 请求API接口
    __QIANKUN__GUID__: () => string // 获取唯一标识
    __QIANKUN__OPEN__TAG__: () => void // 打开标签页
  }
}
// 表单实例
const designer = ref<FcDesignerInstance | null>(null)
const api = ref(null)
// 表单模板元素
// 判断是独立运行的还是qiankun子应用
const height = ref(qiankunWindow.__POWERED_BY_QIANKUN__ ? '90vh' : '100vh')
const config = ref<Config>(formConfig)
// 顶部更多操作按钮
const handle = ref<Handle>([])
// console.log('子应用', window.__QIANKUN__EVENT__)

const onSave = (config: { options: string; rule: string }) => {
  const rule = config.rule
  console.log(rule)
}

onMounted(() => {
  designer.value?.openPreview()
  nextTick(() => {
    // @ts-ignore
    designer.value!.preview.state = false
  })
})

onMounted(() => {
  // 注册拖拽规则
  designer.value?.addComponent(RcSelect)
  designer.value?.addComponent(RcRadio)
  designer.value?.addComponent(RcCheckbox)

  // 注册菜单
  designer.value?.addMenu(MenuOptions)
})
</script>

<template>
  <fc-designer
    ref="designer"
    :height="height"
    :handle="handle"
    :config="config"
    @save="onSave"
    v-model:api="api"
  />
</template>
