import * as d3 from 'd3';
import { ConditionalDynamicDisplayElement } from '../base/conditional-dynamic-display-element';
import { GetAlarmsArgs } from '../../config';
import * as moment from 'moment';
import { LOGGER_SERVICE_TOKEN } from '../../logger';
var ScrollAlarmElementStatus;
(function (ScrollAlarmElementStatus) {
    ScrollAlarmElementStatus[ScrollAlarmElementStatus["Normal"] = 0] = "Normal";
    ScrollAlarmElementStatus[ScrollAlarmElementStatus["Loading"] = 1] = "Loading"; // 加载中
})(ScrollAlarmElementStatus || (ScrollAlarmElementStatus = {}));
export class ScrollAlarmElement extends ConditionalDynamicDisplayElement {
    constructor(element, injector, permissionChecker, variableCommunicator, variableStore, alarmsStore, signalRAppId) {
        var _a, _b, _c, _d, _e, _f;
        super(element, permissionChecker, variableCommunicator, variableStore, signalRAppId);
        this.alarmsStore = alarmsStore;
        this.elementStatus = ScrollAlarmElementStatus.Loading;
        this.alarmNames = [];
        this.isWaitingForAlarmRefresh = false; // 是否正在等待刷新(节流期间)
        this.isScrolling = false;
        this.isDisposed = false;
        this.isRefreshingCurrentPage = false; // 标记是否正在刷新当前页（而不是加载新页）
        // 新的分页和滚动逻辑变量
        this.currentPage = 1;
        this.maxResultCount = 500; // 每页数据量
        this.displayedItems = []; // 当前显示的所有数据
        this.pageWidths = []; // 存储每页的宽度
        this.totalWidth = 0; // 所有显示数据的总宽度
        this.currentLeft = 0;
        this.autoCycle = true;
        this.hasMoreData = true;
        this.isLoadingNextPage = false;
        this.hasTriedFirstPage = false; // 是否已经尝试加载过第一页
        this.isSimulateMode = false; // 是否是模拟运行模式
        this.rootElement.selectAll('*').remove();
        this.setStatusAsLoading();
        this.logger = injector.get(LOGGER_SERVICE_TOKEN);
        this.variableCommunicator = variableCommunicator;
        this.autoCycle = (_b = (_a = this.model.generalSetting) === null || _a === void 0 ? void 0 : _a.autoCycle) !== null && _b !== void 0 ? _b : true;
        this.maxResultCount = (_d = (_c = this.model.generalSetting) === null || _c === void 0 ? void 0 : _c.pageSize) !== null && _d !== void 0 ? _d : 500;
        // 检测是否是模拟运行模式（通过检查 alarmsStore 的标记属性，不受代码混淆影响）
        this.isSimulateMode = alarmsStore && alarmsStore.isSimulationStore === true;
        if (this.model.filterSetting && this.model.filterSetting.detailsData && this.model.filterSetting.detailsData.length > 0) {
            this.alarmNames = this.model.filterSetting.detailsData.map(item => item.name);
            // 如果是模拟运行模式，使用静态显示逻辑（类似设计态）
            if (this.isSimulateMode) {
                // 初始化显示容器
                this.initDisplayContainer();
                // 获取字体设置
                this.headerFont = ((_e = this.model.generalSetting) === null || _e === void 0 ? void 0 : _e.headerFont) || {};
                // 构建符合 CSS font 属性规范的字符串
                let fontString = '';
                if (this.headerFont.isItalic) {
                    fontString += 'italic ';
                }
                if (this.headerFont.isBold) {
                    fontString += 'bold ';
                }
                const fontSize = this.headerFont.fontSize || '16px';
                const lineHeight = parseInt(fontSize, 10) + 5;
                fontString += `${fontSize}/${lineHeight}px ${this.headerFont.fontFamily || 'Microsoft YaHei'}`;
                this.fontString = fontString;
                // 使用静态显示逻辑：只显示字段标签
                this.renderStaticDisplay();
                this.setStatusAsNormal();
            }
            else {
                // 真实运行模式：使用原有的数据查询逻辑
                this.updateQueryTimeRange();
                // 监听告警更新 (带节流,1秒内只执行一次)
                variableCommunicator.subscribeUserDeviceAlarms(signalRAppId).subscribe(alarms => {
                    alarms.forEach(alarm => {
                        if (this.alarmNames.indexOf(alarm.name) !== -1) {
                            // 如果已经在等待刷新,直接返回,避免重复清理和创建定时器
                            if (this.isWaitingForAlarmRefresh) {
                                return;
                            }
                            // 标记为等待刷新状态
                            this.isWaitingForAlarmRefresh = true;
                            // 设置节流定时器,1秒后执行
                            this.alarmRefreshThrottleId = setTimeout(() => {
                                // 收到新告警消息，实时替换当前滚动内容，不影响滚动
                                this.replaceCurrentScrollingContent();
                                // 重置等待刷新标志
                                this.isWaitingForAlarmRefresh = false;
                            }, 1000);
                            return;
                        }
                    });
                });
                // 初始化显示容器
                this.initDisplayContainer();
                // 获取字体设置 - 参考 text-element.ts 的实现方式
                this.headerFont = ((_f = this.model.generalSetting) === null || _f === void 0 ? void 0 : _f.headerFont) || {};
                // 构建符合 CSS font 属性规范的字符串
                // 格式：font-style font-weight font-size/line-height font-family
                let fontString = '';
                if (this.headerFont.isItalic) {
                    fontString += 'italic ';
                }
                if (this.headerFont.isBold) {
                    fontString += 'bold ';
                }
                const fontSize = this.headerFont.fontSize || '16px';
                const lineHeight = parseInt(fontSize, 10) + 5;
                fontString += `${fontSize}/${lineHeight}px ${this.headerFont.fontFamily || 'Microsoft YaHei'}`;
                this.fontString = fontString;
                this.getAlarmData();
            }
        }
        else {
            // 未配置告警（没有勾选过告警），不执行，直接展示空
            this.displayedItems = [];
            // 初始化显示容器以显示空内容
            this.initDisplayContainer();
            if (this.allAlarmsContainer) {
                this.allAlarmsContainer.innerHTML = '';
                this.totalWidth = 0;
                this.pageWidths = [];
            }
            this.setStatusAsNormal();
        }
    }
    dispose() {
        this.isDisposed = true;
        clearInterval(this.scrollIntervalId);
        clearTimeout(this.getAlarmDataId);
        clearTimeout(this.alarmRefreshThrottleId);
        if (this.element && this.element.tooltip) {
            this.element.tooltip.hidden(true);
        }
        this.logger.debug(`[GUI]Dispose Scroll Alarm Refresh Interval:${d3.time.format('%x %X')(new Date())}`);
        // 重置所有状态
        this.isScrolling = false;
    }
    getAlarmData() {
        if (this.isDisposed || this.isLoadingNextPage)
            return;
        this.isLoadingNextPage = true;
        // Only show loading for the first page load
        if (this.currentPage === 1 && this.displayedItems.length === 0) {
            this.setStatusAsLoading();
        }
        clearTimeout(this.getAlarmDataId);
        this.getAlarmDataId = setTimeout(() => {
            var _a, _b;
            this.updateQueryTimeRange();
            const skipCount = (this.currentPage - 1) * this.maxResultCount;
            // 从配置中获取状态和排序设置
            const selectedStates = (_a = this.model.generalSetting) === null || _a === void 0 ? void 0 : _a.selectState; // 前端使用的字段名
            const timeSort = (_b = this.model.generalSetting) === null || _b === void 0 ? void 0 : _b.timeSort; // 前端使用的字段名
            // 构建排序字符串 - API 字段名是 sorting
            let sorting;
            if (timeSort === '0') {
                sorting = 'TriggeredTime ASC'; // 升序
            }
            else if (timeSort === '1') {
                sorting = 'TriggeredTime DESC'; // 降序
            }
            // 后端 API 的 state 参数现已支持数组，直接传递 selectedStates
            // 兼容处理：如果 selectedStates 为空数组或 undefined，传 undefined（不过滤）
            const stateFilter = (selectedStates && Array.isArray(selectedStates) && selectedStates.length > 0)
                ? selectedStates
                : undefined;
            const input = new GetAlarmsArgs(this.alarmNames, this.startTime, this.endTime, this.maxResultCount, skipCount, stateFilter, // 传递状态数组到后端，后端已支持数组过滤
            sorting // 传递排序参数
            );
            this.alarmsStore.getHistoryAlarms(input).subscribe(result => {
                this.isLoadingNextPage = false;
                if (!result.error && result.items && result.items.length > 0) {
                    const newPage = result.items;
                    // 检查是否还有更多数据
                    // 如果是第一页且数据量少于 maxResultCount，说明总数据不超过一页
                    if (this.currentPage === 1 && newPage.length < this.maxResultCount) {
                        // 总数据不超过一页，不需要加载更多数据
                        this.hasMoreData = false;
                    }
                    else if (!this.autoCycle && newPage.length < this.maxResultCount) {
                        // 非自动循环模式，且当前页数据不足，说明没有更多数据
                        this.hasMoreData = false;
                    }
                    else {
                        this.hasMoreData = true;
                    }
                    if (this.isRefreshingCurrentPage) {
                        // 刷新当前页模式：替换最后一页的数据，保持滚动位置
                        const itemsPerPage = this.maxResultCount;
                        const startIndex = (this.currentPage - 1) * itemsPerPage;
                        // 移除当前页的旧数据
                        this.displayedItems.splice(startIndex, itemsPerPage);
                        // 移除当前页的DOM元素
                        const oldPageWidth = this.pageWidths.pop() || 0;
                        this.totalWidth -= oldPageWidth;
                        const elementsToRemove = Array.from(this.allAlarmsContainer.children).slice(startIndex, startIndex + itemsPerPage);
                        elementsToRemove.forEach(element => {
                            this.allAlarmsContainer.removeChild(element);
                        });
                        // 插入新的当前页数据
                        this.displayedItems.splice(startIndex, 0, ...newPage);
                        // 渲染新页（会追加到末尾）
                        this.renderNewPage(newPage);
                        // 更新页码
                        this.currentPage++;
                        // 重置标志
                        this.isRefreshingCurrentPage = false;
                    }
                    else {
                        // 正常加载新页模式：追加数据
                        this.displayedItems = this.displayedItems.concat(newPage);
                        // 渲染新页
                        this.renderNewPage(newPage);
                        // 更新页码
                        this.currentPage++;
                    }
                    // 检查是否需要删除旧页（保持最多3页）
                    if (this.currentPage > 4) {
                        this.removeOldestPage();
                    }
                    // 如果是首次加载或还没有开始滚动，初始化滚动
                    if (!this.isScrolling && this.displayedItems.length > 0) {
                        this.initScrolling();
                    }
                    this.setStatusAsNormal();
                    this.hasTriedFirstPage = true;
                }
                else {
                    // 如果没有数据
                    if (this.currentPage === 1 && !this.hasTriedFirstPage) {
                        // 第一次加载就没有数据，设置为正常状态，停止加载
                        this.hasTriedFirstPage = true;
                        this.hasMoreData = false;
                        this.setStatusAsNormal();
                        // 清空显示
                        this.displayedItems = [];
                        if (this.allAlarmsContainer) {
                            this.allAlarmsContainer.innerHTML = '';
                            this.totalWidth = 0;
                            this.pageWidths = [];
                        }
                    }
                    else if (this.autoCycle && this.hasTriedFirstPage && this.displayedItems.length > 0) {
                        // 不是第一页，且之前有数据，自动循环开启，循环回到第一页
                        this.currentPage = 1;
                        this.getAlarmData();
                    }
                    else {
                        // 其他情况：停止加载
                        this.hasMoreData = false;
                        this.setStatusAsNormal();
                    }
                }
            }, error => {
                this.isLoadingNextPage = false;
                this.setStatusAsNormal();
                this.logger.error('Failed to get alarm data:', error);
            });
        }, 500);
    }
    initDisplayContainer() {
        var _a;
        const elementHeight = this.model.size.height;
        const elementWidth = this.model.size.width;
        // 创建foreignObject作为容器
        this.element = document.createElementNS('http://www.w3.org/2000/svg', 'foreignObject');
        this.element.setAttribute('width', elementWidth.toString());
        this.element.setAttribute('height', elementHeight.toString());
        this.$element.append(this.element);
        // 创建背景容器，应用headerFillColor背景色
        this.container = document.createElement('div');
        this.container.style.cssText = `
            height: ${elementHeight}px;
            width: 100%;
            background-color: ${((_a = this.model.generalSetting) === null || _a === void 0 ? void 0 : _a.headerFillColor) || '#ffffff'};
            display: flex;
            align-items: center;
            overflow: hidden;
            position: relative;
            border: 1px solid #8ea0aa;
            border-radius: 2px;
        `;
        this.element.appendChild(this.container);
        // 创建一个大容器来包含所有告警项，初始位置在容器右侧（从右边开始滚入）
        this.allAlarmsContainer = document.createElement('div');
        this.allAlarmsContainer.style.cssText = `
            position: absolute;
            top: 50%;
            transform: translateY(-50%);
            display: flex;
            align-items: center;
            gap: 80px;
        `;
        this.container.appendChild(this.allAlarmsContainer);
        // 设置初始位置为容器宽度，让内容从右侧滚入
        this.currentLeft = elementWidth;
        this.allAlarmsContainer.style.left = `${elementWidth}px`;
        // 添加鼠标悬停暂停和恢复滚动功能
        this.container.addEventListener('mouseenter', () => this.pauseScroll());
        this.container.addEventListener('mouseleave', () => this.resumeScroll());
    }
    renderNewPage(pageData) {
        let pageWidth = 0;
        // 为每个告警数据创建文本容器
        pageData.forEach((alarm) => {
            var _a, _b, _c, _d, _e, _f, _g, _h;
            // 创建告警文本容器
            const textContainer = document.createElement('div');
            textContainer.style.cssText = `
                font: ${this.fontString};
                color: ${this.headerFont.color || '#e33c39'};
                white-space: nowrap;
                overflow: visible;
            `;
            // 应用下划线样式（参考 text-element.ts 的实现）
            if (this.headerFont.isUnderline) {
                textContainer.style.textDecoration = 'underline';
            }
            // 构建告警信息内容，根据配置决定显示哪些字段
            const contentParts = [];
            // 显示触发时间
            if (((_a = this.model.generalSetting) === null || _a === void 0 ? void 0 : _a.showTriggerTime) && alarm.triggeredTime) {
                const formattedTime = moment(alarm.triggeredTime).format('YYYY/MM/DD HH:mm:ss');
                contentParts.push(formattedTime);
            }
            // 获取当前语言环境
            const language = ((_d = (_c = (_b = window.abp) === null || _b === void 0 ? void 0 : _b.localization) === null || _c === void 0 ? void 0 : _c.currentLanguage) === null || _d === void 0 ? void 0 : _d.name) || 'zh-Hans';
            const isChinese = language === 'zh-Hans' || language === 'zh';
            // 显示告警等级
            if (((_e = this.model.generalSetting) === null || _e === void 0 ? void 0 : _e.showAlarmLevel) && alarm.alarmLevel !== undefined) {
                const levelMap = isChinese ? ['警告', '次要', '主要', '严重'] : ['Warning', 'Minor', 'Major', 'Critical'];
                const alarmLevel = levelMap[alarm.alarmLevel] || (isChinese ? '警告' : 'Warning');
                contentParts.push(alarmLevel);
            }
            // 显示告警名称
            if (((_f = this.model.generalSetting) === null || _f === void 0 ? void 0 : _f.showAlarmName) && alarm.name) {
                contentParts.push(alarm.name);
            }
            // 显示告警内容
            if (((_g = this.model.generalSetting) === null || _g === void 0 ? void 0 : _g.showAlarmContent) && alarm.message) {
                contentParts.push(alarm.message);
            }
            // 显示告警状态
            if (((_h = this.model.generalSetting) === null || _h === void 0 ? void 0 : _h.showAlarmState) && alarm.state !== undefined) {
                const stateMap = isChinese ? ['触发/未确认', '触发/已确认', '恢复/未确认', '恢复/已确认'] : ['Triggered/Unconfirmed', 'Triggered/Confirmed', 'Restored/Unconfirmed', 'Restored/Confirmed'];
                const alarmState = stateMap[alarm.state] || (isChinese ? '触发/未确认' : 'Triggered/Unconfirmed');
                contentParts.push(alarmState);
            }
            // 将所有显示字段用空格连接，确保一行显示
            const textContent = contentParts.join(' ');
            textContainer.textContent = textContent;
            this.allAlarmsContainer.appendChild(textContainer);
            // 计算文本宽度
            const textWidth = textContainer.offsetWidth;
            pageWidth += textWidth + 80; // 80是gap大小
        });
        // 移除最后一个gap
        if (pageWidth > 0) {
            pageWidth -= 80;
        }
        // 保存页宽度
        this.pageWidths.push(pageWidth);
        this.totalWidth += pageWidth;
    }
    removeOldestPage() {
        // 移除最旧的一页数据
        this.displayedItems.splice(0, this.maxResultCount);
        const oldPageWidth = this.pageWidths.shift() || 0;
        // 更新总宽度
        this.totalWidth -= oldPageWidth;
        // 从DOM中移除最旧的元素
        const elementsToRemove = Array.from(this.allAlarmsContainer.children).slice(0, this.maxResultCount);
        elementsToRemove.forEach(element => {
            this.allAlarmsContainer.removeChild(element);
        });
        // 调整当前left位置（保持视觉位置不变）- 这里需要等DOM更新完成后再调整
        requestAnimationFrame(() => {
            this.currentLeft += oldPageWidth;
            this.allAlarmsContainer.style.left = `${this.currentLeft}px`;
        });
    }
    scrollContent() {
        if (this.displayedItems.length <= 0)
            return;
        // 每次滚动的距离
        const scrollStep = 6; // 减小滚动步长，使滚动更平滑
        // 更新位置 - 从右往左滚动
        this.currentLeft -= scrollStep;
        // 检查是否需要加载下一页（只有在自动循环模式下才需要预加载）
        if (this.autoCycle && this.hasMoreData && !this.isLoadingNextPage) {
            const currentPosition = Math.abs(this.currentLeft);
            const loadedWidth = this.totalWidth - (this.pageWidths[this.pageWidths.length - 1] || 0);
            // 当滚动到已加载内容的60%时，加载下一页（提前预加载，确保无缝衔接）
            if (currentPosition > loadedWidth * 0.6) {
                this.getAlarmData();
            }
        }
        // 当内容完全滚出容器左侧时（currentLeft + totalWidth < -50）
        // 说明所有内容都已经滚出视图（不开启自动循环时多滚动50px确保最后一个字完全滚出）
        if (this.currentLeft + this.totalWidth < -50) {
            if (this.autoCycle) {
                // 自动循环模式：无缝衔接回到容器右侧
                if (this.hasMoreData) {
                    // 有更多数据：继续加载（但实际上已经在上面预加载了）
                    // 重置到容器宽度，让内容从右侧重新滚入
                    this.currentLeft = this.container.clientWidth;
                }
                else {
                    // 没有更多数据了：重置
                    if (this.currentPage > 2) {
                        // 数据总数超过一页：重置到第一页并重新查询
                        this.resetToFirstPage();
                    }
                    else {
                        // 数据总数只有一页：直接重置到容器右侧，循环滚动当前数据
                        this.currentLeft = this.container.clientWidth;
                    }
                }
            }
            else {
                // 非循环滚动：停止滚动
                clearInterval(this.scrollIntervalId);
                this.isScrolling = false;
                return; // 提前返回，不再更新位置
            }
        }
        // 更新显示位置
        this.allAlarmsContainer.style.left = `${this.currentLeft}px`;
    }
    initScrolling() {
        clearInterval(this.scrollIntervalId);
        // 如果没有数据，则不启动滚动
        if (this.displayedItems.length === 0) {
            return;
        }
        // 确保初始位置在容器右侧（从右边滚入）
        if (this.currentPage === 1 && this.displayedItems.length <= this.maxResultCount) {
            // 第一页初始加载时，确保从右侧开始
            this.currentLeft = this.container.clientWidth;
            this.allAlarmsContainer.style.left = `${this.currentLeft}px`;
        }
        const scrollInterval = 100; // 默认100ms，滚动更流畅
        // 延迟启动滚动确保内容渲染完成
        setTimeout(() => {
            this.isScrolling = true;
            this.scrollIntervalId = setInterval(() => {
                if (this.isScrolling) {
                    this.scrollContent();
                }
            }, scrollInterval);
        }, 500);
    }
    pauseScroll() {
        this.isScrolling = false;
    }
    resumeScroll() {
        this.isScrolling = true;
    }
    resetToFirstPage() {
        // 重置到第一页并重新查询数据
        this.currentPage = 1;
        this.hasMoreData = true;
        this.hasTriedFirstPage = false;
        this.displayedItems = [];
        if (this.allAlarmsContainer) {
            this.allAlarmsContainer.innerHTML = '';
            this.totalWidth = 0;
            this.pageWidths = [];
        }
        // 重置到容器右侧，让内容从右边滚入
        this.currentLeft = this.container.clientWidth;
        this.allAlarmsContainer.style.left = `${this.currentLeft}px`;
        this.getAlarmData();
    }
    updateQueryTimeRange() {
        this.endTime = moment();
        switch (this.model.generalSetting.displayPeriod) {
            case 1:
                this.startTime = moment().subtract(1, 'hours');
                break;
            case 3:
                this.startTime = moment().subtract(7, 'days');
                break;
            case 4:
                this.startTime = moment().subtract(30, 'days');
                break;
            case 5:
                this.startTime = moment().subtract(6, 'months');
                break;
            case 6:
                this.startTime = moment().subtract(30, 'minutes');
                break;
            case 7:
                this.startTime = moment().subtract(8, 'hours');
                break;
            default:
                this.startTime = moment().subtract(1, 'days');
        }
    }
    setStatusAsNormal() {
        this.elementStatus = ScrollAlarmElementStatus.Normal;
        this.clearStatus();
    }
    setStatusAsLoading() {
        this.elementStatus = ScrollAlarmElementStatus.Loading;
        this.renderStatus('assets/img/loading.svg', '#226abc');
    }
    renderStatus(icon, stroke) {
        if (this.elementStatus === ScrollAlarmElementStatus.Normal) {
            this.clearStatus();
            return;
        }
        // 确保宽度和高度为正值，避免 SVG 错误
        const width = Math.max(this.model.size.width || 100, 0);
        const height = Math.max(this.model.size.height || 50, 0);
        this.rootElement.append('rect').attr('id', 'StateFrame').attr('fill', 'transparent')
            .attr('width', width)
            .attr('height', height);
        const document = this.$element[0].ownerDocument;
        const currentRect = this.$element.find('rect#StateFrame').first();
        if (!currentRect.length) {
            return;
        }
        this.$element.find('image#StateImage').remove();
        const imgObj = document.createElementNS('http://www.w3.org/2000/svg', 'image');
        if (imgObj) {
            let x = Number(currentRect[0].getAttribute('width')) - 20;
            const currentRectX = currentRect[0].getAttribute('x');
            if (currentRectX !== null) {
                x += Number(currentRectX);
            }
            currentRect[0].setAttribute('stroke', stroke);
            currentRect[0].setAttribute('stroke-opacity', '0.5');
            imgObj.href.baseVal = icon;
            imgObj.setAttributeNS(null, 'id', 'StateImage');
            imgObj.setAttributeNS(null, 'x', x.toString());
            imgObj.setAttributeNS(null, 'y', '0');
            imgObj.setAttributeNS(null, 'height', '20px');
            imgObj.setAttributeNS(null, 'width', '20px');
            const titleElement = document.createElementNS('http://www.w3.org/2000/svg', 'title');
            imgObj.appendChild(titleElement);
            this.$element.append(imgObj);
        }
    }
    clearStatus() {
        const currentRect = this.$element.find('rect#StateFrame').first();
        if (!currentRect.length) {
            return;
        }
        const stroke = currentRect[0].getAttribute('stroke');
        if (stroke) {
            currentRect[0].removeAttribute('stroke');
        }
        this.$element.find('image#StateImage').remove();
    }
    /**
     * 模拟运行时的静态显示逻辑：只显示字段标签，不查询数据
     */
    renderStaticDisplay() {
        var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s;
        // 根据配置构建显示的字段标签
        const textParts = [];
        if (((_a = this.model.generalSetting) === null || _a === void 0 ? void 0 : _a.showTriggerTime) !== false) {
            // 使用moment.format方法格式化日期时间
            const timeStr = moment().format('YYYY/MM/DD HH:mm:ss');
            textParts.push(timeStr);
        }
        if (((_b = this.model.generalSetting) === null || _b === void 0 ? void 0 : _b.showAlarmLevel) !== false) {
            // 获取当前语言环境
            const language = ((_e = (_d = (_c = window.abp) === null || _c === void 0 ? void 0 : _c.localization) === null || _d === void 0 ? void 0 : _d.currentLanguage) === null || _e === void 0 ? void 0 : _e.name) || 'zh-Hans';
            const isChinese = language === 'zh-Hans' || language === 'zh';
            textParts.push(isChinese ? '严重' : 'Critical');
        }
        if (((_f = this.model.generalSetting) === null || _f === void 0 ? void 0 : _f.showAlarmName) === true) {
            // 获取当前语言环境
            const language = ((_j = (_h = (_g = window.abp) === null || _g === void 0 ? void 0 : _g.localization) === null || _h === void 0 ? void 0 : _h.currentLanguage) === null || _j === void 0 ? void 0 : _j.name) || 'zh-Hans';
            const isChinese = language === 'zh-Hans' || language === 'zh';
            textParts.push(isChinese ? '室内温度' : 'Indoor Temperature');
        }
        if (((_k = this.model.generalSetting) === null || _k === void 0 ? void 0 : _k.showAlarmContent) !== false) {
            // 获取当前语言环境
            const language = ((_o = (_m = (_l = window.abp) === null || _l === void 0 ? void 0 : _l.localization) === null || _m === void 0 ? void 0 : _m.currentLanguage) === null || _o === void 0 ? void 0 : _o.name) || 'zh-Hans';
            const isChinese = language === 'zh-Hans' || language === 'zh';
            textParts.push(isChinese ? '室内温度高于30°C或小于10°C' : 'Indoor temperature is higher than 30℃ or lower than 10℃');
        }
        if (((_p = this.model.generalSetting) === null || _p === void 0 ? void 0 : _p.showAlarmState) === true) {
            // 获取当前语言环境
            const language = ((_s = (_r = (_q = window.abp) === null || _q === void 0 ? void 0 : _q.localization) === null || _r === void 0 ? void 0 : _r.currentLanguage) === null || _s === void 0 ? void 0 : _s.name) || 'zh-Hans';
            const isChinese = language === 'zh-Hans' || language === 'zh';
            textParts.push(isChinese ? '触发/未确认' : 'Triggered/Unconfirmed');
        }
        // 创建文本容器
        const textContainer = document.createElement('div');
        textContainer.style.cssText = `
            font: ${this.fontString};
            color: ${this.headerFont.color || '#e33c39'};
            white-space: nowrap;
            overflow: visible;
        `;
        // 应用下划线样式
        if (this.headerFont.isUnderline) {
            textContainer.style.textDecoration = 'underline';
        }
        // 设置文本内容
        textContainer.textContent = textParts.join(' ');
        // 使用配置的宽度，而不是 clientWidth（因为DOM可能还没渲染完成）
        const containerWidth = this.model.size.width;
        // 先设置容器位置到右侧（屏幕外），这样添加元素时不会闪烁
        this.currentLeft = containerWidth;
        this.allAlarmsContainer.style.left = `${this.currentLeft}px`;
        // 添加到DOM以便计算宽度
        this.allAlarmsContainer.appendChild(textContainer);
        // 使用 setTimeout 确保 DOM 渲染完成后再计算宽度
        setTimeout(() => {
            // 计算文本宽度
            const textWidth = textContainer.offsetWidth;
            this.totalWidth = textWidth;
            this.pageWidths.push(textWidth);
            // 启动滚动（autoCycle 只控制是否循环，不控制是否滚动）
            this.initStaticScrolling();
        }, 50);
    }
    /**
     * 模拟运行时的静态滚动逻辑
     */
    initStaticScrolling() {
        clearInterval(this.scrollIntervalId);
        const scrollInterval = 100;
        // 延迟启动滚动确保内容渲染完成
        setTimeout(() => {
            this.isScrolling = true;
            this.scrollIntervalId = setInterval(() => {
                if (this.isScrolling) {
                    this.scrollStaticContent();
                }
            }, scrollInterval);
        }, 500);
    }
    /**
     * 模拟运行时的静态内容滚动
     */
    scrollStaticContent() {
        // 每次滚动的距离
        const scrollStep = 2;
        // 更新位置 - 从右往左滚动
        this.currentLeft -= scrollStep;
        // 更新显示位置
        this.allAlarmsContainer.style.left = `${this.currentLeft}px`;
        // 当内容完全滚出容器左侧时（内容右边缘完全移出容器左边缘）
        // currentLeft + totalWidth 表示内容右边缘的位置
        // 当这个值 <= -50 时，表示内容完全不可见（不开启自动循环时多滚动50px确保最后一个字完全滚出）
        const rightEdge = this.currentLeft + this.totalWidth;
        if (rightEdge <= -50) {
            if (this.autoCycle) {
                // 自动循环模式：重置到容器右侧（使用配置宽度）
                this.currentLeft = this.model.size.width;
                this.allAlarmsContainer.style.left = `${this.currentLeft}px`;
            }
            else {
                // 非循环模式：停止滚动
                clearInterval(this.scrollIntervalId);
                this.isScrolling = false;
                return;
            }
        }
    }
    /**
     * 实时替换当前滚动内容（用于告警数据变化时）
     */
    replaceCurrentScrollingContent() {
        var _a, _b;
        // 更新查询时间范围
        this.updateQueryTimeRange();
        // 查询所有当前应该显示的数据（查询足够多的数据以确保包含所有新增/删除）
        const selectedStates = (_a = this.model.generalSetting) === null || _a === void 0 ? void 0 : _a.selectState;
        const timeSort = (_b = this.model.generalSetting) === null || _b === void 0 ? void 0 : _b.timeSort;
        // 使用一个较大的值确保能查询到所有数据，避免因新增数据导致查询不全
        const queryCount = Math.max(this.displayedItems.length || this.maxResultCount, 100);
        // 确定排序参数
        let sorting = 'TriggeredTime ASC'; // 默认升序
        if (timeSort === 0 || timeSort === '0') {
            sorting = 'TriggeredTime ASC'; // 升序
        }
        else if (timeSort === 1 || timeSort === '1') {
            sorting = 'TriggeredTime DESC'; // 降序
        }
        // 兼容处理：如果 selectedStates 为空数组或 undefined，传 undefined（不过滤）
        const stateFilter = (selectedStates && Array.isArray(selectedStates) && selectedStates.length > 0)
            ? selectedStates
            : undefined;
        const input = new GetAlarmsArgs(this.alarmNames, this.startTime, this.endTime, queryCount, 0, // skipCount
        stateFilter, sorting);
        this.alarmsStore.getHistoryAlarms(input).subscribe(result => {
            var _a, _b, _c, _d, _e, _f, _g, _h;
            if (!result.error && result.items) {
                const newItems = result.items;
                // 如果没有数据，清空显示
                if (newItems.length === 0) {
                    this.displayedItems = [];
                    this.totalWidth = 0;
                    this.pageWidths = [];
                    this.currentPage = 1;
                    this.hasTriedFirstPage = false;
                    this.hasMoreData = true;
                    // 清空DOM
                    if (this.allAlarmsContainer) {
                        this.allAlarmsContainer.innerHTML = '';
                        const containerWidth = this.model.size.width;
                        this.currentLeft = containerWidth;
                        this.allAlarmsContainer.style.left = `${containerWidth}px`;
                    }
                    return;
                }
                // 如果是首次加载或当前没有数据，直接渲染并启动滚动
                if (this.displayedItems.length === 0) {
                    this.displayedItems = newItems;
                    this.allAlarmsContainer.innerHTML = '';
                    this.totalWidth = 0;
                    this.pageWidths = [];
                    // 设置 hasMoreData 状态，防止滚动时误触发 getAlarmData
                    this.hasMoreData = result.totalCount > newItems.length;
                    // 设置初始位置到容器右侧
                    this.currentLeft = this.container.clientWidth;
                    this.allAlarmsContainer.style.left = `${this.currentLeft}px`;
                    this.renderNewPage(newItems);
                    // 启动滚动
                    if (!this.isScrolling) {
                        this.initScrolling();
                    }
                    return;
                }
                // 保存当前的滚动位置
                const currentScrollPosition = this.currentLeft;
                // 清空所有DOM元素
                this.allAlarmsContainer.innerHTML = '';
                // 获取语言设置
                const language = ((_c = (_b = (_a = window.abp) === null || _a === void 0 ? void 0 : _a.localization) === null || _b === void 0 ? void 0 : _b.currentLanguage) === null || _c === void 0 ? void 0 : _c.name) || 'zh-Hans';
                const isChinese = language === 'zh-Hans' || language === 'zh';
                // 重新创建所有新数据的DOM元素
                for (let i = 0; i < newItems.length; i++) {
                    const alarm = newItems[i];
                    const textContainer = document.createElement('div');
                    textContainer.style.cssText = `
                        font: ${this.fontString};
                        color: ${this.headerFont.color || '#e33c39'};
                        white-space: nowrap;
                        overflow: visible;
                    `;
                    if (this.headerFont.isUnderline) {
                        textContainer.style.textDecoration = 'underline';
                    }
                    const contentParts = [];
                    // 显示触发时间
                    if (((_d = this.model.generalSetting) === null || _d === void 0 ? void 0 : _d.showTriggerTime) && alarm.triggeredTime) {
                        const formattedTime = moment(alarm.triggeredTime).format('YYYY/MM/DD HH:mm:ss');
                        contentParts.push(formattedTime);
                    }
                    // 显示告警等级
                    if (((_e = this.model.generalSetting) === null || _e === void 0 ? void 0 : _e.showAlarmLevel) && alarm.alarmLevel !== undefined) {
                        const levelMap = isChinese ? ['警告', '次要', '主要', '严重'] : ['Warning', 'Minor', 'Major', 'Critical'];
                        const alarmLevel = levelMap[alarm.alarmLevel] || (isChinese ? '警告' : 'Warning');
                        contentParts.push(alarmLevel);
                    }
                    // 显示告警名称
                    if (((_f = this.model.generalSetting) === null || _f === void 0 ? void 0 : _f.showAlarmName) && alarm.name) {
                        contentParts.push(alarm.name);
                    }
                    // 显示告警内容
                    if (((_g = this.model.generalSetting) === null || _g === void 0 ? void 0 : _g.showAlarmContent) && alarm.message) {
                        contentParts.push(alarm.message);
                    }
                    // 显示告警状态
                    if (((_h = this.model.generalSetting) === null || _h === void 0 ? void 0 : _h.showAlarmState) && alarm.state !== undefined) {
                        const stateMap = isChinese ? ['触发/未确认', '触发/已确认', '恢复/未确认', '恢复/已确认'] : ['Triggered/Unconfirmed', 'Triggered/Confirmed', 'Restored/Unconfirmed', 'Restored/Confirmed'];
                        const alarmState = stateMap[alarm.state] || (isChinese ? '触发/未确认' : 'Triggered/Unconfirmed');
                        contentParts.push(alarmState);
                    }
                    textContainer.textContent = contentParts.join(' ');
                    textContainer.setAttribute('data-index', i.toString());
                    this.allAlarmsContainer.appendChild(textContainer);
                }
                // 重新计算totalWidth
                const allChildren = Array.from(this.allAlarmsContainer.children);
                let newTotalWidth = 0;
                allChildren.forEach(child => {
                    newTotalWidth += child.offsetWidth + 80;
                });
                if (newTotalWidth > 0) {
                    newTotalWidth -= 80; // 移除最后一个gap
                }
                // 更新状态
                this.displayedItems = newItems;
                this.totalWidth = newTotalWidth;
                this.pageWidths = [newTotalWidth]; // 重置为单页
                this.hasMoreData = result.totalCount > newItems.length;
                // 保持滚动位置不变，继续滚动
                this.currentLeft = currentScrollPosition;
                this.allAlarmsContainer.style.left = `${this.currentLeft}px`;
            }
        });
    }
}
