import React from 'react';
import p from 'prefix-classname';
import { Input, Empty, Image, Tabs, Typography, Spin, Popover } from 'antd';
import { useDrag } from 'react-dnd';
import Fuse from 'fuse.js';
import { SearchOutlined, InfoCircleOutlined } from '@ant-design/icons';
import { CLS_PREFIX } from '../../../config/const';
import './style.scss';
import { useHeaderStatus } from '../header';
const cn = p('');
const c = p(`${CLS_PREFIX}-material-panel`);
const PreviewRender = ({ runtime }) => {
    const containerRef = React.useRef();
    React.useEffect(() => {
        var _a;
        const render = (_a = runtime === null || runtime === void 0 ? void 0 : runtime.previewRender) !== null && _a !== void 0 ? _a : runtime === null || runtime === void 0 ? void 0 : runtime.__fallbackPreviewRender;
        const dispose = render(containerRef.current);
        if (dispose) {
            return dispose;
        }
    }, [runtime === null || runtime === void 0 ? void 0 : runtime.__fallbackPreviewRender, runtime === null || runtime === void 0 ? void 0 : runtime.previewRender]);
    return React.createElement("div", { ref: containerRef });
};
const InfoIcon = ({ runtime, homepage, name, key }) => {
    if (!runtime) {
        return null;
    }
    return (React.createElement(Popover, { trigger: ['click'], content: React.createElement(PreviewRender, { runtime: runtime }), onVisibleChange: (v) => { }, placement: 'rightBottom', overlayInnerStyle: { minWidth: 200, minHeight: 100 }, title: React.createElement("span", { style: { display: 'flex', justifyContent: 'space-between' } },
            React.createElement("span", null, `${name}${key ? `(${key})` : ''}`),
            !!homepage && (React.createElement("a", { style: { fontWeight: 'normal' }, href: homepage, target: '_blank' }, "\u67E5\u770B\u8BE6\u60C5"))) },
        React.createElement(InfoCircleOutlined, { style: { marginRight: 2, fontSize: 12 } })));
};
const AssetUI = React.memo((asset) => {
    const { homepage, cover, name, data, runtime } = asset;
    const item = React.useMemo(() => ({ cover, name, data }), [cover, name, data]);
    const [{ isDragging }, drag, preview] = useDrag(() => ({
        type: 'asset',
        item,
        end: (item, monitor) => { },
        collect: (monitor) => ({
            isDragging: monitor.isDragging()
        })
    }), [item]);
    const opacity = isDragging ? 0.4 : 1;
    const renderComp = ({ ref, opacity, style, className }) => {
        return (React.createElement("div", { ref: ref, className: c('__asset-group__cell', className), style: Object.assign({ opacity }, style) },
            React.createElement(Image, { preview: false, wrapperClassName: c('__asset-group__cell__img__wrapper'), className: c('__asset-group__cell__img'), src: cover }),
            React.createElement("span", { className: c('__asset-group__cell__name') },
                React.createElement(InfoIcon, Object.assign({}, asset)),
                React.createElement("span", { style: { display: 'inline-flex', padding: '2px 3px', fontSize: 12 }, ref: preview }, homepage && !runtime ? (React.createElement("a", { href: homepage, style: { lineHeight: 1 }, target: '_blank' }, name)) : (name)))));
    };
    // preview
    return renderComp({ ref: drag, opacity, className: isDragging && '-dragging' });
});
const AssetGroupComp = React.memo(({ assetGroup }) => {
    var _a;
    return (React.createElement("div", { className: c('__asset-group') },
        React.createElement("h4", null, assetGroup.name),
        React.createElement("div", { className: c('__asset-group__container') }, (_a = assetGroup.assets) === null || _a === void 0 ? void 0 : _a.map((asset) => {
            return React.createElement(AssetUI, Object.assign({}, asset));
        }))));
});
const MaterialUi = ({ mat }) => {
    const [input, setInput] = React.useState('');
    const [{ canSelect }] = useHeaderStatus();
    const assetGroups = React.useMemo(() => {
        if (!input || !input.trim()) {
            return mat.assetGroups;
        }
        if (!mat.assetGroups) {
            return [];
        }
        return mat.assetGroups
            .map((g) => {
            var _a;
            const fuse = new Fuse((_a = g.assets) !== null && _a !== void 0 ? _a : [], {
                keys: ['name', 'key'],
                includeScore: true,
                findAllMatches: true,
                threshold: 0.3,
                isCaseSensitive: false
            });
            return Object.assign(Object.assign({}, g), { assets: fuse.search(input.trim()).map((x) => x.item) });
        })
            .filter((g) => { var _a; return (_a = g.assets) === null || _a === void 0 ? void 0 : _a.length; });
    }, [input, mat === null || mat === void 0 ? void 0 : mat.assetGroups]);
    return (React.createElement(React.Fragment, null,
        React.createElement("div", { className: c('__search-wrapper') },
            React.createElement(Input, { value: input, onChange: (e) => {
                    setInput(e.target.value);
                }, suffix: React.createElement(SearchOutlined, null), className: c('__search'), placeholder: '输入关键字过滤物料' }),
            canSelect && React.createElement(Typography.Text, { type: 'secondary' }, "\u8BF7\u9009\u62E9\u4EE5\u4E0B\u7269\u6599\u62D6\u5165\u300C\u9875\u9762\u300D\u4E2D")),
        React.createElement("div", { className: c('__mp') }, assetGroups === null || assetGroups === void 0 ? void 0 : assetGroups.map((group, index) => {
            var _a;
            return (React.createElement(AssetGroupComp, { key: (_a = group.key) !== null && _a !== void 0 ? _a : index, assetGroup: group }));
        }))));
};
const MaterialPanel = React.memo(({ loading, className, materials }) => {
    return (React.createElement(Spin, { spinning: loading, delay: 200, className: cn(c(), className) },
        !(materials === null || materials === void 0 ? void 0 : materials.length) && React.createElement(Empty, { description: '暂无物料', style: { paddingTop: 40 } }),
        !!(materials === null || materials === void 0 ? void 0 : materials.length) && (React.createElement(Tabs, { className: c('__tabs') }, materials.map((mat, i) => {
            var _a;
            const matKey = (_a = mat.key) !== null && _a !== void 0 ? _a : i;
            return (React.createElement(Tabs.TabPane, { tab: mat.name, key: matKey },
                React.createElement(MaterialUi, { mat: mat })));
        })))));
});
MaterialPanel.defaultProps = {};
export default MaterialPanel;
//# sourceMappingURL=index.js.map