finai/miniapp/pages/home/home.js

116 lines
3.3 KiB
JavaScript

const { request } = require('../../utils/request')
const app = getApp()
Page({
data: {
userName: '',
userSub: '',
avatarChar: '?',
question: '',
quickPrompts: [
{ key: 'policy', icon: '📖', label: '政策解读', prompt: '请解读一下最新的财税政策要点。' },
{ key: 'rule', icon: '📋', label: '制度问答', prompt: '我想了解报销制度的具体流程。' }
],
drawerOpen: false,
sessions: [],
sessionsLoading: false
},
onLoad() {
const token = app.globalData.token || wx.getStorageSync('token')
if (!token) {
wx.redirectTo({ url: '/pages/login/login' })
return
}
const user = app.globalData.user || wx.getStorageSync('user') || {}
const userName = user.name || user.phone || ''
const userSub = user.name && user.phone ? user.phone : ''
const avatarChar = (userName || '?').trim().charAt(0).toUpperCase() || '?'
this.setData({ userName, userSub, avatarChar })
},
onQuestionInput(e) {
this.setData({ question: e.detail.value })
},
onQuickTap(e) {
const key = e.currentTarget.dataset.key
const hit = (this.data.quickPrompts || []).find((q) => q.key === key)
if (!hit) return
this._toChat({ question: hit.prompt })
},
submit() {
const text = (this.data.question || '').trim()
if (!text) return
this._toChat({ question: text })
},
goChatAttach() {
this._toChat({ attach: 1 })
},
goChatVoice() {
this._toChat({ voice: 1 })
},
_toChat(payload) {
app.globalData.chatPending = payload || {}
wx.navigateTo({ url: '/pages/chat/chat' })
},
// ---------------- 抽屉 ----------------
openDrawer() {
this.setData({ drawerOpen: true })
this._loadSessions()
},
closeDrawer() {
this.setData({ drawerOpen: false })
},
async _loadSessions() {
this.setData({ sessionsLoading: true })
try {
const list = await request('/api/chat/sessions')
const items = (list || []).map((s) => Object.assign({}, s, { _time: this._formatTime(s.last_message_at || s.created_at) }))
this.setData({ sessions: items })
} catch (e) {
wx.showToast({ title: '历史加载失败:' + e.message, icon: 'none' })
} finally {
this.setData({ sessionsLoading: false })
}
},
_formatTime(iso) {
if (!iso) return ''
const d = new Date(iso)
if (isNaN(d.getTime())) return ''
const pad = (n) => (n < 10 ? '0' + n : '' + n)
const now = new Date()
if (d.getFullYear() === now.getFullYear() && d.getMonth() === now.getMonth() && d.getDate() === now.getDate()) {
return `${pad(d.getHours())}:${pad(d.getMinutes())}`
}
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`
},
onSelectSession(e) {
const id = e.detail && e.detail.id
if (!id) return
this.setData({ drawerOpen: false })
app.globalData.chatPending = { sid: id }
wx.navigateTo({ url: '/pages/chat/chat?sid=' + id })
},
logout() {
wx.showModal({
title: '提示',
content: '确定退出登录?',
success: (res) => {
if (!res.confirm) return
app.globalData.token = ''
app.globalData.user = null
wx.removeStorageSync('token')
wx.removeStorageSync('user')
wx.redirectTo({ url: '/pages/login/login' })
}
})
}
})