<template>
  <div class="menu-index">
    <n-card :bordered="false" class="pt-3 mb-3 proCard">
      <n-spin :show="loading">
        <BasicTable
          ref="tableRef"
          :columns="columns"
          :paginate-single-page="false"
          :request="loadDataTable"
          :row-key="(row) => row.id"
          :autoScrollX="true"
          :actionColumn="actionColumn"
          v-model:expanded-row-keys="expandKeys"
        >
          <template #tableTitle>
            <n-space>
              <n-button type="primary" @click="handleAdd()" v-perm="['sys:menu:add']">
                <template #icon>
                  <n-icon>
                    <PlusOutlined />
                  </n-icon>
                </template>
                新增
              </n-button>
              <n-button @click="handleExpand"> 展开/折叠 </n-button>
            </n-space>
          </template>
        </BasicTable>
      </n-spin>
    </n-card>
    <editDialog
      ref="createModalRef"
      v-if="editVisible"
      :menuId="menuId"
      :pid="pid"
      v-model:visible="editVisible"
      @success="loadDataTable"
    />
  </div>
</template>

<script lang="ts" setup name="menus">
  import { defineAsyncComponent, nextTick, onMounted, ref, reactive, h } from 'vue';
  import { PlusOutlined, EditOutlined, DeleteOutlined, FormOutlined } from '@vicons/antd';
  import { TableAction } from '@/components/Table';
  import { renderIcon } from '@/utils';
  import editDialog from './edit.vue';
  import { getMenuList, menuDelete } from '@/api/system/menu';
  import { getTreeValues } from '@/utils/helper/treeHelper';
  import { useMessage, useDialog } from 'naive-ui';
  import { columns } from './columns';
  import { buildTree } from '@/utils/auth';

  /**
   * 定义参数变量
   */
  const message = useMessage();
  const dialog = useDialog();
  const tableRef = ref();
  const loading = ref(false);
  const editVisible = ref(false);
  const expandKeys = ref([]);
  const createModalRef = ref();
  const menuId = ref(0);
  const pid = ref(0);

  /**
   * 定义操作栏
   */
  const actionColumn = reactive({
    width: 250,
    title: '操作',
    align: 'left',
    key: 'action',
    fixed: 'right',
    render(record) {
      return h(TableAction as any, {
        style: 'button',
        actions: [
          {
            label: '编辑',
            type: 'warning',
            icon: renderIcon(FormOutlined),
            auth: ['sys:menu:update'],
            onclick: handleEdit.bind(null, record),
          },
          {
            label: '删除',
            type: 'error',
            icon: renderIcon(DeleteOutlined),
            auth: ['sys:menu:delete'],
            onclick: handleDelete.bind(null, record),
          },
          {
            label: '新增',
            type: 'info',
            icon: renderIcon(PlusOutlined),
            auth: ['sys:menu:add'],
            ifShow: () => {
              return record.type !== 1;
            },
            onclick: handleAdd.bind(null, record),
          },
        ],
      });
    },
  });

  /**
   * 获取菜单列表
   */
  const loadDataTable = async (res) => {
    const data = await getMenuList();
    data.map((item) => {
      item.key = item.id;
    });
    const result = {
      records: buildTree(data),
      total: 1,
    };
    return result;
  };

  /**
   * 执行添加
   */
  const handleAdd = async (record: any) => {
    menuId.value = 0;
    pid.value = record ? record.parentId : 0;
    editVisible.value = true;
    await nextTick();
    createModalRef.value.openModal();
  };

  /**
   * 执行编辑
   * @param data 参数
   */
  const handleEdit = async (data: any) => {
    menuId.value = data.id;
    editVisible.value = true;
    await nextTick();
    createModalRef.value.openModal();
  };

  /**
   * 执行删除
   * @param id 菜单ID
   */
  const handleDelete = (row: number) => {
    dialog.warning({
      title: '提示',
      content: '确定要删除？',
      positiveText: '确定',
      negativeText: '取消',
      onPositiveClick: async () => {
        loading.value = true;
        await menuDelete(row.id);
        message.success('删除成功');
        loadDataTable();
        loading.value = false;
      },
    });
  };

  /**
   * 执行扩展、收缩
   */
  const handleExpand = () => {
    loading.value = true;
    if (!expandKeys.value.length) {
      expandKeys.value = getTreeValues(tableRef.value.getDataSource(), 'id');
      loading.value = false;
    } else {
      expandKeys.value = [];
      loading.value = false;
    }
  };
</script>

<style scoped></style>
