import React, { useCallback, useRef } from 'react';
import { createRoot } from 'react-dom/client';
import WauModal from '../wau-modal';
import WauCropper from './cropper';
import { jsx as _jsx } from "react/jsx-runtime";
const CropperModal = props => {
  const {
    visible,
    open = visible,
    onClose,
    afterClose,
    width = 800,
    resultType,
    onCropperDone,
    title = '裁剪图片',
    ...cropperProps
  } = props;
  const cropperInstanceRef = useRef();
  const handleModalOk = useCallback(() => {
    if (cropperInstanceRef.current) {
      if (resultType === 'base64') {
        const url = cropperInstanceRef.current.getCroppedCanvas().toDataURL();
        onCropperDone === null || onCropperDone === void 0 ? void 0 : onCropperDone(url);
        onClose === null || onClose === void 0 ? void 0 : onClose();
      } else {
        cropperInstanceRef.current.getCroppedCanvas().toBlob(blob => {
          onCropperDone === null || onCropperDone === void 0 ? void 0 : onCropperDone(blob);
          onClose === null || onClose === void 0 ? void 0 : onClose();
        });
      }
    }
  }, [onClose, onCropperDone, resultType]);
  return /*#__PURE__*/_jsx(WauModal, {
    title: title,
    open: open,
    width: width,
    onCancel: close,
    afterClose: afterClose,
    okText: "\u88C1\u526A",
    cancelText: "\u53D6\u6D88",
    onOk: handleModalOk,
    children: /*#__PURE__*/_jsx(WauCropper, {
      ...cropperProps,
      ref: cropperInstanceRef,
      toolbar: {
        extra: false
      }
    })
  });
};
export default function showCropper(option) {
  const div = document.createElement('div');
  document.body.appendChild(div);
  const root = createRoot(div);
  // eslint-disable-next-line @typescript-eslint/no-use-before-define
  let currentConfig = {
    ...option,
    onClose: close,
    open: true
  };
  function destroy() {
    root.unmount();
    document.body.removeChild(div);
  }
  function close() {
    currentConfig = {
      ...currentConfig,
      open: false,
      afterClose: () => {
        if (currentConfig.onClose) {
          currentConfig.onClose();
        }
        destroy();
      }
    };
    root.render( /*#__PURE__*/_jsx(CropperModal, {
      ...currentConfig
    }));
  }
  root.render( /*#__PURE__*/_jsx(CropperModal, {
    ...currentConfig
  }));
}