feat: 增加AI报告分析功能

This commit is contained in:
2026-09-03 17:29:29 +08:00
parent 7ba7dbc942
commit 5bc782d5f5
14 changed files with 6375 additions and 68 deletions

View File

@@ -7,17 +7,10 @@
custom-style="border-radius: 32rpx 32rpx 0 0; padding: 40rpx 32rpx"
>
<view class="flex flex-col align-center gap-2 max-h-[70vh] overflow-y-auto">
<view class="flex items-center justify-between mb-4">
<text class="text-lg font-bold">AI 健康分析</text>
<wd-icon name="close" size="20px" @click="recordStore.showAIResultPopup = false" />
</view>
<view class="bg-blue-50 rounded-lg">
<text class="text-gray-800 leading-relaxed whitespace-pre-wrap">{{ recordStore.aiResult }}</text>
</view>
<ua-markdown :source="recordStore.aiResult" />
<view class="flex w-full items-center justify-evenly">
<wd-button type="info" @click="recordStore.showAIResultPopup = false">
<wd-button type="info" @click="cancelClick">
取消
</wd-button>
<wd-button type="primary">
@@ -32,4 +25,9 @@
import { useRecordStore } from '@/store/record'
const recordStore = useRecordStore()
function cancelClick() {
recordStore.showAIResultPopup = false
recordStore.showAIButton = true
}
</script>

View File

