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

import { importTemplate } from 'services/template';
import exportConfig from 'constants/export-config';

const { extension } = exportConfig;

interface IProps {
  children: React.ReactElement;
  onComplete: () => void;
}

interface IState {
  visible: boolean;
  templates: any[];
}
class ImportTemplatesModal extends Component<IProps, IState> {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      templates: []
    };
  }

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

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

  onFileSelect = (file) => {
    JSZip.loadAsync(file).then((zip) => {
      let files = Object.keys(zip.files);
      let isMultiZip = files[0].slice(files[0].lastIndexOf('.')) === extension.template;
      if (isMultiZip) {
        zip.forEach((d, i) => {
          zip
            .file(d)
            ?.async('blob')
            .then((res: any) => {
              res.name = d;
              res.uid = `rc-upload-${+new Date()}-${i}`;
              this.setState((prev) => ({
                templates: prev.templates.concat(res)
              }));
            });
        });
      } else {
        this.setState((prev) => ({
          templates: prev.templates.concat(file)
        }));
      }
    });
  };

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

  onDataUpload = async (data, signal) => {
    // if (!window.appConfig.LOCAL && !data.info) {
    //   const result = await transformScreenPackage({
    //     from: 3.5,
    //     to: 3.6,
    //     data: {
    //       componentsConfig: data.componentsConfig,
    //       sourceConfig: data.sourceConfig,
    //       filterConfig: data.filterConfig,
    //       panelConfig: data.panelConfig
    //     }
    //   });

    //   if (!result) {
    //     return Promise.reject();
    //   }

    //   data = {
    //     ...data,
    //     ...result
    //   };
    // }
    const result = await importTemplate(data, signal);

    return result;
  };

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

    return (
      <span>
        <span onClick={this.showModal}>{this.props.children}</span>
        {visible && (
          <ConfirmModal
            visible={visible}
            title="导入模板"
            onClose={this.hideModal}
            footer={true}
            okText="关闭"
            onOk={this.hideModal}
            cancelText={''}>
            <FileSelect onComplete={this.onFileSelect} accept={[extension.template]} />

            <div className="import-container">
              {templates.map((d) => {
                return (
                  <ImportAssets
                    key={d.uid}
                    file={d}
                    data={[
                      { name: 'templateConfig', file: 'templateConfig.json' },
                      { name: 'componentsConfig', file: 'componentsConfig.json' },
                      { name: 'screenConfig', file: 'screenConfig.json' },
                      { name: 'panelsConfig', file: 'panelsConfig.json', notRequired: true },
                      { name: 'filtersConfig', file: 'filtersConfig.json', notRequired: true }
                    ]}
                    assets={['components', 'data', 'template', 'screen', 'easyv-market']}
                    dataRequest={this.onDataUpload}
                    onRemove={this.onRemove}
                  />
                );
              })}
            </div>
          </ConfirmModal>
        )}
      </span>
    );
  }
}

export default ImportTemplatesModal;
