/**
 * ldesign v0.2.14
 * (c) 2022/11/2 16:16 built by swimly
 * @license MIT
 */

import { getCurrentInstance, ref, defineComponent, computed, toRefs, watch } from '@vue/composition-api';
import { ChevronDownIcon, ChevronLeftIcon, CloseIcon } from '@ldesign/icons-vue';
import kebabCase from 'lodash/kebabCase';
import useDefaultValue from '../../hooks/use-default-value.js';
import { usePrefixClass } from '../../hooks/use-config.js';
import { renderLNodeJSX } from '../../utils/render-node.js';
import props from './props.js';
import TImageViewerIcon from './base/ImageModalIcon.js';
import TImageViewerUtils from './base/ImageViewerUtils.js';
import TImageItem from './base/ImageItem.js';
import TImageViewerModal from './base/ImageViewerModal.js';
import { useMirror, useScale, useRotate } from './hooks/index.js';
import { getOverlay, formatImages } from './utils.js';
import { EVENT_CODE } from './const.js';
import Container from './base/Container.js';
import { setTransform } from '../../utils/helper.js';
import '../config-provider/useConfig.js';
import '../config-provider/context.js';
import 'lodash';
import '../../_chunks/dep-def4c2ce.js';
import 'vue';
import '../../hooks/lnode.js';
import 'lodash/isEmpty';
import 'lodash/isFunction';
import 'lodash/camelCase';
import '../../hooks/render-lnode.js';
import '../tooltip/index.js';
import '../../utils/map-props.js';
import '../../utils/with-install.js';
import '../../config.js';
import '../tooltip/tooltip.js';
import '../../_chunks/dep-29915b8e.js';
import '../popup/props.js';
import '../popup/popup.js';
import '@popperjs/core';
import '../../_chunks/dep-cf772670.js';
import '../../utils/dom.js';
import 'raf';
import 'lodash/isString';
import '../../_chunks/dep-70c789e5.js';
import '../../_chunks/dep-5210251b.js';
import '../../utils/easing.js';
import '../config-provider/config-receiver.js';
import 'lodash/mergeWith';
import '../../utils/mixins.js';
import '../popup/container.js';
import '../tooltip/props.js';
import '../dialog/index.js';
import '../dialog/dialog.js';
import 'lodash/isNumber';
import 'lodash/throttle';
import '../button/index.js';
import '../button/button.js';
import '../loading/index.js';
import '../loading/loading.js';
import '../../utils/transfer-dom.js';
import '../loading/props.js';
import '../loading/icon/gradient.js';
import '../../_chunks/dep-eb467ddf.js';
import '../../_chunks/dep-47d77fc8.js';
import '../loading/plugin.js';
import '../../utils/ripple.js';
import '../button/props.js';
import '../../utils/event.js';
import '../../hooks/use-destroy-onclose.js';
import '../dialog/props.js';
import '../dialog/mixins/action.js';
import 'lodash/isObject';
import '../dialog/stack.js';
import '../dialog/plugin.js';

function useVModel(value, defaultValue, onChange) {
  let eventName = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : "change";
  let propName = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : "value";
  let alias = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : [];
  const {
    emit,
    vnode
  } = getCurrentInstance();
  const internalValue = ref();
  internalValue.value = defaultValue;
  const isControlled = Object.prototype.hasOwnProperty.call(vnode.componentOptions.propsData, propName) || Object.prototype.hasOwnProperty.call(vnode.componentOptions.propsData, kebabCase(propName));
  if (isControlled) {
    return [value, function (newValue) {
      for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
        args[_key - 1] = arguments[_key];
      }
      emit === null || emit === void 0 ? void 0 : emit("input", newValue, ...args);
      onChange === null || onChange === void 0 ? void 0 : onChange(newValue, ...args);
      if (eventName && eventName !== "input") emit === null || emit === void 0 ? void 0 : emit(eventName, newValue, ...args);
    }];
  }
  for (let i = 0, len = alias.length; i < len; i++) {
    const item = alias[i];
    if (Object.prototype.hasOwnProperty.call(vnode.componentOptions.propsData, item.propName)) {
      return [item.value, function (newValue) {
        for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
          args[_key2 - 1] = arguments[_key2];
        }
        emit === null || emit === void 0 ? void 0 : emit(`update:${item.propName}`, newValue, ...args);
        onChange === null || onChange === void 0 ? void 0 : onChange(newValue, ...args);
        if (item.eventName && item.eventName !== "input") emit === null || emit === void 0 ? void 0 : emit(item.eventName, newValue, ...args);
      }];
    }
  }
  return [internalValue, function (newValue) {
    internalValue.value = newValue;
    for (var _len3 = arguments.length, args = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) {
      args[_key3 - 1] = arguments[_key3];
    }
    onChange === null || onChange === void 0 ? void 0 : onChange(newValue, ...args);
    if (eventName && eventName !== "input") emit === null || emit === void 0 ? void 0 : emit(eventName, newValue, ...args);
  }];
}

