import { DeleteButton } from '@/common';
import { Apis } from '@/gen/Apis';
import { GuardNameEnum } from '@/gen/Enums';
import { DataSourceType, useSysRolesDataSource } from '@/hooks/dataSources';
import { PageContainer, ProTable } from '@ant-design/pro-components';
import { clearCache, useMemoizedFn } from 'ahooks';
import { Space, Tag } from 'antd';
import Create from './modals/Create';
import Update from './modals/Update';

type TableType = ApiRespTypes.SysRoles.List;

export default function Index() {
  const title = '角色';

  const { data, run } = useSysRolesDataSource();

  const handleCreateFinish = useMemoizedFn(() => {
    clearCache(DataSourceType.SysRoles);
    run();
  });

  const handleUpdateFinish = useMemoizedFn(() => {
    clearCache(DataSourceType.SysRoles);
    run();
  });

  const handleDelete = useMemoizedFn((entity: TableType[0]) => {
    Apis.SysRoles.Delete({ id: entity.id }).then(() => {
      clearCache(DataSourceType.SysRoles);
      run();
    });
  });

  return !data ? (
    <></>
  ) : (
    <PageContainer>
      <ProTable<TableType[0]>
        scroll={{ x: 'max-content', scrollToFirstRowOnChange: true }}
        bordered
        size="small"
        rowKey="id"
        options={false}
        expandable={{
          defaultExpandAllRows: true,
        }}
        toolBarRender={() => [
          <Create key="Create" onFinish={handleCreateFinish} title={title} />,
        ]}
        dataSource={data}
        columns={[
          {
            title: 'ID',
            dataIndex: 'id',
          },
          {
            title: '权限组',
            dataIndex: 'guard_name',
            valueEnum: GuardNameEnum,
          },
          {
            title: '名称',
            dataIndex: 'name',
          },
          {
            title: '颜色',
            dataIndex: 'color',
            renderText: (color) => <Tag color={color as string}>{color}</Tag>,
          },
          {
            title: '创建时间',
            dataIndex: 'created_at',
            valueType: 'dateTime',
          },
          {
            title: '操作',
            render: (_, entity) => {
              return (
                <Space key={entity.id}>
                  <Update
                    item={entity}
                    title={title}
                    onFinish={handleUpdateFinish}
                  />
                  <DeleteButton onConfirm={() => handleDelete(entity)} />
                </Space>
              );
            },
          },
        ]}
      />
    </PageContainer>
  );
}
