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 { importMobileConstants } from 'models/mobile-constant';
import exportConfig from 'constants/export-config';

const { extension } = exportConfig;

interface IProps {
  children: React.ReactElement;
  onComplete: () => void;
  importMobileConstants: (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 = (data) => {
    return this.props.importMobileConstants({
      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.mobileConstant]} />
          <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 = {
  importMobileConstants
};

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