import { insert, createComponent, effect, className, style, setAttribute, template } from 'solid-js/web';
import { OriginComponent, atom } from '@cn-ui/use';
import CropperJS from 'cropperjs';
import 'cropperjs/dist/cropper.min.css';
import { onCleanup, Show } from 'solid-js';
import { Box, DefaultIcon } from '@cn-ui/core';

const _tmpl$ = /*#__PURE__*/template(`<div><img class="cropper-hidden" crossorigin></div>`, 3);
const Cropper = OriginComponent(props => {
  let cropper;
  onCleanup(() => {
    cropper && cropper.destroy();
  });
  const loading = atom(true);

  const _self$ = undefined;

  return (() => {
    const _el$ = _tmpl$.cloneNode(true),
          _el$2 = _el$.firstChild;

    insert(_el$, createComponent(Show, {
      get when() {
        return loading();
      },

      get children() {
        return props.loading ?? createComponent(Box, {
          get icon() {
            return createComponent(DefaultIcon, {
              name: "replay",
              color: "green",
              spin: true,
              size: 50
            });
          },

          title: "加载中"
        });
      }

    }), _el$2);

    (image => {
      image.addEventListener('load', () => {
        cropper = new CropperJS(image, { ...(props.options || {}),

          crop() {
            props.previewDataURL && props.previewDataURL(() => {
              // 获取数据
              return cropper.getCroppedCanvas().toDataURL('image/jpeg');
            });
            return props.options.crop && props.options.crop.apply(_self$, arguments);
          },

          ready() {
            loading(false);
            console.log('加载完成');
            return props.options.ready && props.options.ready.apply(_self$, arguments);
          }

        });
      });
    })(_el$2);

    effect(_p$ => {
      const _v$ = props.class(),
            _v$2 = props.style,
            _v$3 = props.src;

      _v$ !== _p$._v$ && className(_el$, _p$._v$ = _v$);
      _p$._v$2 = style(_el$, _v$2, _p$._v$2);
      _v$3 !== _p$._v$3 && setAttribute(_el$2, "src", _p$._v$3 = _v$3);
      return _p$;
    }, {
      _v$: undefined,
      _v$2: undefined,
      _v$3: undefined
    });

    return _el$;
  })();
});

export { Cropper };
