<template>
  <PageWrapper dense contentFullHeight fixedHeight>
    <BasicTable @register="registerTable">
      <template #toolbar>
        <a-button type="primary" v-auth="'menu:add'" @click="handleCreate">
          {{ t('新增菜单') }}
        </a-button>
      </template>
      <template #action="{ record, index }">
        <TableAction
          :actions="[
            {
              label: '编辑',
              auth: 'menu:edit',
              onClick: handleEdit.bind(null, record),
            },
            {
              label: '删除',
              auth: 'menu:delete',
              color: 'error',
              popConfirm: {
                title: t('是否确认删除'),
                visible: popVisible(index),
                onVisibleChange: handleVisibleChange.bind(null, index),
                confirm: handleDelete.bind(null, record),
                cancel: handleCancel,
              },
            },
          ]"
        />
      </template>
    </BasicTable>
    <MenuModal @register="registerModal" @success="handleSuccess" />
  </PageWrapper>
</template>
<script lang="ts">
  import { defineComponent, h, ref } from 'vue';

  import { BasicTable, useTable, TableAction, BasicColumn, FormSchema } from '/@/components/Table';
  import { getMenuTree, deleteMenu } from '/@/api/system/menu';
  import { PageWrapper } from '/@/components/Page';
  import MenuModal from './components/MenuModal.vue';
  import Icon from '/@/components/Icon';
  import { Tag } from 'ant-design-vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { usePermissionStore } from '/@/store/modules/permission';
  import { usePermission } from '/@/hooks/web/usePermission';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useModal } from '/@/components/Modal';
  const { t } = useI18n();

  export const columns: BasicColumn[] = [
    {
      title: t('菜单名称'),
      dataIndex: 'title',
      width: 200,
      align: 'left',
      resizable: true,
    },
    {
      title: t('组件名称'),
      dataIndex: 'name',
      align: 'center',
      resizable: true,
    },
    {
      title: t('编码'),
      dataIndex: 'code',
      align: 'center',
      resizable: true,
    },
    {
      title: t('图标'),
      dataIndex: 'icon',
      align: 'center',
      width: 70,
      resizable: true,
      customRender: ({ record }) => {
        return h(Icon, { icon: record.icon });
      },
    },
    {
      title: t('组件'),
      dataIndex: 'component',
      align: 'center',
      resizable: true,
    },

    {
      title: t('状态'),
      dataIndex: 'enabledMark',
      width: 80,
      align: 'center',
      resizable: true,
      customRender: ({ record }) => {
        const enabledMark = record.enabledMark;
        const enable = ~~enabledMark === 1;
        const color = enable ? 'blue' : 'red';
        const text = enable ? t('启用') : t('停用');
        return h(Tag, { color: color }, () => text);
      },
    },
    {
      title: t('备注'),
      dataIndex: 'remark',
      align: 'center',
      width: 180,
      resizable: true,
    },
  ];

  export const searchFormSchema: FormSchema[] = [
    {
      field: 'title',
      label: t('菜单名称'),
      component: 'Input',
      colProps: { lg: 8, md: 12, sm: 12 },
    },
    {
      field: 'name',
      label: t('组件名称'),
      component: 'Input',
      colProps: { lg: 8, md: 12, sm: 12 },
    },
    {
      field: 'enabledMark',
      label: t('状态'),
      component: 'Select',
      componentProps: {
        options: [
          { label: t('启用'), value: 1 },
          { label: t('停用'), value: 0 },
        ],
      },
      colProps: { lg: 8, md: 12, sm: 12 },
    },
  ];

  export default defineComponent({
    name: 'MenuManagement',
    components: { BasicTable, MenuModal, TableAction, PageWrapper },
    setup() {
      const { notification } = useMessage();
      const { hasPermission } = usePermission();

      const [registerModal, { openModal }] = useModal();
      const [registerTable, { reload }] = useTable({
        title: t('菜单列表'),
        api: getMenuTree,
        columns,
        rowKey: 'id',
        formConfig: {
          rowProps: {
            gutter: 16,
          },
          schemas: searchFormSchema,
          showResetButton: false,
        },
        pagination: {
          pageSize: 20,
        },
        striped: false,
        useSearchForm: true,
        showTableSetting: true,
        showIndexColumn: false,
        actionColumn: {
          width: 88,
          title: t('操作'),
          dataIndex: 'action',
          slots: { customRender: 'action' },
          fixed: undefined,
        },
        tableSetting: {
          size: false,
        },
        customRow: (record) => {
          return {
            ondblclick: () => {
              if (hasPermission('menu:edit')) {
                handleEdit(record);
              }
            },
          };
        },
      });
      const isVisible = ref<boolean>(false);
      const deleteIndex = ref();
      function handleCreate() {
        openModal(true, {
          isUpdate: false,
        });
      }
      function handleEdit(record: Recordable) {
        const childIds = [];
        getChildrenIds(record.children, childIds);
        openModal(true, {
          record,
          isUpdate: true,
          childIds,
        });
      }

      function getChildrenIds(data, childIds) {
        data.forEach((item) => {
          childIds.push(item.id);
          if (item.children && item.children.length) {
            getChildrenIds(item.children, childIds);
          }
        });
      }

      function handleDelete(record: Recordable) {
        isVisible.value = false;
        const permissionStore = usePermissionStore();
        deleteMenu([record.id]).then(async (_) => {
          await permissionStore.buildRoutesAction(false);
          reload();
          notification.success({
            message: t('提示'),
            description: t('删除成功'),
          }); //提示消息
        });
      }

      function handleSuccess() {
        reload();
      }

      function handleCancel() {
        isVisible.value = false;
      }

      function popVisible(index) {
        return isVisible.value && index === deleteIndex.value;
      }

      function handleVisibleChange(index, bool) {
        if (!bool) {
          isVisible.value = false;
          return;
        }
        if (import.meta.env.VITE_GLOB_PRODUCTION === 'true') {
          notification.warning({
            message: '在线环境暂不允许该操作，请联系管理员。',
          });
          return;
        }
        isVisible.value = true;
        deleteIndex.value = index;
      }

      return {
        registerTable,
        registerModal,
        handleCreate,
        handleEdit,
        handleDelete,
        handleSuccess,
        handleCancel,
        handleVisibleChange,
        popVisible,
        t,
      };
    },
  });
</script>
