import { Form, InputNumber, Input, Select, Radio, Switch } 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' | 'radio' | 'textArea' | 'switch';
  record: any;
  index: number;
  children: React.ReactNode;
}
const EditableCell: React.FC<
  EditableCellProps & {
    selectOption?: { name: string; id: number }[];
    radioOption?: { name: string; id: number }[];
    uploadSuccess?: (record: any, result: any) => void;
    rules?: any;
    maxLength?: number;
    placeholder?: string;
  }
> = ({
  editing,
  dataIndex,
  title,
  inputType,
  record,
  index,
  selectOption,
  radioOption,
  uploadSuccess,
  children,
  rules,
  maxLength,
  placeholder,
  ...restProps
}) => {
  const inputNode = () => {
    switch (inputType) {
      case 'number':
        return <InputNumber placeholder={`请输入${placeholder || title}`} maxLength={maxLength} />;
      case 'select':
        return (
          <Select placeholder={`请选择${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>
        );
      case 'radio':
        return (
          <Radio.Group>
            {radioOption?.map((v) => (
              <Radio value={v.id} key={v.id}>
                {v.name}
              </Radio>
            ))}
          </Radio.Group>
        );
      case 'textArea':
        return (
          <Input.TextArea
            placeholder={`请输入${placeholder || title}`}
            maxLength={maxLength}
            showCount
          />
        );
      case 'switch':
        return <Switch />;
      default:
        return <Input placeholder={`请输入${placeholder || title}`} maxLength={maxLength} />;
    }
  };
  return (
    <td {...restProps}>
      {editing ? (
        <Form.Item
          name={dataIndex + record.id}
          style={{ margin: 0 }}
          rules={rules}
          //valuePropName：当 form setFieldsValue 设置switch不生效时
          valuePropName={inputType === 'switch' ? 'checked' : undefined}
        >
          {inputNode()}
        </Form.Item>
      ) : (
        children
      )}
    </td>
  );
};

export default EditableCell;
