if (!("finalizeConstruction" in ViewPU.prototype)) {
    Reflect.set(ViewPU.prototype, "finalizeConstruction", () => { });
}
interface AIQna_Params {
    chatHistory?: IChatMessage[];
    inputText?: string;
    isAIThinking?: boolean;
    globalDarkMode?: boolean;
    lastError?: string;
    listenerId?: string;
}
import router from "@ohos:router";
import http from "@ohos:net.http";
import type { BusinessError } from "@ohos:base";
import ThemeManager from "@bundle:com.example.myapplication/entry/ets/common/ThemeManager";
// ==================== 明确定义所有接口 ====================
interface IChatMessage {
    content: string;
    isUser: boolean;
    timestamp: number;
}
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 BorderRadius {
    topLeft?: number;
    topRight?: number;
    bottomLeft?: number;
    bottomRight?: 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';
}
class ChatMessageImpl implements IChatMessage {
    content: string;
    isUser: boolean;
    timestamp: number;
    constructor(content: string, isUser: boolean) {
        this.content = content;
        this.isUser = isUser;
        this.timestamp = new Date().getTime();
    }
}
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.listenerId = '';
        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.listenerId !== undefined) {
            this.listenerId = params.listenerId;
        }
    }
    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);
    }
    aboutToBeDeleted() {
        this.__chatHistory.aboutToBeDeleted();
        this.__inputText.aboutToBeDeleted();
        this.__isAIThinking.aboutToBeDeleted();
        this.__globalDarkMode.aboutToBeDeleted();
        this.__lastError.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 listenerId: string;
    private getHeaderPadding(): Padding {
        return { left: 20, right: 20 };
    }
    private getUserBorderRadius(): BorderRadius {
        return { topLeft: 0 };
    }
    private getAIBorderRadius(): BorderRadius {
        return { topRight: 0 };
    }
    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 aboutToAppear(): Promise<void> {
        console.info('AI问答页面初始化');
        this.globalDarkMode = await ThemeManager.getIsDarkMode();
        // 添加主题监听器
        this.listenerId = ThemeManager.addListener((isDark: boolean) => {
            this.globalDarkMode = isDark;
        });
        const welcomeMessage: IChatMessage = new ChatMessageImpl('您好！我是基于DeepSeek的AI助手，请问有什么可以帮助您的？', false);
        this.chatHistory = [welcomeMessage];
    }
    aboutToDisappear(): void {
        // 移除监听器避免内存泄漏
        ThemeManager.removeListener(this.listenerId);
    }
    private buildMessages(newQuestion: string): IApiMessage[] {
        const messages: IApiMessage[] = [];
        const systemMessage: IApiMessage = {
            role: "system",
            content: "你是一个有帮助的AI助手，请用中文回答用户的问题。回答要简洁明了，控制在500字以内。"
        };
        messages.push(systemMessage);
        const recentHistory = this.chatHistory.slice(-4);
        recentHistory.forEach((msg: IChatMessage) => {
            const historyMessage: IApiMessage = {
                role: msg.isUser ? "user" : "assistant",
                content: msg.content
            };
            messages.push(historyMessage);
        });
        const userMessage: IApiMessage = {
            role: "user",
            content: newQuestion
        };
        messages.push(userMessage);
        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 = new ChatMessageImpl(userQuestion, true);
        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 = new ChatMessageImpl(aiResponse, false);
            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 = new ChatMessageImpl(errorMessage, false);
            this.chatHistory = [...this.chatHistory, errorMessageObj];
        }
        finally {
            this.isAIThinking = false;
        }
    }
    private getErrorMessage(error: Error): string {
        const errorStr: string = error.message;
        if (errorStr.includes('network') || errorStr.includes('Network')) {
            return '网络连接失败，请检查网络设置后重试。';
        }
        else if (errorStr.includes('timeout')) {
            return '请求超时，请稍后重试。';
        }
        else if (errorStr.includes('401') || errorStr.includes('authentication')) {
            return 'API密钥验证失败，请检查配置。';
        }
        else if (errorStr.includes('403')) {
            return '访问被拒绝，可能是权限问题或配额已用尽。';
        }
        else if (errorStr.includes('429')) {
            return '请求频率过高，请稍后再试。';
        }
        else if (errorStr.includes('500') || errorStr.includes('502') || errorStr.includes('503')) {
            return '服务器暂时不可用，请稍后重试。';
        }
        else {
            return '抱歉，暂时无法获取AI回复，请稍后重试。';
        }
    }
    clearChat(): void {
        const welcomeMessage: IChatMessage = new ChatMessageImpl('您好！我是基于DeepSeek的AI助手，请问有什么可以帮助您的？', false);
        this.chatHistory = [welcomeMessage];
        this.lastError = '';
    }
    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';
    }
    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(this.globalDarkMode ? '浅色' : '深色');
            Button.type(ButtonType.Normal);
            Button.width(60);
            Button.height(30);
            Button.backgroundColor(this.getCardColor());
            Button.fontColor(this.getTextColor());
            Button.onClick(() => {
                const newTheme = !this.globalDarkMode;
                ThemeManager.setTheme(newTheme);
            });
        }, Button);
        Button.pop();
        Row.pop();
        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 });
                        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);
                                                    Text.fontSize(16);
                                                    Text.padding(12);
                                                    Text.backgroundColor('#007AFF');
                                                    Text.fontColor('#FFFFFF');
                                                    Text.borderRadius(16);
                                                    Text.borderRadius(this.getUserBorderRadius());
                                                }, Text);
                                                Text.pop();
                                            });
                                        }
                                        else {
                                            this.ifElseBranchUpdateFunction(1, () => {
                                                this.observeComponentCreation2((elmtId, isInitialRender) => {
                                                    Text.create(message.content);
                                                    Text.fontSize(16);
                                                    Text.padding(12);
                                                    Text.backgroundColor(this.globalDarkMode ? '#2C2C2E' : '#F2F2F7');
                                                    Text.fontColor(this.getTextColor());
                                                    Text.borderRadius(16);
                                                    Text.borderRadius(this.getAIBorderRadius());
                                                }, 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('#007AFF');
            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.clearChat());
        }, Button);
        Button.pop();
        this.observeComponentCreation2((elmtId, isInitialRender) => {
            Button.createWithLabel('返回');
            Button.layoutWeight(1);
            Button.height(40);
            Button.backgroundColor('#007AFF');
            Button.fontColor('#FFFFFF');
            Button.onClick(() => {
                router.back();
            });
        }, Button);
        Button.pop();
        Row.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" });
