import { Flicker } from '../../../model';
export class TextStateElement {
    constructor(textStates, width, height, logger, version, faultFlickers, textLibrarySetting, textLibraryService, languageService, guiContext) {
        this.textStates = textStates;
        this.width = width;
        this.height = height;
        this.logger = logger;
        this.version = version;
        this.faultFlickers = faultFlickers;
        this.textLibrarySetting = textLibrarySetting;
        this.textLibraryService = textLibraryService;
        this.languageService = languageService;
        this.guiContext = guiContext;
        this.faultFlickerStatus = false;
        this.faultFlickerInterval = undefined;
        this._element = document.createElementNS('http://www.w3.org/2000/svg', 'g');
        // 订阅语种变化事件
        this.subscribeLanguageChange();
    }
    get Element() {
        return this._element;
    }
    switchToState(stateId) {
        // 保存当前状态ID，用于语种切换时重新渲染
        this.currentStateId = stateId;
        const textState = this.textStates.find(t => t.id === stateId);
        if (textState === undefined) {
            this.removeForeignObjectlement();
            this.logger.debug(`Can not find text state:${stateId}.`);
            return;
        }
        // 获取显示文本（支持文本库）
        const content = this.getDisplayText(stateId, textState.text.content);
        if (content === '' || content == null) {
            this.removeForeignObjectlement();
            return;
        }
        const font = textState.text.font;
        if (!font) {
            this.removeForeignObjectlement();
            this.logger.debug('The font is undefined.');
            return;
        }
        const textElement = this.getforeignObjectElement();
        // 清空旧内容
        textElement.textContent = '';
        // 设置 text-anchor 和 dominant-baseline
        textElement.setAttribute('text-anchor', 'middle');
        textElement.setAttribute('dominant-baseline', 'middle');
        textElement.setAttribute('pointer-events', 'auto');
        // 拆分换行
        const lines = content.split('\n');
        const fontSize = parseInt(font.fontSize, 10);
        const lineHeight = fontSize + 4;
        // 总高度 = 行数 * 行高
        const totalHeight = lines.length * lineHeight;
        // 调整文本整体垂直居中（通过 dy）
        const startY = (this.height / 2) - (totalHeight / 2) + (lineHeight / 2);
        // 添加每行文本
        for (let i = 0; i < lines.length; i++) {
            const tspan = document.createElementNS('http://www.w3.org/2000/svg', 'tspan');
            tspan.setAttribute('x', (this.width / 2).toString());
            tspan.setAttribute('y', startY + i * lineHeight + 'px');
            tspan.textContent = lines[i].replace(/ /g, '\u00A0');
            tspan.setAttribute('font-size', font.fontSize);
            tspan.setAttribute('fill', font.color);
            tspan.setAttribute('font-family', font.fontFamily);
            tspan.setAttribute('font-weight', font.isBold ? 'bold' : 'normal');
            tspan.setAttribute('font-style', font.isItalic ? 'italic' : 'normal');
            tspan.setAttribute('text-decoration', font.isUnderline ? 'underline' : 'none');
            tspan.setAttribute('text-anchor', 'middle');
            tspan.setAttribute('dominant-baseline', 'middle');
            textElement.appendChild(tspan);
        }
        this.doFaultFlicker(textElement, stateId);
    }
    /**
     * 订阅语种变化事件
     * 当设备的语种ID改变时，重新渲染当前状态的文本
     */
    subscribeLanguageChange() {
        // 只有使用文本库时才需要订阅语种变化
        if (!this.textLibrarySetting || this.textLibrarySetting.labelType !== 'textLibrary') {
            return;
        }
        if (this.guiContext && this.guiContext.languageChanged$) {
            this.languageChangeSubscription = this.guiContext.languageChanged$.subscribe(() => {
                // 如果当前有状态，重新渲染
                if (this.currentStateId !== undefined) {
                    this.switchToState(this.currentStateId);
                }
            });
        }
    }
    /**
     * 释放资源
     */
    dispose() {
        // 取消语种变化订阅
        if (this.languageChangeSubscription) {
            this.languageChangeSubscription.unsubscribe();
            this.languageChangeSubscription = undefined;
        }
        // 清除闪烁定时器
        if (this.faultFlickerInterval) {
            clearInterval(this.faultFlickerInterval);
            this.faultFlickerInterval = undefined;
        }
    }
    getforeignObjectElement() {
        if (!this.textElement) {
            this.textElement = document.createElementNS('http://www.w3.org/2000/svg', 'text');
            this.textElement.setAttribute('x', (this.width / 2).toString());
            this.textElement.setAttribute('y', (this.height / 2).toString());
            this.textElement.setAttribute('text-anchor', 'middle');
            this.textElement.setAttribute('dominant-baseline', 'middle');
            this.textElement.setAttribute('pointer-events', 'auto'); // 确保能接收事件
            this._element.appendChild(this.textElement);
        }
        return this.textElement;
    }
    removeForeignObjectlement() {
        if (this.textElement) {
            this._element.removeChild(this.textElement);
            delete this.textElement;
        }
    }
    doFaultFlicker(textElement, stateId) {
        if (this.version > 3 && this.faultFlickers) {
            this.clearFlickerInterval(textElement);
            const faultFlicker = this.faultFlickers.find(t => t.id === stateId);
            if (faultFlicker && faultFlicker.faultFlicker) {
                if (faultFlicker.faultFlicker.flicker === Flicker.Label) {
                    this.faultFlickerInterval = setInterval(() => {
                        if (this.faultFlickerStatus) {
                            textElement.setAttributeNS(null, 'display', 'block');
                            this.faultFlickerStatus = false;
                        }
                        else {
                            textElement.setAttributeNS(null, 'display', 'none');
                            this.faultFlickerStatus = true;
                        }
                    }, faultFlicker.faultFlicker.frequency * 500);
                }
            }
        }
    }
    clearFlickerInterval(textElement) {
        if (this.faultFlickerInterval) {
            clearInterval(this.faultFlickerInterval);
            if (this.faultFlickerStatus) {
                textElement.setAttributeNS(null, 'display', 'block');
            }
        }
    }
    /**
     * 获取显示文本
     * 如果配置了文本库，则根据状态ID和当前语种ID从文本库中获取对应语种的文本
     * 否则返回默认文本
     */
    getDisplayText(stateId, defaultContent) {
        var _a, _b, _c, _d, _e, _f;
        // 检查是否使用文本库
        if (this.textLibrarySetting && this.textLibrarySetting.labelType === 'textLibrary') {
            const textLibraryId = this.textLibrarySetting.selectedTextLibraryItem;
            if (textLibraryId && this.textLibraryService) {
                // 获取文本库数据
                const textLibraryData = this.textLibraryService.getTextLibraryById(typeof textLibraryId === 'string' ? parseInt(textLibraryId, 10) : textLibraryId);
                if (textLibraryData && textLibraryData.data) {
                    // 使用状态ID作为value查找对应的文本条目
                    const textEntry = textLibraryData.data.find(entry => entry.value === stateId.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) {
                                // 直接使用设备设置的语种，不再fallback
                                targetLanguage = currentLanguage;
                            }
                            else {
                                targetLanguage = defaultLanguage;
                            }
                        }
                        // 返回对应语种的文本，如果没有则返回空字符串
                        if (textEntry.cultures && textEntry.cultures[targetLanguage]) {
                            const text = textEntry.cultures[targetLanguage];
                            return text;
                        }
                        else {
                            // 对应语种没有文本，返回空字符串
                            return '';
                        }
                    }
                }
            }
            // 文本库配置但未找到数据，返回空字符串
            return '';
        }
        // 默认返回文本内容
        return defaultContent || '';
    }
}
