import React, { useState } from 'react';
import JSZip from 'jszip';
import ConfirmModal from 'components/ConfirmModal';
import FileSelect from 'components/FileSelect';
import ImportAssets from 'components/ImportAssets';
import exportConfig from 'constants/export-config';
import { request } from 'utils/fetch';
import { api } from 'constants/config';

const { extension } = exportConfig;

export default function MultiImportModal({ refresh, children }) {
  const [visible, setVisible] = useState(false);
  const [all, setAll] = useState<any[]>([]);

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

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

  const onDataUpload = async (data, signal) => {
    const result = await request(api.platformMaterialImport, undefined, undefined, data.data, { signal });
    return result;
  };

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

  return (
    <span>
      <span onClick={() => setVisible(true)}>{children}</span>
      {visible && (
        <ConfirmModal
          visible={visible}
          title="导入"
          onClose={() => setVisible(false)}
          footer={true}
          okText="关闭"
          onOk={handleClose}
          cancelText={''}>
          <FileSelect onComplete={onFileSelect} accept={[extension.material]} />

          <div className="import-container">
            {all.map((d) => {
              return (
                <ImportAssets
                  key={d.uid}
                  file={d}
                  data={[{ name: 'data', file: 'data.json' }]}
                  assets={['data']}
                  dataRequest={onDataUpload}
                  onRemove={onRemove}
                />
              );
            })}
          </div>
        </ConfirmModal>
      )}
    </span>
  );
}
