import { ConditionalDynamicDisplayElement } from '../base/conditional-dynamic-display-element';
import { GraphStateElement } from '../shared/graph/graph-state-element';
import { LOGGER_SERVICE_TOKEN } from '../../logger';
import { TextElementModal } from '../shared/text/text-element';
export class HyperlinkElement extends ConditionalDynamicDisplayElement {
    constructor(element, injector, permissionChecker, variableCommunicator, variableStore, graphStore, signalRAppId, textLibraryService, languageService, guiContext) {
        super(element, permissionChecker, variableCommunicator, variableStore, signalRAppId);
        this.graphStore = graphStore;
        this.textLibraryService = textLibraryService;
        this.languageService = languageService;
        this.guiContext = guiContext;
        this.logger = injector.get(LOGGER_SERVICE_TOKEN);
        if (this.model.size) {
            this.initGraphAndText();
            // 订阅语种变化
            this.subscribeLanguageChange();
        }
        if (this.model && this.model.linkAddress) {
            this.rootElement.style('cursor', 'hand');
            this.rootElement.on('mousedown', () => {
                let linkAddress = this.model.linkAddress;
                const reg = /^http(s)?:\/\/.+$/;
                if (!reg.test(linkAddress)) {
                    linkAddress = 'http://' + linkAddress;
                }
                window.open(linkAddress, '_system');
            });
        }
    }
    dispose() {
        // 取消语种变化订阅
        if (this.languageChangeSubscription) {
            this.languageChangeSubscription.unsubscribe();
            this.languageChangeSubscription = undefined;
        }
        if (this.$element) {
            this.$element.remove();
        }
    }
    /**
     * 订阅语种变化事件
     * 当设备的语种ID改变时，重新渲染文本
     */
    subscribeLanguageChange() {
        // 只有使用文本库时才需要订阅语种变化
        if (!this.model.textLibrary || this.model.textLibrary.labelType !== 'textLibrary') {
            return;
        }
        if (this.guiContext && this.guiContext.languageChanged$) {
            this.languageChangeSubscription = this.guiContext.languageChanged$.subscribe(() => {
                // 重新渲染文本
                this.reRenderText();
            });
        }
    }
    /**
     * 重新渲染文本
     */
    reRenderText() {
        if (!this.textElementModal || !this.model.size) {
            return;
        }
        // 获取新的显示文本
        const displayText = this.getDisplayText();
        // 直接更新文本内容，而不是重新创建元素
        this.textElementModal.updateText(displayText);
    }
    initGraphAndText() {
        this.rootElement.selectAll('*').remove();
        const size = this.model.size;
        const width = size.width;
        const height = size.height;
        this.rootElement.append('rect').attr('id', 'StateFrame').attr('width', width).attr('height', height).attr('fill', 'transparent');
        if (this.model.useGraph === true) {
            const graphStateElement = new GraphStateElement(this.model.graphSetting, width, height, this.graphStore, this.logger);
            graphStateElement.switchToState(0);
            this.$element.prepend(graphStateElement.Element);
        }
        const font = {
            isUnderline: this.model.isUnderline,
            isBold: this.isBold(this.model.font),
            isItalic: this.isItalic(this.model.font),
            fontSize: this.model.fontSize,
            fontFamily: this.fontFamily(this.model.font),
            color: this.model.stroke,
            textAlign: this.model.textAlign
        };
        // 获取显示文本（支持文本库）
        const displayText = this.getDisplayText();
        this.textElementModal = new TextElementModal(displayText, font, width, height);
        this.$element.append(this.textElementModal.Element);
    }
    /**
     * 获取显示文本
     * 如果配置了文本库，则从文本库中获取对应语种的文本
     * 否则返回默认文本
     */
    getDisplayText() {
        var _a, _b, _c, _d, _e, _f;
        // 检查是否使用文本库
        if (this.model.textLibrary && this.model.textLibrary.labelType === 'textLibrary') {
            const textLibraryId = this.model.textLibrary.selectedTextLibraryItem;
            const textItem = this.model.textLibrary.selectedTextItem;
            if (textLibraryId && textItem && this.textLibraryService) {
                // 获取文本库数据
                const textLibraryData = this.textLibraryService.getTextLibraryById(typeof textLibraryId === 'string' ? parseInt(textLibraryId, 10) : textLibraryId);
                if (textLibraryData && textLibraryData.data) {
                    // 查找对应的文本条目
                    const textEntry = textLibraryData.data.find(entry => entry.key === textItem.toString());
                    if (textEntry) {
                        // 获取当前语种ID
                        const currentLanguageId = (_c = (_b = (_a = this.guiContext) === null || _a === void 0 ? void 0 : _a.getCurrentLanguageId) === null || _b === void 0 ? void 0 : _b.call(_a)) !== null && _c !== void 0 ? _c : null;
                        // 确定要使用的语种代码（culture）
                        let targetLanguage;
                        const defaultLanguage = ((_d = this.languageService) === null || _d === void 0 ? void 0 : _d.getDefaultLanguage()) || 'zh-CN';
                        if (currentLanguageId === null || currentLanguageId === undefined) {
                            // 设备未设置当前语种，使用默认语种
                            targetLanguage = defaultLanguage;
                        }
                        else {
                            // 设备已设置当前语种，获取对应的语种代码
                            const currentLanguage = (_f = (_e = this.guiContext) === null || _e === void 0 ? void 0 : _e.getLanguageCultureById) === null || _f === void 0 ? void 0 : _f.call(_e, currentLanguageId);
                            if (currentLanguage) {
                                targetLanguage = currentLanguage;
                            }
                            else {
                                // 无法获取语种代码，使用默认语种
                                targetLanguage = defaultLanguage;
                            }
                        }
                        // 返回对应语种的文本
                        if (textEntry.cultures && textEntry.cultures[targetLanguage]) {
                            return textEntry.cultures[targetLanguage];
                        }
                        // 如果没有对应语种，返回空字符串
                        return '';
                    }
                }
            }
            // 文本库配置但未找到数据，返回空字符串
            return '';
        }
        // 默认返回文本内容
        return this.model.text || '';
    }
}
