import React, { useState, useEffect, useCallback } from 'react';
import { connect } from 'react-redux';
import JSZip from 'jszip';
import saveAs from 'file-saver';
import ExportModal from './ExportModal';
import { exportThemes } from 'models/theme';
import exportConfig from 'constants/export-config';
import { ThemeType } from 'models/theme.types';
const { extension } = exportConfig;

function ExportContainer({
  children,
  list,
  ids,
  onComplete
}: {
  children: React.ReactElement;
  list: ThemeType[];
  ids: number[];
  onComplete?: () => void;
}) {
  const [visible, setVisible] = useState(false);
  const [status, setStatus] = useState('normal');
  const [retryCount, setRetryCount] = useState(0);

  useEffect(() => {
    const controller = window.AbortController && new AbortController();

    async function startExport() {
      const result = list.filter((d) => {
        return ids.includes(d.id);
      });

      if (result) {
        const zip = new JSZip();

        // 数据
        zip.file('themepack.json', JSON.stringify(result));
        setStatus('success');

        zip.generateAsync({ type: 'blob' }).then((blob) => {
          hideModal();
          onComplete && onComplete();
          if (result.length === 1) {
            saveAs(blob, `主题包_${result[0].name}${extension.themepack}`);
          } else {
            saveAs(blob, `主题包(${result.length})${extension.themepack}`);
          }
        });
      } else {
        controller && controller.abort();
        setStatus('exception');
      }
    }

    if (visible) {
      setStatus('active');

      startExport();
    }
    return () => {
      controller && controller.abort();
    };
  }, [visible, retryCount, list]);

  const hideModal = useCallback(() => {
    setVisible(false);
  }, []);

  const handleRestart = useCallback(() => {
    setRetryCount((prev) => prev + 1);
  }, []);

  const percent = 99;

  return (
    <span>
      <span onClick={() => setVisible(true)}>{children}</span>
      <ExportModal
        visible={visible}
        title="主题包导出"
        status={status}
        statusText={status === 'success' ? '导出成功' : status === 'exception' ? '导出失败，请重试' : '主题包正在导出，请稍后...'}
        percent={percent}
        onCancel={hideModal}
        onRestart={handleRestart}
      />
    </span>
  );
}

const mapDispatchToProps = {
  exportThemes
};

export default connect(null, mapDispatchToProps)(ExportContainer);
