import { Form, InputNumber, Input, Select } from 'antd';
import React from 'react';
import { Uploader } from '~/components/uploader';
import { UploadOutlined } from '@ant-design/icons';

// 表格可编辑单元格
export interface EditableCellProps extends React.HTMLAttributes<HTMLElement> {
  editing: boolean;
  dataIndex: string;
  title: any;
  inputType: 'number' | 'text' | 'select' | 'uploader';
  record: any;
  index: number;
  children: React.ReactNode;
}
const EditableCell: React.FC<
  EditableCellProps & {
    selectOption?: { name: string; id: number }[];
    uploadSuccess?: (record: any, result: any) => void;
  }
> = ({
  editing,
  dataIndex,
  title,
  inputType,
  record,
  index,
  selectOption,
  uploadSuccess,
  children,
  ...restProps
}) => {
  const inputNode = () => {
    switch (inputType) {
      case 'number':
        return <InputNumber />;
      case 'select':
        return (
          <Select placeholder={`请选择${title}`} style={{ textAlign: 'start' }}>
            {selectOption &&
              selectOption.map((v) => (
                <Select.Option value={v.id} key={v.id}>
                  {v.name}
                </Select.Option>
              ))}
          </Select>
        );
      case 'uploader':
        return (
          <Uploader
            fileUpload
            listType='picture-card'
            onChange={(value) => uploadSuccess?.(record, value)}
            defaultFileList={record.fileList}
          >
            <UploadOutlined />
          </Uploader>
        );
      default:
        return <Input placeholder={`请输入${title}`} />;
    }
  };
  const getMessage = () => {
    switch (inputType) {
      case 'number':
      case 'text':
        return `请输入${title}`;
      case 'select':
        return `请选择${title}`;
      case 'uploader':
        return `请上传${title}`;
      default:
        return `请输入${title}`;
    }
  };
  return (
    <td {...restProps}>
      {editing ? (
        <Form.Item
          name={dataIndex + record.id}
          style={{ margin: 0 }}
          rules={[
            {
              required: true,
              message: getMessage(),
            },
          ]}
        >
          {inputNode()}
        </Form.Item>
      ) : (
        children
      )}
    </td>
  );
};

export default EditableCell;
