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

interface IState {
  total: number;
  loaded: number;
  status: 'normal' | 'active' | 'success' | 'exception';
  signature: any;
  allowUnknowedUser: boolean;
  replace: boolean;
}

class ImportAssets extends Component<IProps, IState> {
  controller: AbortController;
  constructor(props) {
    super(props);
    this.state = {
      total: 0,
      loaded: 0,
      status: 'normal',
      signature: {},
      allowUnknowedUser: false,
      replace: false
    };
  }

  componentDidMount() {
    this.handleUpload();
  }

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

    this.setState({
      status: 'active'
    });

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

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

  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: this.state.allowUnknowedUser, replace: this.state.replace },
      formData,
      { signal }
    ).then((res) => {
      if (res) {
        if (res.code === 'ALLOW_UNKNOWED_USER_CONFIRM') {
          Confirm({
            title: '未知开发者的组件，是否允许导入？',
            okText: '确定',
            content: null,
            cancelText: '取消',
            className: 'light',
            onOk: () => {
              this.setState(
                {
                  allowUnknowedUser: true
                },
                () => {
                  this.handleUpload();
                }
              );
            }
          });
          throw Error('导入失败');
        } else if (res.code === 'REPLACE_CONFIRM') {
          Confirm({
            title: '与租户组件出现组件同名，是否覆盖',
            okText: '确定',
            content: null,
            cancelText: '取消',
            className: 'light',
            onOk: () => {
              this.setState(
                {
                  replace: true
                },
                () => {
                  this.handleUpload();
                }
              );
            },
            onCancel: () => {}
          });
          throw Error('导入失败');
        } else {
          this.setState((prev) => ({
            loaded: prev.loaded + 1
          }));
        }
      } else {
        throw Error('导入失败');
      }
    });
  };

  componentWillUnmount() {
    this.controller && this.controller.abort();
  }

  onRestart = () => {
    const { status } = this.state;
    if (status == 'exception') {
      this.setState(
        {
          total: 0,
          loaded: 0,
          status: 'normal'
        },
        () => {
          this.handleUpload();
        }
      );
    }
  };

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

  render() {
    const { total, loaded, status } = this.state;
    const { file } = this.props;
    const percent = loaded ? Math.round((loaded / total) * 100) : 0;

    return (
      <div className={styles.container}>
        <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={this.onRestart} />
            )}
            {status !== 'success' && (
              <i className={classNames('icon', 'iconfont', 'icon-btn_close', styles.closeIcon)} onClick={this.onRemove} />
            )}
          </div>
        </div>
        {status !== 'success' && (
          <div className={styles.progressContainer}>
            <Progress className={styles.progress} showInfo={false} strokeWidth={4} percent={percent} status={status} />
          </div>
        )}
      </div>
    );
  }
}

export default ImportAssets;
