<script setup lang="tsx">
import { type Ref, computed, ref, withDirectives } from 'vue';
import { NButton, NPopconfirm, NTag } from 'naive-ui';
import dayjs from 'dayjs';
import { type MenuObj, fetchDeleteMenu, fetchGetMenuList } from '@/service/api/system/menu';
import { useAppStore } from '@/store/modules/app';
import { useTable, useTableOperate } from '@/hooks/common/table';
import { $t } from '@/locales';
import SvgIcon from '@/components/custom/svg-icon.vue';
import { handleTree } from '@/utils/ruoyi';
import MenuOperateModal from '@/views/system/menu/modules/menu-operate-modal.vue';
import hasPermission from '@/directive/permission/hasPermission';

const appStore = useAppStore();
export type OperateType = NaiveUI.TableOperateType | 'addChild';

const wrapperRef = ref<HTMLElement | null>(null);
const { columns, columnChecks, data, loading, getData } = useTable({
  apiFn: fetchGetMenuList<Api.SystemManage.MenuList>,
  columns: () => [
    {
      key: 'menuName',
      title: '菜单名称',
      align: 'left',
      width: 160,
      render: row => {
        return <span>{row.menuName}</span>;
      }
    },
    {
      key: 'icon',
      title: $t('page.manage.menu.icon'),
      align: 'center',
      width: 60,
      render: row => {
        const icon = row.iconType === '1' ? row.icon : undefined;
        const localIcon = row.iconType === '2' ? row.icon : undefined;
        return (
          <div class="flex-center">
            <SvgIcon icon={icon} localIcon={localIcon} class="text-icon" />
          </div>
        );
      }
    },
    {
      key: 'orderNum',
      title: '排序',
      align: 'center',
      width: 60,
      render: row => <span>{row.orderNum}</span>
    },
    {
      key: 'perms',
      title: '权限标识',
      align: 'center',
      render: row => <span>{row.perms}</span>
    },
    {
      key: 'component',
      title: '组件路径',
      align: 'center',
      render: row => <span title={row.component}>{row.component}</span>
    },
    {
      key: 'path',
      title: '路由路径',
      align: 'center',
      render: row => <span title={row.path}>{row.path}</span>
    },
    {
      key: 'status',
      title: '状态',
      align: 'center',
      width: 80,
      render: row => {
        if (row.status === undefined || row.status === null) {
          return null;
        }
        const tagMap: Record<Api.Common.SpecialEnableStatus, NaiveUI.ThemeColor> = {
          '0': 'success',
          '1': 'warning'
        };
        return <NTag type={tagMap[row.status]}>{row.status === '0' ? '启用' : '禁用'}</NTag>;
      }
    },
    {
      key: 'createTime',
      title: '创建时间',
      align: 'center',
      width: 160,
      render: row => <span>{dayjs(row.createTime).format('YYYY-MM-DD HH:mm:ss')}</span>
    },
    {
      key: 'operate',
      title: '操作',
      align: 'center',
      width: 210,
      render: row => (
        <div class="flex-center justify-end gap-8px">
          {withDirectives(
            <NButton type="primary" ghost size="small" onClick={() => edit(row)}>
              {$t('common.edit')}
            </NButton>,
            [[hasPermission, ['system:menu:edit']]]
          )}
          {withDirectives(
            <NButton type="primary" ghost size="small" onClick={() => handleAddChild(row)}>
              新增子菜单
            </NButton>,
            [[hasPermission, ['system:menu:add']]]
          )}
          {withDirectives(
            <div>
              <NPopconfirm onPositiveClick={() => handleDelete(row.menuId as number)}>
                {{
                  default: () => $t('common.confirmDelete'),
                  trigger: () => (
                    <NButton type="error" ghost size="small">
                      {$t('common.delete')}
                    </NButton>
                  )
                }}
              </NPopconfirm>
            </div>,
            [[hasPermission, ['system:menu:remove']]]
          )}
        </div>
      )
    }
  ]
});

const { drawerVisible, checkedRowKeys, onDeleted } = useTableOperate(data, getData);

// 计算树形
const treeData = computed(() => {
  return handleTree(data.value, 'menuId');
});

const allPages = computed(() => {
  return data.value
    .filter(item => (item.menuType === 'M' || item.menuType === 'C') && item.routeName)
    .map(item => item.routeName as string);
});

const operateType = ref<OperateType>('add');
const editingData: Ref<Api.SystemManage.Menu | null> = ref(null);

function handleAdd() {
  operateType.value = 'add';
  drawerVisible.value = true;
}

function handleAddChild(item: Api.SystemManage.Menu) {
  operateType.value = 'addChild';
  editingData.value = { ...item };
  drawerVisible.value = true;
}

// 删除菜单
async function handleDelete(menuId: number) {
  const { error } = await fetchDeleteMenu(menuId);
  if (!error) {
    await onDeleted();
  }
}

async function edit(item: Api.SystemManage.Menu) {
  operateType.value = 'edit';
  editingData.value = item;
  drawerVisible.value = true;
}
</script>

<template>
  <div ref="wrapperRef" class="flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <NCard :title="$t('page.manage.menu.title')" :bordered="false" size="small" class="sm:flex-1-hidden card-wrapper">
      <template #header-extra>
        <TableHeaderOperation
          v-model:columns="columnChecks"
          :disabled-delete="checkedRowKeys.length === 0"
          :loading="loading"
          :show-delete-btn="false"
          :has-perm="['system:menu:add', null]"
          @add="handleAdd"
          @refresh="getData"
        />
      </template>
      <NDataTable
        v-model:checked-row-keys="checkedRowKeys"
        :columns="columns"
        :data="treeData"
        size="small"
        :flex-height="!appStore.isMobile"
        :scroll-x="1088"
        :loading="loading"
        :row-key="(row: MenuObj) => row.menuId"
        remote
        class="sm:h-full"
      />
      <MenuOperateModal
        v-model:visible="drawerVisible"
        :operate-type="operateType"
        :row-data="editingData"
        :all-pages="allPages"
        @submitted="getData"
      />
    </NCard>
  </div>
</template>

<style scoped></style>
