import { InboxOutlined } from '@ant-design/icons';
import { Upload } from 'antd';
import { DraggerProps } from 'antd/es/upload';
import cx from 'classnames';
import React from 'react';
import type { StdCallback } from './types';

const CLASS_NAME = 'ac-upload-dragger';
const { Dragger } = Upload;
type CustomRequest = (inEvent: any) => Promise<any>;

export type AcUploadDraggerProps = {
  className?: string;
  value?: any[];
  defaultValue?: any[];
  onChange?: StdCallback;
  onRequest?: CustomRequest;
} & DraggerProps;

export class AcUploadDragger extends React.Component<AcUploadDraggerProps> {
  static displayName = CLASS_NAME;
  static formSchema = CLASS_NAME;
  static defaultProps = {
    onRequest: (inEvent) => Promise.resolve(inEvent),
  };

  handleChange = (inEvent) => {
    const { onChange } = this.props;
    onChange?.({ target: { value: inEvent } });
  };

  handleCustomRequest = (inRequestOption) => {
    const { onRequest } = this.props;
    const { file } = inRequestOption;
    onRequest!(file)
      .then((res) => inRequestOption.onSuccess(res, file))
      .catch((err) => inRequestOption.onError(err, file));
  };

  render() {
    const { className, value, onChange, ...props } = this.props;
    return (
      <Dragger
        className={cx(CLASS_NAME, className)}
        listType="picture"
        onChange={this.handleChange}
        customRequest={this.handleCustomRequest}
        {...props}>
        <p className="ant-upload-drag-icon">
          <InboxOutlined />
        </p>
        <p className="ant-upload-text">单击或拖动文件到此区域以上传</p>
        <p className="ant-upload-hint">支持单个或批量上传，请不要上传公司数据或其他重要文件</p>
      </Dragger>
    );
  }
}

export const AcUploadDraggerFc = (props: AcUploadDraggerProps) => {
  return <AcUploadDragger {...props} />;
};
