import React, { memo, useState, useEffect } from 'react';
import html2canvas from 'html2canvas';
import Button from 'components/EasyvButton';
import { uploadAssets } from 'utils/upload';
import { dataURItoBlob } from 'utils/utils';
import message from 'components/message';

function ScreenShot({ id, onComplete }) {
  const [loading, setLoading] = useState(false);
  const [controller, setController] = useState<AbortController>();

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

    return () => {
      controller && controller.abort();
    };
  }, []);

  const handleScreenShot = () => {
    setLoading(true);
    const hide = message.loading('正在截屏...', 0);

    const dom = document.getElementById('m-simulator-container') as HTMLDivElement;

    html2canvas(dom, {
      proxy: '/api/v3/screen/image/proxy',
      useCORS: true
    })
      .then(async (canvas) => {
        const dataurl = canvas.toDataURL('image/png');
        const blob = dataURItoBlob(dataurl);

        const result = await uploadAssets({
          file: blob,
          path: `screen/${id}/thumb.png`, //thumb.png 可以为随意名称
          signal: controller && controller.signal,
          rename: true
        });
        if (result) {
          onComplete(result);
        }
        hide();
        message.success('截屏成功');

        setLoading(false);
      })
      .catch((err) => {
        console.error(err);
        hide();
        message.error('截屏失败');
        setLoading(false);
      });
  };

  return (
    <Button theme="primary" disabled={loading} onClick={handleScreenShot}>
      {loading ? '截屏中...' : '截屏'}
    </Button>
  );
}

export default memo(ScreenShot);
