import { _ as _object_spread } from "@swc/helpers/_/_object_spread";
import { _ as _object_spread_props } from "@swc/helpers/_/_object_spread_props";
import { _ as _sliced_to_array } from "@swc/helpers/_/_sliced_to_array";
import React, { useEffect, useState, useRef } from "react";
import classNames from "classnames";
import { Close } from "@nutui/icons-react";
import Popup from "../popup";
import Image from "../image";
import Video from "../video";
import Swiper from "../swiper";
import SwiperItem from "../swiperitem";
import { ComponentDefaults } from "../../utils/typings";
import { usePropsValue } from "../../hooks/use-props-value";
var defaultProps = _object_spread_props(_object_spread({}, ComponentDefaults), {
    images: [],
    videos: [],
    visible: false,
    autoPlay: 3000,
    defaultValue: 0,
    closeOnContentClick: false,
    pagination: true,
    indicator: false,
    indicatorColor: '#fff',
    closeIcon: false,
    closeIconPosition: 'top-right',
    onChange: function(value) {},
    onClose: function() {}
});
export var ImagePreview = function(props) {
    var _$_object_spread = _object_spread({}, defaultProps, props), value = _$_object_spread.value, className = _$_object_spread.className, style = _$_object_spread.style, images = _$_object_spread.images, videos = _$_object_spread.videos, visible = _$_object_spread.visible, defaultValue = _$_object_spread.defaultValue, indicatorColor = _$_object_spread.indicatorColor, pagination = _$_object_spread.pagination, indicator = _$_object_spread.indicator, autoPlay = _$_object_spread.autoPlay, closeOnContentClick = _$_object_spread.closeOnContentClick, closeIcon = _$_object_spread.closeIcon, closeIconPosition = _$_object_spread.closeIconPosition, onClose = _$_object_spread.onClose, onChange = _$_object_spread.onChange;
    var classPrefix = 'nut-imagepreview';
    var ref = useRef(null);
    var _usePropsValue = _sliced_to_array(usePropsValue({
        value: value,
        defaultValue: defaultValue,
        finalValue: defaultValue,
        onChange: function(val) {
            onChange === null || onChange === void 0 ? void 0 : onChange(val);
        }
    }), 2), innerNo = _usePropsValue[0], setInnerNo = _usePropsValue[1];
    var _useState = _sliced_to_array(useState(visible), 2), showPop = _useState[0], setShowPop = _useState[1];
    var _useState1 = _sliced_to_array(useState(0), 2), active = _useState1[0], setActive = _useState1[1];
    var _useState2 = _sliced_to_array(useState((images === null || images === void 0 ? void 0 : images.length) || 0 + ((videos === null || videos === void 0 ? void 0 : videos.length) || 0)), 2), maxNo = _useState2[0], setMaxNo = _useState2[1];
    var _useState3 = _sliced_to_array(useState({
        scale: 1,
        moveable: false
    }), 2), store = _useState3[0], setStore = _useState3[1];
    var _useState4 // 用来辅助监听双击
     = _sliced_to_array(useState(0), 2), lastTouchEndTime = _useState4[0], setLastTouchEndTime = _useState4[1];
    var onTouchStart = function(event) {
        var touches = event.touches;
        var events = touches[0];
        var events2 = touches[1];
        // 如果已经放大，双击应变回原尺寸；如果是原尺寸，双击应放大
        var curTouchTime = new Date().getTime();
        if (curTouchTime - lastTouchEndTime < 300) {
            var store1 = store;
            if (store1.scale > 1) {
                store1.scale = 1;
            } else if (store1.scale === 1) {
                store1.scale = 2;
            }
            scaleNow();
        }
        var store11 = store;
        store11.moveable = true;
        if (events2) {
            // 如果开始两指操作，记录初始时刻两指间的距离
            store11.oriDistance = getDistance({
                x: events.pageX,
                y: events.pageY
            }, {
                x: events2.pageX,
                y: events2.pageY
            });
        }
        // 取到开始两指操作时的放大（缩小比例），store.scale 存储的是当前的放缩比（相对于标准大小 scale 为 1 的情况的放大缩小比）
        store11.originScale = store11.scale || 1;
    };
    var onTouchMove = function(event) {
        var touches = event.touches;
        var events = touches[0];
        var events2 = touches[1];
        if (!store.moveable) {
            return;
        }
        var store1 = store;
        // 双指移动
        if (events2) {
            // 获得当前两点间的距离
            var curDistance = getDistance({
                x: events.pageX,
                y: events.pageY
            }, {
                x: events2.pageX,
                y: events2.pageY
            });
            /** 此处计算倍数，距离放大（缩小） k 倍则 scale 也 扩大（缩小） k 倍。距离放大（缩小）倍数 = 结束时两点距离 除以 开始时两点距离
       * 注意此处的 scale 变化是基于 store.scale 的。
       * store.scale 是一个暂存值，比如第一次放大 2 倍，则 store.scale 为 2。
       * 再次两指触碰的时候，store.originScale 就为 store.scale 的值，基于此时的 store.scale 继续放大缩小。 * */ var curScale = curDistance / store1.oriDistance;
            store1.scale = store1.originScale * curScale;
            // 最大放大 3 倍，缩小后松手要弹回原比例
            if (store1.scale > 3) {
                store1.scale = 3;
            }
            scaleNow();
        }
    };
    var onTouchEnd = function() {
        setLastTouchEndTime(new Date().getTime());
        var store1 = store;
        store1.moveable = false;
        if (store1.scale < 1.1 && store1.scale > 1 || store1.scale < 1) {
            store1.scale = 1;
            scaleNow();
        }
    };
    useEffect(function() {
        init();
    }, []);
    var init = function() {
        document.addEventListener('touchmove', onTouchMove);
        document.addEventListener('touchend', onTouchEnd);
        document.addEventListener('touchcancel', onTouchEnd);
    };
    useEffect(function() {
        setShowPop(visible);
    }, [
        visible
    ]);
    useEffect(function() {
        setInnerNo(defaultValue || 1);
    }, [
        defaultValue
    ]);
    useEffect(function() {
        setActive(innerNo);
    }, [
        innerNo
    ]);
    useEffect(function() {
        setMaxNo((images === null || images === void 0 ? void 0 : images.length) || 0 + ((videos === null || videos === void 0 ? void 0 : videos.length) || 0));
    }, [
        images,
        videos
    ]);
    var scaleNow = function() {
        if (ref.current) {
            ;
            ref.current.style.transform = "scale(".concat(store.scale, ")");
        }
    };
    // 计算两个点的距离
    var getDistance = function(first, second) {
        // 计算两个点起始时刻的距离和终止时刻的距离，终止时刻距离变大了则放大，变小了则缩小
        // 放大 k 倍则 scale 也 扩大 k 倍
        return Math.hypot(Math.abs(second.x - first.x), Math.abs(second.y - first.y));
    };
    var slideChangeEnd = function(page) {
        setActive(page + 1);
        onChange === null || onChange === void 0 ? void 0 : onChange(page + 1);
    };
    var onCloseInner = function(e) {
        e.stopPropagation();
        setShowPop(false);
        setActive(innerNo);
        scaleNow();
        onClose && onClose();
        setStore(_object_spread_props(_object_spread({}, store), {
            scale: 1
        }));
    };
    var closeOnImg = function(e) {
        e.stopPropagation();
        // 点击内容区域的图片是否可以关闭弹层（视频区域由于nut-video做了限制，无法关闭弹层）
        if (closeOnContentClick) {
            onCloseInner(e);
        }
    };
    var duration = typeof autoPlay === 'string' ? parseInt(autoPlay) : autoPlay;
    return /*#__PURE__*/ React.createElement(Popup, {
        visible: showPop,
        className: "".concat(classPrefix, "-pop"),
        style: {
            width: '100%'
        },
        onClick: onCloseInner
    }, /*#__PURE__*/ React.createElement("div", {
        className: classNames(classPrefix, className),
        style: style,
        ref: ref,
        onTouchStart: onTouchStart
    }, showPop ? /*#__PURE__*/ React.createElement(Swiper, {
        autoPlay: !!duration,
        duration: duration,
        className: "".concat(classPrefix, "-swiper"),
        loop: true,
        style: {
            '--nutui-indicator-color': indicatorColor
        },
        direction: "horizontal",
        onChange: function(page) {
            return slideChangeEnd(page);
        },
        defaultValue: innerNo && (innerNo > maxNo ? maxNo - 1 : innerNo - 1),
        indicator: indicator
    }, (videos !== null && videos !== void 0 ? videos : []).map(function(item) {
        return {
            type: 'video',
            data: item
        };
    }).concat((images !== null && images !== void 0 ? images : []).map(function(item) {
        return {
            type: 'image',
            data: item
        };
    })).sort(function(a, b) {
        var _a_data, _b_data;
        var _a_data_index, _b_data_index;
        return ((_a_data_index = (_a_data = a.data) === null || _a_data === void 0 ? void 0 : _a_data.index) !== null && _a_data_index !== void 0 ? _a_data_index : 0) - ((_b_data_index = (_b_data = b.data) === null || _b_data === void 0 ? void 0 : _b_data.index) !== null && _b_data_index !== void 0 ? _b_data_index : 0);
    }).map(function(item, index) {
        if (item.type === 'video') {
            var _item_data = item.data, source = _item_data.source, options = _item_data.options;
            return /*#__PURE__*/ React.createElement(SwiperItem, {
                key: index
            }, /*#__PURE__*/ React.createElement(Video, {
                source: source,
                options: options,
                onClick: closeOnImg
            }));
        }
        if (item.type === 'image') {
            var src = item.data.src;
            return /*#__PURE__*/ React.createElement(SwiperItem, {
                key: index
            }, /*#__PURE__*/ React.createElement(Image, {
                src: src,
                draggable: false,
                onClick: closeOnImg
            }));
        }
        return null;
    })) : null), pagination ? /*#__PURE__*/ React.createElement("div", {
        className: "".concat(classPrefix, "-index")
    }, active, "/", (images ? images.length : 0) + (videos ? videos.length : 0)) : null, closeIcon !== false ? /*#__PURE__*/ React.createElement("div", {
        className: "".concat(classPrefix, "-close ").concat(closeIconPosition),
        onClick: onCloseInner
    }, closeIcon === true ? /*#__PURE__*/ React.createElement(Close, null) : closeIcon) : null);
};
ImagePreview.displayName = 'NutImagePreview';
