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';
import message from 'components/message';

const { extension } = exportConfig;

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

  const onFileSelect = (file) => {
    JSZip.loadAsync(file).then((zip) => {
      const files = Object.keys(zip.files);
      const isMultiZip = files[0].slice(files[0].lastIndexOf('.')) === extension.modal;
      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));
      }
    });
    setFilename(file.name);
  };

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

  const onDataUpload = async (data, signal) => {
    const result = await request(api.modalImport, undefined, undefined, data.data, {
      signal,
      error: (err) => {
        if (err.message === 'Bad Request Exception') {
          message.error(`${fileName} 上传失败`);
        } else {
          message.error(err.message);
        }
      }
    });
    return result;
  };

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

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

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

          <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>
  );
}
