if (!("finalizeConstruction" in ViewPU.prototype)) {
    Reflect.set(ViewPU.prototype, "finalizeConstruction", () => { });
}
interface AIQna_Params {
    chatHistory?: IChatMessage[];
    inputText?: string;
    isAIThinking?: boolean;
    globalDarkMode?: boolean;
    lastError?: string;
    historySessions?: IHistorySession[];
    showHistory?: boolean;
    highlightedMessageId?: number;
    listenerId?: string;
    preference?: preferences.Preferences | null;
    isInitialized?: boolean;
    lastSavedTimestamp?: number;
    scroller?: Scroller;
}
import router from "@ohos:router";
import http from "@ohos:net.http";
import type { BusinessError } from "@ohos:base";
import preferences from "@ohos:data.preferences";
import ThemeManager from "@bundle:com.example.myapplication/entry/ets/common/ThemeManager";
import type common from "@ohos:app.ability.common";
// ==================== 接口定义 ====================
interface IChatMessage {
    content: string;
    isUser: boolean;
    timestamp: number;
}
interface IHistorySession {
    timestamp: number;
    title: string;
    messages: IChatMessage[];
}
interface IApiMessage {
    role: string;
    content: string;
}
interface IApiRequest {
    model: string;
    messages: IApiMessage[];
    max_tokens: number;
    temperature: number;
    stream?: boolean;
}
interface IMessageContent {
    content: string;
}
interface IErrorDetail {
    message: string;
}
interface IApiResponseChoice {
    message: IMessageContent;
}
interface IApiResponse {
    choices?: IApiResponseChoice[];
    error?: IErrorDetail;
}
interface IHttpHeader {
    'Content-Type': string;
    'Authorization': string;
    'HTTP-Referer': string;
    'X-Title': string;
}
interface IHttpRequestOptions {
    method: http.RequestMethod;
    header: IHttpHeader;
    extraData: string;
    readTimeout: number;
    connectTimeout: number;
}
interface Padding {
    left?: number;
    right?: number;
    top?: number;
    bottom?: number;
}
interface Margin {
    top?: number;
    bottom?: number;
    left?: number;
    right?: number;
}
class AppConfig {
    static readonly API_KEY: string = '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';
    static readonly API_ENDPOINT: string = 'https://openrouter.ai/api/v1/chat/completions';
    static readonly DEFAULT_MODEL: string = 'deepseek/deepseek-chat';
    static readonly MAX_HISTORY_SESSIONS: number = 10;
}
class AIQna extends ViewPU {
    constructor(parent, params, __localStorage, elmtId = -1, paramsLambda = undefined, extraInfo) {
        super(parent, __localStorage, elmtId, extraInfo);
        if (typeof paramsLambda === "function") {
            this.paramsGenerator_ = paramsLambda;
        }
        this.__chatHistory = new ObservedPropertyObjectPU([], this, "chatHistory");
        this.__inputText = new ObservedPropertySimplePU('', this, "inputText");
        this.__isAIThinking = new ObservedPropertySimplePU(false, this, "isAIThinking");
        this.__globalDarkMode = new ObservedPropertySimplePU(false, this, "globalDarkMode");
        this.__lastError = new ObservedPropertySimplePU('', this, "lastError");
        this.__historySessions = new ObservedPropertyObjectPU([], this, "historySessions");
        this.__showHistory = new ObservedPropertySimplePU(false, this, "showHistory");
        this.__highlightedMessageId = new ObservedPropertySimplePU(-1, this, "highlightedMessageId");
        this.listenerId = '';
        this.preference = null;
        this.isInitialized = false;
        this.lastSavedTimestamp = 0;
        this.scroller = new Scroller();
        this.setInitiallyProvidedValue(params);
        this.finalizeConstruction();
    }
    setInitiallyProvidedValue(params: AIQna_Params) {
        if (params.chatHistory !== undefined) {
            this.chatHistory = params.chatHistory;
        }
        if (params.inputText !== undefined) {
            this.inputText = params.inputText;
        }
        if (params.isAIThinking !== undefined) {
            this.isAIThinking = params.isAIThinking;
        }
        if (params.globalDarkMode !== undefined) {
            this.globalDarkMode = params.globalDarkMode;
        }
        if (params.lastError !== undefined) {
            this.lastError = params.lastError;
        }
        if (params.historySessions !== undefined) {
            this.historySessions = params.historySessions;
        }
        if (params.showHistory !== undefined) {
            this.showHistory = params.showHistory;
        }
        if (params.highlightedMessageId !== undefined) {
            this.highlightedMessageId = params.highlightedMessageId;
        }
        if (params.listenerId !== undefined) {
            this.listenerId = params.listenerId;
        }
        if (params.preference !== undefined) {
            this.preference = params.preference;
        }
        if (params.isInitialized !== undefined) {
            this.isInitialized = params.isInitialized;
        }
        if (params.lastSavedTimestamp !== undefined) {
            this.lastSavedTimestamp = params.lastSavedTimestamp;
        }
        if (params.scroller !== undefined) {
            this.scroller = params.scroller;
        }
    }
    updateStateVars(params: AIQna_Params) {
    }
    purgeVariableDependenciesOnElmtId(rmElmtId) {
        this.__chatHistory.purgeDependencyOnElmtId(rmElmtId);
        this.__inputText.purgeDependencyOnElmtId(rmElmtId);
        this.__isAIThinking.purgeDependencyOnElmtId(rmElmtId);
        this.__globalDarkMode.purgeDependencyOnElmtId(rmElmtId);
        this.__lastError.purgeDependencyOnElmtId(rmElmtId);
        this.__historySessions.purgeDependencyOnElmtId(rmElmtId);
        this.__showHistory.purgeDependencyOnElmtId(rmElmtId);
        this.__highlightedMessageId.purgeDependencyOnElmtId(rmElmtId);
    }
    aboutToBeDeleted() {
        this.__chatHistory.aboutToBeDeleted();
        this.__inputText.aboutToBeDeleted();
        this.__isAIThinking.aboutToBeDeleted();
        this.__globalDarkMode.aboutToBeDeleted();
        this.__lastError.aboutToBeDeleted();
        this.__historySessions.aboutToBeDeleted();
        this.__showHistory.aboutToBeDeleted();
        this.__highlightedMessageId.aboutToBeDeleted();
        SubscriberManager.Get().delete(this.id__());
        this.aboutToBeDeletedInternal();
    }
    private __chatHistory: ObservedPropertyObjectPU<IChatMessage[]>;
    get chatHistory() {
        return this.__chatHistory.get();
    }
    set chatHistory(newValue: IChatMessage[]) {
        this.__chatHistory.set(newValue);
    }
    private __inputText: ObservedPropertySimplePU<string>;
    get inputText() {
        return this.__inputText.get();
    }
    set inputText(newValue: string) {
        this.__inputText.set(newValue);
    }
    private __isAIThinking: ObservedPropertySimplePU<boolean>;
    get isAIThinking() {
        return this.__isAIThinking.get();
    }
    set isAIThinking(newValue: boolean) {
        this.__isAIThinking.set(newValue);
    }
    private __globalDarkMode: ObservedPropertySimplePU<boolean>;
    get globalDarkMode() {
        return this.__globalDarkMode.get();
    }
    set globalDarkMode(newValue: boolean) {
        this.__globalDarkMode.set(newValue);
    }
    private __lastError: ObservedPropertySimplePU<string>;
    get lastError() {
        return this.__lastError.get();
    }
    set lastError(newValue: string) {
        this.__lastError.set(newValue);
    }
    private __historySessions: ObservedPropertyObjectPU<IHistorySession[]>;
    get historySessions() {
        return this.__historySessions.get();
    }
    set historySessions(newValue: IHistorySession[]) {
        this.__historySessions.set(newValue);
    }
    private __showHistory: ObservedPropertySimplePU<boolean>;
    get showHistory() {
        return this.__showHistory.get();
    }
    set showHistory(newValue: boolean) {
        this.__showHistory.set(newValue);
    }
    private __highlightedMessageId: ObservedPropertySimplePU<number>;
    get highlightedMessageId() {
        return this.__highlightedMessageId.get();
    }
    set highlightedMessageId(newValue: number) {
        this.__highlightedMessageId.set(newValue);
    }
    private listenerId: string;
    private preference: preferences.Preferences | null;
    private isInitialized: boolean;
    private lastSavedTimestamp: number;
    private scroller: Scroller; // 控制滚动
    private getHeaderPadding(): Padding {
        return { left: 20, right: 20 };
    }
    private getMessageMargin(): Margin {
        return { top: 8, bottom: 8 };
    }
    private getThinkingMargin(): Margin {
        return { top: 10 };
    }
    private getRequestHeader(): IHttpHeader {
        return {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${AppConfig.API_KEY}`,
            'HTTP-Referer': 'https://ai-assistant.harmonyos.com',
            'X-Title': 'HarmonyOS AI Assistant'
        };
    }
    // ==================== 初始化历史记录（带去重） ====================
    async initPreferencesAndHistory(): Promise<void> {
        try {
            const context = getContext(this) as common.UIAbilityContext;
            this.preference = await preferences.getPreferences(context, 'ai_history');
            console.log('AI历史 Preferences 初始化成功');
            const savedHistory = await this.preference.get('history_sessions', '[]');
            let historyDataStr: string = typeof savedHistory === 'string' ? savedHistory : JSON.stringify(savedHistory);
            if (historyDataStr.trim() !== '' && historyDataStr !== '[]') {
                try {
                    let loadedSessions = JSON.parse(historyDataStr) as IHistorySession[];
                    loadedSessions = loadedSessions.filter((session, index, self) => index === self.findIndex(s => s.title === session.title && s.timestamp === session.timestamp));
                    this.historySessions = loadedSessions;
                    console.log(`加载历史会话: ${this.historySessions.length} 个（已去重）`);
                }
                catch (parseError) {
                    console.error('历史数据解析失败，使用空数组');
                    this.historySessions = [];
                }
            }
            else {
                this.historySessions = [];
            }
        }
        catch (error) {
            console.error('AI历史初始化失败:', error);
            this.historySessions = [];
        }
    }
    // ==================== 保存完整对话（防重复） ====================
    async saveCurrentSession(): Promise<void> {
        if (!this.preference)
            return;
        const messages = this.chatHistory;
        if (messages.length < 2)
            return;
        const welcomeContent = '您好！我是基于DeepSeek的AI助手，请问有什么可以帮助您的？';
        const lastMsg = messages[messages.length - 1];
        const secondLastMsg = messages[messages.length - 2];
        if (lastMsg.isUser ||
            lastMsg.content === welcomeContent ||
            !secondLastMsg.isUser) {
            console.log('非完整对话，跳过保存');
            return;
        }
        const now = new Date().getTime();
        if (now - this.lastSavedTimestamp < 5000)
            return;
        const currentHash = this.generateHash(JSON.stringify(messages));
        const latestSession = this.historySessions[0];
        if (latestSession) {
            const latestHash = this.generateHash(JSON.stringify(latestSession.messages));
            if (latestHash === currentHash && now - latestSession.timestamp < 10000)
                return;
        }
        const firstUserMsg = messages.find(m => m.isUser)?.content || '未命名会话';
        const proposedTitle = firstUserMsg.substring(0, 20) + (firstUserMsg.length > 20 ? '...' : '');
        const session: IHistorySession = {
            timestamp: now,
            title: proposedTitle,
            messages: [...messages]
        };
        let currentHistory = [...this.historySessions];
        currentHistory.unshift(session);
        if (currentHistory.length > AppConfig.MAX_HISTORY_SESSIONS) {
            currentHistory = currentHistory.slice(0, AppConfig.MAX_HISTORY_SESSIONS);
        }
        try {
            await this.preference.put('history_sessions', JSON.stringify(currentHistory));
            await this.preference.flush();
            this.historySessions = currentHistory;
            this.lastSavedTimestamp = now;
            console.log('完整会话保存成功');
        }
        catch (error) {
            console.error('保存失败:', error);
        }
    }
    private generateHash(str: string): string {
        let hash = 0;
        for (let i = 0; i < str.length; i++) {
            const char = str.charCodeAt(i);
            hash = ((hash << 5) - hash) + char;
            hash = hash & hash;
        }
        return hash.toString();
    }
    // ==================== 加载会话（自动滚到底部 + 高亮） ====================
    loadSelectedSession(session: IHistorySession): void {
        this.chatHistory = [...session.messages];
        this.showHistory = false;
        if (session.messages.length > 0) {
            const lastMsg = session.messages[session.messages.length - 1];
            this.highlightedMessageId = lastMsg.timestamp;
            setTimeout(() => {
                this.highlightedMessageId = -1;
            }, 2000);
        }
        setTimeout(() => {
            if (this.chatHistory.length > 0) {
                this.scroller.scrollToIndex(this.chatHistory.length - 1, true, ScrollAlign.END);
            }
        }, 100);
        console.log(`加载历史会话: ${session.title}`);
    }
    async deleteSession(timestamp: number): Promise<void> {
        if (!this.preference)
            return;
        this.historySessions = this.historySessions.filter(s => s.timestamp !== timestamp);
        try {
            await this.preference.put('history_sessions', JSON.stringify(this.historySessions));
            await this.preference.flush();
            console.log('历史会话删除成功');
        }
        catch (error) {
            console.error('删除失败:', error);
        }
    }
    // ==================== 生命周期 ====================
    async aboutToAppear(): Promise<void> {
        console.info('AI问答页面初始化');
        if (this.isInitialized)
            return;
        const context = getContext(this) as common.UIAbilityContext;
        await ThemeManager.initTheme(context);
        await this.initPreferencesAndHistory();
        this.globalDarkMode = ThemeManager.getCurrentThemeSync();
        try {
            const actualTheme = await ThemeManager.getIsDarkMode();
            if (this.globalDarkMode !== actualTheme) {
                this.globalDarkMode = actualTheme;
            }
            console.info(`AIQna 初始化完成: ${this.globalDarkMode ? '深色' : '浅色'}`);
        }
        catch (error) {
            console.error('主题初始化失败:', error);
            this.globalDarkMode = false;
        }
        const themeCallback = (isDark: boolean) => {
            if (this.globalDarkMode !== isDark) {
                console.info(`主题变更: ${isDark ? '深色' : '浅色'}`);
                this.globalDarkMode = isDark;
            }
        };
        this.listenerId = ThemeManager.addListener(themeCallback);
        const welcomeMessage: IChatMessage = {
            content: '您好！我是基于DeepSeek的AI助手，请问有什么可以帮助您的？',
            isUser: false,
            timestamp: new Date().getTime()
        };
        this.chatHistory = [welcomeMessage];
        this.isInitialized = true;
    }
    aboutToDisappear(): void {
        if (this.listenerId) {
            ThemeManager.removeListener(this.listenerId);
            this.listenerId = '';
        }
    }
    // ==================== AI 请求 ====================
    private buildMessages(newQuestion: string): IApiMessage[] {
        const messages: IApiMessage[] = [];
        messages.push({
            role: "system",
            content: "你是一个有帮助的AI助手，请用中文回答用户的问题。回答要简洁明了，控制在500字以内。"
        });
        const recentHistory = this.chatHistory.slice(-4);
        recentHistory.forEach((msg: IChatMessage) => {
            messages.push({
                role: msg.isUser ? "user" : "assistant",
                content: msg.content
            });
        });
        messages.push({ role: "user", content: newQuestion });
        return messages;
    }
    private async sendAIRequest(messages: IApiMessage[]): Promise<string> {
        return new Promise((resolve, reject) => {
            const httpRequest = http.createHttp();
            const requestData: IApiRequest = {
                model: AppConfig.DEFAULT_MODEL,
                messages: messages,
                max_tokens: 800,
                temperature: 0.7
            };
            const options: IHttpRequestOptions = {
                method: http.RequestMethod.POST,
                header: this.getRequestHeader(),
                extraData: JSON.stringify(requestData),
                readTimeout: 30000,
                connectTimeout: 10000
            };
            httpRequest.request(AppConfig.API_ENDPOINT, options, (err: BusinessError, data: http.HttpResponse) => {
                if (err) {
                    httpRequest.destroy();
                    reject(err);
                    return;
                }
                if (data.responseCode === http.ResponseCode.OK) {
                    try {
                        const result: IApiResponse = JSON.parse(data.result as string);
                        if (result.choices && result.choices.length > 0 && result.choices[0].message) {
                            resolve(result.choices[0].message.content);
                        }
                        else if (result.error) {
                            reject(new Error(result.error.message));
                        }
                        else {
                            reject(new Error('API返回格式异常'));
                        }
                    }
                    catch (parseError) {
                        reject(new Error('响应数据解析失败'));
                    }
                }
                else {
                    reject(new Error(`HTTP错误代码: ${data.responseCode}`));
                }
                httpRequest.destroy();
            });
        });
    }
    // ==================== 发送消息（自动滚到底部） ====================
    async sendMessage(): Promise<void> {
        if (!this.inputText.trim())
            return;
        const userQuestion = this.inputText.trim();
        const userMessage: IChatMessage = {
            content: userQuestion,
            isUser: true,
            timestamp: new Date().getTime()
        };
        this.chatHistory = [...this.chatHistory, userMessage];
        this.inputText = '';
        this.isAIThinking = true;
        this.lastError = '';
        try {
            const messages = this.buildMessages(userQuestion);
            const aiResponse = await this.sendAIRequest(messages);
            const aiMessage: IChatMessage = {
                content: aiResponse,
                isUser: false,
                timestamp: new Date().getTime()
            };
            this.chatHistory = [...this.chatHistory, aiMessage];
        }
        catch (error) {
            console.error(`API调用错误: ${JSON.stringify(error)}`);
            const errorMessage = this.getErrorMessage(error as Error);
            this.lastError = errorMessage;
            const errorMessageObj: IChatMessage = {
                content: errorMessage,
                isUser: false,
                timestamp: new Date().getTime()
            };
            this.chatHistory = [...this.chatHistory, errorMessageObj];
        }
        finally {
            this.isAIThinking = false;
            if (!this.lastError &&
                this.chatHistory.length > 0 &&
                !this.chatHistory[this.chatHistory.length - 1].isUser) {
                await this.saveCurrentSession();
            }
            setTimeout(() => {
                if (this.chatHistory.length > 0) {
                    this.scroller.scrollToIndex(this.chatHistory.length - 1, true, ScrollAlign.END);
                }
            }, 100);
        }
    }
    private getErrorMessage(error: Error): string {
        const errorStr: string = error.message;
        if (errorStr.includes('network') || errorStr.includes('Network'))
            return '网络连接失败，请检查网络设置后重试。';
        if (errorStr.includes('timeout'))
            return '请求超时，请稍后重试。';
        if (errorStr.includes('401') || errorStr.includes('authentication'))
            return 'API密钥验证失败，请检查配置。';
        if (errorStr.includes('403'))
            return '访问被拒绝，可能是权限问题或配额已用尽。';
        if (errorStr.includes('429'))
            return '请求频率过高，请稍后再试。';
        if (errorStr.includes('500') || errorStr.includes('502') || errorStr.includes('503'))
            return '服务器暂时不可用，请稍后重试。';
        return '抱歉，暂时无法获取AI回复，请稍后重试。';
    }
    // ==================== 交互功能 ====================
    toggleHistory(): void {
        this.showHistory = !this.showHistory;
    }
    async newConversation(): Promise<void> {
        if (this.chatHistory.length > 1 &&
            !this.chatHistory[this.chatHistory.length - 1].isUser) {
            await this.saveCurrentSession();
        }
        const welcomeMessage: IChatMessage = {
            content: '您好！我是基于DeepSeek的AI助手，请问有什么可以帮助您的？',
            isUser: false,
            timestamp: new Date().getTime()
        };
        this.chatHistory = [welcomeMessage];
        this.lastError = '';
        this.highlightedMessageId = -1;
        console.log('新建对话成功');
    }
    // ==================== 样式 ====================
    getBackgroundColor(): string {
        return this.globalDarkMode ? '#000000' : '#F7F9FC';
    }
    getCardColor(): string {
        return this.globalDarkMode ? '#1C1C1E' : '#FFFFFF';
    }
    getTextColor(): string {
        return this.globalDarkMode ? '#FFFFFF' : '#000000';
    }
    getSecondaryTextColor(): string {
        return this.globalDarkMode ? '#8E8E93' : '#666666';
    }
    getErrorColor(): string {
        return '#FF3B30';
    }
    getAccentColor(): string {
        return this.globalDarkMode ? '#0A84FF' : '#007AFF';
    }
    formatHistoryDate(timestamp: number): string {
        const date = new Date(timestamp);
        const now = new Date();
        const diffDays = (now.getTime() - timestamp) / (1000 * 60 * 60 * 24);
        if (diffDays < 1)
            return '今天';
        if (diffDays < 2)
            return '昨天';
        return date.toLocaleDateString('zh-CN', { month: 'short', day: 'numeric' });
    }
    // ==================== UI 构建 ====================
    initialRender() {
        this.observeComponentCreation2((elmtId, isInitialRender) => {
            Column.create({ space: 20 });
            Column.width('100%');
            Column.height('100%');
            Column.padding(16);
            Column.backgroundColor(this.getBackgroundColor());
        }, Column);
        this.observeComponentCreation2((elmtId, isInitialRender) => {
            // 标题栏
            Row.create();
            // 标题栏
            Row.width('100%');
            // 标题栏
            Row.height(60);
            // 标题栏
            Row.padding(this.getHeaderPadding());
        }, Row);
        this.observeComponentCreation2((elmtId, isInitialRender) => {
            Text.create('DeepSeek AI智能助手');
            Text.fontSize(24);
            Text.fontWeight(FontWeight.Bold);
            Text.fontColor(this.getTextColor());
            Text.layoutWeight(1);
        }, Text);
        Text.pop();
        this.observeComponentCreation2((elmtId, isInitialRender) => {
            Button.createWithLabel('历史查阅');
            Button.type(ButtonType.Normal);
            Button.width(80);
            Button.height(30);
            Button.backgroundColor(this.getCardColor());
            Button.fontColor(this.getTextColor());
            Button.fontSize(12);
            Button.onClick(() => this.toggleHistory());
        }, Button);
        Button.pop();
        // 标题栏
        Row.pop();
        this.observeComponentCreation2((elmtId, isInitialRender) => {
            If.create();
            // 历史视图
            if (this.showHistory) {
                this.ifElseBranchUpdateFunction(0, () => {
                    this.observeComponentCreation2((elmtId, isInitialRender) => {
                        Column.create({ space: 10 });
                        Column.width('100%');
                        Column.height('100%');
                        Column.layoutWeight(1);
                    }, Column);
                    this.observeComponentCreation2((elmtId, isInitialRender) => {
                        Text.create('历史查询记录');
                        Text.fontSize(18);
                        Text.fontWeight(FontWeight.Bold);
                        Text.fontColor(this.getTextColor());
                        Text.margin({ bottom: 10 });
                    }, Text);
                    Text.pop();
                    this.observeComponentCreation2((elmtId, isInitialRender) => {
                        If.create();
                        if (this.historySessions.length === 0) {
                            this.ifElseBranchUpdateFunction(0, () => {
                                this.observeComponentCreation2((elmtId, isInitialRender) => {
                                    Text.create('暂无历史记录');
                                    Text.fontSize(16);
                                    Text.fontColor(this.getSecondaryTextColor());
                                    Text.textAlign(TextAlign.Center);
                                    Text.layoutWeight(1);
                                }, Text);
                                Text.pop();
                            });
                        }
                        else {
                            this.ifElseBranchUpdateFunction(1, () => {
                                this.observeComponentCreation2((elmtId, isInitialRender) => {
                                    List.create({ space: 10 });
                                    List.layoutWeight(1);
                                    List.width('100%');
                                    List.height('100%');
                                }, List);
                                this.observeComponentCreation2((elmtId, isInitialRender) => {
                                    ForEach.create();
                                    const forEachItemGenFunction = _item => {
                                        const session = _item;
                                        {
                                            const itemCreation = (elmtId, isInitialRender) => {
                                                ViewStackProcessor.StartGetAccessRecordingFor(elmtId);
                                                itemCreation2(elmtId, isInitialRender);
                                                if (!isInitialRender) {
                                                    ListItem.pop();
                                                }
                                                ViewStackProcessor.StopGetAccessRecording();
                                            };
                                            const itemCreation2 = (elmtId, isInitialRender) => {
                                                ListItem.create(deepRenderFunction, true);
                                            };
                                            const deepRenderFunction = (elmtId, isInitialRender) => {
                                                itemCreation(elmtId, isInitialRender);
                                                this.observeComponentCreation2((elmtId, isInitialRender) => {
                                                    Column.create();
                                                    Column.width('100%');
                                                    Column.padding(12);
                                                    Column.backgroundColor(this.getCardColor());
                                                    Column.borderRadius(8);
                                                    Column.clip(false);
                                                }, Column);
                                                this.observeComponentCreation2((elmtId, isInitialRender) => {
                                                    Row.create();
                                                    Row.width('100%');
                                                    Row.justifyContent(FlexAlign.SpaceBetween);
                                                }, Row);
                                                this.observeComponentCreation2((elmtId, isInitialRender) => {
                                                    Text.create(session.title);
                                                    Text.fontSize(16);
                                                    Text.fontWeight(FontWeight.Medium);
                                                    Text.fontColor(this.getTextColor());
                                                    Text.layoutWeight(1);
                                                }, Text);
                                                Text.pop();
                                                this.observeComponentCreation2((elmtId, isInitialRender) => {
                                                    // 日期 + 叉号（右对齐，叉号左移紧贴日期）
                                                    Row.create();
                                                    // 日期 + 叉号（右对齐，叉号左移紧贴日期）
                                                    Row.justifyContent(FlexAlign.End);
                                                    // 日期 + 叉号（右对齐，叉号左移紧贴日期）
                                                    Row.margin({ right: 12 });
                                                }, Row);
                                                this.observeComponentCreation2((elmtId, isInitialRender) => {
                                                    Text.create(this.formatHistoryDate(session.timestamp));
                                                    Text.fontSize(12);
                                                    Text.fontColor(this.getSecondaryTextColor());
                                                    Text.margin({ right: 6 });
                                                }, Text);
                                                Text.pop();
                                                this.observeComponentCreation2((elmtId, isInitialRender) => {
                                                    Button.createWithLabel('X');
                                                    Button.type(ButtonType.Normal);
                                                    Button.width(32);
                                                    Button.height(32);
                                                    Button.backgroundColor(this.getErrorColor());
                                                    Button.fontColor('#FFFFFF');
                                                    Button.fontSize(16);
                                                    Button.fontWeight(FontWeight.Bold);
                                                    Button.borderRadius(6);
                                                    Button.onClick(() => this.deleteSession(session.timestamp));
                                                }, Button);
                                                Button.pop();
                                                // 日期 + 叉号（右对齐，叉号左移紧贴日期）
                                                Row.pop();
                                                Row.pop();
                                                this.observeComponentCreation2((elmtId, isInitialRender) => {
                                                    Button.createWithLabel('加载会话');
                                                    Button.type(ButtonType.Capsule);
                                                    Button.width('100%');
                                                    Button.height(40);
                                                    Button.backgroundColor(this.getAccentColor());
                                                    Button.fontColor('#FFFFFF');
                                                    Button.onClick(() => this.loadSelectedSession(session));
                                                }, Button);
                                                Button.pop();
                                                Column.pop();
                                                ListItem.pop();
                                            };
                                            this.observeComponentCreation2(itemCreation2, ListItem);
                                            ListItem.pop();
                                        }
                                    };
                                    this.forEachUpdateFunction(elmtId, this.historySessions, forEachItemGenFunction, (session: IHistorySession) => session.timestamp.toString(), false, false);
                                }, ForEach);
                                ForEach.pop();
                                List.pop();
                            });
                        }
                    }, If);
                    If.pop();
                    this.observeComponentCreation2((elmtId, isInitialRender) => {
                        Button.createWithLabel('返回聊天');
                        Button.type(ButtonType.Normal);
                        Button.width('100%');
                        Button.height(40);
                        Button.backgroundColor(this.getCardColor());
                        Button.fontColor(this.getTextColor());
                        Button.margin({ top: 10 });
                        Button.onClick(() => this.toggleHistory());
                    }, Button);
                    Button.pop();
                    Column.pop();
                });
            }
            else {
                this.ifElseBranchUpdateFunction(1, () => {
                    this.observeComponentCreation2((elmtId, isInitialRender) => {
                        If.create();
                        // 聊天主界面
                        if (this.lastError) {
                            this.ifElseBranchUpdateFunction(0, () => {
                                this.observeComponentCreation2((elmtId, isInitialRender) => {
                                    Row.create();
                                    Row.width('100%');
                                    Row.justifyContent(FlexAlign.Center);
                                    Row.padding(10);
                                }, Row);
                                this.observeComponentCreation2((elmtId, isInitialRender) => {
                                    Text.create(this.lastError);
                                    Text.fontSize(14);
                                    Text.fontColor(this.getErrorColor());
                                    Text.textAlign(TextAlign.Center);
                                }, Text);
                                Text.pop();
                                Row.pop();
                            });
                        }
                        else {
                            this.ifElseBranchUpdateFunction(1, () => {
                            });
                        }
                    }, If);
                    If.pop();
                    this.observeComponentCreation2((elmtId, isInitialRender) => {
                        Column.create();
                        Column.layoutWeight(1);
                        Column.width('100%');
                        Column.padding(10);
                        Column.backgroundColor(this.getCardColor());
                        Column.borderRadius(16);
                    }, Column);
                    this.observeComponentCreation2((elmtId, isInitialRender) => {
                        If.create();
                        if (this.chatHistory.length === 0) {
                            this.ifElseBranchUpdateFunction(0, () => {
                                this.observeComponentCreation2((elmtId, isInitialRender) => {
                                    Column.create();
                                    Column.width('100%');
                                    Column.height('100%');
                                    Column.justifyContent(FlexAlign.Center);
                                }, Column);
                                this.observeComponentCreation2((elmtId, isInitialRender) => {
                                    Text.create('开始与AI对话吧！');
                                    Text.fontSize(16);
                                    Text.fontColor(this.getSecondaryTextColor());
                                }, Text);
                                Text.pop();
                                Column.pop();
                            });
                        }
                        else {
                            this.ifElseBranchUpdateFunction(1, () => {
                                this.observeComponentCreation2((elmtId, isInitialRender) => {
                                    List.create({ space: 10, scroller: this.scroller });
                                    List.layoutWeight(1);
                                    List.width('100%');
                                    List.height('100%');
                                }, List);
                                this.observeComponentCreation2((elmtId, isInitialRender) => {
                                    ForEach.create();
                                    const forEachItemGenFunction = _item => {
                                        const message = _item;
                                        {
                                            const itemCreation = (elmtId, isInitialRender) => {
                                                ViewStackProcessor.StartGetAccessRecordingFor(elmtId);
                                                itemCreation2(elmtId, isInitialRender);
                                                if (!isInitialRender) {
                                                    ListItem.pop();
                                                }
                                                ViewStackProcessor.StopGetAccessRecording();
                                            };
                                            const itemCreation2 = (elmtId, isInitialRender) => {
                                                ListItem.create(deepRenderFunction, true);
                                            };
                                            const deepRenderFunction = (elmtId, isInitialRender) => {
                                                itemCreation(elmtId, isInitialRender);
                                                this.observeComponentCreation2((elmtId, isInitialRender) => {
                                                    Row.create();
                                                    Row.width('100%');
                                                    Row.margin(this.getMessageMargin());
                                                }, Row);
                                                this.observeComponentCreation2((elmtId, isInitialRender) => {
                                                    If.create();
                                                    if (message.isUser) {
                                                        this.ifElseBranchUpdateFunction(0, () => {
                                                            this.observeComponentCreation2((elmtId, isInitialRender) => {
                                                                Blank.create();
                                                            }, Blank);
                                                            Blank.pop();
                                                            this.observeComponentCreation2((elmtId, isInitialRender) => {
                                                                Text.create(message.content);
                                                                Context.animation({ duration: 300, curve: Curve.EaseInOut });
                                                                Text.fontSize(16);
                                                                Text.padding(12);
                                                                Text.backgroundColor('#007AFF');
                                                                Text.fontColor('#FFFFFF');
                                                                Text.borderRadius(16);
                                                                Text.opacity(this.highlightedMessageId === message.timestamp ? 1.0 : 0.8);
                                                                Text.scale(this.highlightedMessageId === message.timestamp ? { x: 1.05, y: 1.05 } : { x: 1, y: 1 });
                                                                Context.animation(null);
                                                            }, Text);
                                                            Text.pop();
                                                        });
                                                    }
                                                    else {
                                                        this.ifElseBranchUpdateFunction(1, () => {
                                                            this.observeComponentCreation2((elmtId, isInitialRender) => {
                                                                Text.create(message.content);
                                                                Context.animation({ duration: 300, curve: Curve.EaseInOut });
                                                                Text.fontSize(16);
                                                                Text.padding(12);
                                                                Text.backgroundColor(this.globalDarkMode ? '#2C2C2E' : '#F2F2F7');
                                                                Text.fontColor(this.getTextColor());
                                                                Text.borderRadius(16);
                                                                Text.opacity(this.highlightedMessageId === message.timestamp ? 1.0 : 0.8);
                                                                Text.scale(this.highlightedMessageId === message.timestamp ? { x: 1.05, y: 1.05 } : { x: 1, y: 1 });
                                                                Context.animation(null);
                                                            }, Text);
                                                            Text.pop();
                                                            this.observeComponentCreation2((elmtId, isInitialRender) => {
                                                                Blank.create();
                                                            }, Blank);
                                                            Blank.pop();
                                                        });
                                                    }
                                                }, If);
                                                If.pop();
                                                Row.pop();
                                                ListItem.pop();
                                            };
                                            this.observeComponentCreation2(itemCreation2, ListItem);
                                            ListItem.pop();
                                        }
                                    };
                                    this.forEachUpdateFunction(elmtId, this.chatHistory, forEachItemGenFunction, (item: IChatMessage) => item.timestamp.toString(), false, false);
                                }, ForEach);
                                ForEach.pop();
                                List.pop();
                            });
                        }
                    }, If);
                    If.pop();
                    this.observeComponentCreation2((elmtId, isInitialRender) => {
                        If.create();
                        if (this.isAIThinking) {
                            this.ifElseBranchUpdateFunction(0, () => {
                                this.observeComponentCreation2((elmtId, isInitialRender) => {
                                    Row.create();
                                    Row.width('100%');
                                    Row.justifyContent(FlexAlign.Center);
                                    Row.margin(this.getThinkingMargin());
                                }, Row);
                                this.observeComponentCreation2((elmtId, isInitialRender) => {
                                    Text.create('AI正在思考中...');
                                    Text.fontSize(14);
                                    Text.fontColor(this.getSecondaryTextColor());
                                }, Text);
                                Text.pop();
                                this.observeComponentCreation2((elmtId, isInitialRender) => {
                                    LoadingProgress.create();
                                    LoadingProgress.width(20);
                                    LoadingProgress.height(20);
                                }, LoadingProgress);
                                Row.pop();
                            });
                        }
                        else {
                            this.ifElseBranchUpdateFunction(1, () => {
                            });
                        }
                    }, If);
                    If.pop();
                    Column.pop();
                    this.observeComponentCreation2((elmtId, isInitialRender) => {
                        // 输入区
                        Row.create({ space: 10 });
                        // 输入区
                        Row.width('100%');
                        // 输入区
                        Row.padding(10);
                    }, Row);
                    this.observeComponentCreation2((elmtId, isInitialRender) => {
                        TextInput.create({
                            placeholder: '输入您的问题...',
                            text: this.inputText
                        });
                        TextInput.layoutWeight(1);
                        TextInput.height(40);
                        TextInput.fontSize(16);
                        TextInput.padding(8);
                        TextInput.backgroundColor(this.globalDarkMode ? '#2C2C2E' : '#F0F0F0');
                        TextInput.fontColor(this.getTextColor());
                        TextInput.onChange((value: string) => {
                            this.inputText = value;
                        });
                    }, TextInput);
                    this.observeComponentCreation2((elmtId, isInitialRender) => {
                        Button.createWithLabel('发送');
                        Button.width(60);
                        Button.height(40);
                        Button.backgroundColor(this.getAccentColor());
                        Button.fontColor('#FFFFFF');
                        Button.enabled(!!this.inputText.trim() && !this.isAIThinking);
                        Button.onClick(() => this.sendMessage());
                    }, Button);
                    Button.pop();
                    // 输入区
                    Row.pop();
                    this.observeComponentCreation2((elmtId, isInitialRender) => {
                        // 底部按钮
                        Row.create({ space: 15 });
                        // 底部按钮
                        Row.width('100%');
                        // 底部按钮
                        Row.padding(10);
                    }, Row);
                    this.observeComponentCreation2((elmtId, isInitialRender) => {
                        Button.createWithLabel('新建对话');
                        Button.layoutWeight(1);
                        Button.height(40);
                        Button.backgroundColor(this.getCardColor());
                        Button.fontColor(this.getTextColor());
                        Button.onClick(() => this.newConversation());
                    }, Button);
                    Button.pop();
                    this.observeComponentCreation2((elmtId, isInitialRender) => {
                        Button.createWithLabel('返回');
                        Button.layoutWeight(1);
                        Button.height(40);
                        Button.backgroundColor(this.getAccentColor());
                        Button.fontColor('#FFFFFF');
                        Button.onClick(() => router.back());
                    }, Button);
                    Button.pop();
                    // 底部按钮
                    Row.pop();
                });
            }
        }, If);
        If.pop();
        Column.pop();
    }
    rerender() {
        this.updateDirtyElements();
    }
    static getEntryName(): string {
        return "AIQna";
    }
}
registerNamedRoute(() => new AIQna(undefined, {}), "", { bundleName: "com.example.myapplication", moduleName: "entry", pagePath: "pages/AIQna", pageFullPath: "entry/src/main/ets/pages/AIQna", integratedHsp: "false" });
