import {
  MyButtons,
  MyColumns,
  MyProTableProps,
  MyResponseType,
  MyTableActions,
  MyToolBarActions,
} from '@/common';
import { ActionType, ProTable } from '@ant-design/pro-components';
import { message } from 'antd';
import { useRef, useState } from 'react';
import RoleFormModal from './RoleFormModal';

interface RoleApis {
  List: (data?: any) => Promise<MyResponseType>;
  Delete: (data: any) => Promise<MyResponseType>;
  Store: (data: any) => Promise<MyResponseType>;
  Update: (data: any) => Promise<MyResponseType>;
  SetPermissions: (data: any) => Promise<MyResponseType>;
  GetPermissions: (data: any) => Promise<MyResponseType>;
  PermissionTree: () => Promise<MyResponseType>;
}

interface RoleTableProps {
  title: string;
  apis: RoleApis;
  listApi?: (data?: any) => Promise<MyResponseType>;
}

export default function RoleTable({ title, apis, listApi }: RoleTableProps) {
  const actionRef = useRef<ActionType>();
  const [modalOpen, setModalOpen] = useState(false);
  const [editingItem, setEditingItem] = useState<
    Record<string, any> | undefined
  >();

  const handleEdit = (item: Record<string, any>) => {
    setEditingItem(item);
    setModalOpen(true);
  };

  const handleCreate = () => {
    setEditingItem(undefined);
    setModalOpen(true);
  };

  const handleSuccess = () => {
    setModalOpen(false);
    actionRef.current?.reload();
  };

  return (
    <>
      <ProTable
        {...MyProTableProps.props}
        actionRef={actionRef}
        search={false}
        request={async (params, sort) =>
          MyProTableProps.request(params, sort, listApi ?? apis.List)
        }
        toolBarRender={() => [
          <MyToolBarActions
            key="toolbar"
            actions={{
              add: (
                <MyButtons.Create
                  key="create"
                  title={`新增`}
                  onClick={handleCreate}
                />
              ),
            }}
          />,
        ]}
        options={false}
        columns={[
          MyColumns.ID({ search: false }),
          {
            title: '角色名称',
            dataIndex: 'name',
          },
          MyColumns.UpdatedAt(),
          MyColumns.CreatedAt(),
          MyColumns.Option({
            render: (_, item: any, __, action) => (
              <MyTableActions
                actions={{
                  update: (
                    <MyButtons.Edit
                      title="编辑"
                      onClick={() => handleEdit(item)}
                    />
                  ),
                  delete: (
                    <MyButtons.Delete
                      title="删除"
                      onConfirm={() =>
                        apis.Delete({ id: item.id }).then(() => {
                          message.success('删除成功');
                          action?.reload();
                        })
                      }
                    />
                  ),
                }}
              />
            ),
          }),
        ]}
      />
      <RoleFormModal
        open={modalOpen}
        onCancel={() => setModalOpen(false)}
        onSuccess={handleSuccess}
        item={editingItem}
        title={title}
        storeApi={apis.Store}
        updateApi={apis.Update}
        setPermissionsApi={apis.SetPermissions}
        getPermissionsApi={apis.GetPermissions}
        permissionTreeApi={apis.PermissionTree}
      />
    </>
  );
}
