import React, { useState } from 'react';
import saveAs from 'file-saver';
import JSZip from 'jszip';
import ConfirmModal from 'components/ConfirmModal';
import ExportAssets from 'components/ExportAssets';
import exportConfig from 'constants/export-config';
import { request } from 'utils/fetch';
import { api } from 'constants/config';
import { useEffect } from 'react';

const { extension } = exportConfig;

export default function ExportModal({ data, children, onReselect }: { data: any; children: any; onReselect?: any }) {
  const [visible, setVisible] = useState(false);
  const [all, setAll] = useState<any[]>(data);
  const [completed, setCompleted] = useState<any[]>([]);

  useEffect(() => {
    setAll(data);
  }, [data]);

  const onRequest = async (id) => {
    const result = await request(api.exportModal, { id });
    if (result) {
      const { material } = result;
      let materialsFiles = material.reduce((all: any, item: any) => {
        all.push(item.content);
        all.push(item.thumb);
        all.push(item.preview);
        return all;
      }, []);
      materialsFiles = Array.from(new Set(materialsFiles));
      const files = materialsFiles;
      return {
        data: {
          data: result
        },
        files,
        assets: []
      };
    } else {
      return Promise.reject();
    }
  };

  const onComplete = ({ id, zip, name }) => {
    if (all.length === 1) {
      zip.generateAsync({ type: 'blob' }).then((blob) => {
        saveAs(blob, `${name}${extension.modal}`);
        onClose();
        onReselect && onReselect();
      });
    } else {
      setCompleted((prev) => prev.concat([{ id, zip, name }]));
    }
  };

  const onRemove = (id) => {
    setAll((prev) => prev.filter((d) => d.id != id));
  };

  const onDownloadAll = async () => {
    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.modal}`, blob);
            resolve(blob);
          });
        });
      })
    );
    allZip.generateAsync({ type: 'blob' }).then((blob) => {
      saveAs(blob, `模型(${completed.length})${extension.modal}`);
      onClose();
      onReselect && onReselect();
    });
  };

  const onClose = () => {
    setVisible(false);
    setAll([]);
  };

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