import React, { useState, useEffect } from 'react';
import { Progress } from '@easyv/antd';
import classNames from 'classnames';
import styles from './ImportAssets.less';
import { request } from 'utils/fetch';
import { api } from 'constants/config';
import { Modal, ConfigProvider } from '@easyv/react-gui';
import message from 'components/message';
import EasyvModal, { useConfirmRef } from 'components/EasyvModal';
interface IProps {
  file: {
    name: string;
    uid: string;
  };
  onRemove: (id) => void;
}

export default function ImportAssets(props: IProps) {
  const allowRef = useConfirmRef();
  const replaceRef = useConfirmRef();
  const [total, setTotal] = useState<number>(0);
  const [loaded, setLoaded] = useState<number>(0);
  const [status, setStatus] = useState<'normal' | 'active' | 'success' | 'exception'>('normal');
  const [allowUnknowedUser, setAllowUnknowedUser] = useState(false);
  const [replace, setReplace] = useState(false);
  const [controller, setController] = useState<any>(null);

  const [modal, contextHolder] = Modal.useModal();
  const { confirm } = modal;

  useEffect(() => {
    handleUpload();

    return () => {
      controller && controller.abort();
    };
  }, []);

  useEffect(() => {
    if (allowUnknowedUser || replace) {
      handleUpload();
    }
  }, [allowUnknowedUser, replace]);

  const handleUpload = async () => {
    setController(window.AbortController && new AbortController());
    const signal = controller && controller.signal;

    setStatus('active');

    const { file } = props;
    const fileName = file.name;

    try {
      await uploadPkg(file, fileName, signal);
      setStatus('success');
      message.success(`${fileName} 上传成功`);
    } catch (error) {
      console.error(error);
      message.error(`${fileName} 上传失败`);
      setStatus('exception');
    }
  };

  const uploadPkg = (file, key, signal) => {
    const filename = key.split('/').slice(-1)[0];
    const formData = new FormData();
    formData.append('file', file, filename);

    return request(api.tenantConstantImport, undefined, { allowUnknowedUser: allowUnknowedUser, replace: replace }, formData, {
      signal
    }).then((res) => {
      if (res) {
        if (res.code === 'ALLOW_UNKNOWED_USER_CONFIRM') {
          allowRef.current?.show();
          throw Error('导入失败');
        } else if (res.code === 'REPLACE_CONFIRM') {
          replaceRef.current?.show();
          throw Error('导入失败');
        } else {
          setLoaded(loaded + 1);
        }
      } else {
        throw Error('导入失败');
      }
    });
  };

  const onRestart = () => {
    if (status == 'exception') {
      setTotal(0);
      setLoaded(0);
      setStatus('normal');
      handleUpload();
    }
  };

  const onRemove = () => {
    const { file } = props;
    props.onRemove(file.uid);
  };

  const { file } = props;
  const percent = loaded ? Math.round((loaded / total) * 100) : 0;
  return (
    <div className={styles.container}>
      <EasyvModal.Confirm
        ref={allowRef}
        title="导入组件"
        content="未知开发者的组件，是否允许导入？"
        onOkBtnType="primary"
        onOk={() => setAllowUnknowedUser(true)}
      />
      <EasyvModal.Confirm
        ref={replaceRef}
        title="导入组件"
        content="与租户组件出现组件同名，是否覆盖"
        onOkBtnType="primary"
        onOk={() => setReplace(true)}
      />
      <ConfigProvider>{contextHolder}</ConfigProvider>
      <div
        className={classNames(styles.fileTitle, {
          [styles.error]: status === 'exception'
        })}>
        <div className={styles.fileInfo}>
          <i className={classNames('icon', 'iconfont', 'icon-icon_document', styles.fileIcon)} />
          <span
            className={classNames(styles.fileName, {
              [styles.success]: status === 'success'
            })}>
            {file.name}
          </span>
        </div>
        <div className={styles.operate}>
          {status === 'exception' && (
            <i className={classNames('icon', 'iconfont', 'icon-btn_reload', styles.restartIcon)} onClick={onRestart} />
          )}
          {status !== 'success' && <i className={classNames('icon', 'iconfont', 'icon-btn_close', styles.closeIcon)} onClick={onRemove} />}
        </div>
      </div>
      {status !== 'success' && (
        <div className={styles.progressContainer}>
          <Progress className={styles.progress} showInfo={false} strokeWidth={4} percent={percent} status={status} />
        </div>
      )}
    </div>
  );
}
