const app = getApp() Page({ data: { entryId: null, entryType: 'word', enText: '', zhText: '', exampleText: '', loading: false, error: '', isEditMode: false, }, onLoad(options) { const entryId = options.id ? String(options.id) : null this.setData({ entryId, isEditMode: !!entryId }) if (entryId) this.loadEntry(entryId) }, loadEntry(entryId) { if (!app.globalData.openid) { this.setData({ error: '请先登录' }) return } this.setData({ loading: true, error: '' }) wx.request({ url: `${app.globalData.baseUrl}/api/v1/entries/${entryId}`, header: { 'X-OpenID': app.globalData.openid }, success: (res) => { const entry = res.data?.data if (!entry) { this.setData({ error: '词条不存在' }) return } this.setData({ entryType: entry.entry_type || 'word', enText: entry.en_text || '', zhText: entry.zh_text || '', exampleText: entry.example_text || '', }) }, fail: () => this.setData({ error: '词条加载失败' }), complete: () => this.setData({ loading: false }), }) }, switchType(e) { const entryType = e.currentTarget.dataset.type if (this.data.isEditMode && entryType !== this.data.entryType) { wx.showModal({ title: '切换类型', content: '切换类型后,当前内容仍会保留,但字段含义会变成新的类型。是否继续?', confirmText: '继续切换', cancelText: '取消', success: (res) => { if (res.confirm) this.setData({ entryType }) }, }) return } this.setData({ entryType }) }, onEnInput(e) { this.setData({ enText: e.detail.value }) }, onZhInput(e) { this.setData({ zhText: e.detail.value }) }, onExampleInput(e) { this.setData({ exampleText: e.detail.value }) }, goBack() { wx.navigateBack() }, save() { if (!app.globalData.openid) { wx.showToast({ title: '请先登录', icon: 'none' }) return } const method = this.data.isEditMode ? 'PUT' : 'POST' const url = this.data.isEditMode ? `${app.globalData.baseUrl}/api/v1/entries/${this.data.entryId}` : `${app.globalData.baseUrl}/api/v1/entries` this.setData({ loading: true, error: '' }) wx.request({ url, method, header: { 'Content-Type': 'application/json', 'X-OpenID': app.globalData.openid }, data: this.data.isEditMode ? { entry_type: this.data.entryType, en_text: this.data.enText, zh_text: this.data.zhText, example_text: this.data.exampleText, } : { entry_type: this.data.entryType, en_text: this.data.enText, zh_text: this.data.zhText, example_text: this.data.exampleText, source_type: 'manual', upload_date: new Date().toISOString().slice(0, 10), }, success: () => { wx.showToast({ title: this.data.isEditMode ? '更新成功' : '保存成功', icon: 'success' }) if (!this.data.isEditMode) { this.setData({ enText: '', zhText: '', exampleText: '', }) } }, fail: () => this.setData({ error: this.data.isEditMode ? '更新失败' : '保存失败' }), complete: () => this.setData({ loading: false }), }) }, })