<script setup lang="ts">
import apiSysMenu from '@/api/modules/sysMenu'
import DetailForm from './components/DetailForm/index.vue'

defineOptions({ name: 'SysMenuList' })

const formModeProps = ref({ id: '' as number | string, parent_id: undefined as number | undefined })

const searchDefault = { keyword: '' }
const search = ref({ ...searchDefault })
function searchReset() { Object.assign(search.value, searchDefault); getDataList() }

const loading = ref(false)
const treeData = ref<any[]>([])

const columns = [
  { title: '菜单名称', dataIndex: 'menu_name', key: 'menu_name', ellipsis: true },
  { title: '图标', dataIndex: 'icon', key: 'icon', width: 80 },
  { title: '路由地址', dataIndex: 'path', key: 'path', width: 160, ellipsis: true },
  { title: '组件路径', dataIndex: 'component', key: 'component', width: 200, ellipsis: true },
  { title: '权限标识', dataIndex: 'perms', key: 'perms', width: 160, ellipsis: true },
  { title: '类型', dataIndex: 'menu_type', key: 'menu_type', width: 80, align: 'center' as const },
  { title: '排序', dataIndex: 'order_num', key: 'order_num', width: 60 },
  { title: '操作', key: 'action', width: 100, align: 'center' as const },
]

const typeMap: Record<string, string> = { M: '目录', C: '菜单', F: '按钮' }

onMounted(() => getDataList())

function getDataList() {
  loading.value = true
  apiSysMenu.tree({ ...search.value }).then((res: any) => {
    loading.value = false
    treeData.value = res.data || []
  }).catch(() => { loading.value = false })
}

const formRef = ref<InstanceType<typeof DetailForm>>()
const { open: openDrawer, update: updateDrawer } = useFaDrawer().create({
  destroyOnClose: true, closeOnClickOverlay: false, closeOnPressEscape: false,
  beforeClose(action, done) {
    if (action === 'confirm') { formRef.value?.submit().then(() => { getDataList(); done() }) } else { done() }
  },
  content: () => h(DetailForm, { ref: formRef, id: formModeProps.value.id, parent_id: formModeProps.value.parent_id }),
})

const currentAddParentId = ref<number | undefined>()

function onCreate(parentId?: number) {
  formModeProps.value = { id: '', parent_id: parentId }
  updateDrawer({ title: '新增菜单' })
  openDrawer()
}

function onEdit(row: any) {
  formModeProps.value = { id: row.id, parent_id: undefined }
  updateDrawer({ title: '编辑菜单' })
  openDrawer()
}

function onDel(row: any) {
  useFaModal().confirm({ title: '确认删除', content: `确认删除「${row.menu_name}」吗？`, onConfirm: () => apiSysMenu.delete(row.id).then(() => { getDataList(); faToast.success('删除成功') }) })
}
</script>

<template>
  <div class="flex flex-col size-full">
    <FaPageHeader title="菜单管理" class="mb-0" />
    <FaPageMain class="flex-1 flex flex-col overflow-auto">
      <FaSearchBar :show-toggle="false">
        <template #default="{ fold, toggle }">
          <div class="gap-x-8 gap-y-2 grid grid-cols-[repeat(auto-fit,minmax(300px,1fr))]">
            <FaLabel label="关键词"><AInput v-model:value="search.keyword" placeholder="名称/权限标识" allow-clear /></FaLabel>
            <div class="flex gap-2 col-end--1 justify-end">
              <FaButton variant="outline" @click="searchReset()">重置</FaButton>
              <FaButton type="primary" @click="currentChange()"><FaIcon name="i-ri:search-line" />筛选</FaButton>
              <FaButton variant="ghost" @click="toggle">{{ fold ? '展开' : '收起' }}<FaIcon :name="fold ? 'i-ep:caret-bottom' : 'i-ep:caret-top'" /></FaButton>
              <FaButton @click="onCreate()"><FaIcon name="i-ri:add-line" />新增根菜单</FaButton>
            </div>
          </div>
        </template>
      </FaSearchBar>
      <ATable :loading="loading" :columns="columns" :data-source="treeData" :pagination="false" size="middle" row-key="id" :scroll="{ x: 1000 }" default-expand-all-rows>
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'menu_type'">
            <ATag :color="record.menu_type === 'M' ? 'blue' : record.menu_type === 'C' ? 'green' : 'default'">{{ typeMap[record.menu_type] || record.menu_type }}</ATag>
          </template>
          <template v-else-if="column.key === 'action'">
            <ASpace :size="4">
              <FaTooltip text="编辑">
                <FaButton variant="outline" size="icon-sm" @click="onEdit(record)"><FaIcon name="i-ri:edit-line" /></FaButton>
              </FaTooltip>
              <FaDropdown :items="[[
                { label: '新增子菜单', handle: () => onCreate(record.id) },
                { label: '删除', variant: 'destructive', handle: () => onDel(record) },
              ]]">
                <FaTooltip text="更多">
                  <FaButton variant="outline" size="icon-sm"><FaIcon name="i-ri:more-line" /></FaButton>
                </FaTooltip>
              </FaDropdown>
            </ASpace>
          </template>
        </template>
      </ATable>
    </FaPageMain>
  </div>
</template>
