const app = getApp() const difficultyOptions = [ { label: '简单', value: 'easy' }, { label: '普通', value: 'normal' }, { label: '困难', value: 'hard' }, ] const reviewOrderOptions = [ { label: '顺序复习', value: 'sequential' }, { label: '随机复习', value: 'shuffle' }, ] Page({ data: { settings: null, loading: false, error: '', difficultyOptions, reviewOrderOptions, difficultyIndex: 1, reviewOrderIndex: 0, difficultyLabel: '普通', reviewOrderLabel: '顺序复习', }, onShow() { this.loadSettings() }, syncDerivedState(settings) { const difficultyIndex = Math.max(0, difficultyOptions.findIndex((item) => item.value === settings.blank_difficulty)) const reviewOrderIndex = Math.max(0, reviewOrderOptions.findIndex((item) => item.value === settings.review_order)) this.setData({ settings, difficultyIndex: difficultyIndex >= 0 ? difficultyIndex : 1, difficultyLabel: difficultyOptions[difficultyIndex >= 0 ? difficultyIndex : 1].label, reviewOrderIndex: reviewOrderIndex >= 0 ? reviewOrderIndex : 0, reviewOrderLabel: reviewOrderOptions[reviewOrderIndex >= 0 ? reviewOrderIndex : 0].label, }) }, loadSettings() { if (!app.globalData.openid) { this.setData({ error: '请先登录' }) return } this.setData({ loading: true, error: '' }) wx.request({ url: `${app.globalData.baseUrl}/api/v1/settings`, header: { 'X-OpenID': app.globalData.openid }, success: (res) => { this.syncDerivedState(res.data?.data || null) }, fail: () => this.setData({ error: '设置加载失败' }), complete: () => this.setData({ loading: false }), }) }, onBlankCountInput(e) { const value = Number(e.detail.value || 0) this.setData({ settings: { ...this.data.settings, blank_count: Number.isFinite(value) ? value : 0, }, }) }, onDifficultyChange(e) { const index = Number(e.detail.value) const option = difficultyOptions[index] || difficultyOptions[1] this.setData({ difficultyIndex: index, difficultyLabel: option.label, settings: { ...this.data.settings, blank_difficulty: option.value, }, }) }, onReviewOrderChange(e) { const index = Number(e.detail.value) const option = reviewOrderOptions[index] || reviewOrderOptions[0] this.setData({ reviewOrderIndex: index, reviewOrderLabel: option.label, settings: { ...this.data.settings, review_order: option.value, }, }) }, toggleSetting(e) { const key = e.currentTarget.dataset.key const settings = { ...this.data.settings } settings[key] = settings[key] ? 0 : 1 this.setData({ settings }) }, save() { if (!app.globalData.openid) { wx.showToast({ title: '请先登录', icon: 'none' }) return } const settings = this.data.settings || {} wx.request({ url: `${app.globalData.baseUrl}/api/v1/settings`, method: 'PUT', header: { 'Content-Type': 'application/json', 'X-OpenID': app.globalData.openid }, data: settings, success: () => wx.showToast({ title: '已保存', icon: 'success' }), fail: () => wx.showToast({ title: '保存失败', icon: 'none' }), }) }, })