@@ -1,7 +1,7 @@
<template>
<wd-config-provider :theme-vars="getTheme(appStore.themeColor)">
<view class="min-h-screen flex flex-col position" :style="getThemeStyle[appStore.themeColor]">
<liu-drag-button :background="getThemePrimaryColor[appStore.themeColor]" @clickBtn="AIClick">
<liu-drag-button v-if="recordStore.showAIButton" :background="getThemePrimaryColor[appStore.themeColor]" @clickBtn="AIClick">
<wd-text color="#fff" size="18px" text="AI"/>
</liu-drag-button>
@@ -91,6 +91,7 @@
<wd-overlay :show="recordStore.isAnalyzing">
<view class="flex flex-col items-center justify-center h-full">
<wd-loading type="spinner" color="#FFF" >AI 正在分析中...</wd-loading>
<wd-text text="请不要离开此页面预计需要20~30秒" color="#FFF"></wd-text>
</view>
</wd-overlay>
@@ -100,9 +101,10 @@
</template>
<script lang="ts" setup>
import { computed, ref } from 'vue'
import {computed, ref} from 'vue'
import {
deleteRecordByDate, getDateStr,
deleteRecordByDate,
getDateStr,
getMonthRecords,
getMonthStr,
getRecordMeta,
@@ -118,6 +120,8 @@ import { share } from '@/utils/share'
import { useDialog } from '@wot-ui/ui'
import AiResultPopup from "@/components/Record/AiResultPopup.vue";
import { useRecordStore } from '@/store/record'
import { getProfile } from "@/utils/profile";
import { preprocessHealthData } from "@/utils/ai";
const { onShareAppMessage } = share()
onShareAppMessage()
@@ -249,63 +253,63 @@ function deleteClick(item: IHealthRecord) {
const dialog = useDialog()
const AIClick = () => {
dialog
.confirm({
title: `开始分析${selectMonth.value}记录数据,本次分析将消耗 100 积分,是否继续?`,
})
.then(async () => {
recordStore.isAnalyzing = true
recordStore.aiResult = ''
recordStore.showAIButton = false
const profile = getProfile()
if (profile.name && profile.gender && profile.height && profile.birthYear) {
const preprocess = JSON.stringify(preprocessHealthData(getProfile(), getMonthRecords(selectMonth.value)))
dialog
.confirm({
title: `开始分析${selectMonth.value}记录数据,本次分析将消耗 100 积分,是否继续?`,
})
.then(async () => {
try {
recordStore.isAnalyzing = true
recordStore.aiResult = ''
// 模拟请求延迟
await new Promise(r => setTimeout(r, 2000))
recordStore.isAnalyzing = false
// 模拟返回结果
recordStore.aiResult = generateMockResult()
recordStore.showAIResultPopup = true
})
.catch(() => {
console.log('点击了取消')
})
const data = await getReport(preprocess)
recordStore.aiResult = data
recordStore.showAIResultPopup = true
} catch (error) {
recordStore.showAIButton = true
recordStore.aiResult = ''
recordStore.showAIResultPopup = false
await dialog.alert({
title: '提示',
msg: 'AI生成报告失败请联系管理员'
})
} finally {
recordStore.isAnalyzing = false
}
})
.catch(()=> {
recordStore.showAIButton = true
})
} else {
dialog.alert({
title: '提示',
msg: '请先完善个人信息(昵称、性别、身高和出生年份)'
})
recordStore.showAIButton = true
}
}
function generateMockResult() {
return `📊 ${selectMonth.value}健康分析
• 本月共记录 23 天,覆盖率 74%
• 平均睡眠 6.5 小时,低于目标 7.5 小时
• 血压整体平稳,但有 3 天偏高(周一、周三)
• 建议:增加周末睡眠时间,注意周一血压波动
• 本月共记录 23 天,覆盖率 74%
• 平均睡眠 6.5 小时,低于目标 7.5 小时
• 血压整体平稳,但有 3 天偏高(周一、周三)
• 建议:增加周末睡眠时间,注意周一血压波动
• 本月共记录 23 天,覆盖率 74%
• 平均睡眠 6.5 小时,低于目标 7.5 小时
• 血压整体平稳,但有 3 天偏高(周一、周三)
• 建议:增加周末睡眠时间,注意周一血压波动
• 本月共记录 23 天,覆盖率 74%
• 平均睡眠 6.5 小时,低于目标 7.5 小时
• 血压整体平稳,但有 3 天偏高(周一、周三)
• 建议:增加周末睡眠时间,注意周一血压波动
• 本月共记录 23 天,覆盖率 74%
• 平均睡眠 6.5 小时,低于目标 7.5 小时
• 血压整体平稳,但有 3 天偏高(周一、周三)
• 建议:增加周末睡眠时间,注意周一血压波动
• 本月共记录 23 天,覆盖率 74%
• 平均睡眠 6.5 小时,低于目标 7.5 小时
• 血压整体平稳,但有 3 天偏高(周一、周三)
• 建议:增加周末睡眠时间,注意周一血压波动
• 本月共记录 23 天,覆盖率 74%
• 平均睡眠 6.5 小时,低于目标 7.5 小时
• 血压整体平稳,但有 3 天偏高(周一、周三)
• 建议:增加周末睡眠时间,注意周一血压波动
• 本月共记录 23 天,覆盖率 74%
• 平均睡眠 6.5 小时,低于目标 7.5 小时
• 血压整体平稳,但有 3 天偏高(周一、周三)
• 建议:增加周末睡眠时间,注意周一血压波动
`
async function getReport(query: string) {
return new Promise((resolve, reject) => {
wx.request({
url: 'http://127.0.0.1:8000/agent/report',
method: 'POST',
header: { 'Content-Type': 'application/json' },
data: JSON.stringify({ query: query }),
success: (res) => {
if (res.statusCode >= 200 && res.statusCode < 300) {
resolve(res.data)
} else {
reject({ status: res.statusCode, data: res.data })
}
},
fail: (err) => reject(err),
})
})
}
</script>

View File

@@ -136,8 +136,14 @@ watch(() => profileStore.isRefresh, () => {
function openProfile() {
Object.assign(profileStore.profileForm, profile.value)
profileStore.profileForm.height = 170
profileStore.profileForm.birthYear = 1990
if (!profileStore.profileForm.height) {
profileStore.profileForm.height = 170
}
if (!profileStore.profileForm.birthYear) {
profileStore.profileForm.birthYear = 1990
}
profileStore.showProfilePopup = true
}

View File

@@ -52,6 +52,7 @@ export const useRecordStore = defineStore('record', {
isRecord: false,
isAnalyzing: false,
showAIResultPopup: false,
showAIButton: true,
aiResult: ''
}),
actions: {

View File

@@ -0,0 +1 @@
pre code.hljs{display:block;overflow-x:auto;padding:1em}code.hljs{padding:3px 5px}.hljs{color:#abb2bf;background:#282c34}.hljs-comment,.hljs-quote{color:#5c6370;font-style:italic}.hljs-doctag,.hljs-formula,.hljs-keyword{color:#c678dd}.hljs-deletion,.hljs-name,.hljs-section,.hljs-selector-tag,.hljs-subst{color:#e06c75}.hljs-literal{color:#56b6c2}.hljs-addition,.hljs-attribute,.hljs-meta .hljs-string,.hljs-regexp,.hljs-string{color:#98c379}.hljs-attr,.hljs-number,.hljs-selector-attr,.hljs-selector-class,.hljs-selector-pseudo,.hljs-template-variable,.hljs-type,.hljs-variable{color:#d19a66}.hljs-bullet,.hljs-link,.hljs-meta,.hljs-selector-id,.hljs-symbol,.hljs-title{color:#61aeee}.hljs-built_in,.hljs-class .hljs-title,.hljs-title.class_{color:#e6c07b}.hljs-emphasis{font-style:italic}.hljs-strong{font-weight:700}.hljs-link{text-decoration:underline}

View File

@@ -0,0 +1 @@
pre code.hljs{display:block;overflow-x:auto;padding:1em}code.hljs{padding:3px 5px}.hljs{color:#383a42;background:#fafafa}.hljs-comment,.hljs-quote{color:#a0a1a7;font-style:italic}.hljs-doctag,.hljs-formula,.hljs-keyword{color:#a626a4}.hljs-deletion,.hljs-name,.hljs-section,.hljs-selector-tag,.hljs-subst{color:#e45649}.hljs-literal{color:#0184bb}.hljs-addition,.hljs-attribute,.hljs-meta .hljs-string,.hljs-regexp,.hljs-string{color:#50a14f}.hljs-attr,.hljs-number,.hljs-selector-attr,.hljs-selector-class,.hljs-selector-pseudo,.hljs-template-variable,.hljs-type,.hljs-variable{color:#986801}.hljs-bullet,.hljs-link,.hljs-meta,.hljs-selector-id,.hljs-symbol,.hljs-title{color:#4078f2}.hljs-built_in,.hljs-class .hljs-title,.hljs-title.class_{color:#c18401}.hljs-emphasis{font-style:italic}.hljs-strong{font-weight:700}.hljs-link{text-decoration:underline}

View File

@@ -0,0 +1,10 @@
pre code.hljs{display:block;overflow-x:auto;padding:1em}code.hljs{padding:3px 5px}/*!
Theme: GitHub Dark
Description: Dark theme as seen on github.com
Author: github.com
Maintainer: @Hirse
Updated: 2021-05-15
Outdated base version: https://github.com/primer/github-syntax-dark
Current colors taken from GitHub's CSS
*/.hljs{color:#c9d1d9;background:#0d1117}.hljs-doctag,.hljs-keyword,.hljs-meta .hljs-keyword,.hljs-template-tag,.hljs-template-variable,.hljs-type,.hljs-variable.language_{color:#ff7b72}.hljs-title,.hljs-title.class_,.hljs-title.class_.inherited__,.hljs-title.function_{color:#d2a8ff}.hljs-attr,.hljs-attribute,.hljs-literal,.hljs-meta,.hljs-number,.hljs-operator,.hljs-selector-attr,.hljs-selector-class,.hljs-selector-id,.hljs-variable{color:#79c0ff}.hljs-meta .hljs-string,.hljs-regexp,.hljs-string{color:#a5d6ff}.hljs-built_in,.hljs-symbol{color:#ffa657}.hljs-code,.hljs-comment,.hljs-formula{color:#8b949e}.hljs-name,.hljs-quote,.hljs-selector-pseudo,.hljs-selector-tag{color:#7ee787}.hljs-subst{color:#c9d1d9}.hljs-section{color:#1f6feb;font-weight:700}.hljs-bullet{color:#f2cc60}.hljs-emphasis{color:#c9d1d9;font-style:italic}.hljs-strong{color:#c9d1d9;font-weight:700}.hljs-addition{color:#aff5b4;background-color:#033a16}.hljs-deletion{color:#ffdcd7;background-color:#67060c}

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,352 @@
/*
* HTML5 Parser By Sam Blowes
*
* Designed for HTML5 documents
*
* Original code by John Resig (ejohn.org)
* http://ejohn.org/blog/pure-javascript-html-parser/
* Original code by Erik Arvidsson, Mozilla Public License
* http://erik.eae.net/simplehtmlparser/simplehtmlparser.js
*
* ----------------------------------------------------------------------------
* License
* ----------------------------------------------------------------------------
*
* This code is triple licensed using Apache Software License 2.0,
* Mozilla Public License or GNU Public License
*
* ////////////////////////////////////////////////////////////////////////////
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* ////////////////////////////////////////////////////////////////////////////
*
* The contents of this file are subject to the Mozilla Public License
* Version 1.1 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
* License for the specific language governing rights and limitations
* under the License.
*
* The Original Code is Simple HTML Parser.
*
* The Initial Developer of the Original Code is Erik Arvidsson.
* Portions created by Erik Arvidssson are Copyright (C) 2004. All Rights
* Reserved.
*
* ////////////////////////////////////////////////////////////////////////////
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* ----------------------------------------------------------------------------
* Usage
* ----------------------------------------------------------------------------
*
* // Use like so:
* HTMLParser(htmlString, {
* start: function(tag, attrs, unary) {},
* end: function(tag) {},
* chars: function(text) {},
* comment: function(text) {}
* });
*
* // or to get an XML string:
* HTMLtoXML(htmlString);
*
* // or to get an XML DOM Document
* HTMLtoDOM(htmlString);
*
* // or to inject into an existing document/DOM node
* HTMLtoDOM(htmlString, document);
* HTMLtoDOM(htmlString, document.body);
*
*/
// Regular Expressions for parsing tags and attributes
var startTag = /^<([-A-Za-z0-9_]+)((?:\s+[a-zA-Z_:][-a-zA-Z0-9_:.]*(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*(\/?)>/;
var endTag = /^<\/([-A-Za-z0-9_]+)[^>]*>/;
var attr = /([a-zA-Z_:][-a-zA-Z0-9_:.]*)(?:\s*=\s*(?:(?:"((?:\\.|[^"])*)")|(?:'((?:\\.|[^'])*)')|([^>\s]+)))?/g; // Empty Elements - HTML 5
var empty = makeMap('area,base,basefont,br,col,frame,hr,img,input,link,meta,param,embed,command,keygen,source,track,wbr'); // Block Elements - HTML 5
// fixed by xxx 将 ins 标签从块级名单中移除
var block = makeMap('a,address,article,applet,aside,audio,blockquote,button,canvas,center,dd,del,dir,div,dl,dt,fieldset,figcaption,figure,footer,form,frameset,h1,h2,h3,h4,h5,h6,header,hgroup,hr,iframe,isindex,li,map,menu,noframes,noscript,object,ol,output,p,pre,section,script,table,tbody,td,tfoot,th,thead,tr,ul,video'); // Inline Elements - HTML 5
var inline = makeMap('abbr,acronym,applet,b,basefont,bdo,big,br,button,cite,code,del,dfn,em,font,i,iframe,img,input,ins,kbd,label,map,object,q,s,samp,script,select,small,span,strike,strong,sub,sup,textarea,tt,u,var'); // Elements that you can, intentionally, leave open
// (and which close themselves)
var closeSelf = makeMap('colgroup,dd,dt,li,options,p,td,tfoot,th,thead,tr'); // Attributes that have their values filled in disabled="disabled"
var fillAttrs = makeMap('checked,compact,declare,defer,disabled,ismap,multiple,nohref,noresize,noshade,nowrap,readonly,selected'); // Special Elements (can contain anything)
var special = makeMap('script,style');
function HTMLParser(html, handler) {
var index;
var chars;
var match;
var stack = [];
var last = html;
stack.last = function () {
return this[this.length - 1];
};
while (html) {
chars = true; // Make sure we're not in a script or style element
if (!stack.last() || !special[stack.last()]) {
// Comment
if (html.indexOf('<!--') == 0) {
index = html.indexOf('-->');
if (index >= 0) {
if (handler.comment) {
handler.comment(html.substring(4, index));
}
html = html.substring(index + 3);
chars = false;
} // end tag
} else if (html.indexOf('</') == 0) {
match = html.match(endTag);
if (match) {
html = html.substring(match[0].length);
match[0].replace(endTag, parseEndTag);
chars = false;
} // start tag
} else if (html.indexOf('<') == 0) {
match = html.match(startTag);
if (match) {
html = html.substring(match[0].length);
match[0].replace(startTag, parseStartTag);
chars = false;
}
}
if (chars) {
index = html.indexOf('<');
var text = index < 0 ? html : html.substring(0, index);
html = index < 0 ? '' : html.substring(index);
if (handler.chars) {
handler.chars(text);
}
}
} else {
html = html.replace(new RegExp('([\\s\\S]*?)<\/' + stack.last() + '[^>]*>'), function (all, text) {
text = text.replace(/<!--([\s\S]*?)-->|<!\[CDATA\[([\s\S]*?)]]>/g, '$1$2');
if (handler.chars) {
handler.chars(text);
}
return '';
});
parseEndTag('', stack.last());
}
if (html == last) {
throw 'Parse Error: ' + html;
}
last = html;
} // Clean up any remaining tags
parseEndTag();
function parseStartTag(tag, tagName, rest, unary) {
tagName = tagName.toLowerCase();
if (block[tagName]) {
while (stack.last() && inline[stack.last()]) {
parseEndTag('', stack.last());
}
}
if (closeSelf[tagName] && stack.last() == tagName) {
parseEndTag('', tagName);
}
unary = empty[tagName] || !!unary;
if (!unary) {
stack.push(tagName);
}
if (handler.start) {
var attrs = [];
rest.replace(attr, function (match, name) {
var value = arguments[2] ? arguments[2] : arguments[3] ? arguments[3] : arguments[4] ? arguments[4] : fillAttrs[name] ? name : '';
attrs.push({
name: name,
value: value,
escaped: value.replace(/(^|[^\\])"/g, '$1\\\"') // "
});
});
if (handler.start) {
handler.start(tagName, attrs, unary);
}
}
}
function parseEndTag(tag, tagName) {
// If no tag name is provided, clean shop
if (!tagName) {
var pos = 0;
} // Find the closest opened tag of the same type
else {
for (var pos = stack.length - 1; pos >= 0; pos--) {
if (stack[pos] == tagName) {
break;
}
}
}
if (pos >= 0) {
// Close all the open elements, up the stack
for (var i = stack.length - 1; i >= pos; i--) {
if (handler.end) {
handler.end(stack[i]);
}
} // Remove the open elements from the stack
stack.length = pos;
}
}
}
function makeMap(str) {
var obj = {};
var items = str.split(',');
for (var i = 0; i < items.length; i++) {
obj[items[i]] = true;
}
return obj;
}
function removeDOCTYPE(html) {
return html.replace(/<\?xml.*\?>\n/, '').replace(/<!doctype.*>\n/, '').replace(/<!DOCTYPE.*>\n/, '');
}
function parseAttrs(attrs) {
return attrs.reduce(function (pre, attr) {
var value = attr.value;
var name = attr.name;
if (pre[name]) {
pre[name] = pre[name] + " " + value;
} else {
pre[name] = value;
}
return pre;
}, {});
}
function parseHtml(html) {
html = removeDOCTYPE(html);
var stacks = [];
var results = {
node: 'root',
children: []
};
HTMLParser(html, {
start: function start(tag, attrs, unary) {
var node = {
name: tag
};
if (attrs.length !== 0) {
node.attrs = parseAttrs(attrs);
}
if (unary) {
var parent = stacks[0] || results;
if (!parent.children) {
parent.children = [];
}
parent.children.push(node);
} else {
stacks.unshift(node);
}
},
end: function end(tag) {
var node = stacks.shift();
if (node.name !== tag) console.error('invalid state: mismatch end tag');
if (stacks.length === 0) {
results.children.push(node);
} else {
var parent = stacks[0];
if (!parent.children) {
parent.children = [];
}
parent.children.push(node);
}
},
chars: function chars(text) {
var node = {
type: 'text',
text: text
};
if (stacks.length === 0) {
results.children.push(node);
} else {
var parent = stacks[0];
if (!parent.children) {
parent.children = [];
}
parent.children.push(node);
}
},
comment: function comment(text) {
var node = {
node: 'comment',
text: text
};
var parent = stacks[0];
if (!parent.children) {
parent.children = [];
}
parent.children.push(node);
}
});
return results.children;
}
export default parseHtml;

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,318 @@
<!-- uniapp vue3 markdown解析 -->
<template>
<view class="ua__markdown"><rich-text space="nbsp" :nodes="parseNodes(source)" @itemclick="handleItemClick"></rich-text></view>
</template>
<script setup>
import { ref, computed } from 'vue'
import MarkdownIt from './lib/markdown-it.min.js'
import hljs from './lib/highlight/uni-highlight.min.js'
import './lib/highlight/atom-one-dark.css'
import parseHtml from './lib/html-parser.js'
const props = defineProps({
// 解析内容
source: String,
showLine: { type: [Boolean, String], default: true }
})
let copyCodeData = []
const markdown = MarkdownIt({
html: true,
highlight: function(str, lang) {
let preCode = ""
try {
preCode = hljs.highlightAuto(str).value
} catch (err) {
preCode = markdown.utils.escapeHtml(str);
}
const lines = preCode.split(/\n/).slice(0, -1)
// 添加自定义行号
let html = lines.map((item, index) => {
if( item == ''){
return ''
}
return '<li><span class="line-num" data-line="' + (index + 1) + '"></span>' + item +'</li>'
}).join('')
if(props.showLine) {
html = '<ol style="padding: 0px 30px;">' + html + '</ol>'
}else {
html = '<ol style="padding: 0px 7px;list-style:none;">' + html + '</ol>'
}
copyCodeData.push(str)
let htmlCode = `<div class="markdown-wrap">`
// #ifndef MP-WEIXIN
htmlCode += `<div style="color: #aaa;text-align: right;font-size: 12px;padding:8px;">`
htmlCode += `${lang}<a class="copy-btn" code-data-index="${copyCodeData.length - 1}" style="margin-left: 8px;">复制代码</a>`
htmlCode += `</div>`
// #endif
htmlCode += `<pre class="hljs" style="padding:10px 8px 0;margin-bottom:5px;overflow: auto;display: block;border-radius: 5px;"><code>${html}</code></pre>`;
htmlCode += '</div>'
return htmlCode
}
})
const parseNodes = (value) => {
if(!value) return
// 解析<br />到\n
value = value.replace(/<br>|<br\/>|<br \/>/g, "\n")
value = value.replace(/&nbsp;/g, " ")
let htmlString = ''
if (value.split("```").length % 2) {
let mdtext = value
if(mdtext[mdtext.length-1] != '\n'){
mdtext += '\n'
}
htmlString = markdown.render(mdtext)
} else {
htmlString = markdown.render(value)
}
// 解决小程序表格边框型失效问题
htmlString = htmlString.replace(/<table/g, `<table class="table"`)
htmlString = htmlString.replace(/<tr/g, `<tr class="tr"`)
htmlString = htmlString.replace(/<th>/g, `<th class="th">`)
htmlString = htmlString.replace(/<td/g, `<td class="td"`)
htmlString = htmlString.replace(/<hr>|<hr\/>|<hr \/>/g, `<hr class="hr">`)
// #ifndef APP-NVUE
return htmlString
// #endif
// 将htmlString转成htmlArray反之使用rich-text解析
// #ifdef APP-NVUE
return parseHtml(htmlString)
// #endif
}
// 复制代码
const handleItemClick = (e) => {
let {attrs} = e.detail.node
let {"code-data-index":codeDataIndex,"class":className} = attrs
if(className == 'copy-btn'){
uni.setClipboardData({
data: copyCodeData[codeDataIndex],showToast: false,
success() {
uni.showToast({
title: '复制成功',icon: 'none'
});
}
})
}
}
</script>
<style lang="scss" scoped>
.ua__markdown {
font-size: 14px;line-height: 1.5; word-break: break-all;
h1,h2,h3,h4,h5,h6 {
font-family: inherit;font-weight: 500;line-height: 1.1;color: inherit;
}
h1,h2,h3 {margin-top: 20px;margin-bottom: 10px}
h4,h5,h6 {margin-top: 10px;margin-bottom: 10px}
.h1,h1 {font-size: 36px
}
.h2,h2 {font-size: 30px
}
.h3,h3 {font-size: 24px
}
.h4,h4 {font-size: 18px
}
.h5,h5 {font-size: 14px
}
.h6,h6 {font-size: 12px
}
a {
background-color: transparent;color: #2196f3;
text-decoration: none;
}
hr, ::v-deep .hr {
margin-top: 20px;margin-bottom: 20px; border: 0; border-top: 1px solid #e5e5e5;
}
img { max-width: 35%;
}
p {margin: 0 0 10px}
em {
font-style: italic; font-weight: inherit;
}
ol,ul {
margin-top: 0; margin-bottom: 10px;padding-left: 40px;
}
ol ol,ol ul,ul ol,ul ul {margin-bottom: 0;
}
ol ol, ul ol {list-style-type: lower-roman;
}
ol ol ol, ul ul ol {list-style-type: lower-alpha;
}
dl {
margin-top: 0;margin-bottom: 20px;
}
dt {font-weight: 600;
}
dt, dd {line-height: 1.4;
}
.task-list-item { list-style-type: none;
}
.task-list-item input {
margin: 0 .2em .25em -1.6em;vertical-align: middle;
}
pre {
position: relative; z-index: 11;
}
code,kbd,pre,samp { font-family: Menlo,Monaco,Consolas,"Courier New",monospace;}
code:not(.hljs) {
padding: 2px 4px;font-size: 90%;color: #c7254e;background-color: #ffe7ee;border-radius: 4px;
}
code:empty {display: none;
}
pre code.hljs {
color: var(--vg__text-1); border-radius: 16px; background: var(--vg__bg-1);font-size: 12px;
}
.markdown-wrap {
font-size: 12px;margin-bottom: 10px;
}
pre.code-block-wrapper {background: #2b2b2b;color: #f8f8f2;border-radius: 4px;overflow-x: auto;
padding: 1em;
position: relative;
}
pre.code-block-wrapper code {
padding: auto;
font-size: inherit;
color: inherit;
background-color: inherit;
border-radius: 0;
}
.code-block-header__copy {
font-size: 16px;margin-left: 5px;
}
abbr[data-original-title],abbr[title] {
cursor: help;border-bottom: 1px dotted #777;
}
blockquote {
padding: 10px 20px;margin: 0 0 20px;font-size: 17.5px;
border-left: 5px solid #e5e5e5;
}
blockquote ol:last-child,blockquote p:last-child,blockquote ul:last-child {
margin-bottom: 0
}
blockquote .small,blockquote footer,blockquote small {
display: block;font-size: 80%;line-height: 1.42857143;color: #777
}
blockquote .small:before,blockquote footer:before,blockquote small:before {
content: '\2014 \00A0'
}
.blockquote-reverse,blockquote.pull-right {
padding-right: 15px; padding-left: 0;
text-align: right;border-right: 5px solid #eee;border-left: 0
}
.blockquote-reverse .small:before,.blockquote-reverse footer:before,.blockquote-reverse small:before,blockquote.pull-right .small:before,blockquote.pull-right footer:before,blockquote.pull-right small:before {
content: ''
}
.blockquote-reverse .small:after,.blockquote-reverse footer:after,.blockquote-reverse small:after,blockquote.pull-right .small:after,blockquote.pull-right footer:after,blockquote.pull-right small:after {
content: '\00A0 \2014'
}
.footnotes {
-moz-column-count: 2;
-webkit-column-count: 2;
column-count: 2
}
.footnotes-list {padding-left: 2em}
table, ::v-deep .table {
border-spacing: 0;border-collapse: collapse; width: 100%;max-width: 65em; overflow: auto;margin-top: 0;
margin-bottom: 16px;
}
table tr, ::v-deep .table .tr {
border-top: 1px solid #e5e5e5;
}
table th, table td, ::v-deep .table .th, ::v-deep .table .td {
padding: 6px 13px;border: 1px solid #e5e5e5;
}
table th, ::v-deep .table .th {
font-weight: 600;background-color: #eee;
}
.hljs[class*=language-]:before {
position: absolute; z-index: 3;top: .8em; right: 1em; font-size: .8em; color: #999;
}
.hljs[class~=language-js]:before {
content: "js"
}
.hljs[class~=language-ts]:before {
content: "ts"
}
.hljs[class~=language-html]:before {
content: "html"
}
.hljs[class~=language-md]:before {
content: "md"
}
.hljs[class~=language-vue]:before {
content: "vue"
}
.hljs[class~=language-css]:before {
content: "css"
}
.hljs[class~=language-sass]:before {
content: "sass"
}
.hljs[class~=language-scss]:before {
content: "scss"
}
.hljs[class~=language-less]:before {
content: "less"
}
.hljs[class~=language-stylus]:before {
content: "stylus"
}
.hljs[class~=language-go]:before {
content: "go"
}
.hljs[class~=language-java]:before {
content: "java"
}
.hljs[class~=language-c]:before {
content: "c"
}
.hljs[class~=language-sh]:before {
content: "sh"
}
.hljs[class~=language-yaml]:before {
content: "yaml"
}
.hljs[class~=language-py]:before {
content: "py"
}
.hljs[class~=language-docker]:before {
content: "docker"
}
.hljs[class~=language-dockerfile]:before {
content: "dockerfile"
}
.hljs[class~=language-makefile]:before {
content: "makefile"
}
.hljs[class~=language-javascript]:before {
content: "js"
}
.hljs[class~=language-typescript]:before {
content: "ts"
}
.hljs[class~=language-markup]:before {
content: "html"
}
.hljs[class~=language-markdown]:before {
content: "md"
}
.hljs[class~=language-json]:before {
content: "json"
}
.hljs[class~=language-ruby]:before {
content: "rb"
}
.hljs[class~=language-python]:before {
content: "py"
}
.hljs[class~=language-bash]:before {
content: "sh"
}
.hljs[class~=language-php]:before {
content: "php"
}
}
</style>

View File

@@ -0,0 +1,18 @@
{
"id": "ua-markdown",
"name": "uniapp markdown语法渲染及代码高亮",
"displayName": "uniapp markdown语法渲染及代码高亮",
"version": "1.2.4",
"description": "基于uniapp+vue3自定义解析markdown语法/高亮适用于h5+小程序+App端。",
"keywords": [
"ua-markdown",
"uni-markdown",
"markdown"
],
"dcloudext": {
"category": [
"前端组件",
"通用组件"
]
}
}

View File

@@ -0,0 +1,49 @@
# vue3版本
vue2版本已经上线欢迎下载使用。
[https://ext.dcloud.net.cn/plugin?id=13864](https://ext.dcloud.net.cn/plugin?id=13864)
## uniapp markdown渲染解析.md语法及代码高亮
> **组件名uaMarkdown**
> 代码块: `<ua-markdown>`
uaMarkdown组件是基于uniapp+vue3自定义解析markdown语法结构插件、支持代码块高亮编译兼容H5+小程序端+App端。
### 引入方式
本组件符合[easycom](https://uniapp.dcloud.io/collocation/pages?id=easycom)规范,只需将本组件`ua-markdown`放在components目录在页面`template`中即可直接使用。
### 基本用法
**示例**
- 基础用法
```html
const mdvalue = '### uniapp markdwon'
<ua-markdown :source="mdvalue" />
```
- 去掉代码块行号
```html
<ua-markdown :source="xxx" :showLine="false" />
```
### API
### uaMarkdown Props
|属性名|类型|默认值|说明|
|:-:|:-:|:-:|:-:|
|source|String|-| 渲染解析内容 |
|showLine|Boolean|true| 是否显示代码块行号 |
### 💝最后
开发不易,希望各位小伙伴们多多支持下哈~~ ☕️☕️

293
src/utils/ai.ts Normal file
View File

@@ -0,0 +1,293 @@
import type { IProfile } from "@/type/profile";
import type { IHealthRecord } from "@/type/record";
export function preprocessHealthData(userInfo: IProfile, records: IHealthRecord[]) {
const currentYear = new Date().getFullYear();
const currentMonth = new Date().getMonth() + 1;
const age = currentYear - userInfo.birthYear;
// ---------- 基础汇总 ----------
const uniqueDates = new Set(records.map(r => r.date));
const indicators = [...new Set(records.map(r => r.type))];
const typeCount = {};
records.forEach(r => {
typeCount[r.type] = (typeCount[r.type] || 0) + 1;
});
let mostFrequent = null;
let maxCount = 0;
for (const [type, count] of Object.entries(typeCount)) {
if (count > maxCount) {
maxCount = count;
mostFrequent = type;
}
}
const totalDays = uniqueDates.size;
let quality = '偏少';
if (records.length >= 20) quality = '充足';
else if (records.length >= 10) quality = '中等';
// ---------- 各指标处理 ----------
const metrics = {
weight: {},
bloodPressure: {},
bloodSugar: {},
temperature: {},
sport: {},
sleep: {}
};
const anomalies = [];
// ---- 体重 ----
const weightRecords = records.filter(r => r.type === 'weight');
if (weightRecords.length > 0) {
const values = weightRecords.map(r => r.value);
const mean = values.reduce((a, b) => a + b, 0) / values.length;
const first = weightRecords[0].value;
const last = weightRecords[weightRecords.length - 1].value;
const change = last - first;
let trend = '平稳';
if (change < -0.3) trend = '下降';
else if (change > 0.3) trend = '上升';
const heightM = userInfo.height / 100;
const bmi = last / (heightM * heightM);
let bmiStatus = '正常';
if (bmi < 18.5) bmiStatus = '偏瘦';
else if (bmi < 24) bmiStatus = '正常';
else if (bmi < 28) bmiStatus = '超重';
else bmiStatus = '肥胖';
metrics.weight = {
count: weightRecords.length,
first: first,
last: last,
mean: Math.round(mean * 10) / 10,
trend: trend,
change: Math.round(change * 10) / 10,
bmi: Math.round(bmi * 10) / 10,
bmiStatus: bmiStatus,
};
}
// ---- 血压 ----
const bpRecords = records.filter(r => r.type === 'bloodPressure');
if (bpRecords.length > 0) {
const systolicValues = bpRecords.map(r => r.systolic);
const diastolicValues = bpRecords.map(r => r.diastolic);
const heartRates = bpRecords.filter(r => r.heartRate !== undefined).map(r => r.heartRate);
const systolicMean = systolicValues.reduce((a, b) => a + b, 0) / systolicValues.length;
const diastolicMean = diastolicValues.reduce((a, b) => a + b, 0) / diastolicValues.length;
let status = '正常';
for (const r of bpRecords) {
if (r.systolic >= 140 || r.diastolic >= 90) {
status = '需关注';
break;
}
if (r.systolic >= 130 || r.diastolic >= 80) {
status = '偏高';
}
}
metrics.bloodPressure = {
count: bpRecords.length,
systolicMean: Math.round(systolicMean),
diastolicMean: Math.round(diastolicMean),
systolicMax: Math.max(...systolicValues),
diastolicMax: Math.max(...diastolicValues),
heartRateMean: heartRates.length > 0 ? Math.round(heartRates.reduce((a, b) => a + b, 0) / heartRates.length) : undefined,
status: status,
};
for (const r of bpRecords) {
if (r.systolic >= 140 || r.diastolic >= 90) {
anomalies.push({
type: '血压',
date: r.date,
detail: `收缩压${r.systolic}mmHg/舒张压${r.diastolic}mmHg 偏高`,
});
}
}
}
// ---- 血糖(按类型分组) ----
const sugarRecords = records.filter(r => r.type === 'bloodSugar');
if (sugarRecords.length > 0) {
const sugarByPeriod = {};
for (const r of sugarRecords) {
const key = r.period || '未标注';
if (!sugarByPeriod[key]) {
sugarByPeriod[key] = { count: 0, values: [], mean: 0, max: -Infinity, min: Infinity, anomalies: [] };
}
const group = sugarByPeriod[key];
group.count++;
group.values.push(r.value);
group.max = Math.max(group.max, r.value);
group.min = Math.min(group.min, r.value);
let isAnomaly = false;
if (key === '空腹' || key === '餐前') {
if (r.value < 3.9 || r.value > 6.1) isAnomaly = true;
} else if (key === '餐后2h') {
if (r.value >= 7.8) isAnomaly = true;
} else if (key === '睡前') {
if (r.value < 4.0 || r.value > 6.7) isAnomaly = true;
}
if (isAnomaly) {
group.anomalies.push({ date: r.date, value: r.value });
anomalies.push({
type: `血糖(${key})`,
date: r.date,
detail: `${r.value}mmol/L 超出正常范围`,
});
}
}
for (const key of Object.keys(sugarByPeriod)) {
const group = sugarByPeriod[key];
group.mean = Math.round((group.values.reduce((a, b) => a + b, 0) / group.count) * 10) / 10;
}
metrics.bloodSugar = sugarByPeriod;
}
// ---- 体温 ----
const tempRecords = records.filter(r => r.type === 'temperature');
if (tempRecords.length > 0) {
const values = tempRecords.map(r => r.value);
const mean = values.reduce((a, b) => a + b, 0) / values.length;
const tempAnomalies = [];
for (const r of tempRecords) {
if (r.value < 36.0 || r.value > 37.2) {
tempAnomalies.push({ date: r.date, value: r.value });
anomalies.push({
type: '体温',
date: r.date,
detail: `${r.value}℃ 超出正常范围(36.0-37.2℃)`,
});
}
}
metrics.temperature = {
count: tempRecords.length,
values: values,
mean: Math.round(mean * 10) / 10,
max: Math.max(...values),
min: Math.min(...values),
status: tempAnomalies.length > 0 ? '需关注' : '正常',
anomalies: tempAnomalies,
};
}
// ---- 运动 ----
const sportRecords = records.filter(r => r.type === 'sport');
if (sportRecords.length > 0) {
const categories = {};
let totalDuration = 0;
for (const r of sportRecords) {
categories[r.category] = (categories[r.category] || 0) + 1;
totalDuration += r.duration;
}
let mainCategory = null;
let maxCatCount = 0;
for (const [cat, count] of Object.entries(categories)) {
if (count > maxCatCount) {
maxCatCount = count;
mainCategory = cat;
}
}
metrics.sport = {
count: sportRecords.length,
categories: categories,
totalDuration: totalDuration,
avgDuration: Math.round(totalDuration / sportRecords.length),
mainCategory: mainCategory,
};
}
// ---- 睡眠 ----
const sleepRecords = records.filter(r => r.type === 'sleep');
if (sleepRecords.length > 0) {
const durations = sleepRecords.map(r => r.duration);
const mean = durations.reduce((a, b) => a + b, 0) / durations.length;
const shortDays = durations.filter(d => d < 7).length;
const longDays = durations.filter(d => d > 9).length;
let status = '正常';
if (shortDays > sleepRecords.length / 2) status = '偏少';
else if (longDays > sleepRecords.length / 2) status = '偏多';
else if (Math.max(...durations) - Math.min(...durations) > 2) status = '波动较大';
metrics.sleep = {
count: sleepRecords.length,
durations: durations,
mean: Math.round(mean * 10) / 10,
min: Math.min(...durations),
max: Math.max(...durations),
shortDays: shortDays,
longDays: longDays,
status: status,
};
for (const r of sleepRecords) {
if (r.duration < 7) {
anomalies.push({
type: '睡眠',
date: r.date,
detail: `${r.duration}小时低于推荐7小时`,
});
}
}
}
// ---- 交叉天数 ----
const dateIndicatorMap = {};
for (const r of records) {
if (!dateIndicatorMap[r.date]) dateIndicatorMap[r.date] = new Set();
dateIndicatorMap[r.date].add(r.type);
}
let crossDays = 0;
for (const indicatorsOfDay of Object.values(dateIndicatorMap)) {
if (indicatorsOfDay.size >= 2) crossDays++;
}
// ---- 指标名转中文 ----
const indicatorMap = {
weight: '体重',
bloodPressure: '血压',
bloodSugar: '血糖',
temperature: '体温',
sport: '运动',
sleep: '睡眠'
};
// ============ 返回 ============
return {
user: {
age: age,
gender: userInfo.gender === 'male' ? '男' : '女',
height: userInfo.height,
occupation: userInfo.occupation,
goal: userInfo.goal,
},
period: currentYear + '年' + currentMonth + '月',
summary: {
totalDays: totalDays,
indicators: indicators.map(i => indicatorMap[i] || i),
mostFrequent: mostFrequent ? (indicatorMap[mostFrequent] || mostFrequent) : null,
quality: quality,
},
metrics: metrics,
crossDays: crossDays,
anomalies: anomalies,
recordCount: records.length,
};
}