function _array_like_to_array(arr, len) {
    if (len == null || len > arr.length) len = arr.length;
    for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
    return arr2;
}
function _array_with_holes(arr) {
    if (Array.isArray(arr)) return arr;
}
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
    try {
        var info = gen[key](arg);
        var value = info.value;
    } catch (error) {
        reject(error);
        return;
    }
    if (info.done) {
        resolve(value);
    } else {
        Promise.resolve(value).then(_next, _throw);
    }
}
function _async_to_generator(fn) {
    return function() {
        var self = this, args = arguments;
        return new Promise(function(resolve, reject) {
            var gen = fn.apply(self, args);
            function _next(value) {
                asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
            }
            function _throw(err) {
                asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
            }
            _next(undefined);
        });
    };
}
function _define_property(obj, key, value) {
    if (key in obj) {
        Object.defineProperty(obj, key, {
            value: value,
            enumerable: true,
            configurable: true,
            writable: true
        });
    } else {
        obj[key] = value;
    }
    return obj;
}
function _iterable_to_array_limit(arr, i) {
    var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
    if (_i == null) return;
    var _arr = [];
    var _n = true;
    var _d = false;
    var _s, _e;
    try {
        for(_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true){
            _arr.push(_s.value);
            if (i && _arr.length === i) break;
        }
    } catch (err) {
        _d = true;
        _e = err;
    } finally{
        try {
            if (!_n && _i["return"] != null) _i["return"]();
        } finally{
            if (_d) throw _e;
        }
    }
    return _arr;
}
function _non_iterable_rest() {
    throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _sliced_to_array(arr, i) {
    return _array_with_holes(arr) || _iterable_to_array_limit(arr, i) || _unsupported_iterable_to_array(arr, i) || _non_iterable_rest();
}
function _unsupported_iterable_to_array(o, minLen) {
    if (!o) return;
    if (typeof o === "string") return _array_like_to_array(o, minLen);
    var n = Object.prototype.toString.call(o).slice(8, -1);
    if (n === "Object" && o.constructor) n = o.constructor.name;
    if (n === "Map" || n === "Set") return Array.from(n);
    if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
}
function _ts_generator(thisArg, body) {
    var f, y, t, _ = {
        label: 0,
        sent: function() {
            if (t[0] & 1) throw t[1];
            return t[1];
        },
        trys: [],
        ops: []
    }, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype), d = Object.defineProperty;
    return d(g, "next", {
        value: verb(0)
    }), d(g, "throw", {
        value: verb(1)
    }), d(g, "return", {
        value: verb(2)
    }), typeof Symbol === "function" && d(g, Symbol.iterator, {
        value: function() {
            return this;
        }
    }), g;
    function verb(n) {
        return function(v) {
            return step([
                n,
                v
            ]);
        };
    }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while(g && (g = 0, op[0] && (_ = 0)), _)try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [
                op[0] & 2,
                t.value
            ];
            switch(op[0]){
                case 0:
                case 1:
                    t = op;
                    break;
                case 4:
                    _.label++;
                    return {
                        value: op[1],
                        done: false
                    };
                case 5:
                    _.label++;
                    y = op[1];
                    op = [
                        0
                    ];
                    continue;
                case 7:
                    op = _.ops.pop();
                    _.trys.pop();
                    continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
                        _ = 0;
                        continue;
                    }
                    if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
                        _.label = op[1];
                        break;
                    }
                    if (op[0] === 6 && _.label < t[1]) {
                        _.label = t[1];
                        t = op;
                        break;
                    }
                    if (t && _.label < t[2]) {
                        _.label = t[2];
                        _.ops.push(op);
                        break;
                    }
                    if (t[2]) _.ops.pop();
                    _.trys.pop();
                    continue;
            }
            op = body.call(thisArg, _);
        } catch (e) {
            op = [
                6,
                e
            ];
            y = 0;
        } finally{
            f = t = 0;
        }
        if (op[0] & 5) throw op[1];
        return {
            value: op[0] ? op[1] : void 0,
            done: true
        };
    }
}
import { FileSearch, Play } from "@sofa-design/icons";
import { ConfigProvider, Image, Modal } from "antd";
import classNames from "clsx";
import { motion } from "framer-motion";
import React, { useContext, useMemo, useState } from "react";
import { isImageFile, isVideoFile } from "../AttachmentButton/utils";
import { FileMapViewItem } from "./FileMapViewItem";
import { useStyle } from "./style";
/**
 * FileMapView 组件 - 文件映射视图组件
 *
 * 该组件用于显示文件列表，支持图片预览、文件下载、文件预览等功能。
 * 根据文件类型提供不同的显示方式，图片文件以网格形式显示，其他文件以列表形式显示。
 *
 * @component
 * @description 文件映射视图组件，显示文件列表和预览功能
 * @param {FileMapViewProps} props - 组件属性
 * @param {Map<string, AttachmentFile>} props.fileMap - 文件映射表
 * @param {string} [props.className] - 自定义CSS类名
 * @param {React.CSSProperties} [props.style] - 自定义样式
 * @param {(file: AttachmentFile) => void} [props.onFileClick] - 文件点击回调
 * @param {(file: AttachmentFile) => void} [props.onPreview] - 文件预览回调
 * @param {(file: AttachmentFile) => void} [props.onDownload] - 文件下载回调
 * @param {boolean} [props.collapsible] - 是否可折叠
 * @param {number} [props.maxDisplayCount] - 最大显示数量
 *
 * @example
 * ```tsx
 * <FileMapView
 *   fileMap={fileMap}
 *   onFileClick={(file) => console.log('点击文件', file)}
 *   onPreview={(file) => console.log('预览文件', file)}
 *   onDownload={(file) => console.log('下载文件', file)}
 * />
 * ```
 *
 * @returns {React.ReactElement} 渲染的文件映射视图组件
 *
 * @remarks
 * - 支持图片文件的网格预览
 * - 支持其他文件类型的列表显示
 * - 提供文件预览和下载功能
 * - 支持文件列表折叠
 * - 提供动画效果
 * - 自动识别文件类型
 * - 支持自定义样式和交互
 */ export var FileMapView = function FileMapView(props) {
    var _props_style;
    var _props_placement = props.placement, placement = _props_placement === void 0 ? 'left' : _props_placement;
    var context = useContext(ConfigProvider.ConfigContext);
    var prefix = context === null || context === void 0 ? void 0 : context.getPrefixCls('agentic-md-editor-file-view-list');
    var _useStyle = useStyle(prefix), wrapSSR = _useStyle.wrapSSR, hashId = _useStyle.hashId;
    var _useState = _sliced_to_array(useState(false), 2), showAllFiles = _useState[0], setShowAllFiles = _useState[1];
    var fileList = useMemo(function() {
        var _props_fileMap;
        if (!props.fileMap) {
            return [];
        }
        return Array.from(((_props_fileMap = props.fileMap) === null || _props_fileMap === void 0 ? void 0 : _props_fileMap.values()) || []);
    }, [
        props.fileMap
    ]);
    // 图片列表不受 maxDisplayCount 限制，显示所有图片
    var imgList = useMemo(function() {
        return fileList.filter(function(file) {
            return isImageFile(file);
        });
    }, [
        fileList
    ]);
    // 视频列表，与图片一样以缩略图形式展示
    var videoList = useMemo(function() {
        return fileList.filter(function(file) {
            return isVideoFile(file);
        });
    }, [
        fileList
    ]);
    // 所有非图片、非视频文件列表
    var allNoMediaFiles = useMemo(function() {
        return fileList.filter(function(file) {
            return !isImageFile(file) && !isVideoFile(file);
        });
    }, [
        fileList
    ]);
    // 根据 maxDisplayCount 限制显示的非媒体文件列表
    var noMediaFileList = useMemo(function() {
        if (showAllFiles || props.maxDisplayCount === undefined) {
            return allNoMediaFiles;
        }
        return allNoMediaFiles.slice(0, Math.max(0, props.maxDisplayCount));
    }, [
        allNoMediaFiles,
        props.maxDisplayCount,
        showAllFiles
    ]);
    var _useState1 = _sliced_to_array(useState(false), 2), videoModalOpen = _useState1[0], setVideoModalOpen = _useState1[1];
    var _useState2 = _sliced_to_array(useState(null), 2), previewingVideo = _useState2[0], setPreviewingVideo = _useState2[1];
    var handleVideoClick = function handleVideoClick(file) {
        if (file.status === 'error') return;
        if (props.onPreview) {
            props.onPreview(file);
        } else {
            setPreviewingVideo(file);
            setVideoModalOpen(true);
        }
    };
    var handleVideoModalClose = function handleVideoModalClose() {
        setVideoModalOpen(false);
        setPreviewingVideo(null);
    };
    var handleViewAllClick = function handleViewAllClick() {
        return _async_to_generator(function() {
            var shouldExpand;
            return _ts_generator(this, function(_state) {
                switch(_state.label){
                    case 0:
                        if (!props.onViewAll) return [
                            3,
                            2
                        ];
                        return [
                            4,
                            props.onViewAll(fileList)
                        ];
                    case 1:
                        shouldExpand = _state.sent();
                        if (shouldExpand) {
                            setShowAllFiles(true);
                        }
                        return [
                            3,
                            3
                        ];
                    case 2:
                        // 如果没有提供 onViewAll 回调，默认展开所有文件
                        setShowAllFiles(true);
                        _state.label = 3;
                    case 3:
                        return [
                            2
                        ];
                }
            });
        })();
    };
    var _obj;
    return wrapSSR(/*#__PURE__*/ React.createElement("div", {
        style: {
            display: 'flex',
            flexDirection: 'column',
            gap: 4,
            maxWidth: '100%',
            minWidth: 0,
            alignItems: placement === 'left' ? 'flex-start' : 'flex-end',
            width: 'max-content'
        }
    }, /*#__PURE__*/ React.createElement(motion.div, {
        variants: {
            visible: {
                opacity: 1,
                transition: {
                    when: 'beforeChildren',
                    staggerChildren: 0.1
                }
            },
            hidden: {
                opacity: 0,
                transition: {
                    when: 'afterChildren'
                }
            }
        },
        whileInView: "visible",
        initial: "hidden",
        animate: 'visible',
        style: props.style,
        className: classNames(prefix, hashId, props.className, "".concat(prefix, "-").concat(placement), (_obj = {}, _define_property(_obj, "".concat(prefix, "-image-list-view"), imgList.length > 1), _define_property(_obj, "".concat(prefix, "-image-list-view-").concat(placement), imgList.length > 1), _obj))
    }, /*#__PURE__*/ React.createElement(Image.PreviewGroup, null, imgList.map(function(file, index) {
        return /*#__PURE__*/ React.createElement(Image, {
            rootClassName: classNames("".concat(prefix, "-image"), hashId),
            width: 124,
            height: 124,
            src: file.previewUrl || file.url,
            key: file.uuid || file.name || index
        });
    }))), videoList.length > 0 && /*#__PURE__*/ React.createElement(motion.div, {
        variants: {
            visible: {
                opacity: 1
            },
            hidden: {
                opacity: 0
            }
        },
        whileInView: "visible",
        initial: "hidden",
        animate: "visible",
        className: classNames("".concat(prefix, "-video-row"), "".concat(prefix, "-video-row-").concat(placement), hashId),
        style: props.style
    }, videoList.map(function(file, index) {
        var videoUrl = file.previewUrl || file.url || '';
        var isSingleVideo = videoList.length === 1;
        var thumbSize = isSingleVideo ? {
            width: 330,
            height: 188
        } : {
            width: 124,
            height: 124
        };
        return /*#__PURE__*/ React.createElement("div", {
            role: "button",
            tabIndex: 0,
            className: classNames("".concat(prefix, "-image"), "".concat(prefix, "-video-thumb"), hashId),
            key: file.uuid || file.name || index,
            onClick: function onClick() {
                return handleVideoClick(file);
            },
            onKeyDown: function onKeyDown(e) {
                if (e.key === 'Enter' || e.key === ' ') {
                    e.preventDefault();
                    handleVideoClick(file);
                }
            },
            "aria-label": "播放视频：".concat(file.name),
            style: thumbSize
        }, /*#__PURE__*/ React.createElement("video", {
            src: videoUrl,
            preload: "metadata",
            muted: true,
            playsInline: true,
            style: {
                width: '100%',
                height: '100%',
                objectFit: 'cover'
            }
        }), /*#__PURE__*/ React.createElement("div", {
            className: classNames("".concat(prefix, "-video-play-overlay"), hashId),
            "aria-hidden": true
        }, /*#__PURE__*/ React.createElement(Play, null)));
    })), /*#__PURE__*/ React.createElement(Modal, {
        open: videoModalOpen,
        onCancel: handleVideoModalClose,
        footer: null,
        width: "auto",
        centered: true,
        destroyOnClose: true,
        styles: {
            body: {
                padding: 0
            }
        }
    }, previewingVideo && /*#__PURE__*/ React.createElement("video", {
        src: previewingVideo.previewUrl || previewingVideo.url,
        controls: true,
        autoPlay: true,
        style: {
            maxWidth: '80vw',
            maxHeight: '80vh'
        }
    })), /*#__PURE__*/ React.createElement(motion.div, {
        variants: {
            visible: {
                opacity: 1,
                transition: {
                    when: 'beforeChildren',
                    staggerChildren: 0.1
                }
            },
            hidden: {
                opacity: 0,
                transition: {
                    when: 'afterChildren'
                }
            }
        },
        whileInView: "visible",
        initial: "hidden",
        animate: 'visible',
        className: classNames(prefix, hashId, props.className, "".concat(prefix, "-").concat(placement), "".concat(prefix, "-vertical")),
        style: props.style
    }, noMediaFileList.map(function(file, index) {
        var _props_style;
        return /*#__PURE__*/ React.createElement(FileMapViewItem, {
            style: {
                width: (_props_style = props.style) === null || _props_style === void 0 ? void 0 : _props_style.width
            },
            onPreview: props.onPreview ? function() {
                var _props_onPreview;
                (_props_onPreview = props.onPreview) === null || _props_onPreview === void 0 ? void 0 : _props_onPreview.call(props, file);
            } : undefined,
            onDownload: props.onDownload ? function() {
                var _props_onDownload;
                (_props_onDownload = props.onDownload) === null || _props_onDownload === void 0 ? void 0 : _props_onDownload.call(props, file);
            } : undefined,
            renderMoreAction: props.renderMoreAction,
            customSlot: props.customSlot,
            key: (file === null || file === void 0 ? void 0 : file.uuid) || (file === null || file === void 0 ? void 0 : file.name) || index,
            prefixCls: "".concat(prefix, "-item"),
            hashId: hashId,
            className: classNames(hashId, "".concat(prefix, "-item")),
            file: file
        });
    }), props.maxDisplayCount !== undefined && allNoMediaFiles.length > props.maxDisplayCount && !showAllFiles ? /*#__PURE__*/ React.createElement("div", {
        style: {
            width: (_props_style = props.style) === null || _props_style === void 0 ? void 0 : _props_style.width
        },
        className: classNames(hashId, "".concat(prefix, "-more-file-container")),
        onClick: handleViewAllClick
    }, /*#__PURE__*/ React.createElement(FileSearch, {
        color: "var(--color-gray-text-secondary)"
    }), /*#__PURE__*/ React.createElement("div", {
        className: classNames(hashId, "".concat(prefix, "-more-file-name"))
    }, /*#__PURE__*/ React.createElement("span", {
        style: {
            whiteSpace: 'nowrap'
        }
    }, "查看此任务中的所有文件"))) : null)));
};
