// src/pages/system/menu/index.tsx

import {
  ExclamationCircleOutlined,
  PlusOutlined,
  ReloadOutlined,
} from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { useModel } from '@umijs/max';
import { Modal, Popconfirm } from 'antd';
import React, { useCallback, useRef, useState } from 'react';
import ConfigurableDrawerForm, {
  type ConfigurableDrawerFormRef,
} from '@/components/DrawerForm';
import EnhancedProTable from '@/components/EnhancedProTable';
import type { ToolbarAction } from '@/components/EnhancedProTable/types';
import { formStatusType } from '@/constants';
import {
  createMenu,
  deleteMenu,
  getMenuList,
  type MenuReqVO,
  type MenuVO,
  updateMenu,
} from '@/services/system/menu';
import { handleTree } from '@/utils/tree';
import { baseMenuColumns, formColumns } from './config';

const SystemMenu = () => {
  const configurableDrawerRef = useRef<ConfigurableDrawerFormRef>(null);
  const tableRef = useRef<ActionType>(null);
  const [modal, contextHolder] = Modal.useModal();
  const [type, setType] = useState<'create' | 'update'>('create');
  const [id, setId] = useState<number>(0);
  const { initialState } = useModel('@@initialState');
  const handleEdit = (record: MenuVO) => {
    setType('update');
    setId(record.id);

    configurableDrawerRef.current?.open(record);
  };

  const onFetch = async (params: MenuReqVO) => {
    const data = await getMenuList({
      ...params,
    });
    return {
      data: handleTree(data),
      success: true,
      total: data.total,
    };
  };
  const handleAdd = () => {
    setType('create');
    configurableDrawerRef.current?.open({ type: 1 });
  };

  const handleReload = async () => {
    try {
      await modal.confirm({
        title: '刷新菜单缓存',
        icon: <ExclamationCircleOutlined />,
        content: '即将更新缓存刷新浏览器！',
        okText: '确认',
        cancelText: '取消',
        onOk: async () => {
          await initialState?.fetchUserInfo?.();
          // 刷新浏览器
          location.reload();
        },
      });
    } catch {}
  };

  const handleSubmit = useCallback(
    async (values: MenuVO) => {
      if (type === 'create') {
        await createMenu(values);
      } else {
        await updateMenu({
          ...values,
          id,
        });
      }
      tableRef.current?.reload();
      return true;
    },
    [type, id],
  );

  const toolbarActions: ToolbarAction[] = [
    {
      key: 'add',
      label: '新建',
      type: 'primary',
      icon: <PlusOutlined />,
      onClick: handleAdd,
    },
    {
      key: 'reload',
      label: '刷新菜单缓存',
      type: 'primary',
      icon: <ReloadOutlined />,
      onClick: handleReload,
    },
  ];

  const actionColumns: ProColumns<MenuVO> = {
    title: '操作',
    dataIndex: 'option',
    valueType: 'option',
    fixed: 'right',
    width: 120,
    render: (_text: React.ReactNode, record: MenuVO, _: any, action: any) => [
      <a key="editable" onClick={() => handleEdit(record)}>
        编辑
      </a>,
      <Popconfirm
        title="是否删除?"
        key="delete"
        onConfirm={async () => {
          await deleteMenu(record.id);
          action?.reload();
        }}
        okText="是"
        cancelText="否"
      >
        <a>删除</a>
      </Popconfirm>,
    ],
  };
  const columns = [...baseMenuColumns, actionColumns];
  return (
    <>
      {contextHolder}
      <EnhancedProTable<MenuVO>
        ref={tableRef}
        columns={columns}
        request={onFetch}
        toolbarActions={toolbarActions}
        headerTitle="菜单管理"
        showIndex={false}
        showSelection={false}
      />

      <ConfigurableDrawerForm
        ref={configurableDrawerRef}
        title={formStatusType[type]}
        columns={formColumns(type)}
        onSubmit={handleSubmit}
        width={900}
      />
    </>
  );
};

export default SystemMenu;
