import React, { Component } from 'react';
import saveAs from 'file-saver';
import JSZip from 'jszip';
import ConfirmModal from '../../../../components/ConfirmModal';
import ExportAssets from '../../../../components/ExportAssets';

import { exportTemplate } from 'services/template';
import { getAssetsFromConfig } from 'utils/component';
import exportConfig from 'constants/export-config';

const { extension } = exportConfig;

interface IProps {
  list: any[];
  onComplete?: () => void;
  children: React.ReactElement
}

interface IState {
  visible: boolean; 
  templates: any[]; 
  completed: any[];
}

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

  showModal = () => {
    const { list } = this.props;
    // if (!window.appConfig.LOCAL) {
    //   confirm({
    //     title: '选择需要导出的版本？',
    //     okText: '新版本',
    //     cancelText: '3.6以前的版本',
    //     onOk: () => {
    //       this.setState({
    //         visible: true,
    //         templates: list,
    //         version: 'new'
    //       });
    //     },
    //     onCancel: () => {
    //       this.setState({
    //         visible: true,
    //         templates: list,
    //         version: 'old'
    //       });
    //     }
    //   });
    // } else {
    this.setState({
      visible: true,
      templates: list
      // version: 'new'
    });
    // }
  };

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

  onRequest = (id) => {
    return exportTemplate(id).then(async (res) => {
      if (res) {
        let data = res;
        // if (version == 'old') {
        //   const result = await transformScreenPackage({
        //     from: 3.6,
        //     to: 3.5,
        //     data: {
        //       componentsConfig: res.componentsConfig,
        //       filterConfig: res.filterConfig,
        //       panelConfig: res.panelConfig
        //     }
        //   });

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

        //   data = {
        //     ...data,
        //     ...result
        //   };
        // }

        let components = data.componentsConfig;
        let screens = [data.screenConfig];
        const getComponentsConfigAndScreenConfig = (config) => {
          config.forEach((d) => {
            if (d.statesConfig.length) {
              d.statesConfig.forEach((o) => {
                components.push(...o.componentsConfig);
                screens.push(o.screenConfig);
                if (o.panelsConfig.length) {
                  getComponentsConfigAndScreenConfig(o.panelsConfig);
                }
              });
            }
          });
        };
        getComponentsConfigAndScreenConfig(data.panelsConfig);

        let componentsFiles = components.reduce((all, item) => {
          if (!item.parent) {
            let base = JSON.parse(item.base);
            all.push(`components/${base.module_name}/${base.version}/${base.module_name}.js`);
          }
          return all;
        }, []);
        componentsFiles = Array.from(new Set(componentsFiles));

        const componentsThumbs = components.reduce((all, item) => {
          if (!item.parent) {
            let base = JSON.parse(item.base);
            if (base.thumb) {
              all.push(base.thumb);
            }
          }
          return all;
        }, []);

        const componentsAssets = components.reduce((all, item) => all.concat(getAssetsFromConfig(JSON.parse(item.config))), []);
        const screensAssets = screens.reduce((all, item) => all.concat(getAssetsFromConfig(JSON.parse(item.config))), []);
        const templateThumb = data.templateConfig.thumb;
        const templatePreviewThumb = data.templateConfig.previewThumb;

        const assets = Array.from(
          new Set(componentsThumbs.concat(componentsAssets).concat(screensAssets).concat([templateThumb, templatePreviewThumb]))
        );

        return { data, files: componentsFiles, assets };
      } else {
        return Promise.reject();
      }
    });
  };

  onComplete = ({ id, zip, name }) => {
    const { templates } = this.state;
    if (templates.length === 1) {
      this.hideModal();
      zip.generateAsync({ type: 'blob' }).then((blob) => {
        saveAs(blob, `${name}${extension.template}`);
      });
    } else {
      this.setState((prev) => ({
        completed: prev.completed.concat([{ id, zip, name }])
      }));
    }
  };

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

  onDownloadAll = async () => {
    const { completed } = this.state;
    const allZip = new JSZip();
    await Promise.all(
      completed.map((d) => {
        return new Promise((resolve) => {
          d.zip.generateAsync({ type: 'blob' }).then((blob) => {
            allZip.file(`${d.name.replace(/\//g, '_')}${extension.template}`, blob);
            resolve(blob);
          });
        });
      })
    );
    allZip.generateAsync({ type: 'blob' }).then((blob) => {
      saveAs(blob, `templates(${completed.length})${extension.template}`);
      this.hideModal();
      this.props.onComplete && this.props.onComplete();
    });
  };

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

    return (
      <span>
        <span onClick={this.showModal}>{children}</span>
        {visible && (
          <ConfirmModal
            title="导出模板"
            visible={visible}
            onClose={this.hideModal}
            onOk={this.onDownloadAll}
            footer={templates.length > 1 ? true : false}
            okText="下载"
            cancelText={''}>
            <div className="export-container">
              {templates.map((item) => (
                <ExportAssets
                  key={item.id}
                  name={item.name}
                  id={item.id}
                  onRequest={this.onRequest}
                  onComplete={this.onComplete}
                  onRemove={this.onRemove}
                />
              ))}
            </div>
          </ConfirmModal>
        )}
      </span>
    );
  }
}

export default ExportTemplatesModal;
