import React, { Component } from 'react';
import JSZip from 'jszip';
import ConfirmModal from 'components/ConfirmModal';
import FileSelect from 'components/FileSelect';
import ImportAssets from './ImportAssets';
import { generateId } from 'utils/utils';

interface IProps {
  onComplete: () => void;
}

interface IState {
  visible: boolean;
  constants: any[];
}

class ImportConstantModal extends Component<IProps, IState> {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      constants: []
    };
  }

  showModal = () => {
    this.setState({
      visible: true
    });
  };

  hideModal = () => {
    this.setState(
      {
        visible: false,
        constants: []
      },
      () => {
        this.props.onComplete && this.props.onComplete();
      }
    );
  };

  onFileSelect = async (file) => {
    JSZip.loadAsync(file).then(async (zip) => {
      const files = zip.file(/\.constant$/);
      if (files.length > 0) {
        files.map((d) =>
          zip
            .file(d.name)
            ?.async('blob')
            .then((res: any) => {
              res.name = d.name;
              res.uid = generateId();
              this.setState((prev) => ({
                constants: prev.constants.concat(res)
              }));
            })
        );
      } else {
        this.setState((prev) => ({
          constants: prev.constants.concat(file)
        }));
      }
    });
  };

  onRemove = (id) => {
    this.setState((prev) => ({
      constants: prev.constants.filter((file) => file.uid !== id)
    }));
  };

  render() {
    const { visible, constants } = this.state;

    return (
      <span>
        <span onClick={this.showModal}>{this.props.children}</span>
        <ConfirmModal
          theme="black"
          title="导入组件包"
          visible={visible}
          destroyOnClose
          onClose={this.hideModal}
          onOk={this.hideModal}
          okText="关闭"
          cancelText={''}
          footer={true}>
          <FileSelect onComplete={this.onFileSelect} accept={['.constant']} />
          <div className="import-container">
            {constants.map((file) => {
              return <ImportAssets key={file.uid} file={file} onRemove={this.onRemove} />;
            })}
          </div>
        </ConfirmModal>
      </span>
    );
  }
}

export default ImportConstantModal;