var _ImageViewer = defineComponent({
  name: "LImageViewer",
  model: {
    prop: "visible",
    event: "change"
  },
  props: {
    ...props
  },
  setup(props2, _ref) {
    let {
      emit
    } = _ref;
    const classPrefix = usePrefixClass();
    const COMPONENT_NAME = usePrefixClass("image-viewer");
    const isExpand = ref(false);
    const showOverlayValue = computed(() => getOverlay(props2));
    const {
      index,
      visible
    } = toRefs(props2);
    const [indexValue, setIndexValue] = useDefaultValue(index, props2.defaultIndex ?? 0, props2.onIndexChange, "index", "index-change");
    const [visibleValue, setVisibleValue] = useVModel(visible, props2.defaultVisible, () => {}, "change", "visible");
    const rootClass = computed(() => [`${COMPONENT_NAME.value}`]);
    const wrapClass = computed(() => [`${COMPONENT_NAME.value}-preview-image`, {
      [`${classPrefix.value}-is-hide`]: !visibleValue.value
    }]);
    const headerClass = computed(() => [`${classPrefix.value}-image-viewer__modal-header`, {
      [`${classPrefix.value}-is-show`]: isExpand.value
    }]);
    const zIndexValue = computed(() => props2.zIndex ?? 2600);
    const toggleExpand = () => {
      isExpand.value = !isExpand.value;
    };
    const {
      mirror,
      onMirror,
      resetMirror
    } = useMirror();
    const {
      scale,
      onZoomIn,
      onZoomOut,
      resetScale
    } = useScale(props2.imageScale);
    const {
      rotate,
      onRotate,
      resetRotate
    } = useRotate();
    const onRest = () => {
      resetMirror();
      resetScale();
      resetRotate();
    };
    const imagesList = computed(() => formatImages(props2.images));
    const currentImage = computed(() => imagesList.value[indexValue.value] ?? {
      mainImage: ""
    });
    const prevImage = () => {
      const newIndex = indexValue.value - 1;
      setIndexValue(newIndex < 0 ? 0 : newIndex, {
        trigger: "prev"
      });
    };
    const nextImage = () => {
      const newIndex = indexValue.value + 1;
      setIndexValue(newIndex >= imagesList.value.length ? indexValue.value : newIndex, {
        trigger: "next"
      });
    };
    const onImgClick = i => {
      setIndexValue(i, {
        trigger: i > indexValue.value ? "next" : "prev"
      });
    };
    const openHandler = () => {
      setVisibleValue(true);
    };
    const onCloseHandle = ctx => {
      var _props2$onClose;
      setVisibleValue(false);
      (_props2$onClose = props2.onClose) === null || _props2$onClose === void 0 ? void 0 : _props2$onClose.call(props2, ctx);
      emit("close", ctx);
    };
    const closeBtnAction = e => {
      onCloseHandle({
        e,
        trigger: "close-btn"
      });
    };
    const clickOverlayHandler = e => {
      if (props2.closeOnOverlay) onCloseHandle({
        e,
        trigger: "overlay"
      });
    };
    const keydownHandler = e => {
      switch (e.code) {
        case EVENT_CODE.left:
          prevImage();
          break;
        case EVENT_CODE.right:
          nextImage();
          break;
        case EVENT_CODE.up:
          onZoomIn();
          break;
        case EVENT_CODE.down:
          onZoomOut();
          break;
        case EVENT_CODE.esc:
          onCloseHandle({
            e,
            trigger: "esc"
          });
          break;
      }
    };
    const containerRef = ref();
    const mountContent = () => {
      if (containerRef.value) containerRef.value.mountContent();
    };
    const unmountContent = () => {
      if (containerRef.value) containerRef.value.unmountContent();
    };
    watch(() => visibleValue.value, val => {
      if (val) {
        window.addEventListener("keydown", keydownHandler);
        mountContent();
        return;
      }
      window.removeEventListener("keydown", keydownHandler);
      unmountContent();
    });
    const onWheel = e => {
      e.preventDefault();
      const {
        deltaY,
        ctrlKey
      } = e;
      if (ctrlKey) return deltaY > 0 ? onZoomOut() : onZoomIn();
      deltaY > 0 ? onZoomIn() : onZoomOut();
    };
    const transStyle = computed(() => setTransform(`translateX(-${indexValue.value * 84}px)`));
    const isMultipleImg = computed(() => imagesList.value.length > 1);
    return {
      COMPONENT_NAME,
      rootClass,
      classPrefix,
      prevImage,
      nextImage,
      zIndexValue,
      visibleValue,
      indexValue,
      imagesList,
      showOverlayValue,
      wrapClass,
      rotate,
      mirror,
      currentImage,
      onRotate,
      onZoomIn,
      onZoomOut,
      onMirror,
      onRest,
      openHandler,
      onCloseHandle,
      onWheel,
      clickOverlayHandler,
      headerClass,
      toggleExpand,
      transStyle,
      onImgClick,
      closeBtnAction,
      scale,
      isMultipleImg,
      containerRef
    };
  },
  methods: {
    renderHeader() {
      const h = this.$createElement;
      return h("div", {
        "class": this.headerClass
      }, [h(TImageViewerIcon, {
        "attrs": {
          "icon": () => h(ChevronDownIcon, {
            "attrs": {
              "size": "20px"
            }
          }),
          "clickHandler": this.toggleExpand
        },
        "class": `${this.COMPONENT_NAME}__header-pre-bt`
      }), h("div", {
        "class": `${this.COMPONENT_NAME}__header-prev`
      }, [h("div", {
        "class": `${this.COMPONENT_NAME}__bokeh-left`
      }), h("div", {
        "class": `${this.COMPONENT_NAME}__bokeh-right`
      }), h("div", {
        "class": `${this.COMPONENT_NAME}__header-trans`,
        "style": this.transStyle
      }, [this.imagesList.map((image, index) => h("div", {
        "key": index,
        "class": [`${this.COMPONENT_NAME}__header-box`, {
          [`${this.classPrefix}-is-active`]: index === this.indexValue
        }]
      }, [h("img", {
        "attrs": {
          "alt": "",
          "src": image.thumbnail || image.mainImage
        },
        "class": `${this.COMPONENT_NAME}__header-img`,
        "on": {
          "click": () => this.onImgClick(index)
        }
      })]))])])]);
    },
    renderNavigationArrow(type) {
      const h = this.$createElement;
      const rotateDeg = type === "prev" ? 0 : 180;
      const icon = renderLNodeJSX(this, "navigationArrow", h(ChevronLeftIcon, {
        "style": setTransform(`rotate(${rotateDeg}deg)`),
        "attrs": {
          "size": "24px"
        }
      }));
      return h(TImageViewerIcon, {
        "class": `${this.COMPONENT_NAME}__modal-${type}-bt`,
        "attrs": {
          "clickHandler": type === "prev" ? this.prevImage : this.nextImage,
          "icon": () => icon
        }
      });
    },
    renderModal() {
      const h = this.$createElement;
      return h(TImageViewerModal, {
        "attrs": {
          "zIndex": this.zIndexValue,
          "visible": this.visibleValue,
          "index": this.indexValue,
          "images": this.imagesList,
          "scale": this.scale,
          "rotate": this.rotate,
          "mirror": this.mirror,
          "currentImage": this.currentImage,
          "rotateHandler": this.onRotate,
          "zoomInHandler": this.onZoomIn,
          "zoomOutHandler": this.onZoomOut,
          "mirrorHandler": this.onMirror,
          "resetHandler": this.onRest,
          "closeHandler": this.onCloseHandle,
          "draggable": this.draggable,
          "showOverlay": this.showOverlayValue,
          "closeBtn": this.closeBtn
        }
      });
    },
    renderViewer() {
      const h = this.$createElement;
      return h("div", {
        "class": this.wrapClass,
        "style": {
          zIndex: this.zIndexValue
        },
        "on": {
          "wheel": this.onWheel
        }
      }, [!!this.showOverlayValue && h("div", {
        "class": `${this.COMPONENT_NAME}__modal-mask`,
        "on": {
          "click": this.clickOverlayHandler
        }
      }), this.isMultipleImg && this.renderHeader(), this.isMultipleImg && this.renderNavigationArrow("prev"), this.isMultipleImg && this.renderNavigationArrow("next"), this.isMultipleImg && h("div", {
        "class": `${this.COMPONENT_NAME}__modal-index`
      }, [renderLNodeJSX(this, "title"), `${this.indexValue + 1}/${this.imagesList.length}`]), h("div", {
        "class": [`${this.COMPONENT_NAME}__modal-icon`, `${this.COMPONENT_NAME}__modal-close-bt`],
        "on": {
          "click": this.closeBtnAction
        }
      }, [renderLNodeJSX(this, "closeBtn", h(CloseIcon, {
        "attrs": {
          "size": "24px"
        }
      }))]), h(TImageViewerUtils, {
        "attrs": {
          "zoomInHandler": this.onZoomIn,
          "zoomOutHandler": this.onZoomOut,
          "mirrorHandler": this.onMirror,
          "resetHandler": this.onRest,
          "rotateHandler": this.onRotate,
          "scale": this.scale,
          "currentImage": this.currentImage
        }
      }), h(TImageItem, {
        "attrs": {
          "scale": this.scale,
          "rotate": this.rotate,
          "mirror": this.mirror,
          "src": this.currentImage.mainImage,
          "placementSrc": this.currentImage.thumbnail
        }
      })]);
    }
  },
  render() {
    const h = arguments[0];
    return h(Container, {
      "ref": "containerRef",
      "attrs": {
        "mode": this.mode,
        "renderModal": this.renderModal,
        "renderViewer": this.renderViewer
      }
    }, [renderLNodeJSX(this, "trigger", {
      params: {
        open: this.openHandler
      }
    })]);
  }
});

export { _ImageViewer as default };
//# sourceMappingURL=image-viewer.js.map
