"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 });
exports.ResourceTabEnum = void 0;
const react_1 = __importStar(require("react"));
const react_redux_1 = require("react-redux");
const antd_1 = require("antd");
const styled_components_1 = __importDefault(require("styled-components"));
const ACTIONS = __importStar(require("@/actions/builder/header"));
const PAGE_ACTIONS = __importStar(require("@/actions/builder/main"));
const index_1 = require("@/components/index");
const global_1 = require("@/constants/global");
const system_1 = require("@/pages/system");
const utils_1 = require("@/store/sagas/builder/utils");
const image_url_env_1 = require("@/utils/image-url-env");
var ResourceTabEnum;
(function (ResourceTabEnum) {
    ResourceTabEnum["application"] = "application";
    ResourceTabEnum["store"] = "store";
})(ResourceTabEnum = exports.ResourceTabEnum || (exports.ResourceTabEnum = {}));
const StyledModal = (0, styled_components_1.default)(antd_1.Modal) `
  .ant-modal-content {
    height: 100%;
    .ant-modal-body {
      height: calc(100% - 110px);
      overflow: auto;
      padding-top: 0;
    }
  }
`;
const FileName = styled_components_1.default.div `
  margin-top: 12px;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
  display: block;
`;
const { Meta } = antd_1.Card;
const { TabPane } = antd_1.Tabs;
const mapStateToProps = (store) => ({
    fileType: store.builder.header.storeModalType,
    open: store.builder.header.storeModalVisible,
    applicationId: store.builder.header.applicationId,
    contentId: store.builder.header.contentId,
    loading: store.builder.header.loading,
    pageInfo: store.builder.header.pageInfo,
    templates: store.builder.header.templates,
    storeResourceList: store.builder.header.storeResourceList,
    templateInPage: store.builder.main.templateOpenInPage,
    pageNode: store.builder.main.pageNode,
});
const mapDispatchToProps = {
    fetchApplicationTemplate: ACTIONS.fetchApplicationTemplate,
    fetchStoreProjectGoods: ACTIONS.fetchStoreProjectGoods,
    openModal: ACTIONS.updateStoreModalVisible,
    cloneContent: PAGE_ACTIONS.cloneContent,
    updatePageNode: PAGE_ACTIONS.pushPageNode,
};
const TemplateSelectModal = (props) => {
    const { open, applicationId, loading, pageInfo, fileType, templates, storeResourceList, fetchApplicationTemplate, fetchStoreProjectGoods, openModal, cloneContent, templateInPage, pageNode, updatePageNode, } = props;
    const [selectedTemplateId, setSelectedTemplateId] = (0, react_1.useState)();
    const [resourceList, setResourceList] = (0, react_1.useState)([]);
    const [tab, setTab] = (0, react_1.useState)(ResourceTabEnum.application);
    // i18n
    const { locale } = (0, react_1.useContext)(system_1.GlobalContext);
    const { builder, global, store } = locale.business;
    (0, react_1.useEffect)(() => {
        if (open) {
            fileType === global_1.FileType.page
                ? fetchStoreProjectGoods(Object.assign({ applicationId, type: fileType }, pageInfo))
                : fetchApplicationTemplate(applicationId);
        }
    }, [open]);
    (0, react_1.useEffect)(() => {
        setTab(fileType === global_1.FileType.page ? ResourceTabEnum.store : ResourceTabEnum.application);
    }, [open, fileType]);
    (0, react_1.useEffect)(() => {
        setResourceList(tab === ResourceTabEnum.application ? templates : storeResourceList);
    }, [tab, templates, storeResourceList]);
    const handleTabsChange = (tab) => {
        setTab(tab);
        if (tab === ResourceTabEnum.application) {
            fetchApplicationTemplate(applicationId);
        }
        else {
            fetchStoreProjectGoods({ page: 1, size: pageInfo.size, applicationId, type: fileType });
        }
    };
    const handleCardClick = (id) => {
        if (tab === ResourceTabEnum.application) {
            setSelectedTemplateId(id);
        }
    };
    const handleOk = (0, react_1.useCallback)(() => {
        if (!selectedTemplateId) {
            antd_1.message.warning(builder.selectPageError);
            return;
        }
        if (templateInPage) {
            // TODO: need to clean
            const tpl = (0, utils_1.getTemplateRelationKey)(selectedTemplateId);
            const newPageNode = Object.assign(Object.assign({}, pageNode), { directive: Object.assign(Object.assign({}, (pageNode.directive || {})), { tpl: `{{${tpl}}}` }) });
            updatePageNode(newPageNode);
        }
        else {
            cloneContent(selectedTemplateId);
        }
        openModal(false);
    }, [selectedTemplateId]);
    const TemplateRowContent = (0, react_1.useMemo)(() => {
        return (react_1.default.createElement(antd_1.Spin, { spinning: loading },
            react_1.default.createElement(antd_1.Row, { gutter: 16, style: { paddingBottom: 12 } },
                resourceList &&
                    resourceList.map((resource) => {
                        var _a, _b, _c;
                        let actions, MetaContent;
                        if (tab === ResourceTabEnum.application) {
                            MetaContent = react_1.default.createElement(Meta, { title: resource.title, style: { marginBottom: 12 } });
                            actions = [react_1.default.createElement(antd_1.Radio, { checked: resource.id === selectedTemplateId })];
                        }
                        else {
                            MetaContent = (react_1.default.createElement(Meta, { title: resource.name, description: `Application:${(_a = resource.application) === null || _a === void 0 ? void 0 : _a.name}`, style: { marginBottom: 12 } }));
                            actions = [];
                        }
                        const CardContent = (react_1.default.createElement(antd_1.Card, { key: resource.id, style: { width: 258, margin: '12px 6px' }, cover: react_1.default.createElement("img", { alt: "example", src: (0, image_url_env_1.getImageUrlByEnv)('/images/placeholder.png') }), actions: actions, hoverable: true, onClick: () => {
                                handleCardClick(resource.id);
                            } },
                            MetaContent,
                            tab === ResourceTabEnum.store && (react_1.default.createElement(FileName, null,
                                "Content:", (_b = resource.files) === null || _b === void 0 ? void 0 :
                                _b.map((file) => {
                                    var _a;
                                    return (_a = file.contents) === null || _a === void 0 ? void 0 : _a.map((item) => {
                                        return react_1.default.createElement("span", { style: { marginLeft: 6 } }, item.title);
                                    });
                                }).flat()))));
                        return tab === ResourceTabEnum.application ? (CardContent) : (react_1.default.createElement(antd_1.Popover, { placement: "bottom", title: "Content", content: react_1.default.createElement(antd_1.Radio.Group, { name: "radiogroup", value: selectedTemplateId, onChange: (e) => {
                                    setSelectedTemplateId(e.target.value);
                                } },
                                react_1.default.createElement(antd_1.Space, { direction: "vertical" }, (_c = resource.files) === null || _c === void 0 ? void 0 : _c.map((file) => {
                                    var _a;
                                    return (_a = file.contents) === null || _a === void 0 ? void 0 : _a.map((item) => {
                                        return (react_1.default.createElement(antd_1.Radio, { value: item.id },
                                            item.title,
                                            react_1.default.createElement(index_1.LocaleView, { maxLocaleCount: 100, locales: item.tags
                                                    .filter((item) => item.locale)
                                                    .map((item) => item.locale) })));
                                    });
                                }).flat())), autoAdjustOverflow: true, arrowPointAtCenter: true }, CardContent));
                    }),
                (resourceList === null || resourceList === void 0 ? void 0 : resourceList.length) === 0 && !loading && (react_1.default.createElement(antd_1.Empty, { image: antd_1.Empty.PRESENTED_IMAGE_SIMPLE, style: { margin: '48px auto' } })))));
    }, [tab, resourceList, selectedTemplateId, loading]);
    const PaginationContent = (0, react_1.useMemo)(() => {
        return (react_1.default.createElement(antd_1.Pagination, { showQuickJumper: true, hideOnSinglePage: true, current: pageInfo.page, size: pageInfo.size, total: pageInfo.total, onChange: (page, pageSize) => {
                fetchStoreProjectGoods({
                    page,
                    size: pageSize,
                    applicationId,
                    type: fileType,
                });
            } }));
    }, [pageInfo, fileType]);
    return (react_1.default.createElement(StyledModal, { destroyOnClose: true, maskClosable: false, width: "1112px", title: builder.selectPageModalTitle, visible: open, onOk: handleOk, onCancel: () => openModal(false), style: { height: '70%' } }, fileType === global_1.FileType.page ? (TemplateRowContent) : (react_1.default.createElement(antd_1.Tabs, { centered: true, destroyInactiveTabPane: true, defaultActiveKey: "application", onChange: handleTabsChange },
        react_1.default.createElement(TabPane, { tab: global.application, key: ResourceTabEnum.application }, TemplateRowContent),
        react_1.default.createElement(TabPane, { tab: store.name, key: ResourceTabEnum.store },
            TemplateRowContent,
            PaginationContent)))));
};
exports.default = (0, react_redux_1.connect)(mapStateToProps, mapDispatchToProps)(TemplateSelectModal);
