"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const react_1 = __importStar(require("react"));
const react_router_dom_1 = require("react-router-dom");
const icons_1 = require("@ant-design/icons");
const antd_1 = require("antd");
const styled_components_1 = __importDefault(require("styled-components"));
const index_1 = require("@/components/index");
const file_1 = require("@/constants/file");
const system_1 = require("@/pages/system");
const index_2 = require("@/utils/index");
const CONTENT_LIST = 'Content-list';
const MenuTitle = styled_components_1.default.a `
  display: flex;
  align-items: center;
  padding: 0 12px;
  color: #5b6b73;
  &:hover {
    color: #5b6b73;
    background: #f7f7f7;
  }
`;
const MenuTitleText = styled_components_1.default.span `
  display: inline-block;
  max-width: 280px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
`;
const Menu = styled_components_1.default.ul `
  width: 320px;
  max-height: 400px;
  overflow: auto;
  margin: 0;
  padding: 8px;
  list-style: none;
  background: #ffffff;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
`;
const MenuItem = styled_components_1.default.li `
  position: relative;
  display: flex;
  justify-content: flex-start;
  align-items: center;
  padding: 8px 16px;
  cursor: pointer;
  border-bottom: 1px dashed #e8e8e8;
  user-select: none;
  color: #000000d8;
  &:last-of-type {
    border-bottom: none;
  }
  &:hover {
    background: #f7f7f7;
  }
  &.active {
    background: #f2f8ff;
  }
  &.disabled {
    color: #00000040 !important;
    background: 0 0;
    cursor: not-allowed;
  }
  &.no-select {
    &:hover {
      color: inherit;
      background: inherit;
    }
  }
  a {
    color: #000000d8;
  }
`;
const MenuItemSlot = styled_components_1.default.div `
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
`;
const ContentName = styled_components_1.default.div `
  display: inline-block;
  margin-right: 12px;
  padding-left: 18px;
  width: 150px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  text-align: left;
`;
const Main = (props) => {
    const { root, applicationId, contentId, fileId: propsFileId, folderId, contentList = [], locale, selectContent, selectFoldStatus, setLocale, } = props;
    const [folderOpen, setFolderOpen] = (0, react_1.useState)(true);
    const [fileId, setFileId] = (0, react_1.useState)('');
    const { locale: i18n } = (0, react_1.useContext)(system_1.GlobalContext);
    (0, react_1.useEffect)(() => {
        if (propsFileId)
            setFileId(propsFileId);
    }, [propsFileId]);
    // expand current file by default
    (0, react_1.useEffect)(() => {
        if (fileId) {
            selectFoldStatus(fileId, false);
            // } else {
            // use first file when there is no file id in url search params
            // const defaultFile = contentList.find((item) => item.contents && item.contents.length > 0);
            // if (defaultFile) selectFoldStatus(defaultFile.id, false);
        }
    }, [fileId, selectFoldStatus]);
    // get current content
    const currentContent = (0, react_1.useMemo)(() => {
        const currentFile = (contentList && contentList.find((file) => file.id === fileId)) ||
            contentList.find((item) => item.contents && item.contents.length > 0);
        const currentFileContents = currentFile && currentFile.contents;
        return currentFileContents && currentFileContents.find((content) => content.id === contentId);
    }, [contentList, fileId, contentId]);
    const reSortList = (0, react_1.useCallback)((originList) => {
        const contentRecord = {};
        const extendRecord = {};
        const list = [];
        originList.forEach((item) => {
            if (item.isBase || !item.extendId) {
                list.push(item);
            }
            else {
                if (!contentRecord[item.extendId]) {
                    contentRecord[item.extendId] = [];
                }
                contentRecord[item.extendId].push(item);
                if (!extendRecord[item.extendId]) {
                    extendRecord[item.extendId] = [];
                }
                extendRecord[item.extendId].push(item.id);
            }
        });
        Object.keys(contentRecord).forEach((key) => {
            const children = contentRecord[key];
            if (children && children.length > 0) {
                const idx = list.findIndex((item) => item.id === key);
                list.splice(idx + 1, 0, ...children);
            }
        });
        return list;
    }, []);
    const handleSecondFolderClick = (menu) => {
        const { id, contents, fold } = menu;
        if (id && contents && contents.length > 0)
            selectFoldStatus(id, !fold);
    };
    const handlePopoverShow = (visible) => {
        if (contentId) {
            if (visible) {
                setTimeout(() => {
                    var _a;
                    (_a = document.getElementById(contentId)) === null || _a === void 0 ? void 0 : _a.scrollIntoView({ behavior: 'smooth', block: 'center' });
                }, 100);
            }
        }
    };
    const iconStyle = {
        marginRight: 4,
        transform: 'scale(0.8)',
    };
    const menu = (react_1.default.createElement(Menu, { id: CONTENT_LIST },
        react_1.default.createElement(MenuItem, { onClick: () => {
                setFolderOpen(!folderOpen);
            }, style: { paddingLeft: 2 } },
            react_1.default.createElement(icons_1.CaretDownOutlined, { rotate: folderOpen ? 0 : 270, style: iconStyle }),
            folderOpen ? react_1.default.createElement(icons_1.FolderOpenOutlined, { style: iconStyle }) : react_1.default.createElement(icons_1.FolderOutlined, { style: iconStyle }),
            root),
        folderOpen &&
            contentList.map((item) => (react_1.default.createElement(react_1.default.Fragment, { key: item.id },
                react_1.default.createElement(MenuItem, { className: item.contents && item.contents.length > 0 ? '' : 'disabled', onClick: () => handleSecondFolderClick(item) },
                    react_1.default.createElement(icons_1.CaretDownOutlined, { rotate: !item.fold ? 0 : 270, style: iconStyle }),
                    react_1.default.createElement(antd_1.Tag, { style: { transform: 'scale(0.8)' }, color: file_1.suffixTagColor[item.type] }, i18n.business.file[item.type]),
                    react_1.default.createElement(MenuTitleText, { style: { maxWidth: 190 } },
                        react_1.default.createElement(antd_1.Tooltip, { title: item.name }, item.name))),
                !item.fold && item.contents && item.contents.length > 0 && (react_1.default.createElement(react_1.default.Fragment, null, reSortList(item.contents).map((subItem) => {
                    const { id, isBase, extendId, tags = [] } = subItem || {};
                    const isSelected = contentId === id;
                    const _isBase = isBase && !!item.contents && item.contents.find((content) => content.extendId === id);
                    const isInherited = !_isBase && !!extendId;
                    const locales = tags.filter((localeItem) => localeItem.locale).map((item) => item.locale);
                    return (react_1.default.createElement(MenuItem, { id: id, key: id, className: isSelected ? 'active' : '', style: { paddingLeft: 34, paddingRight: 4 }, onClick: () => {
                            if (!isSelected) {
                                const localeTags = tags.filter((item) => item.locale);
                                selectContent({
                                    applicationId,
                                    folderId,
                                    fileId: item.id,
                                    contentId: id,
                                    locale: localeTags.length > 0 ? localeTags[0].locale : '',
                                    fileType: item.type,
                                });
                            }
                        } },
                        react_1.default.createElement(react_router_dom_1.Link, { to: {
                                pathname: '/builder',
                                search: `?applicationId=${applicationId}&folderId=${folderId}&fileId=${item.id}&contentId=${subItem.id}`,
                            } },
                            react_1.default.createElement(MenuItemSlot, null,
                                isBase && react_1.default.createElement(index_1.BasicTemRing, { style: { left: 34 } }),
                                isInherited && (react_1.default.createElement(react_1.default.Fragment, null,
                                    react_1.default.createElement(index_1.VLine, { style: { left: 38 } }),
                                    react_1.default.createElement(index_1.Ring, { style: { left: 36 } }))),
                                react_1.default.createElement(ContentName, { className: isSelected ? 'selected' : '' },
                                    react_1.default.createElement(antd_1.Tooltip, { title: subItem.title }, subItem.title)),
                                react_1.default.createElement("div", { style: { width: 50 } }, locales.length > 0 ? (react_1.default.createElement(index_1.LocaleTag, { color: "blue", style: {
                                        marginRight: 4,
                                        transform: 'scale(0.8)',
                                        padding: '2px 0 !important ',
                                    } }, locales[0])) : (react_1.default.createElement(react_1.default.Fragment, null))),
                                subItem.liveVersionNumber && subItem.liveVersionNumber > 0 ? (react_1.default.createElement(antd_1.Tag, { color: "orange", style: { margin: '0 0 0 4px', transform: 'scale(0.8)' } }, (0, index_2.formatter)(subItem.liveVersionNumber))) : (react_1.default.createElement(react_1.default.Fragment, null))))));
                }))))))));
    const localeMenu = (0, react_1.useMemo)(() => (react_1.default.createElement(Menu, { style: { width: 76, padding: 0 } }, currentContent &&
        currentContent.tags
            .filter((localeItem) => localeItem.locale)
            .map((item) => {
            const locale = item.locale;
            return (react_1.default.createElement(react_1.default.Fragment, { key: locale },
                react_1.default.createElement(MenuItem, { onClick: () => setLocale(locale) }, locale)));
        }))), [currentContent]);
    return (react_1.default.createElement(react_1.default.Fragment, null,
        react_1.default.createElement(antd_1.Popover, { zIndex: 99, placement: "bottomLeft", overlayClassName: "foxpage-builder-header_popover foxpage-builder-header_content_popover", trigger: ['hover'], content: menu, getPopupContainer: (triggerNode) => triggerNode.parentNode, onVisibleChange: handlePopoverShow },
            react_1.default.createElement(MenuTitle, null,
                react_1.default.createElement(MenuTitleText, null, (currentContent === null || currentContent === void 0 ? void 0 : currentContent.title) || ''),
                react_1.default.createElement(icons_1.CaretDownOutlined, { style: { fontSize: 8, marginLeft: 4 } }))),
        locale && (react_1.default.createElement(antd_1.Popover, { zIndex: 99, placement: "bottomLeft", overlayClassName: "foxpage-builder-header_popover", trigger: ['hover'], content: localeMenu, getPopupContainer: (triggerNode) => triggerNode.parentNode },
            react_1.default.createElement(MenuTitle, { style: { width: 80, display: 'flex', justifyContent: 'space-between' } },
                react_1.default.createElement(MenuTitleText, null, locale),
                react_1.default.createElement(icons_1.CaretDownOutlined, { style: { fontSize: 8, marginLeft: 4 } }))))));
};
exports.default = Main;
