import React, { useState, useEffect } from 'react';
import { v4 } from 'uuid';
import { isArray } from 'lodash';
import { usePassport } from '@sensoro/core';
import UploadFile from './upload';
import { UploadImageProps } from '@sensoro/sensoro-design/es/upload-image/upload-image';

interface UploadProps extends UploadImageProps {
  appName?: string;
}

const Upload: React.FC<UploadProps> = ({
  appName,
  data = {},
  onChange,
  value,
  ...rest
}) => {
  const [fileList, setFileList] = useState<UploadImageProps['fileList']>([]);

  const { token } = usePassport();

  useEffect(() => {
    if (isArray(value)) {
      setFileList(
        (value || []).map(item => ({ ...item, uid: item?.uid || v4() })) || [],
      );
      return;
    }
    setFileList(value || []);
  }, [value]);

  rest.headers = {
    ...rest.headers,
    authorization: `Bearer ${token}`,
  };
  rest.action = rest.action || `${window.BASE_URL}/oss/v1/private/uploadFile`;

  if (appName) {
    // @ts-ignore
    data.appName = appName;
  }

  const getValue = (e: any) => {
    if (Array.isArray(e)) {
      return e;
    }
    return e && e.fileList;
  };

  const handleChange: UploadImageProps['onChange'] = (e: any) => {
    const list = getValue(e);

    setFileList(list);
    // 过滤数据
    onChange?.(list);
  };

  return (
    <UploadFile
      {...rest}
      multiple={false}
      value={fileList}
      data={data}
      onChange={handleChange}
    />
  );
};

Upload.defaultProps = {
  appName: 'alarm-pic',
};

export default Upload;
