/**
 * amis-ui v6.12.0-beta.0
 * Copyright 2018-2025 fex
 */

import { __extends, __decorate, __metadata } from 'tslib';
import React__default from 'react';
import debounce from 'lodash/debounce';
import { autobind, themeable, localeable } from 'amis-core';
import FinalModal from './Modal.js';
import { Icon } from './icons.js';

var ImageActionKey;
(function (ImageActionKey) {
    /** 右旋转 */
    ImageActionKey["ROTATE_RIGHT"] = "rotateRight";
    /** 左旋转 */
    ImageActionKey["ROTATE_LEFT"] = "rotateLeft";
    /** 等比例放大 */
    ImageActionKey["ZOOM_IN"] = "zoomIn";
    /** 等比例缩小 */
    ImageActionKey["ZOOM_OUT"] = "zoomOut";
    /** 恢复原图缩放比例尺 */
    ImageActionKey["SCALE_ORIGIN"] = "scaleOrigin";
})(ImageActionKey || (ImageActionKey = {}));
var ImageGallery = /** @class */ (function (_super) {
    __extends(ImageGallery, _super);
    function ImageGallery() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.state = {
            isOpened: false,
            index: -1,
            items: [],
            tx: 0,
            ty: 0,
            scale: 1,
            rotate: 0,
            showToolbar: false,
            imageGallaryClassName: '',
            actions: ImageGallery.defaultProps.actions
        };
        _this.startX = 0;
        _this.startY = 0;
        _this.startTx = 0;
        _this.startTy = 0;
        _this.handleToolbarAction = debounce(function (action) {
            if (action.disabled) {
                return;
            }
            switch (action.key) {
                case ImageActionKey.ROTATE_LEFT:
                    _this.setState(function (prevState) { return ({
                        rotate: prevState.rotate - 90,
                        tx: 0,
                        ty: 0
                    }); });
                    break;
                case ImageActionKey.ROTATE_RIGHT:
                    _this.setState(function (prevState) { return ({
                        rotate: prevState.rotate + 90,
                        tx: 0,
                        ty: 0
                    }); });
                    break;
                case ImageActionKey.ZOOM_IN:
                    _this.setState(function (prevState) { return ({
                        scale: prevState.scale + 0.5,
                        tx: 0,
                        ty: 0
                    }); });
                    break;
                case ImageActionKey.ZOOM_OUT:
                    _this.setState(function (prevState) {
                        return prevState.scale - 0.5 > 0
                            ? { scale: prevState.scale - 0.5, tx: 0, ty: 0 }
                            : null;
                    });
                    break;
                case ImageActionKey.SCALE_ORIGIN:
                    _this.setState(function () { return ({ scale: 1, tx: 0, ty: 0 }); });
                    break;
            }
            if (action.onClick && typeof action.onClick === 'function') {
                action.onClick(_this);
            }
        }, 250, { leading: true, trailing: false });
        _this.scrollBar = React__default.createRef();
        return _this;
    }
    ImageGallery.prototype.galleryMainRef = function (ref) {
        var _a, _b;
        if (ref) {
            ref.addEventListener('wheel', this.onWheelScroll, {
                passive: false
            });
            ref.addEventListener('mousedown', this.onMouseDown);
        }
        else {
            (_a = this.galleryMain) === null || _a === void 0 ? void 0 : _a.removeEventListener('wheel', this.onWheelScroll);
            (_b = this.galleryMain) === null || _b === void 0 ? void 0 : _b.removeEventListener('mousedown', this.onMouseDown);
        }
        this.galleryMain = ref;
    };
    ImageGallery.prototype.onWheelScroll = function (event) {
        var _a;
        var showToolbar = (_a = this.state) === null || _a === void 0 ? void 0 : _a.showToolbar;
        if (!showToolbar) {
            return;
        }
        event.preventDefault();
        /** 向上滚动放大，向下滚动缩小 */
        if (event.deltaY > 0) {
            this.handleToolbarAction({ key: 'zoomOut' });
        }
        else if (event.deltaY < 0) {
            this.handleToolbarAction({ key: 'zoomIn' });
        }
    };
    ImageGallery.prototype.onMouseDown = function (event) {
        var _a;
        var isLeftButton = (event.button === 1 && window.event !== null) || event.button === 0;
        if (!isLeftButton || event.defaultPrevented)
            return;
        event.preventDefault();
        (_a = this.galleryMain) === null || _a === void 0 ? void 0 : _a.classList.add('is-dragging');
        document.body.addEventListener('mousemove', this.onMouseMove);
        document.body.addEventListener('mouseup', this.onMouseUp);
        this.startX = event.clientX;
        this.startY = event.clientY;
        this.startTx = this.state.tx;
        this.startTy = this.state.ty;
    };
    ImageGallery.prototype.onMouseMove = function (event) {
        this.setState({
            tx: this.startTx + event.clientX - this.startX,
            ty: this.startTy + event.clientY - this.startY
        });
    };
    ImageGallery.prototype.onMouseUp = function () {
        var _a;
        (_a = this.galleryMain) === null || _a === void 0 ? void 0 : _a.classList.remove('is-dragging');
        document.body.removeEventListener('mousemove', this.onMouseMove);
        document.body.removeEventListener('mouseup', this.onMouseUp);
    };
    ImageGallery.prototype.handleImageEnlarge = function (info) {
        var actions = this.props.actions;
        var validActionKeys = Object.values(ImageActionKey);
        this.setState({
            isOpened: true,
            tx: 0,
            ty: 0,
            rotate: 0,
            scale: 1,
            items: info.list ? info.list : [info],
            index: info.index || 0,
            /* children组件可以控制工具栏的展示 */
            showToolbar: !!info.showToolbar,
            enlargeWithGallary: info.enlargeWithGallary,
            imageGallaryClassName: info.imageGallaryClassName,
            /** 外部传入合法key值的actions才会生效 */
            actions: Array.isArray(info.toolbarActions)
                ? info.toolbarActions.filter(function (action) {
                    return validActionKeys.includes(action === null || action === void 0 ? void 0 : action.key);
                })
                : actions,
            scrollBarLeading: true,
            scrollBarTrailing: false
        });
    };
    ImageGallery.prototype.resetImageAction = function () {
        this.setState({ scale: 1, rotate: 0 });
    };
    ImageGallery.prototype.close = function () {
        this.setState({
            isOpened: false
        });
        this.resetImageAction();
    };
    ImageGallery.prototype.prev = function () {
        var index = this.state.index;
        this.setState({ index: index - 1 });
        this.resetImageAction();
    };
    ImageGallery.prototype.next = function () {
        var index = this.state.index;
        this.setState({ index: index + 1 });
        this.resetImageAction();
    };
    ImageGallery.prototype.handleItemClick = function (e) {
        var index = parseInt(e.currentTarget.getAttribute('data-index'), 10);
        this.setState({ index: index });
        this.resetImageAction();
    };
    ImageGallery.prototype.handleModalEntered = function () {
        if (this.scrollBar.current) {
            var item = this.scrollBar.current.querySelector("div[data-index=\"".concat(this.state.index, "\"]"));
            item === null || item === void 0 ? void 0 : item.scrollIntoView({
                behavior: 'smooth'
            });
        }
    };
    ImageGallery.prototype.handleBarScroll = function () {
        var scrollBar = this.scrollBar.current;
        var inner = scrollBar.firstElementChild;
        this.setState({
            scrollBarLeading: scrollBar.scrollLeft === 0,
            scrollBarTrailing: scrollBar.offsetWidth + scrollBar.scrollLeft >= inner.offsetWidth
        });
    };
    ImageGallery.prototype.scroll = function (direction) {
        if (direction === void 0) { direction = 1; }
        var scrollBar = this.scrollBar.current;
        var inner = scrollBar.firstElementChild;
        var gap = inner.offsetWidth - scrollBar.offsetWidth;
        scrollBar.scrollTo({
            left: scrollBar.scrollLeft + gap * 0.1 * direction,
            top: 0,
            behavior: 'smooth'
        });
        var timer = setInterval(function () {
            scrollBar.scrollTo({
                left: scrollBar.scrollLeft + 5 * direction,
                top: 0,
                behavior: 'smooth'
            });
        }, 50);
        var onMouseUp = function () {
            document.body.removeEventListener('mouseup', onMouseUp);
            clearInterval(timer);
        };
        document.body.addEventListener('mouseup', onMouseUp);
    };
    ImageGallery.prototype.scrollRight = function () {
        this.scroll(1);
    };
    ImageGallery.prototype.scrollLeft = function () {
        this.scroll(-1);
    };
    ImageGallery.prototype.renderToolbar = function (actions) {
        var _this = this;
        var _a = this.props, cx = _a.classnames, __ = _a.translate, className = _a.className;
        var scale = this.state.scale;
        return (React__default.createElement("div", { className: cx('ImageGallery-toolbar', className) }, actions.map(function (action) { return (React__default.createElement("div", { className: cx('ImageGallery-toolbar-action', {
                'is-disabled': action.disabled ||
                    (action.key === ImageActionKey.ZOOM_OUT && scale - 0.5 <= 0)
            }), key: action.key, onClick: function () { return _this.handleToolbarAction(action); } },
            React__default.createElement("a", { className: cx('ImageGallery-toolbar-action-icon'), "data-tooltip": __(action.label), "data-position": "top" }, React__default.isValidElement(action.icon) ? (React__default.cloneElement(action.icon, {
                className: cx('icon', action.iconClassName)
            })) : (React__default.createElement(Icon, { icon: action.icon, className: cx('icon', action.iconClassName) }))))); })));
    };
    ImageGallery.prototype.render = function () {
        var _this = this;
        var _a = this.props, children = _a.children, cx = _a.classnames, modalContainer = _a.modalContainer;
        var _b = this.state, index = _b.index, items = _b.items, rotate = _b.rotate, scale = _b.scale, tx = _b.tx, ty = _b.ty, showToolbar = _b.showToolbar, enlargeWithGallary = _b.enlargeWithGallary, actions = _b.actions, imageGallaryClassName = _b.imageGallaryClassName, scrollBarLeading = _b.scrollBarLeading, scrollBarTrailing = _b.scrollBarTrailing;
        var __ = this.props.translate;
        return (React__default.createElement(React__default.Fragment, null,
            React__default.cloneElement(children, {
                onImageEnlarge: this.handleImageEnlarge
            }),
            React__default.createElement(FinalModal, { closeOnEsc: true, closeOnOutside: true, size: "full", onHide: this.close, show: this.state.isOpened, contentClassName: cx('ImageGallery', imageGallaryClassName), container: modalContainer, onEntered: this.handleModalEntered },
                React__default.createElement("a", { "data-tooltip": __('Dialog.close'), "data-position": "left", className: cx('ImageGallery-close'), onClick: this.close },
                    React__default.createElement(Icon, { icon: "close", className: "icon" })),
                ~index && items[index] ? (React__default.createElement(React__default.Fragment, null,
                    React__default.createElement("div", { className: cx('ImageGallery-title') }, items[index].title),
                    items[index].caption ? (React__default.createElement("div", { className: cx('ImageGallery-caption') }, items[index].caption)) : null,
                    React__default.createElement("div", { className: cx('ImageGallery-main'), ref: this.galleryMainRef },
                        React__default.createElement("img", { draggable: false, src: items[index].originalSrc, style: {
                                transform: "translate(".concat(tx, "px, ").concat(ty, "px) scale(").concat(scale, ") rotate(").concat(rotate, "deg)")
                            } }),
                        showToolbar && Array.isArray(actions) && actions.length > 0
                            ? this.renderToolbar(actions)
                            : null,
                        items.length > 1 && enlargeWithGallary !== false ? (React__default.createElement(React__default.Fragment, null,
                            React__default.createElement("a", { className: cx('ImageGallery-prevBtn', index <= 0 ? 'is-disabled' : ''), onClick: this.prev },
                                React__default.createElement(Icon, { icon: "prev", className: "icon", iconContent: "ImageGallery-prevBtn" })),
                            React__default.createElement("a", { className: cx('ImageGallery-nextBtn', index >= items.length - 1 ? 'is-disabled' : ''), onClick: this.next },
                                React__default.createElement(Icon, { icon: "next", className: "icon", iconContent: "ImageGallery-nextBtn" })))) : null))) : null,
                items.length > 1 && enlargeWithGallary !== false ? (React__default.createElement("div", { className: cx('ImageGallery-footer') },
                    React__default.createElement("a", { className: cx('ImageGallery-prevList', scrollBarLeading ? 'is-disabled' : ''), onMouseDown: this.scrollLeft },
                        React__default.createElement(Icon, { icon: "prev", className: "icon" })),
                    React__default.createElement("div", { className: cx('ImageGallery-itemsWrap'), ref: this.scrollBar, onScroll: this.handleBarScroll },
                        React__default.createElement("div", { className: cx('ImageGallery-items') }, items.map(function (item, i) { return (React__default.createElement("div", { key: i, "data-index": i, onClick: _this.handleItemClick, className: cx('ImageGallery-item', i === index ? 'is-active' : '') },
                            React__default.createElement("img", { src: item.src }))); }))),
                    React__default.createElement("a", { className: cx('ImageGallery-nextList', scrollBarTrailing ? 'is-disabled' : ''), onMouseDown: this.scrollRight },
                        React__default.createElement(Icon, { icon: "next", className: "icon" })))) : null)));
    };
    ImageGallery.defaultProps = {
        actions: [
            {
                key: ImageActionKey.ROTATE_LEFT,
                icon: 'rotate-left',
                label: 'rotate.left'
            },
            {
                key: ImageActionKey.ROTATE_RIGHT,
                icon: 'rotate-right',
                label: 'rotate.right'
            },
            { key: ImageActionKey.ZOOM_IN, icon: 'zoom-in', label: 'zoomIn' },
            { key: ImageActionKey.ZOOM_OUT, icon: 'zoom-out', label: 'zoomOut' },
            {
                key: ImageActionKey.SCALE_ORIGIN,
                icon: 'scale-origin',
                label: 'scale.origin'
            }
        ]
    };
    __decorate([
        autobind,
        __metadata("design:type", Function),
        __metadata("design:paramtypes", [HTMLDivElement]),
        __metadata("design:returntype", void 0)
    ], ImageGallery.prototype, "galleryMainRef", null);
    __decorate([
        autobind,
        __metadata("design:type", Function),
        __metadata("design:paramtypes", [WheelEvent]),
        __metadata("design:returntype", void 0)
    ], ImageGallery.prototype, "onWheelScroll", null);
    __decorate([
        autobind,
        __metadata("design:type", Function),
        __metadata("design:paramtypes", [MouseEvent]),
        __metadata("design:returntype", void 0)
    ], ImageGallery.prototype, "onMouseDown", null);
    __decorate([
        autobind,
        __metadata("design:type", Function),
        __metadata("design:paramtypes", [MouseEvent]),
        __metadata("design:returntype", void 0)
    ], ImageGallery.prototype, "onMouseMove", null);
    __decorate([
        autobind,
        __metadata("design:type", Function),
        __metadata("design:paramtypes", []),
        __metadata("design:returntype", void 0)
    ], ImageGallery.prototype, "onMouseUp", null);
    __decorate([
        autobind,
        __metadata("design:type", Function),
        __metadata("design:paramtypes", [Object]),
        __metadata("design:returntype", void 0)
    ], ImageGallery.prototype, "handleImageEnlarge", null);
    __decorate([
        autobind,
        __metadata("design:type", Function),
        __metadata("design:paramtypes", []),
        __metadata("design:returntype", void 0)
    ], ImageGallery.prototype, "close", null);
    __decorate([
        autobind,
        __metadata("design:type", Function),
        __metadata("design:paramtypes", []),
        __metadata("design:returntype", void 0)
    ], ImageGallery.prototype, "prev", null);
    __decorate([
        autobind,
        __metadata("design:type", Function),
        __metadata("design:paramtypes", []),
        __metadata("design:returntype", void 0)
    ], ImageGallery.prototype, "next", null);
    __decorate([
        autobind,
        __metadata("design:type", Function),
        __metadata("design:paramtypes", [Object]),
        __metadata("design:returntype", void 0)
    ], ImageGallery.prototype, "handleItemClick", null);
    __decorate([
        autobind,
        __metadata("design:type", Function),
        __metadata("design:paramtypes", []),
        __metadata("design:returntype", void 0)
    ], ImageGallery.prototype, "handleModalEntered", null);
    __decorate([
        autobind,
        __metadata("design:type", Function),
        __metadata("design:paramtypes", []),
        __metadata("design:returntype", void 0)
    ], ImageGallery.prototype, "handleBarScroll", null);
    __decorate([
        autobind,
        __metadata("design:type", Function),
        __metadata("design:paramtypes", []),
        __metadata("design:returntype", void 0)
    ], ImageGallery.prototype, "scrollRight", null);
    __decorate([
        autobind,
        __metadata("design:type", Function),
        __metadata("design:paramtypes", []),
        __metadata("design:returntype", void 0)
    ], ImageGallery.prototype, "scrollLeft", null);
    return ImageGallery;
}(React__default.Component));
var ImageGallery$1 = themeable(localeable(ImageGallery));

export { ImageActionKey, ImageGallery, ImageGallery$1 as default };
