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;
    rules?: any;
  }
> = ({
  editing,
  dataIndex,
  title,
  inputType,
  record,
  index,
  selectOption,
  uploadSuccess,
  children,
  rules,
  ...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}`} />;
    }
  };
  return (
    <td {...restProps}>
      {editing ? (
        <Form.Item name={dataIndex + record.id} style={{ margin: 0 }} rules={rules}>
          {inputNode()}
        </Form.Item>
      ) : (
        children
      )}
    </td>
  );
};

export default EditableCell;
