import {
  MyButtons,
  MyColumns,
  MyProTableProps,
  useCurrentPermissions,
} from '@/common';
import { Apis } from '@/gen/Apis';
import { PlusOutlined } from '@ant-design/icons';
import { ProTable } from '@ant-design/pro-components';
import { useNavigate } from '@umijs/max';
import { Space } from 'antd';

export default function SurveysList({ title = '问卷设置' }) {
  const navigate = useNavigate();
  const getCurrentPermissions = useCurrentPermissions();
  let toolBarRender = () => {
    return getCurrentPermissions(
      {
        add: (
          <MyButtons.Default
            key="Create"
            size="middle"
            type="primary"
            icon={<PlusOutlined />}
            onClick={() => {
              navigate('/marketing/survey/pages/create_surveys');
            }}
            title="新增问卷"
          />
        ),
      },
      'MySurveysList',
    );
  };

  let tableRender = (item: any, action: any) => {
    return (
      getCurrentPermissions({
        update: (
          <MyButtons.Default
            key="update"
            type="primary"
            onClick={() => {
              navigate(`/marketing/survey/pages/update_surveys?id=${item.id}`);
            }}
            title="编辑"
          />
        ),
        delete: (
          <MyButtons.Delete
            onConfirm={() =>
              Apis.Survey.Surveys.Delete({ id: item.id }).then(() =>
                action?.reload(),
              )
            }
          />
        ),
      }),
      'MySurveysList'
    );
  };

  return (
    <ProTable
      {...MyProTableProps.props}
      headerTitle={`${title}`}
      request={async (params, sort) =>
        MyProTableProps.request(params, sort, Apis.Survey.Surveys.List)
      }
      toolBarRender={() => [toolBarRender()]}
      columns={[
        MyColumns.ID({
          search: false,
        }),
        { dataIndex: 'name', title: '问卷' },
        MyColumns.Boolean({
          dataIndex: 'is_enabled',
          title: '是否启用',
          search: false,
        }),
        MyColumns.CreatedAt(),
        MyColumns.Option({
          width: 120,
          render: (_, item: any, index, action) => (
            <Space key={`item_${index}`}>{tableRender(item, action)}</Space>
          ),
        }),
      ]}
    />
  );
}
