File size: 7,600 Bytes
e636070
 
d738a3f
 
 
 
 
 
e636070
d738a3f
e636070
 
d738a3f
 
 
e636070
d738a3f
 
 
 
e636070
d738a3f
e636070
d738a3f
 
 
 
e636070
d738a3f
 
 
e636070
 
d738a3f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e636070
 
d738a3f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e636070
 
d738a3f
 
 
 
 
 
e636070
d738a3f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e636070
d738a3f
 
 
 
 
 
 
 
 
 
 
e636070
 
d738a3f
 
 
 
e636070
d738a3f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e636070
d738a3f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e636070
 
 
d738a3f
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
class APIPanel {
    constructor() {
        // 强制单例模式
        if (window.apiPanelInstance) {
            console.warn('APIPanel: Instance already exists, returning existing one.');
            return window.apiPanelInstance;
        }
        console.log('APIPanel: Creating new instance.');

        // 初始化DOM元素引用
        this.providerSelect = document.getElementById('api-provider');
        this.modelSelect = document.getElementById('api-model');
        this.apiKeyInput = document.getElementById('api-key');
        // Use a more specific selector if multiple buttons might exist
        this.submitButton = document.querySelector('#api-panel .api-submit-btn');

        // Check if elements were found
        if (!this.providerSelect || !this.modelSelect || !this.apiKeyInput || !this.submitButton) {
            console.error("APIPanel: One or more required DOM elements not found during construction.");
        }

        this.initialized = false;

        this.handleSubmit = this.handleSubmit.bind(this);
        this.updateModelOptions = this.updateModelOptions.bind(this);
        if (this.providerSelect && this.modelSelect) {
            this.updateModelOptions();
        }

        window.apiPanelInstance = this;
        console.log('APIPanel: New instance created.');
    }

    init() {
        if (this.initialized) {
            console.log('APIPanel: Listeners already initialized, skipping.');
            return;
        }
        
        if (!this.providerSelect || !this.modelSelect || !this.apiKeyInput || !this.submitButton) {
             console.error("APIPanel: Cannot init listeners, required DOM elements missing.");
             return;
        }

        console.log('APIPanel: Initializing event listeners.');
        this.setupEventListeners();
        this.initialized = true; 
        console.log('APIPanel: Event listeners initialized successfully.');
    }

    setupEventListeners() {
        // Submit Button Listener
        if (this.submitButton) {
            this.submitButton.removeEventListener('click', this.handleSubmit);
            // Add the listener
            this.submitButton.addEventListener('click', this.handleSubmit);
            console.log('APIPanel: Submit button listener attached.');
        }

        // Provider Select Listener
        if (this.providerSelect) {
            this.providerSelect.removeEventListener('change', this.updateModelOptions);
            this.providerSelect.addEventListener('change', this.updateModelOptions);
            console.log('APIPanel: Provider select listener attached.');
        }
    }

    updateModelOptions() {
        if (!this.providerSelect || !this.modelSelect) {
            console.warn('APIPanel: DOM elements missing for updateModelOptions.');
            return;
        }

        const provider = this.providerSelect.value;
        const models = {
            openai: ['gpt-3.5-turbo', 'gpt-4'],
            anthropic: ['claude-3-opus', 'claude-3-sonnet'],
            alibaba: ['qwen-turbo', 'qwen-max'],
            openrouter: ['gpt-4o-mini']
        };

        const currentModelValue = this.modelSelect.value;
        this.modelSelect.innerHTML = ''; // Clear existing

        if (models[provider] && models[provider].length > 0) {
            models[provider].forEach(model => {
                const option = document.createElement('option');
                option.value = model;
                option.textContent = model;
                this.modelSelect.appendChild(option);
            });
            // Restore selection if possible
            if (models[provider].includes(currentModelValue)) {
                this.modelSelect.value = currentModelValue;
            }
        } else {
            // Add placeholder if no models
            const option = document.createElement('option');
            option.textContent = 'No models available';
            option.disabled = true;
            this.modelSelect.appendChild(option);
        }
    }

    handleSubmit(event) {
        // 防止表单默认提交行为和事件冒泡
        event.preventDefault();
        event.stopPropagation();

        if (APIPanel.isSubmitting) {
            console.log('APIPanel: Submission in progress, ignoring duplicate click.');
            return;
        }

        // Check elements exist before proceeding
        if (!this.providerSelect || !this.modelSelect || !this.apiKeyInput || !this.submitButton) {
             console.error("APIPanel: Cannot handle submit, critical elements missing.");
             alert(window.i18n?.get('internalError') ?? '内部错误,无法提交。');
             return;
        }


        // 设置标记,防止短时间内重复提交
        APIPanel.isSubmitting = true;
        this.submitButton.disabled = true; // Disable button
        // Use setTimeout for debounce, not for resetting the flag immediately after fetch starts
        const resetButton = () => {
             APIPanel.isSubmitting = false;
             if (this.submitButton) { // Check if button still exists
                 this.submitButton.disabled = false;
             }
             console.log('APIPanel: Submit button re-enabled.');
        };


        // 获取表单值
        const provider = this.providerSelect.value;
        const model = this.modelSelect.value;
        const apiKey = this.apiKeyInput.value.trim(); // Trim whitespace

        // 检查字段是否填写完整
        if (!provider || !model || !apiKey) {
            const message = window.i18n?.get('fillAllFields') ?? '请填写所有字段!';
            alert(message);
            resetButton(); // Re-enable button on validation failure
            return;
        }

        const requestData = {
            provider: provider,
            model: model,
            apiKey: apiKey
        };

        console.log('APIPanel: Sending config data (key hidden):', { provider, model, apiKey: '***' });

        // 发送HTTP请求
        fetch('/api/save-config', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(requestData)
        })
        .then(response => {
            if (response.ok) {
                const message = window.i18n?.get('configSubmitted') ?? '配置已提交到服务器!';
                alert(message);
            } else {
                 // Try to get more specific error
                 response.text().then(text => {
                     console.error('APIPanel: Submit failed.', response.status, text);
                     const message = (window.i18n?.get('submitFailed') ?? '提交失败,请检查服务器状态。') + ` (Status: ${response.status})`;
                     alert(message);
                 }).catch(() => {
                      console.error('APIPanel: Submit failed.', response.status);
                      const message = (window.i18n?.get('submitFailed') ?? '提交失败,请检查服务器状态。') + ` (Status: ${response.status})`;
                      alert(message);
                 });
            }
        })
        .catch(error => {
            console.error('APIPanel: HTTP request failed:', error);
            const message = window.i18n?.get('networkError') ?? '提交失败,请检查网络连接。';
            alert(message);
        })
        .finally(() => {
            // Always re-enable the button after fetch completes (success or error)
            resetButton();
        });
    }
}

APIPanel.isSubmitting = false;
window.APIPanel = APIPanel;