<template>
  <AFormPanel
    ref="formPanel"
    v-bind="formPanelProps">
    <template #default="formData">
      <div class="form-items">
        <ElFormItem label="上级">
          <ElTreeSelect v-model="formData.pid" v-loading="loadingMenus" :data="menuTreeDataSource" :default-expanded-keys="['0']" :render-after-expand="false" check-strictly placeholder="选择上级菜单"/>
        </ElFormItem>
        <ElFormItem label="客户端" prop="clients">
          <ElCheckboxGroup v-model="formData.clients">
            <ElCheckbox v-for="client in  ClientUtil.clients" :key="client.val" :label="client.txt" :value="client.val"/>
          </ElCheckboxGroup>
        </ElFormItem>
        <ElFormItem label="类型">
          <ElSelect v-model="formData.menuCategory" :data="menuCategoryData" placeholder="选择类型">
            <ElOption v-for="menuCategory in menuCategoryData" :key="menuCategory.key" :label="menuCategory.label" :value="menuCategory.key"/>
          </ElSelect>
        </ElFormItem>

        <ElFormItem label="名称">
          <ElInput v-model="formData.title" placeholder="名称"/>
        </ElFormItem>

        <ElFormItem v-if="formData.menuCategory === MenuCategory.Page || formData.menuCategory === MenuCategory.SubPage" label="路由名称">
          <ElInput v-model="formData.routeName" :min="0" placeholder="路由名称"/>
        </ElFormItem>
        <ElFormItem v-if="formData.menuCategory === MenuCategory.Page || formData.menuCategory === MenuCategory.SubPage" label="路由地址">
          <ElInput v-model="formData.routePath" :min="0" placeholder="路由地址"/>
        </ElFormItem>
        <ElFormItem label="编码">
          <ElInput v-model="formData.sn" :min="0" placeholder="编码"/>
        </ElFormItem>
        <ElFormItem label="图标">
          <AIconDropTable v-model="formData.icon"/>
        </ElFormItem>
        <ElFormItem label="排序">
          <ElInputNumber v-model="formData.sort" :min="0" controls-position="right" placeholder="排序"/>
        </ElFormItem>
      </div>
    </template>
  </AFormPanel>
</template>

<script lang="ts" setup>
import {
  MenuCategory,
  MenuCategoryDict,
} from '@/common/app/constants.ts'
import MenuApi from '@/pages/sys/menus/menu-api.ts'
import Colls from '@/common/utils/colls.ts'
import Strings from '@/common/utils/strings.ts'
import ClientUtil from '@/common/utils/client-util.ts'
import AFormPanel, {
  type AFormPanelInstance,
  buildFormPanelProps,
} from '@/components/a-form-panel/AFormPanel.tsx'
import AIconDropTable from '@/components/a-icon/AIconDropTable.vue'
import { nanoid } from 'nanoid'

const props = withDefaults(defineProps<{
  research?: () => void
}>(), {
  research: () => {
  },
})
const status = ref<'add' | 'modify'>('add')
const loadingMenus = ref<boolean>(false)
const formPanelIns = useTemplateRef<AFormPanelInstance>('formPanel')

const menuCategoryData = computed(() => {
  const data: { key: string; label: string }[] = []
  for (const key in MenuCategoryDict) {
    data.push({
      key,
      label: MenuCategoryDict[key as keyof typeof MenuCategoryDict],
    })
  }
  return data
})

const menuTreeDataSource = ref<MenuTypes.SysMenu[]>()
const formPanelProps = buildFormPanelProps<MenuTypes.MenuForm>({
  detailsLoader(id?: string) {
    if (Strings.isBlank(id)) {
      status.value = 'add'
      return Promise.resolve({
        icon: 'dianzixiaopiao',
        pid: '0',
        clients: [ 1 ],
        menuCategory: MenuCategory.Catalog,
        sn: nanoid(10),
      } as MenuTypes.MenuForm)
    } else {
      status.value = 'modify'
      return MenuApi
        .detail(id!)
        .then((res) => {
          return {
            ...res.data,
            clients: ClientUtil.getClients(res.data.clientCode!).map(it => it.val),
          } as MenuTypes.MenuForm
        })
    }
  },
  doSubmit(data) {
    if (status.value === 'add') {
      return MenuApi.add(data)
        .then(props.research)
    } else {
      return MenuApi.modify(data)
        .then(props.research)
    }
  },
})
watchEffect(() => {
  formPanelProps.title = status.value === 'add' ? '新建菜单' : '修改菜单'
})
defineExpose({
  open(data?: MenuTypes.MenuForm) {
    loadingMenus.value = true
    MenuApi.list()
      .then(({data}) => {
        const nodes = Colls.toTree(data.map((it) => ({value: it.id, label: it.title, ...it})))
        menuTreeDataSource.value = [ {value: '0', label: '顶级菜单', id: '0', pid: '0', children: nodes} ]
      })
      .finally(() => {
        loadingMenus.value = false
      })
    formPanelIns.value?.open(data?.id)
  },
})
</script>

<style lang="stylus" scoped>
.form-items {
  grid-template-columns: 1fr 1fr;
}

.dropdown-table-wrapper {
  padding 10px
  display flex
  flex-direction column
  align-items end
  justify-content space-between
  gap 10px
}
</style>
