const API = require('../../utils/api.js') const MAX_MATERIALS = 6 const MAX_SINGLE_BYTES = 6 * 1024 * 1024 // wx.request 请求体约 10MB 上限,base64 会膨胀 4/3: // 与 ai 聊天页同口径,材料原始字节收到 7MB(编码后约 9.3MB) const MAX_TOTAL_BYTES = 7 * 1024 * 1024 const JOB_STORAGE_PREFIX = 'inquiry_parse_job_' const EMPTY_FIELDS = { basicHealth: '', treatmentHistory: '', medications: '', demand: '' } const JOB_TEXT = { queued: '已提交,等待解析', processing: '正在识别和整理', waiting_confirmation: '解析完成,请核对四段摘要', failed: '解析未完成', confirmed: '已保存', cancelled: '任务已取消' } Page({ data: { recordId: '', loading: true, loadError: '', saving: false, creating: false, fields: { ...EMPTY_FIELDS }, sourceText: '', focusSourceText: false, materials: [], recording: false, jobId: '', jobStatus: '', jobStatusText: '', jobError: '', jobProcessing: false, uncertainties: [] }, onLoad(options) { if (!options.id) { wx.showToast({ title: '缺少订单参数', icon: 'none' }) setTimeout(() => wx.navigateBack(), 800) return } this.setData({ recordId: options.id }) this.initRecorder() }, onShow() { this._visible = true if (!this.data.recordId) return this.loadRecord() if (this.data.jobId && this.data.jobProcessing) this.startPolling() else this.resumeJob() }, onHide() { this._visible = false this.stopPolling() if (this.data.recording && this.recorderManager) { // 切后台/来电打断的录音不保留,避免用户回到页面看到半截材料。 this._discardRecording = true this.recorderManager.stop() } }, onUnload() { this._visible = false this._unloaded = true this._payloads = {} this.stopPolling() if (this.recorderManager) { if (this._onRecorderStop) this.recorderManager.offStop(this._onRecorderStop) if (this._onRecorderError) this.recorderManager.offError(this._onRecorderError) if (this.data.recording) this.recorderManager.stop() } }, storageKey() { return `${JOB_STORAGE_PREFIX}${this.data.recordId}` }, async loadRecord(force = false) { try { await getApp().waitForAuth() const res = await API.escort.getRecordById(this.data.recordId) if (res.code !== 0 || !res.data?.record) throw new Error(res.msg || '订单加载失败') const inquiry = res.data.record.inquiry || {} const hasStructured = inquiry.basicHealth || inquiry.treatmentHistory || inquiry.medications const fields = { basicHealth: inquiry.basicHealth || '', treatmentHistory: hasStructured ? (inquiry.treatmentHistory || '') : (inquiry.medicalHistory || ''), medications: inquiry.medications || '', demand: inquiry.demand || '' } this.setData({ loadError: '' }) // 解析草稿优先:订单请求与任务查询并行返回时,不能用订单旧值覆盖草稿。 if ((force || !this._loaded) && !this.data.jobStatus) { this.setData({ fields }) this._loaded = true } } catch (err) { this.setData({ loadError: err.message || '订单加载失败' }) wx.showToast({ title: err.message || '订单加载失败', icon: 'none' }) } finally { this.setData({ loading: false }) } }, onRetryLoad() { this.setData({ loading: true, loadError: '' }) this.loadRecord(true) }, async resumeJob() { const jobId = wx.getStorageSync(this.storageKey()) if (!jobId || this.data.jobStatus) return try { await getApp().waitForAuth() } catch (err) { return } if (this._unloaded) return this.setData({ jobId }) this.fetchJob(jobId) }, async fetchJob(jobId) { if (this._fetchingJob) return this._fetchingJob = true try { const res = await API.escort.getInquiryParseJob(this.data.recordId, jobId) if (res.code !== 0 || !res.data?.job) { if (res.code === 404) this.clearStoredJob() else wx.showToast({ title: res.msg || '任务状态获取失败', icon: 'none' }) this.stopPolling() return } this.applyJob(res.data.job) if (['queued', 'processing'].includes(res.data.job.status)) this.startPolling() } catch (err) { this.stopPolling() wx.showToast({ title: '任务状态获取失败,请重新进入页面', icon: 'none' }) } finally { this._fetchingJob = false } }, applyJob(job) { const previousStatus = this.data.jobStatus const processing = ['queued', 'processing'].includes(job.status) this.setData({ jobId: job.id, jobStatus: job.status, jobStatusText: JOB_TEXT[job.status] || '解析任务', jobError: job.errorMessage || '', jobProcessing: processing, uncertainties: job.uncertainties || [] }) if (job.status === 'waiting_confirmation' && previousStatus !== 'waiting_confirmation') { this.setData({ fields: { ...EMPTY_FIELDS, ...(job.draft || {}) } }) this.clearMaterials() this.stopPolling() } else if (['failed', 'cancelled', 'confirmed'].includes(job.status)) { this.stopPolling() } }, startPolling() { if (this.pollTimer || !this._visible) return this.pollTimer = setInterval(() => { if (this.data.jobId) this.fetchJob(this.data.jobId) }, 2000) }, stopPolling() { if (this.pollTimer) clearInterval(this.pollTimer) this.pollTimer = null }, clearStoredJob() { wx.removeStorageSync(this.storageKey()) this.stopPolling() this.setData({ jobId: '', jobStatus: '', jobStatusText: '', jobError: '', jobProcessing: false, uncertainties: [] }) }, onFieldInput(e) { this.setData({ [`fields.${e.currentTarget.dataset.field}`]: e.detail.value }) }, onSourceTextInput(e) { this.setData({ sourceText: e.detail.value }) }, onFocusText() { this.setData({ focusSourceText: false }) setTimeout(() => this.setData({ focusSourceText: true }), 0) }, onChoosePdf() { if (!this.canAddMaterials()) return wx.chooseMessageFile({ count: 1, type: 'file', extension: ['pdf'], success: async (res) => { const file = res.tempFiles?.[0] if (!file) return try { if (!/\.pdf$/i.test(file.name || file.path || '')) throw new Error('请选择 PDF 文件') if (file.size > MAX_SINGLE_BYTES) throw new Error('PDF 不能超过 6MB') const data = await this.readFileBase64(file.path) this.addMaterial({ type: 'pdf', typeText: 'PDF 报告', name: file.name || 'PDF 报告', mime: 'application/pdf', data }) } catch (err) { wx.showToast({ title: err.message || 'PDF 读取失败', icon: 'none' }) } } }) }, onChooseImages() { const count = this.canAddMaterials() if (!count) return wx.chooseMedia({ count, mediaType: ['image'], sourceType: ['album', 'camera'], sizeType: ['compressed'], camera: 'back', success: async (res) => { const baseCount = this.data.materials.length for (const [index, file] of (res.tempFiles || []).entries()) { try { if (file.size > MAX_SINGLE_BYTES) throw new Error('单张图片不能超过 6MB') const data = await this.readFileBase64(file.tempFilePath) const added = this.addMaterial({ type: 'image', typeText: '图片', name: `病历图片 ${baseCount + index + 1}`, mime: this.resolveImageMime(file.tempFilePath), tempFilePath: file.tempFilePath, width: file.width || 0, height: file.height || 0, kind: 'auto', data }) if (!added) break } catch (err) { wx.showToast({ title: err.message || '图片读取失败', icon: 'none' }) break } } } }) }, canAddMaterials() { const remaining = MAX_MATERIALS - this.data.materials.length if (remaining <= 0) { wx.showToast({ title: '每次最多添加 6 份材料', icon: 'none' }) return 0 } if (this.totalMaterialBytes() >= MAX_TOTAL_BYTES) { wx.showToast({ title: '材料总大小不能超过 7MB', icon: 'none' }) return 0 } return remaining }, addMaterial(material) { const bytes = this.estimateBytes(material.data) if (!bytes) { wx.showToast({ title: '文件内容为空', icon: 'none' }) return false } if (bytes > MAX_SINGLE_BYTES) { wx.showToast({ title: '单个文件不能超过 6MB', icon: 'none' }) return false } if (this.totalMaterialBytes() + bytes > MAX_TOTAL_BYTES) { wx.showToast({ title: '材料总大小不能超过 7MB,请分批整理', icon: 'none' }) return false } const item = { ...material, id: `${Date.now()}_${Math.random().toString(36).slice(2, 8)}`, bytes, sizeText: this.formatSize(bytes) } // base64 不能进 data:setData 走视图层序列化,多张图会超过 ~1MB 上限。 // 二进制只挂在页面实例上,data 里仅保留展示字段。 this._payloads = this._payloads || {} this._payloads[item.id] = item.data delete item.data this.setData({ materials: [...this.data.materials, item] }) return true }, onRemoveMaterial(e) { const index = Number(e.currentTarget.dataset.index) const removed = this.data.materials[index] if (removed && this._payloads) delete this._payloads[removed.id] const materials = this.data.materials.filter((_, i) => i !== index) this.setData({ materials }) }, clearMaterials() { this._payloads = {} this.setData({ materials: [], sourceText: '' }) }, totalMaterialBytes() { return this.data.materials.reduce((sum, item) => sum + (item.bytes || 0), 0) }, initRecorder() { if (!wx.getRecorderManager) return this.recorderManager = wx.getRecorderManager() this._onRecorderStop = (res) => this.handleRecorderStop(res) this._onRecorderError = () => { if (this._unloaded) return this.setData({ recording: false }) wx.showToast({ title: '录音失败,请检查麦克风权限', icon: 'none' }) } this.recorderManager.onStop(this._onRecorderStop) this.recorderManager.onError(this._onRecorderError) }, onToggleVoice() { if (!this.recorderManager) { wx.showToast({ title: '当前微信版本不支持录音', icon: 'none' }) return } if (this.data.recording) { this.recorderManager.stop() return } if (!this.canAddMaterials()) return this.recorderManager.start({ duration: 60000, format: 'mp3', sampleRate: 16000, numberOfChannels: 1, encodeBitRate: 48000 }) this.setData({ recording: true }) }, async handleRecorderStop(res) { const discard = this._discardRecording this._discardRecording = false if (this._unloaded) return this.setData({ recording: false }) if (discard) return if (!res.tempFilePath || Number(res.duration || 0) < 500) { wx.showToast({ title: '录音时间太短,请重新录制', icon: 'none' }) return } try { const data = await this.readFileBase64(res.tempFilePath) this.addMaterial({ type: 'audio', typeText: '语音', name: `语音 ${Math.max(1, Math.round((res.duration || 0) / 1000))} 秒`, mime: 'audio/mpeg', format: 'mp3', sampleRate: 16000, channels: 1, data }) } catch (err) { wx.showToast({ title: err.message || '录音读取失败', icon: 'none' }) } }, async onStartParse() { if (this.data.creating || this.data.recording || this.data.jobProcessing || this.data.loadError) return if (['waiting_confirmation'].includes(this.data.jobStatus)) { wx.showToast({ title: '请先保存或取消当前草稿', icon: 'none' }) return } const text = this.data.sourceText.trim() if (!text && !this.data.materials.length) { wx.showToast({ title: '请先添加材料或输入文字', icon: 'none' }) return } const payloads = this._payloads || {} const materials = [] for (const item of this.data.materials) { const data = payloads[item.id] // 实例上的原始内容可能因页面重进而丢失:此时提示重新添加,不发空材料。 if (!data) { wx.showToast({ title: `${item.name} 需重新添加`, icon: 'none' }) return } const payload = { type: item.type, name: item.name, mime: item.mime, data } if (item.type === 'image') Object.assign(payload, { width: item.width, height: item.height, kind: 'auto' }) if (item.type === 'audio') Object.assign(payload, { format: 'mp3', sampleRate: 16000, channels: 1 }) materials.push(payload) } this.setData({ creating: true, jobError: '' }) try { const res = await API.escort.createInquiryParseJob(this.data.recordId, { text, materials }) if (res.code !== 0 || !res.data?.job) throw new Error(res.msg || '解析任务创建失败') wx.setStorageSync(this.storageKey(), res.data.job.id) this.applyJob(res.data.job) this.startPolling() } catch (err) { this.setData({ jobError: err.message || '解析任务创建失败' }) wx.showToast({ title: err.message || '解析任务创建失败', icon: 'none' }) } finally { this.setData({ creating: false }) } }, async onCancelJob() { if (!this.data.jobId) return try { const res = await API.escort.cancelInquiryParseJob(this.data.recordId, this.data.jobId) if (res.code !== 0) throw new Error(res.msg || '取消失败') this.clearStoredJob() await this.loadRecord(true) wx.showToast({ title: '已取消解析', icon: 'none' }) } catch (err) { wx.showToast({ title: err.message || '取消失败', icon: 'none' }) } }, async onSave() { if (this.data.saving || this.data.jobProcessing || this.data.loadError) return const fields = Object.fromEntries( Object.keys(EMPTY_FIELDS).map((key) => [key, String(this.data.fields[key] || '').trim()]) ) this.setData({ saving: true }) try { const waiting = this.data.jobStatus === 'waiting_confirmation' && this.data.jobId const res = waiting ? await API.escort.confirmInquiryParseJob(this.data.recordId, this.data.jobId, fields) : await API.escort.updateRecord(this.data.recordId, { 'inquiry.basicHealth': fields.basicHealth, 'inquiry.treatmentHistory': fields.treatmentHistory, 'inquiry.medications': fields.medications, 'inquiry.demand': fields.demand }) if (res.code !== 0) throw new Error(res.msg || '保存失败') this.clearStoredJob() wx.showToast({ title: '保存成功', icon: 'success' }) setTimeout(() => wx.navigateBack(), 600) } catch (err) { wx.showToast({ title: err.message || '保存失败', icon: 'none' }) } finally { this.setData({ saving: false }) } }, onBack() { if (this.data.recording && this.recorderManager) { this._discardRecording = true this.recorderManager.stop() } wx.navigateBack() }, readFileBase64(filePath) { return new Promise((resolve, reject) => { wx.getFileSystemManager().readFile({ filePath, encoding: 'base64', success: (res) => resolve(res.data), fail: () => reject(new Error('文件读取失败,请重试')) }) }) }, estimateBytes(base64) { return Math.round(String(base64 || '').length * 3 / 4) }, resolveImageMime(filePath) { const ext = String(filePath || '').split('.').pop().toLowerCase() if (ext === 'png') return 'image/png' if (ext === 'webp') return 'image/webp' return 'image/jpeg' }, formatSize(bytes) { if (bytes >= 1024 * 1024) return `${(bytes / 1024 / 1024).toFixed(1)}MB` return `${Math.max(1, Math.round(bytes / 1024))}KB` } })