import AuthorSelect from '@/components/AuthorSelect';
import { poemListUsingPOST } from '@/services/luigi/poem';
import ProTable from '@ant-design/pro-table';
import React, { useRef } from 'react';

import PoemForm from './components/PoemForm';

import type { ProColumns, ActionType } from '@ant-design/pro-table';
import { Popconfirm } from 'antd';
import { savePoemUsingPOST } from '../../services/luigi/poem';
const columns: ProColumns<API.PoemBo>[] = [
  {
    dataIndex: 'id',
    title: 'id',
  },
  {
    title: '标题',
    dataIndex: 'title',
    ellipsis: true,
    tip: '标题过长会自动收缩',
    formItemProps: {
      rules: [
        {
          required: true,
          message: '此项为必填项',
        },
      ],
    },
  },
  {
    title: '状态',
    dataIndex: 'status',
    valueType: 'select',
    valueEnum: {
      0: {
        text: '未校准',
        status: 'Error',
      },
      1: {
        text: '已校准',
        status: 'Success',
      },
    },
  },
  {
    title: '作者',
    dataIndex: 'authorName',
    hideInSearch: true,
  },
  {
    title: '作者',
    dataIndex: 'authorId',
    hideInTable: true,
    formItemProps: {
      rules: [
        {
          required: true,
          message: '此项为必填项',
        },
      ],
    },
    renderFormItem: (item, { type, defaultRender, ...rest }) => {
      return <AuthorSelect {...rest} />;
    },
  },
  {
    title: '操作',
    valueType: 'option',
    key: 'option',
    render: (text, record, _, action) => [
      <PoemForm
        key={record.id}
        poemId={record.id}
        formTitle={record.title || '编辑'}
        triggerText="编辑"
        refresh={() => action?.reload()}
      />,
      <Popconfirm
        title="确定删除吗?"
        key={'delete' + record.id}
        onConfirm={async () => {
          await savePoemUsingPOST({ id: record.id, status: -1 });
          action?.reload();
        }}
        okText="Yes"
        cancelText="No"
      >
        <a href="#">删除</a>
      </Popconfirm>,
      <Popconfirm
        title="确定标记吗?"
        key={'mark_' + record.id}
        onConfirm={async () => {
          await savePoemUsingPOST({ id: record.id, status: record.status == 0 ? 1 : 0 });
          action?.reload();
        }}
        okText="Yes"
        cancelText="No"
      >
        <a href="#">{record.status == 0 ? '校准' : '取消校准'}</a>
      </Popconfirm>,
    ],
  },
];

export default () => {
  const actionRef = useRef<ActionType>();

  return (
    <ProTable<API.PoemBo>
      columns={columns}
      actionRef={actionRef}
      cardBordered
      request={async (params = {}) => {
        const query: API.QueryParam[] = [];
        const allowedKey = ['authorId', 'title', 'status', 'id'];
        Object.keys(params).forEach((x) => {
          if (allowedKey.includes(x) && params[x]) {
            query.push({ key: x, val: params[x] });
          }
        });

        const response = await poemListUsingPOST({
          current: params.current,
          pageSize: params.pageSize,
          query: query,
        });
        return { data: response.data?.list, total: response.data?.total };
      }}
      columnsState={{
        persistenceKey: 'pro-table-singe-demos',
        persistenceType: 'localStorage',
      }}
      rowKey="id"
      search={{
        labelWidth: 'auto',
      }}
      pagination={{
        pageSize: 20,
      }}
      form={{
        // 由于配置了 transform，提交的参与与定义的不同这里需要转化一下
        syncToUrl: (values, type) => {
          if (type === 'get') {
            return {
              ...values,
              created_at: [values.startTime, values.endTime],
            };
          }
          return values;
        },
      }}
      headerTitle="列表"
      dateFormatter="string"
      toolBarRender={() => [<PoemForm key="new" triggerText="新建" formTitle="创建" />]}
    />
  );
};
