import React, { Component } from 'react';
import { connect } from 'react-redux';
import ConfirmModal from '../../../../components/ConfirmModal';
import FileSelect from '../../../../components/FileSelect';
import ImportAssets from '../../../../components/ImportAssets';
import exportConfig from 'constants/export-config';
import { importConstants } from 'models/constant';

const { extension } = exportConfig;

interface IProps {
  children: React.ReactElement;
  onComplete: () => void;
  importConstants: (param: { configs: string; orderConfig: string }) => 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 = (file) => {
    this.setState((prev) => ({
      constants: prev.constants.concat(file)
    }));
  };

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

  onDataUpload = async (data) => {
    return this.props.importConstants({
      configs: JSON.parse(data.configs),
      orderConfig: JSON.parse(data.orderConfig)
    });
  };

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

    return (
      <span>
        <span onClick={this.showModal}>{this.props.children}</span>
        <ConfirmModal
          title="导入组件包"
          visible={visible}
          destroyOnClose
          onClose={this.hideModal}
          onOk={this.hideModal}
          okText="关闭"
          cancelText={''}
          footer={true}>
          <FileSelect onComplete={this.onFileSelect} accept={[extension.constant]} />
          <div className="import-container">
            {constants.map((file) => {
              return (
                <ImportAssets
                  key={file.uid}
                  file={file}
                  onRemove={this.onRemove}
                  data={[
                    { name: 'configs', file: 'constant.json' },
                    { name: 'orderConfig', file: 'orderConfig.json', notRequired: true }
                  ]}
                  dataRequest={this.onDataUpload}
                  assets={['components', 'thumb']}
                />
              );
            })}
          </div>
        </ConfirmModal>
      </span>
    );
  }
}

const mapDispatchToProps = {
  importConstants
};

export default connect(null, mapDispatchToProps)(ImportConstantModal);
