import { Upload, message, notification } from 'antd';
import React, { useEffect, useState } from 'react';
import { PlusOutlined } from '@ant-design/icons';
import config from '../../../../config/env.config';
import UUID from '../../../utils/uuid';
import { qiniuToken } from '@/services/qiniu';

const qiniu = require('@/utils/qiniu.min.js');

const { qiniuHost } = config;

const CustomUpload = props => {
  const { limit = 1 } = props;
  const [fileList, setFileList] = useState([]);
  const [token, setToken] = useState(null);

  const customRequest = ({ file, onError, onSuccess }) => {
    let suffix = '';
    if (file.name) {
      const index = file.name.lastIndexOf('.');
      suffix = file.name.substr(index + 1, file.name.length - 1);
      const types = ['pdf', 'doc', 'docx', 'zip', 'rar', 'png', 'jpeg', 'jpg'];
      if (!types.includes(suffix)) {
        message.error('文件格式错误！');
        return;
      }
    }
    if (fileList.length >= limit) {
      message.warning(`最多上传${limit}个!`);
      return;
    }

    // eslint-disable-next-line new-cap
    const data = `${UUID.createUUID()}.${suffix}`;
    if (!token) {
      message.error('上传失败，请刷新页面重试！');
      return;
    }
    const observable = qiniu.upload(file, data, token);
    const observer = {
      next() {
        // ...
      },
      error(t) {
        if (t.code === 614) {
          notification.error({
            message: '文件名重复，请更换文件名。',
          });
        }
        onError(file);
        // ...
      },
      complete(res) {
        const comFile = file;
        const url = `${qiniuHost}/${res.key}`;
        comFile.url = url;
        const list = fileList;
        list.push({
          url: file.url,
          name: file.name,
          uid: list.length,
          status: 'done',
        });
        setFileList([...list]);
        props.onChange(list);
        onSuccess(comFile);
      },
    };
    observable.subscribe(observer); // 上传开始
  };

  const onRemove = item => {
    const arr = (fileList || []).filter(file => file.uid !== item.uid);
    setTimeout(() => {
      props.onChange(arr);
    }, 100);
  };

  const getToken = async () => {
    setToken(await qiniuToken());
  };

  useEffect(() => {
    if (props.value instanceof Array) {
      console.log('initFileList(props.value) :>> ', JSON.stringify(initFileList(props.value)));
      setFileList(initFileList(props.value));
    }
  }, [props.value]);

  useEffect(() => {
    getToken();
  }, []);

  return (
    <Upload
      onChange={props.onChange}
      customRequest={customRequest}
      listType="picture-card"
      fileList={fileList}
      onRemove={onRemove}
      accept=".pdf,.doc,.docx,.zip,.rar,.png,.jpeg,.jpg"
    >
      <div>
        <PlusOutlined />
        <div style={{ marginTop: 8 }}>上传文件</div>
      </div>
    </Upload>
  );
};

export default CustomUpload;

function initFileList(fileList) {
  const fileLists = (fileList || []).map((item, index) => ({
    url: item.url,
    name: item.name ? item.name : '发票',
    uid: index,
    status: 'done',
  }));
  return fileLists;
}
