This commit is contained in:
HuangHai
2026-01-20 08:21:08 +08:00
parent 34501faafb
commit a5e8da0f9e
11 changed files with 1044 additions and 1215 deletions

View File

@@ -112,7 +112,7 @@ async def chat(q: str):
"""
match_result_str = ""
async for chunk in get_llm_response_async(match_prompt, stream=True):
async for chunk in get_llm_response(match_prompt, stream=True):
match_result_str += chunk
# 清理并解析匹配结果

View File

@@ -253,20 +253,30 @@ class Db:
processed_sql = sql_template
# 处理#if条件判断
# 修复正则表达式,确保正确匹配条件块
if_pattern = r'#if\((\w+)\)([\s\S]*?)#end'
# 修复正则表达式,确保正确匹配条件块,支持 ! 取反
if_pattern = r'#if\((!?\w+)\)([\s\S]*?)#end'
# 使用finditer来获取匹配的位置信息
matches = list(re.finditer(if_pattern, processed_sql))
# 从后向前替换,避免位置偏移问题
for match in reversed(matches):
param_name = match.group(1)
raw_param_name = match.group(1)
sql_block = match.group(2)
# 处理取反逻辑
is_negation = raw_param_name.startswith('!')
param_name = raw_param_name[1:] if is_negation else raw_param_name
# 检查参数是否存在且不为None
if param_name in params and params[param_name] is not None:
# 如果条件为真,保留SQL块
# 检查参数是否存在且不为None (且不为空,如果需要更严格的检查)
# 这里保持原逻辑基础上增加对空值的判定,因为空列表通常也意味着False
has_value = param_name in params and params[param_name] is not None and params[param_name]
# 决定是否保留代码块
keep_block = (not has_value) if is_negation else has_value
if keep_block:
# 如果条件满足,保留SQL块
# 移除多余的空白行和缩进
lines = sql_block.strip().split('\n')
cleaned_lines = [line.strip() for line in lines if line.strip()]
@@ -275,11 +285,11 @@ class Db:
# 替换原始匹配的内容
processed_sql = processed_sql[:match.start()] + cleaned_block + processed_sql[match.end():]
logger.debug(f"保留条件块 #if({param_name}),内容: {cleaned_block}")
logger.debug(f"保留条件块 #if({raw_param_name}),内容: {cleaned_block}")
else:
# 如果条件为假,移除整个条件块
# 如果条件不满足,移除整个条件块
processed_sql = processed_sql[:match.start()] + "" + processed_sql[match.end():]
logger.debug(f"移除条件块 #if({param_name})")
logger.debug(f"移除条件块 #if({raw_param_name})")
# 创建参数字典的副本,用于存储处理后的参数
if params is not None:

Binary file not shown.

View File

@@ -19,7 +19,7 @@ def setup_api_logger():
return logger
log_dir = os.path.join(project_root, "Logs")
os.makedirs(log_dir, exist_ok=True)
log_file = os.path.join(log_dir, "YLT_Analytics_Api.log")
log_file = os.path.join(log_dir, "Start.log")
file_handler = logging.FileHandler(log_file, encoding="utf-8")
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
file_handler.setFormatter(formatter)

View File

@@ -51,6 +51,38 @@ body {
letter-spacing: -0.5px;
}
/* Navigation Tabs */
.nav-tabs {
display: flex;
background: rgba(30, 41, 59, 0.5);
border-radius: 8px;
padding: 4px;
gap: 4px;
}
.nav-tab {
padding: 8px 16px;
border-radius: 6px;
color: var(--text-secondary);
font-weight: 600;
font-size: 14px;
cursor: pointer;
transition: all 0.2s;
background: transparent;
border: none;
}
.nav-tab:hover {
color: var(--text-primary);
background: rgba(255, 255, 255, 0.05);
}
.nav-tab.active {
background: var(--accent-color);
color: white;
box-shadow: 0 2px 4px rgba(59, 130, 246, 0.3);
}
/* Main Layout */
.main-content {
display: flex;
@@ -330,3 +362,420 @@ body {
background: #64748b;
}
/* =========================================
INTEGRATED DEGREE STYLES
========================================= */
.degree-container {
max-width: 1000px;
margin: 40px auto;
padding: 0 20px;
width: 100%;
flex: 1;
overflow-y: auto;
scrollbar-width: thin;
}
.query-section {
background: rgba(15, 23, 42, 0.96);
border-radius: 12px;
padding: 30px;
box-shadow: 0 24px 60px rgba(15, 23, 42, 0.9);
margin-bottom: 30px;
text-align: center;
border: 1px solid var(--card-border);
}
.page-title {
font-size: 32px;
background: linear-gradient(135deg, #fff 0%, #94a3b8 100%);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
margin-bottom: 16px;
font-weight: 700;
letter-spacing: -0.025em;
}
.page-subtitle {
margin-bottom: 32px;
color: #94a3b8;
font-size: 16px;
opacity: 0.9;
}
.input-wrapper {
max-width: 700px;
margin: 0 auto;
position: relative;
}
/* 搜索框样式优化 */
.search-input.el-input {
--el-input-border-color: rgba(148, 163, 184, 0.5);
--el-input-hover-border-color: rgba(56, 189, 248, 0.9);
--el-input-focus-border-color: rgba(56, 189, 248, 0.9);
--el-input-bg-color: rgba(15, 23, 42, 0.9);
--el-input-text-color: #e5e7eb;
}
.search-input .el-input__wrapper {
padding-left: 20px;
padding-right: 20px;
box-shadow: 0 2px 18px rgba(15, 23, 42, 0.6);
background-color: rgba(15, 23, 42, 0.9);
border: 1px solid rgba(148, 163, 184, 0.5);
transition: all 0.3s ease;
}
.search-input.el-input-group--append .el-input__wrapper {
border-radius: 24px 0 0 24px;
border-right: none;
}
.search-input:not(.el-input-group--append) .el-input__wrapper {
border-radius: 24px;
}
.search-input .el-input-group__append {
background-color: rgba(56, 189, 248, 0.9);
border: 1px solid rgba(56, 189, 248, 0.9);
border-left: none;
border-radius: 0 24px 24px 0;
padding: 0;
box-shadow: 0 2px 18px rgba(15, 23, 42, 0.6);
}
.search-input .el-input-group__append .el-button,
.search-input .el-input-group__append .el-button.el-button--primary {
border: none;
margin: 0;
padding: 0 30px;
height: 48px;
color: #fff;
background-color: transparent;
font-weight: 600;
font-size: 16px;
transition: all 0.2s;
border-radius: 0;
}
.search-input .el-input-group__append .el-button:hover,
.search-input .el-input-group__append .el-button.el-button--primary:hover {
background-color: rgba(14, 165, 233, 1);
color: #fff;
}
.search-input .el-input-group__append .el-button:active {
transform: scale(0.98);
}
.search-input .el-input__wrapper:hover,
.search-input .el-input__wrapper.is-focus {
box-shadow: 0 0 0 1px rgba(56, 189, 248, 0.9), 0 20px 40px rgba(15, 23, 42, 0.9);
border-color: rgba(56, 189, 248, 0.9);
z-index: 1;
}
.search-input .el-input-group__append:hover {
border-color: rgba(56, 189, 248, 0.9);
}
.search-input .el-input__inner {
height: 48px;
font-size: 16px;
color: #e5e7eb;
}
.search-input .el-input__inner::placeholder {
color: rgba(148, 163, 184, 0.8);
}
.example-tags {
margin-top: 16px;
display: flex;
justify-content: center;
gap: 10px;
flex-wrap: wrap;
}
.example-tag {
cursor: pointer;
transition: all 0.2s;
border-color: rgba(148, 163, 184, 0.6);
color: #cbd5f5;
background-color: rgba(15, 23, 42, 0.8);
}
.example-tag:hover {
transform: translateY(-2px);
border-color: rgba(56, 189, 248, 0.9);
color: #e0f2fe;
background-color: rgba(15, 23, 42, 1);
}
.result-section {
background: rgba(15, 23, 42, 0.96);
border-radius: 12px;
padding: 30px;
box-shadow: 0 24px 60px rgba(15, 23, 42, 0.9);
min-height: 200px;
border: 1px solid var(--card-border);
}
.result-header {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 20px;
border-bottom: 1px solid #eee;
padding-bottom: 15px;
}
.result-title {
font-size: 18px;
font-weight: 600;
color: #e5e7eb;
display: flex;
align-items: center;
gap: 8px;
}
.markdown-body {
font-size: 16px;
line-height: 1.7;
color: #e5e7eb;
}
.markdown-body table {
width: 100%;
border-collapse: collapse;
margin: 16px 0;
}
.markdown-body th,
.markdown-body td {
padding: 12px;
border: 1px solid rgba(51, 65, 85, 0.9);
}
.markdown-body th {
background-color: rgba(30, 64, 175, 0.95);
font-weight: 600;
}
.markdown-body tr:nth-child(even) {
background-color: rgba(15, 23, 42, 0.9);
}
.loading-container {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
padding: 40px 0;
color: rgba(148, 163, 184, 0.9);
}
/* Cursor blink animation for streaming effect */
.cursor-blink {
display: inline-block;
width: 2px;
height: 1em;
background-color: #38bdf8;
vertical-align: text-bottom;
animation: blink 1s step-end infinite;
}
@keyframes blink {
0%, 100% { opacity: 1; }
50% { opacity: 0; }
}
/* 二维码容器 */
.qr-sidebar {
position: fixed;
right: 20px;
bottom: 20px;
background: rgba(15, 23, 42, 0.95);
border: 1px solid rgba(148, 163, 184, 0.25);
border-radius: 12px;
padding: 16px;
box-shadow: 0 10px 30px rgba(0, 0, 0, 0.5);
z-index: 1000;
text-align: center;
transition: all 0.3s ease;
box-sizing: border-box;
}
.qr-sidebar:hover {
transform: translateY(-5px);
border-color: rgba(56, 189, 248, 0.5);
background: rgba(15, 23, 42, 1);
}
.qr-code {
width: 128px;
height: 128px;
background: #fff;
padding: 8px;
border-radius: 8px;
margin-bottom: 10px;
display: flex;
align-items: center;
justify-content: center;
box-sizing: border-box;
overflow: hidden;
}
.qr-code canvas, .qr-code img {
max-width: 100% !important;
max-height: 100% !important;
height: auto !important;
display: block;
}
.qr-text {
font-size: 13px;
font-weight: 500;
color: #94a3b8;
margin: 0;
letter-spacing: 0.5px;
}
/* 响应式调整 */
@media screen and (max-width: 1200px) {
.qr-sidebar {
display: none;
}
}
/* ECharts 图表容器 */
.echarts-container {
width: 100%;
height: 400px;
margin: 24px 0;
background: rgba(15, 23, 42, 0.4);
border: 1px solid rgba(56, 189, 248, 0.1);
border-radius: 12px;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.2);
overflow: hidden;
transition: all 0.3s ease;
}
.echarts-container:hover {
border-color: rgba(56, 189, 248, 0.3);
box-shadow: 0 8px 30px rgba(0, 0, 0, 0.3);
}
@media (max-width: 768px) {
.echarts-container {
height: 300px;
margin: 16px 0;
padding: 10px !important;
}
.degree-container {
margin-top: 20px !important;
padding: 0 15px;
}
.query-section {
padding: 20px 10px;
}
.page-title {
font-size: 22px;
margin-bottom: 10px;
}
.page-subtitle {
font-size: 14px;
margin-bottom: 20px;
}
.result-section {
padding: 15px;
}
.input-wrapper {
max-width: 100%;
}
.search-input .el-input__inner {
height: 40px;
font-size: 14px;
}
.search-input .el-input-group__append .el-button {
padding: 0 12px;
height: 40px;
font-size: 14px;
}
.example-tags {
gap: 6px;
}
.example-tag {
font-size: 12px;
padding: 0 8px;
}
.result-section {
padding: 15px;
margin-top: 20px;
}
.markdown-body {
font-size: 14px;
}
.markdown-body table {
display: block;
width: 100%;
overflow-x: auto;
-webkit-overflow-scrolling: touch;
margin: 16px 0;
border-collapse: collapse;
/* 增加一个细小的滚动条样式,提示可以滚动 */
}
.markdown-body table::-webkit-scrollbar {
height: 4px;
}
.markdown-body table::-webkit-scrollbar-thumb {
background: rgba(56, 189, 248, 0.5);
border-radius: 2px;
}
.markdown-body th,
.markdown-body td {
white-space: nowrap;
padding: 10px 15px;
font-size: 13px;
min-width: 100px;
}
/* 手机端首列固定 */
.markdown-body table tr th:first-child,
.markdown-body table tr td:first-child {
position: sticky;
left: 0;
z-index: 2;
box-shadow: 2px 0 5px rgba(0,0,0,0.3);
}
.markdown-body table tr th:first-child {
background-color: #1e40af !important; /* 统一使用深蓝色 */
}
.markdown-body table tr:nth-child(odd) td:first-child {
background-color: #0f172a !important; /* 与容器背景一致 */
}
.markdown-body table tr:nth-child(even) td:first-child {
background-color: #1e293b !important; /* 稍亮的条纹背景 */
}
}

View File

@@ -1,421 +0,0 @@
body {
background: radial-gradient(circle at top, #1e293b 0, #020617 55%, #000 100%);
color: #e5e7eb;
}
.header {
background: rgba(15, 23, 42, 0.95);
box-shadow: 0 10px 30px rgba(15, 23, 42, 0.8);
border-bottom: 1px solid rgba(148, 163, 184, 0.25);
}
.logo {
color: #e5e7eb;
}
.degree-container {
max-width: 1000px;
margin: 40px auto;
padding: 0 20px;
}
.query-section {
background: rgba(15, 23, 42, 0.96);
border-radius: 12px;
padding: 30px;
box-shadow: 0 24px 60px rgba(15, 23, 42, 0.9);
margin-bottom: 30px;
text-align: center;
}
.page-title {
font-size: 32px;
background: linear-gradient(135deg, #fff 0%, #94a3b8 100%);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
margin-bottom: 16px;
font-weight: 700;
letter-spacing: -0.025em;
}
.page-subtitle {
margin-bottom: 32px;
color: #94a3b8;
font-size: 16px;
opacity: 0.9;
}
.input-wrapper {
max-width: 700px;
margin: 0 auto;
position: relative;
}
/* 搜索框样式优化 */
.search-input.el-input {
--el-input-border-color: rgba(148, 163, 184, 0.5);
--el-input-hover-border-color: rgba(56, 189, 248, 0.9);
--el-input-focus-border-color: rgba(56, 189, 248, 0.9);
--el-input-bg-color: rgba(15, 23, 42, 0.9);
--el-input-text-color: #e5e7eb;
}
.search-input .el-input__wrapper {
padding-left: 20px;
padding-right: 20px;
box-shadow: 0 2px 18px rgba(15, 23, 42, 0.6);
background-color: rgba(15, 23, 42, 0.9);
border: 1px solid rgba(148, 163, 184, 0.5);
transition: all 0.3s ease;
}
.search-input.el-input-group--append .el-input__wrapper {
border-radius: 24px 0 0 24px;
border-right: none;
}
.search-input:not(.el-input-group--append) .el-input__wrapper {
border-radius: 24px;
}
.search-input .el-input-group__append {
background-color: rgba(56, 189, 248, 0.9);
border: 1px solid rgba(56, 189, 248, 0.9);
border-left: none;
border-radius: 0 24px 24px 0;
padding: 0;
box-shadow: 0 2px 18px rgba(15, 23, 42, 0.6);
}
.search-input .el-input-group__append .el-button,
.search-input .el-input-group__append .el-button.el-button--primary {
border: none;
margin: 0;
padding: 0 30px;
height: 48px;
color: #fff;
background-color: transparent;
font-weight: 600;
font-size: 16px;
transition: all 0.2s;
border-radius: 0;
}
.search-input .el-input-group__append .el-button:hover,
.search-input .el-input-group__append .el-button.el-button--primary:hover {
background-color: rgba(14, 165, 233, 1);
color: #fff;
}
.search-input .el-input-group__append .el-button:active {
transform: scale(0.98);
}
.search-input .el-input__wrapper:hover,
.search-input .el-input__wrapper.is-focus {
box-shadow: 0 0 0 1px rgba(56, 189, 248, 0.9), 0 20px 40px rgba(15, 23, 42, 0.9);
border-color: rgba(56, 189, 248, 0.9);
z-index: 1;
}
.search-input .el-input-group__append:hover {
border-color: rgba(56, 189, 248, 0.9);
}
.search-input .el-input__inner {
height: 48px;
font-size: 16px;
color: #e5e7eb;
}
.search-input .el-input__inner::placeholder {
color: rgba(148, 163, 184, 0.8);
}
.example-tags {
margin-top: 16px;
display: flex;
justify-content: center;
gap: 10px;
flex-wrap: wrap;
}
.example-tag {
cursor: pointer;
transition: all 0.2s;
border-color: rgba(148, 163, 184, 0.6);
color: #cbd5f5;
background-color: rgba(15, 23, 42, 0.8);
}
.example-tag:hover {
transform: translateY(-2px);
border-color: rgba(56, 189, 248, 0.9);
color: #e0f2fe;
background-color: rgba(15, 23, 42, 1);
}
.result-section {
background: rgba(15, 23, 42, 0.96);
border-radius: 12px;
padding: 30px;
box-shadow: 0 24px 60px rgba(15, 23, 42, 0.9);
min-height: 200px;
}
.result-header {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 20px;
border-bottom: 1px solid #eee;
padding-bottom: 15px;
}
.result-title {
font-size: 18px;
font-weight: 600;
color: #e5e7eb;
display: flex;
align-items: center;
gap: 8px;
}
.markdown-body {
font-size: 16px;
line-height: 1.7;
color: #e5e7eb;
}
.markdown-body table {
width: 100%;
border-collapse: collapse;
margin: 16px 0;
}
.markdown-body th,
.markdown-body td {
padding: 12px;
border: 1px solid rgba(51, 65, 85, 0.9);
}
.markdown-body th {
background-color: rgba(30, 64, 175, 0.95);
font-weight: 600;
}
.markdown-body tr:nth-child(even) {
background-color: rgba(15, 23, 42, 0.9);
}
.loading-container {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
padding: 40px 0;
color: rgba(148, 163, 184, 0.9);
}
/* Cursor blink animation for streaming effect */
.cursor-blink {
display: inline-block;
width: 2px;
height: 1em;
background-color: #38bdf8;
vertical-align: text-bottom;
animation: blink 1s step-end infinite;
}
@keyframes blink {
0%, 100% { opacity: 1; }
50% { opacity: 0; }
}
/* 二维码容器 */
.qr-sidebar {
position: fixed;
right: 20px;
bottom: 20px;
background: rgba(15, 23, 42, 0.95);
border: 1px solid rgba(148, 163, 184, 0.25);
border-radius: 12px;
padding: 16px;
box-shadow: 0 10px 30px rgba(0, 0, 0, 0.5);
z-index: 1000;
text-align: center;
transition: all 0.3s ease;
box-sizing: border-box;
}
.qr-sidebar:hover {
transform: translateY(-5px);
border-color: rgba(56, 189, 248, 0.5);
background: rgba(15, 23, 42, 1);
}
.qr-code {
width: 128px;
height: 128px;
background: #fff;
padding: 8px;
border-radius: 8px;
margin-bottom: 10px;
display: flex;
align-items: center;
justify-content: center;
box-sizing: border-box;
overflow: hidden;
}
.qr-code canvas, .qr-code img {
max-width: 100% !important;
max-height: 100% !important;
height: auto !important;
display: block;
}
.qr-text {
font-size: 13px;
font-weight: 500;
color: #94a3b8;
margin: 0;
letter-spacing: 0.5px;
}
/* 响应式调整 */
@media screen and (max-width: 1200px) {
.qr-sidebar {
display: none;
}
}
/* ECharts 图表容器 */
.echarts-container {
width: 100%;
height: 400px;
margin: 24px 0;
background: rgba(15, 23, 42, 0.4);
border: 1px solid rgba(56, 189, 248, 0.1);
border-radius: 12px;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.2);
overflow: hidden;
transition: all 0.3s ease;
}
.echarts-container:hover {
border-color: rgba(56, 189, 248, 0.3);
box-shadow: 0 8px 30px rgba(0, 0, 0, 0.3);
}
@media (max-width: 768px) {
.echarts-container {
height: 300px;
margin: 16px 0;
padding: 10px !important;
}
.degree-container {
margin-top: 20px !important;
padding: 0 15px;
}
.query-section {
padding: 20px 10px;
}
.page-title {
font-size: 22px;
margin-bottom: 10px;
}
.page-subtitle {
font-size: 14px;
margin-bottom: 20px;
}
.result-section {
padding: 15px;
}
.input-wrapper {
max-width: 100%;
}
.search-input .el-input__inner {
height: 40px;
font-size: 14px;
}
.search-input .el-input-group__append .el-button {
padding: 0 12px;
height: 40px;
font-size: 14px;
}
.example-tags {
gap: 6px;
}
.example-tag {
font-size: 12px;
padding: 0 8px;
}
.result-section {
padding: 15px;
margin-top: 20px;
}
.markdown-body {
font-size: 14px;
}
.markdown-body table {
display: block;
width: 100%;
overflow-x: auto;
-webkit-overflow-scrolling: touch;
margin: 16px 0;
border-collapse: collapse;
/* 增加一个细小的滚动条样式,提示可以滚动 */
}
.markdown-body table::-webkit-scrollbar {
height: 4px;
}
.markdown-body table::-webkit-scrollbar-thumb {
background: rgba(56, 189, 248, 0.5);
border-radius: 2px;
}
.markdown-body th,
.markdown-body td {
white-space: nowrap;
padding: 10px 15px;
font-size: 13px;
min-width: 100px;
}
/* 手机端首列固定 */
.markdown-body table tr th:first-child,
.markdown-body table tr td:first-child {
position: sticky;
left: 0;
z-index: 2;
box-shadow: 2px 0 5px rgba(0,0,0,0.3);
}
.markdown-body table tr th:first-child {
background-color: #1e40af !important; /* 统一使用深蓝色 */
}
.markdown-body table tr:nth-child(odd) td:first-child {
background-color: #0f172a !important; /* 与容器背景一致 */
}
.markdown-body table tr:nth-child(even) td:first-child {
background-color: #1e293b !important; /* 稍亮的条纹背景 */
}
}

View File

@@ -1,92 +0,0 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>驿来特AI数据查询功能示例</title>
<link rel="stylesheet" href="css/element-plus.index.css">
<link rel="stylesheet" href="css/style.css">
<link rel="stylesheet" href="css/degree.css">
</head>
<body>
<div id="app">
<!-- 悬浮二维码 -->
<div class="qr-sidebar">
<div id="qrcode" class="qr-code"></div>
<p class="qr-text">手机扫码访问</p>
</div>
<div class="degree-container" style="margin-top: 100px;">
<div class="query-section">
<h1 class="page-title">驿来特AI智能数据查询</h1>
<p class="page-subtitle">基于大语言模型,为您提供实时、精准的业务数据分析</p>
<div class="input-wrapper">
<el-input
v-model="query"
placeholder="请输入您的问题,例如:帮我查询12月份充电量TOP 10场站的充电情况"
class="search-input"
size="large"
@keyup.enter="handleSearch"
:disabled="loading"
>
<template #append>
<el-button @click="handleSearch" :loading="loading" type="primary">
{{ loading ? '分析中...' : '开始查询' }}
</el-button>
</template>
</el-input>
</div>
<div class="example-tags">
<el-tag
v-for="(text, index) in examples"
:key="index"
class="example-tag"
effect="plain"
round
size="large"
@click="setExample(text)"
>
{{ text }}
</el-tag>
</div>
</div>
<div class="result-section" v-if="result || loading">
<div class="result-header">
<div class="result-title">
<span>分析结果</span>
<el-tag size="small" type="success" effect="dark" v-if="!loading">完成</el-tag>
<el-tag size="small" type="warning" effect="dark" v-if="loading">生成中</el-tag>
</div>
<el-button
v-if="loading"
type="danger"
link
@click="stopGeneration"
>
停止生成
</el-button>
</div>
<div class="markdown-body" v-html="renderedResult"></div>
<div v-if="loading && !result" class="loading-container">
<p>正在分析数据,请稍候...</p>
</div>
<span v-if="loading" class="cursor-blink">|</span>
</div>
</div>
</div>
<!-- Scripts -->
<script src="js/vue.global.js"></script>
<script src="js/element-plus.index.full.js"></script>
<script src="js/element-plus.zh-cn.min.js"></script>
<script src="js/marked.min.js"></script>
<script src="js/qrcode.min.js"></script>
<script src="js/echarts.min.js"></script>
<script src="js/degree.js"></script>
</body>
</html>

View File

@@ -2,7 +2,9 @@
<html>
<head>
<meta charset="utf-8">
<title>多供应商分时电价分析大屏</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>驿来特AI智能数据分析平台</title>
<link rel="stylesheet" href="css/element-plus.index.css">
<link rel="stylesheet" href="css/app.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.16.9/katex.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/marked/12.0.0/marked.min.js"></script>
@@ -12,8 +14,14 @@
<body>
<div id="app">
<header class="dashboard-header">
<div class="dashboard-title">⚡ 充电站电价分析驾驶舱</div>
<div class="controls">
<div class="dashboard-title">⚡ 驿来特AI智能数据分析平台</div>
<div class="nav-tabs">
<button class="nav-tab" :class="{active: activeTab==='dashboard'}" @click="activeTab='dashboard'">分时电价分析</button>
<button class="nav-tab" :class="{active: activeTab==='degree'}" @click="activeTab='degree'">智能数据查询</button>
</div>
<div class="controls" v-if="activeTab==='dashboard'">
<button class="btn-primary" @click="exportAllPrices" :disabled="exporting">
<span v-if="!exporting">📊 导出分时段电价表</span>
<span v-else>⏳ 导出中...</span>
@@ -23,9 +31,13 @@
<span v-else>⏳ 生成中...</span>
</button>
</div>
<div class="controls" v-else>
<!-- Placeholder for degree tab specific controls if any -->
</div>
</header>
<div class="main-content">
<!-- Dashboard Tab -->
<div class="main-content" v-show="activeTab==='dashboard'">
<div class="left-panel">
<div class="station-list">
<div class="station-list-header">全网供应商24小时电价监控</div>
@@ -77,10 +89,88 @@
</div>
</div>
</div>
<!-- Degree Query Tab -->
<div class="degree-container" v-show="activeTab==='degree'">
<!-- 悬浮二维码 -->
<div class="qr-sidebar">
<div id="qrcode" class="qr-code"></div>
<p class="qr-text">手机扫码访问</p>
</div>
<div class="query-section">
<h1 class="page-title">驿来特AI智能数据查询</h1>
<p class="page-subtitle">基于大语言模型,为您提供实时、精准的业务数据分析</p>
<div class="input-wrapper">
<el-input
v-model="userQuery"
placeholder="请输入您的问题,例如:帮我查询12月份充电量TOP 10场站的充电情况"
class="search-input"
size="large"
@keyup.enter="handleDegreeSearch"
:disabled="queryLoading"
>
<template #append>
<el-button @click="handleDegreeSearch" :loading="queryLoading" type="primary">
{{ queryLoading ? '分析中...' : '开始查询' }}
</el-button>
</template>
</el-input>
</div>
<div class="example-tags">
<el-tag
v-for="(text, index) in examples"
:key="index"
class="example-tag"
effect="plain"
round
size="large"
@click="setExample(text)"
>
{{ text }}
</el-tag>
</div>
</div>
<div class="result-section" v-if="queryResult || queryLoading">
<div class="result-header">
<div class="result-title">
<span>分析结果</span>
<el-tag size="small" type="success" effect="dark" v-if="!queryLoading">完成</el-tag>
<el-tag size="small" type="warning" effect="dark" v-if="queryLoading">生成中</el-tag>
</div>
<el-button
v-if="queryLoading"
type="danger"
link
@click="stopGeneration"
>
停止生成
</el-button>
</div>
<div class="markdown-body" v-html="renderedQueryResult"></div>
<div v-if="queryLoading && !queryResult" class="loading-container">
<p>正在分析数据,请稍候...</p>
</div>
<span v-if="queryLoading" class="cursor-blink">|</span>
</div>
</div>
</div>
<script src="js/vue.global.js"></script>
<script src="js/element-plus.index.full.js"></script>
<script src="js/element-plus.zh-cn.min.js"></script>
<script src="js/qrcode.min.js"></script>
<script src="js/axios.min.js"></script>
<script src="js/echarts.min.js"></script>
<script src="js/marked.min.js"></script>
<!-- Katex for Math Rendering -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.16.8/dist/katex.min.css">
<script src="https://cdn.jsdelivr.net/npm/katex@0.16.8/dist/katex.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/katex@0.16.8/dist/contrib/auto-render.min.js"></script>
<script src="js/app.js"></script>
</body>
</html>

View File

@@ -1,245 +1,490 @@
const {createApp,onMounted,ref} = Vue
const { createApp, ref, computed, watch, nextTick, onMounted } = Vue;
createApp({
setup(){
const apiBase = ref(window.location.origin || "http://localhost:8000")
const operators = ref([
{label:"新电途",value:"新电途"},
{label:"特来电",value:"特来电"},
{label:"驿来特",value:"驿来特"},
{label:"艾特吉易充",value:"艾特吉易充"}
])
const selectedOperator = ref("驿来特")
const aiText = ref("")
const placeholder = ref("点击左侧按钮查询四家供应商最新24小时分时电价,再使用右侧AI综合分析功能对各司定价策略进行对比。")
const loading = ref(false)
const exporting = ref(false)
const exportingReport = ref(false)
const aiLoading = ref(false)
const aiBoxRef = ref(null)
const priceTableRows = ref([])
const hourlyPricesByOperator = ref({})
let chartInstance = null
setup() {
// ==========================================
// Common State
// ==========================================
const activeTab = ref('dashboard');
const apiBase = ref(window.location.origin || "http://localhost:8000");
const isMobile = ref(window.innerWidth <= 768);
const initChart = () => {
const dom = document.getElementById("chart")
if (dom && !chartInstance) {
chartInstance = echarts.init(dom)
}
}
const buildPriceTable = () => {
const rows = []
for (let h = 0; h < 24; h++) {
const row = {hour: (h.toString().padStart(2,"0") + ":00"), values: []}
operators.value.forEach(op => {
const series = hourlyPricesByOperator.value[op.value] || []
const price = series[h] !== undefined ? series[h] : null
row.values.push({operator: op.value, price})
})
rows.push(row)
}
priceTableRows.value = rows
if (chartInstance) {
const series = operators.value.map(op => {
const seriesData = []
for (let h = 0; h < 24; h++) {
const list = hourlyPricesByOperator.value[op.value] || []
seriesData.push(list[h] !== undefined ? list[h] : null)
}
return {name: op.label, type:"line", smooth:true, data:seriesData}
})
const hours = rows.map(r => r.hour)
const option = {
backgroundColor: 'transparent',
tooltip: {
trigger: "axis",
backgroundColor: 'rgba(30, 41, 59, 0.9)',
borderColor: '#334155',
textStyle: { color: '#f1f5f9' }
},
legend: {
data: operators.value.map(o => o.label),
textStyle: { color: "#94a3b8" },
bottom: 0
},
xAxis: {
type: "category",
data: hours,
axisLine: { lineStyle: { color: "#475569" } },
axisLabel: { color: "#94a3b8" }
},
yAxis: {
type: "value",
name: "元/度",
nameTextStyle: { color: "#94a3b8" },
axisLine: { lineStyle: { color: "#475569" } },
axisLabel: { color: "#94a3b8" },
splitLine: { lineStyle: { color: "#334155", type: 'dashed' } }
},
grid: { left: 50, right: 30, top: 40, bottom: 40 },
series: series
}
chartInstance.setOption(option)
}
}
const loadAllOperatorsPrices = async () => {
loading.value = true
try{
const res = await axios.get(apiBase.value + "/api/operators/hourly-prices")
if (res && res.data && Array.isArray(res.data.operators)) {
const dict = {}
res.data.operators.forEach(item => {
dict[item.operator] = item.series || []
})
hourlyPricesByOperator.value = dict
buildPriceTable()
}
}catch(e){
console.error(e)
}finally{
loading.value = false
}
}
const exportAllPrices = async () => {
try{
exporting.value = true
const res = await axios.get(apiBase.value + "/api/export/prices-zip",{responseType:"blob"})
const blob = new Blob([res.data],{type:"application/zip"})
const url = window.URL.createObjectURL(blob)
const a = document.createElement("a")
a.href = url
a.download = "多供应商电价导出.zip"
document.body.appendChild(a)
a.click()
document.body.removeChild(a)
window.URL.revokeObjectURL(url)
}catch(e){
console.error(e)
}finally{
exporting.value = false
}
}
const exportAiReport = async () => {
if (!aiText.value) {
alert("请先生成AI分析报告")
return
}
try {
exportingReport.value = true
const res = await axios.post(apiBase.value + "/api/export/ai-report-docx", {
content: aiText.value
}, {responseType: "blob"})
const blob = new Blob([res.data], {type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document"})
const url = window.URL.createObjectURL(blob)
const a = document.createElement("a")
a.href = url
a.download = "AI分析报告.docx"
document.body.appendChild(a)
a.click()
document.body.removeChild(a)
window.URL.revokeObjectURL(url)
} catch (e) {
console.error(e)
alert("导出失败,请检查是否安装Pandoc")
} finally {
exportingReport.value = false
}
}
const startAiAnalysis = async () => {
if (aiLoading.value) return
aiText.value = ""
aiLoading.value = true
try{
const response = await fetch(apiBase.value + "/api/ai/pricing/strategy-summary")
if (!response.body) return
const reader = response.body.getReader()
const decoder = new TextDecoder()
while (true) {
const {done, value} = await reader.read()
if (done) break
const chunk = decoder.decode(value, {stream: true})
aiText.value += chunk
await Vue.nextTick()
if (aiBoxRef.value) {
aiBoxRef.value.scrollTop = aiBoxRef.value.scrollHeight
}
}
}catch(e){
console.error(e)
aiText.value += "\n(分析过程出错: " + e.message + ")"
}finally{
aiLoading.value = false
}
}
const renderedAiText = Vue.computed(() => {
if (!aiText.value) return ""
try {
// 配置 marked
marked.setOptions({
breaks: true,
gfm: true
// Handle window resize
window.addEventListener('resize', () => {
isMobile.value = window.innerWidth <= 768;
if (chartInstance) chartInstance.resize();
});
let html = marked.parse(aiText.value);
// 简单处理LaTeX (如果有需要的话,可以引入更复杂的处理,这里假设Katex auto-render会处理或者手动处理)
// 由于是computed,我们返回html,然后通过v-html渲染。
// v-html更新后,Vue不保证脚本执行。
// 我们可以在updated hook里调用renderMathInElement,或者这里仅仅返回html。
// 为了支持Latex,我们可以在watch aiText时手动更新DOM,或者使用nextTick。
// 简易方案:返回HTML,由Vue渲染。如果需要Latex渲染,可以在watch里做。
return html;
} catch (e) {
return aiText.value;
}
})
// 监听 aiText 变化以渲染 Latex
Vue.watch(aiText, () => {
Vue.nextTick(() => {
const el = document.querySelector('.ai-result');
if (el && window.renderMathInElement) {
renderMathInElement(el, {
delimiters: [
{left: '$$', right: '$$', display: true},
{left: '$', right: '$', display: false},
{left: '\\(', right: '\\)', display: false},
{left: '\\[', right: '\\]', display: true}
],
throwOnError: false
// ==========================================
// Dashboard State & Logic
// ==========================================
const operators = ref([
{label:"新电途",value:"新电途"},
{label:"特来电",value:"特来电"},
{label:"驿来特",value:"驿来特"},
{label:"艾特吉易充",value:"艾特吉易充"}
]);
const selectedOperator = ref("驿来特");
const aiText = ref("");
const placeholder = ref("点击左侧按钮查询四家供应商最新24小时分时电价,再使用右侧AI综合分析功能对各司定价策略进行对比。");
const loading = ref(false);
const exporting = ref(false);
const exportingReport = ref(false);
const aiLoading = ref(false);
const aiBoxRef = ref(null);
const priceTableRows = ref([]);
const hourlyPricesByOperator = ref({});
let chartInstance = null;
const initChart = () => {
const dom = document.getElementById("chart");
if (dom && !chartInstance) {
chartInstance = echarts.init(dom);
}
};
const buildPriceTable = () => {
const rows = [];
for (let h = 0; h < 24; h++) {
const row = {hour: (h.toString().padStart(2,"0") + ":00"), values: []};
operators.value.forEach(op => {
const series = hourlyPricesByOperator.value[op.value] || [];
const price = series[h] !== undefined ? series[h] : null;
row.values.push({operator: op.value, price});
});
rows.push(row);
}
priceTableRows.value = rows;
if (chartInstance) {
const series = operators.value.map(op => {
const seriesData = [];
for (let h = 0; h < 24; h++) {
const list = hourlyPricesByOperator.value[op.value] || [];
seriesData.push(list[h] !== undefined ? list[h] : null);
}
return {name: op.label, type:"line", smooth:true, data:seriesData};
});
const hours = rows.map(r => r.hour);
const option = {
backgroundColor: 'transparent',
tooltip: {
trigger: "axis",
backgroundColor: 'rgba(30, 41, 59, 0.9)',
borderColor: '#334155',
textStyle: { color: '#f1f5f9' }
},
legend: {
data: operators.value.map(o => o.label),
textStyle: { color: "#94a3b8" },
bottom: 0
},
xAxis: {
type: "category",
data: hours,
axisLine: { lineStyle: { color: "#475569" } },
axisLabel: { color: "#94a3b8" }
},
yAxis: {
type: "value",
name: "元/度",
nameTextStyle: { color: "#94a3b8" },
axisLine: { lineStyle: { color: "#475569" } },
axisLabel: { color: "#94a3b8" },
splitLine: { lineStyle: { color: "#334155", type: 'dashed' } }
},
grid: { left: 50, right: 30, top: 40, bottom: 40 },
series: series
};
chartInstance.setOption(option);
}
};
const loadAllOperatorsPrices = async () => {
loading.value = true;
try{
const res = await axios.get(apiBase.value + "/api/operators/hourly-prices");
if (res && res.data && Array.isArray(res.data.operators)) {
const dict = {};
res.data.operators.forEach(item => {
dict[item.operator] = item.series || [];
});
hourlyPricesByOperator.value = dict;
buildPriceTable();
}
}catch(e){
console.error(e);
}finally{
loading.value = false;
}
};
const exportAllPrices = async () => {
try{
exporting.value = true;
const res = await axios.get(apiBase.value + "/api/export/prices-zip",{responseType:"blob"});
const blob = new Blob([res.data],{type:"application/zip"});
const url = window.URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = "多供应商电价导出.zip";
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
window.URL.revokeObjectURL(url);
}catch(e){
console.error(e);
}finally{
exporting.value = false;
}
};
const exportAiReport = async () => {
if (!aiText.value) {
alert("请先生成AI分析报告");
return;
}
try {
exportingReport.value = true;
const res = await axios.post(apiBase.value + "/api/export/ai-report-docx", {
content: aiText.value
}, {responseType: "blob"});
const blob = new Blob([res.data], {type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document"});
const url = window.URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = "AI分析报告.docx";
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
window.URL.revokeObjectURL(url);
} catch (e) {
console.error(e);
alert("导出失败,请检查是否安装Pandoc");
} finally {
exportingReport.value = false;
}
};
const startAiAnalysis = async () => {
if (aiLoading.value) return;
aiText.value = "";
aiLoading.value = true;
try{
const response = await fetch(apiBase.value + "/api/ai/pricing/strategy-summary");
if (!response.body) return;
const reader = response.body.getReader();
const decoder = new TextDecoder();
while (true) {
const {done, value} = await reader.read();
if (done) break;
const chunk = decoder.decode(value, {stream: true});
aiText.value += chunk;
await Vue.nextTick();
if (aiBoxRef.value) {
aiBoxRef.value.scrollTop = aiBoxRef.value.scrollHeight;
}
}
}catch(e){
console.error(e);
aiText.value += "\n(分析过程出错: " + e.message + ")";
}finally{
aiLoading.value = false;
}
};
const formatCell = v => {
if (v === null || v === undefined || v === "") return "-";
if (typeof v === "number") {
if (Number.isNaN(v)) return "-";
return v.toFixed(2);
}
return v;
};
const getPriceColor = (price) => {
if (price === null || price === undefined) return 'inherit';
if (price > 1.2) return '#ef4444'; // Red-500
if (price < 0.8) return '#10b981'; // Emerald-500
return '#f1f5f9'; // Slate-100
};
// ==========================================
// Degree Query State & Logic
// ==========================================
const userQuery = ref('');
const queryLoading = ref(false);
const queryResult = ref('');
const eventSource = ref(null);
const rowsAcc = ref([]);
const bufferRow = ref(null);
const examples = [
"查询12月份充电量TOP 10场站的充电情况",
"查询净月商贸城站12月的充电量",
"查询12月企业充电量排名的TOP 10",
"查询所有场站的近3个月的充电情况,找出变化最大的前10名"
];
// Helpers
const isPlainObject = (obj) => Object.prototype.toString.call(obj) === '[object Object]';
const colSynonyms = {
name: ['name', 'station', 'station_name', 'site', '场站', '场站名称', '站点', '站名'],
total: ['total', 'total_kwh', 'sum_kwh', 'energy_total', '总电量', '总充电量', '总度', '总度数'],
peak: ['peak', 'peak_kwh', 'energy_peak', '峰', '峰时电量'],
flat: ['flat', 'flat_kwh', 'energy_flat', '平', '平时电量'],
valley: ['valley', 'valley_kwh', 'energy_valley', '谷', '谷时电量'],
};
const pickKey = (obj, keys) => keys.find(k => Object.prototype.hasOwnProperty.call(obj, k));
const pickVal = (obj, keys) => {
const k = pickKey(obj, keys);
return k ? obj[k] : undefined;
};
const formatNumber = (n) => {
if (n === null || n === undefined || n === '') return '';
const v = parseFloat(String(n).replace(/,/g, ''));
if (isNaN(v)) return String(n);
return v.toLocaleString('zh-CN', { maximumFractionDigits: 2 });
};
const pushRow = (row) => {
if (!row || !row.name) return;
rowsAcc.value.push(row);
const r = row;
const line = `| ${r.name ?? ''} | ${formatNumber(r.total)} | ${formatNumber(r.peak)} | ${formatNumber(r.flat)} | ${formatNumber(r.valley)} |`;
if (rowsAcc.value.length === 1) {
const header = `| 场站名称 | 总电量 | 峰 | 平 | 谷 |\n| --- | ---: | ---: | ---: | ---: |`;
if (queryResult.value && !queryResult.value.endsWith('\n')) {
queryResult.value += '\n\n';
} else if (queryResult.value) {
queryResult.value += '\n';
}
queryResult.value += header + '\n';
}
queryResult.value += line + '\n';
};
const toSelectedRow = (row) => {
if (!isPlainObject(row)) return null;
const name = pickVal(row, colSynonyms.name);
const total = pickVal(row, colSynonyms.total);
const peak = pickVal(row, colSynonyms.peak);
const flat = pickVal(row, colSynonyms.flat);
const valley = pickVal(row, colSynonyms.valley);
if (name === undefined) return null;
return { name, total, peak, flat, valley };
};
// Degree Search Logic
const handleDegreeSearch = () => {
if (!userQuery.value.trim()) {
if (typeof ElementPlus !== 'undefined') ElementPlus.ElMessage.warning('请输入您的问题');
else alert('请输入您的问题');
return;
}
if (queryLoading.value) {
if (eventSource.value) {
eventSource.value.close();
}
}
queryLoading.value = true;
queryResult.value = '';
rowsAcc.value = [];
bufferRow.value = null;
// Construct the SSE URL
const url = `${apiBase.value}/degree/chat?q=${encodeURIComponent(userQuery.value)}`;
try {
const es = new EventSource(url);
eventSource.value = es;
es.onmessage = (event) => {
const eventData = event.data.trim();
if (eventData === '[DONE]') {
queryLoading.value = false;
es.close();
return;
}
try {
const data = JSON.parse(event.data);
let chunk = '';
if (data.content) chunk = data.content;
else if (data.markdown) chunk = data.markdown;
else if (data.chunk) chunk = data.chunk;
else if (typeof data === 'string') chunk = data;
if (chunk) {
queryResult.value += chunk;
}
} catch (e) {
if (eventData && eventData !== '[DONE]') {
queryResult.value += event.data;
}
}
};
es.onerror = (err) => {
console.error('SSE Error:', err);
queryLoading.value = false;
es.close();
if (!queryResult.value) {
queryResult.value = '查询过程出现异常,未能获取到数据';
}
};
} catch (err) {
console.error('Failed to create EventSource:', err);
queryLoading.value = false;
if (typeof ElementPlus !== 'undefined') ElementPlus.ElMessage.error('无法建立连接');
else alert('无法建立连接');
}
};
const stopDegreeGeneration = () => {
if (eventSource.value) {
eventSource.value.close();
eventSource.value = null;
}
queryLoading.value = false;
};
const setExample = (text) => {
userQuery.value = text;
handleDegreeSearch();
};
const renderCharts = () => {
if (typeof echarts === 'undefined') return;
nextTick(() => {
const containers = document.querySelectorAll('.echarts-container');
containers.forEach(container => {
if (container.getAttribute('data-rendered') === 'true') return;
try {
const configStr = decodeURIComponent(container.getAttribute('data-config')).trim();
if (!configStr.startsWith('{') || !configStr.endsWith('}')) return;
const config = JSON.parse(configStr);
let chart = echarts.getInstanceByDom(container);
if (!chart) {
chart = echarts.init(container, 'dark');
window.addEventListener('resize', () => chart.resize());
}
chart.setOption(config);
container.setAttribute('data-rendered', 'true');
container.style.opacity = '1';
} catch (e) {
if (queryLoading.value) return;
console.error('ECharts rendering error:', e);
container.innerHTML = `<p style="color: #ef4444; padding: 10px;">图表渲染失败: ${e.message}</p>`;
}
});
});
}
});
});
};
onMounted(()=>{
initChart()
loadAllOperatorsPrices()
})
// ==========================================
// Computed Properties (Markdown)
// ==========================================
marked.use({
gfm: true,
breaks: true,
mangle: false,
headerIds: false,
renderer: {
code(code, language) {
if (language === 'echarts') {
const id = 'chart-' + Math.random().toString(36).substr(2, 9);
return `<div class="echarts-container" id="${id}" style="width: 100%; height: 400px; margin: 20px 0; background: rgba(30, 41, 59, 0.5); border: 1px solid rgba(148, 163, 184, 0.1); border-radius: 12px; padding: 20px;" data-config="${encodeURIComponent(code)}"></div>`;
}
return false; // Use default for others
}
}
});
const formatCell = v => {
if (v === null || v === undefined || v === "") return "-"
if (typeof v === "number") {
if (Number.isNaN(v)) return "-"
return v.toFixed(2)
}
return v
}
const renderedAiText = computed(() => {
if (!aiText.value) return "";
try {
return marked.parse(aiText.value);
} catch (e) {
return aiText.value;
}
});
const getPriceColor = (price) => {
if (price === null || price === undefined) return 'inherit'
if (price > 1.2) return '#ef4444' // Red-500
if (price < 0.8) return '#10b981' // Emerald-500
return '#f1f5f9' // Slate-100
}
const renderedResult = computed(() => {
if (!queryResult.value) return '';
try {
const cleanText = queryResult.value.replace(/\\([\*_`#\[\]\(\)!>-])/g, '$1');
return marked.parse(cleanText);
} catch (e) {
console.error('Markdown parsing error:', e);
return queryResult.value;
}
});
return {apiBase,operators,aiText,placeholder,loading,exporting,exportingReport,aiLoading,priceTableRows,loadAllOperatorsPrices,exportAllPrices,exportAiReport,startAiAnalysis,formatCell,getPriceColor,renderedAiText,aiBoxRef}
}
}).mount("#app")
// ==========================================
// Watchers
// ==========================================
watch(aiText, () => {
nextTick(() => {
const el = document.querySelector('.ai-result');
if (el && window.renderMathInElement) {
renderMathInElement(el, {
delimiters: [
{left: '$$', right: '$$', display: true},
{left: '$', right: '$', display: false},
{left: '\\(', right: '\\)', display: false},
{left: '\\[', right: '\\]', display: true}
],
throwOnError: false
});
}
});
});
watch(queryResult, (newVal) => {
if (newVal && newVal.includes('```echarts')) {
renderCharts();
}
});
// ==========================================
// Lifecycle
// ==========================================
onMounted(() => {
// Dashboard init
initChart();
loadAllOperatorsPrices();
// Degree QR Code
if (!isMobile.value && typeof QRCode !== 'undefined') {
const qrEl = document.getElementById("qrcode");
if (qrEl) {
qrEl.innerHTML = '';
new QRCode(qrEl, {
text: window.location.href,
width: 256,
height: 256,
colorDark: "#000000",
colorLight: "#ffffff",
correctLevel: QRCode.CorrectLevel.M
});
}
}
});
return {
activeTab, apiBase, isMobile,
// Dashboard
operators, selectedOperator, aiText, placeholder, loading, exporting, exportingReport, aiLoading, priceTableRows, aiBoxRef,
loadAllOperatorsPrices, exportAllPrices, exportAiReport, startAiAnalysis, formatCell, getPriceColor, renderedAiText,
// Degree
userQuery, queryLoading, queryResult, examples,
handleDegreeSearch, setExample, renderedResult, stopDegreeGeneration
};
}
}).mount("#app");

View File

@@ -1,452 +0,0 @@
const { createApp, ref, computed, watch, nextTick, onMounted } = Vue;
const app = createApp({
setup() {
const query = ref('');
const loading = ref(false);
const result = ref('');
const eventSource = ref(null);
const isMobile = ref(window.innerWidth <= 768);
// Handle window resize
window.addEventListener('resize', () => {
isMobile.value = window.innerWidth <= 768;
});
// Initialize QR Code
onMounted(() => {
if (!isMobile.value && typeof QRCode !== 'undefined') {
new QRCode(document.getElementById("qrcode"), {
text: window.location.href,
width: 128,
height: 128,
colorDark : "#000000",
colorLight : "#ffffff",
correctLevel : QRCode.CorrectLevel.H
});
}
});
// Examples for the user
const examples = [
"查询12月份充电量TOP 10场站的充电情况",
"查询净月商贸城站12月的充电量",
"查询12月企业充电量排名的TOP 10",
"查询所有场站的近3个月的充电情况,找出变化最大的前10名"
];
// Helpers: convert payloads to readable markdown
const isPlainObject = (obj) => Object.prototype.toString.call(obj) === '[object Object]';
const colSynonyms = {
name: ['name', 'station', 'station_name', 'site', '场站', '场站名称', '站点', '站名'],
total: ['total', 'total_kwh', 'sum_kwh', 'energy_total', '总电量', '总充电量', '总度', '总度数'],
peak: ['peak', 'peak_kwh', 'energy_peak', '峰', '峰时电量'],
flat: ['flat', 'flat_kwh', 'energy_flat', '平', '平时电量'],
valley: ['valley', 'valley_kwh', 'energy_valley', '谷', '谷时电量'],
};
const pickKey = (obj, keys) => keys.find(k => Object.prototype.hasOwnProperty.call(obj, k));
const pickVal = (obj, keys) => {
const k = pickKey(obj, keys);
return k ? obj[k] : undefined;
};
const rowsAcc = ref([]);
const bufferRow = ref(null);
const formatNumber = (n) => {
if (n === null || n === undefined || n === '') return '';
const v = parseFloat(String(n).replace(/,/g, ''));
if (isNaN(v)) return String(n);
return v.toLocaleString('zh-CN', { maximumFractionDigits: 2 });
};
const buildTableFromRows = (rows) => {
if (!rows || rows.length === 0) return '';
const header = `| 场站名称 | 总电量 | 峰 | 平 | 谷 |\n| --- | ---: | ---: | ---: | ---: |`;
const lines = rows.map(r => `| ${r.name ?? ''} | ${formatNumber(r.total)} | ${formatNumber(r.peak)} | ${formatNumber(r.flat)} | ${formatNumber(r.valley)} |`).join('\n');
return `${header}\n${lines}`;
};
const pushRow = (row) => {
if (!row || !row.name) return;
rowsAcc.value.push(row);
// Append the new row to result.value instead of rebuilding the whole table
// This allows mixed content (raw markdown + parsed rows) to coexist
const r = row;
const line = `| ${r.name ?? ''} | ${formatNumber(r.total)} | ${formatNumber(r.peak)} | ${formatNumber(r.flat)} | ${formatNumber(r.valley)} |`;
// If this is the first row, add the header
if (rowsAcc.value.length === 1) {
const header = `| 场站名称 | 总电量 | 峰 | 平 | 谷 |\n| --- | ---: | ---: | ---: | ---: |`;
// If result already has content (e.g. summary text), append header with newline
if (result.value && !result.value.endsWith('\n')) {
result.value += '\n\n';
} else if (result.value) {
result.value += '\n';
}
result.value += header + '\n';
}
result.value += line + '\n';
};
const ingestColumnsRows = (data) => {
const nameCol = data.columns.find(c => colSynonyms.name.includes(c));
const totalCol = data.columns.find(c => colSynonyms.total.includes(c));
const peakCol = data.columns.find(c => colSynonyms.peak.includes(c));
const flatCol = data.columns.find(c => colSynonyms.flat.includes(c));
const valleyCol = data.columns.find(c => colSynonyms.valley.includes(c));
data.rows.forEach(r => pushRow({
name: r[nameCol],
total: r[totalCol],
peak: r[peakCol],
flat: r[flatCol],
valley: r[valleyCol],
}));
};
const ingestDataArray = (arr) => {
arr.forEach(obj => {
const row = toSelectedRow(obj);
if (row) pushRow(row);
});
};
const tryStationName = (line) => {
const m1 = line.match(/(?:站点|场站|充电站|站名)[::]\s*([^\s,,]+)/);
if (m1) return m1[1];
const m2 = line.match(/^\s*(?:\d+[\.\)]\s*)?(.+?(?:充电站|场站|站))(?:(.*))?\s*$/);
if (m2) return m2[1];
return null;
};
const tryMetric = (line, label) => {
const re = new RegExp(label + '\\s*[::]\\s*([\\d.,]+)');
const m = line.match(re);
if (m) return parseFloat(m[1].replace(/,/g, ''));
return null;
};
const ingestChunkText = (text) => {
if (!text || /^\s*$/.test(text)) return false;
let consumed = false;
const lines = String(text).split(/[\r\n]+/);
lines.forEach(line => {
const name = tryStationName(line);
if (name) {
if (bufferRow.value && (bufferRow.value.total != null || bufferRow.value.peak != null || bufferRow.value.flat != null || bufferRow.value.valley != null)) {
pushRow(bufferRow.value);
}
bufferRow.value = { name, total: null, peak: null, flat: null, valley: null };
consumed = true;
return;
}
if (!bufferRow.value) return;
const total = tryMetric(line, '(?:总(?:充电)?电量|总电量)');
const peak = tryMetric(line, '(?:峰(?:时)?电量|峰)');
const flat = tryMetric(line, '(?:平(?:时)?电量|平)');
const valley = tryMetric(line, '(?:谷(?:时)?电量|谷)');
if (total != null) { bufferRow.value.total = total; consumed = true; }
if (peak != null) { bufferRow.value.peak = peak; consumed = true; }
if (flat != null) { bufferRow.value.flat = flat; consumed = true; }
if (valley != null) { bufferRow.value.valley = valley; consumed = true; }
if (bufferRow.value.name && (bufferRow.value.total != null || bufferRow.value.peak != null || bufferRow.value.flat != null || bufferRow.value.valley != null)) {
pushRow(bufferRow.value);
bufferRow.value = null;
}
});
return consumed;
};
const toSelectedRow = (row) => {
if (!isPlainObject(row)) return null;
const name = pickVal(row, colSynonyms.name);
const total = pickVal(row, colSynonyms.total);
const peak = pickVal(row, colSynonyms.peak);
const flat = pickVal(row, colSynonyms.flat);
const valley = pickVal(row, colSynonyms.valley);
if (name === undefined) return null;
return { name, total, peak, flat, valley };
};
const toMarkdownTableFromArray = (arr) => {
if (!Array.isArray(arr) || arr.length === 0) return '';
const selected = arr.map(toSelectedRow).filter(Boolean);
if (selected.length === 0) {
// 如果不能识别出目标字段,避免展示冗余JSON
return '';
}
const header = `| 场站名称 | 总电量 | 峰 | 平 | 谷 |\n| --- | ---: | ---: | ---: | ---: |`;
const rows = selected.map(r => {
const fmt = (v) => v === null || v === undefined ? '' : String(v);
return `| ${fmt(r.name)} | ${fmt(r.total)} | ${fmt(r.peak)} | ${fmt(r.flat)} | ${fmt(r.valley)} |`;
}).join('\n');
return `${header}\n${rows}`;
};
const toMarkdownTableFromObject = (obj) => {
const selected = toSelectedRow(obj);
if (!selected) return '';
const header = `| 场站名称 | 总电量 | 峰 | 平 | 谷 |\n| --- | ---: | ---: | ---: | ---: |`;
const fmt = (v) => v === null || v === undefined ? '' : String(v);
const row = `| ${fmt(selected.name)} | ${fmt(selected.total)} | ${fmt(selected.peak)} | ${fmt(selected.flat)} | ${fmt(selected.valley)} |`;
return `${header}\n${row}`;
};
const payloadToMarkdown = (data) => {
if (data == null) return '';
if (typeof data === 'string') {
// 文本直接作为markdown,但避免无用状态文本
const trimmed = data.trim();
if (/^(analyzing|generating|loading)/i.test(trimmed)) return '';
return trimmed;
}
if (isPlainObject(data)) {
if (typeof data.markdown === 'string') return data.markdown;
if (typeof data.content === 'string') return data.content;
if (typeof data.text === 'string') return data.text;
// 过滤仅含无用状态字段的对象
const keys = Object.keys(data);
const statusKeys = ['step', 'message', 'chunk', 'status'];
if (keys.every(k => statusKeys.includes(k))) return '';
if (Array.isArray(data.rows) && Array.isArray(data.columns)) {
// 映射选择列
const colMap = {
name: data.columns.find(c => colSynonyms.name.includes(c)),
total: data.columns.find(c => colSynonyms.total.includes(c)),
peak: data.columns.find(c => colSynonyms.peak.includes(c)),
flat: data.columns.find(c => colSynonyms.flat.includes(c)),
valley: data.columns.find(c => colSynonyms.valley.includes(c)),
};
const header = `| 场站名称 | 总电量 | 峰 | 平 | 谷 |\n| --- | ---: | ---: | ---: | ---: |`;
const rows = data.rows.map(r => {
const fmt = (v) => v === null || v === undefined ? '' : String(v);
return `| ${fmt(r[colMap.name])} | ${fmt(r[colMap.total])} | ${fmt(r[colMap.peak])} | ${fmt(r[colMap.flat])} | ${fmt(r[colMap.valley])} |`;
}).join('\n');
return `${header}\n${rows}`;
}
if (Array.isArray(data.data)) {
return toMarkdownTableFromArray(data.data);
}
// Fallback: 仅当识别出目标字段时才展示;否则忽略
return toMarkdownTableFromObject(data);
}
if (Array.isArray(data)) {
return toMarkdownTableFromArray(data);
}
return String(data);
};
// 配置 marked
marked.use({
gfm: true,
breaks: true,
mangle: false,
headerIds: false,
renderer: {
code(code, language) {
if (language === 'echarts') {
const id = 'chart-' + Math.random().toString(36).substr(2, 9);
return `<div class="echarts-container" id="${id}" style="width: 100%; height: 400px; margin: 20px 0; background: rgba(30, 41, 59, 0.5); border: 1px solid rgba(148, 163, 184, 0.1); border-radius: 12px; padding: 20px;" data-config="${encodeURIComponent(code)}"></div>`;
}
return false; // 返回 false 使用默认渲染器
}
}
});
// Convert markdown to HTML
const renderedResult = computed(() => {
if (!result.value) return '';
try {
// 修复 LLM 常见的错误转义问题,例如 \*\*加粗\*\*
const cleanText = result.value.replace(/\\([\*_`#\[\]\(\)!>-])/g, '$1');
return marked.parse(cleanText);
} catch (e) {
console.error('Markdown parsing error:', e);
return result.value;
}
});
// 渲染图表函数
const renderCharts = () => {
if (typeof echarts === 'undefined') {
console.warn('ECharts is not loaded yet.');
return;
}
nextTick(() => {
const containers = document.querySelectorAll('.echarts-container');
containers.forEach(container => {
// 如果已经成功渲染,不再重复渲染
if (container.getAttribute('data-rendered') === 'true') return;
try {
const configStr = decodeURIComponent(container.getAttribute('data-config')).trim();
// 检查 JSON 是否完整(简单判断:以 { 开始,以 } 结束)
if (!configStr.startsWith('{') || !configStr.endsWith('}')) {
return; // 还在流式传输中,不完整则跳过
}
const config = JSON.parse(configStr);
// 如果容器还没有 init,则初始化
let chart = echarts.getInstanceByDom(container);
if (!chart) {
chart = echarts.init(container, 'dark');
// 响应式
window.addEventListener('resize', () => chart.resize());
}
chart.setOption(config);
container.setAttribute('data-rendered', 'true');
container.style.opacity = '1';
} catch (e) {
// 忽略流式传输中的解析错误
if (loading.value) return;
console.error('ECharts rendering error:', e);
container.innerHTML = `<p style="color: #ef4444; padding: 10px;">图表渲染失败: ${e.message}</p>`;
}
});
});
};
// 监听结果变化,尝试渲染图表
watch(result, (newVal) => {
if (newVal && newVal.includes('```echarts')) {
renderCharts();
}
});
const setExample = (text) => {
query.value = text;
handleSearch();
};
const handleSearch = () => {
if (!query.value.trim()) {
ElementPlus.ElMessage.warning('请输入您的问题');
return;
}
if (loading.value) {
// If already loading, stop the previous request?
// For now, let's just ignore or maybe cancel.
// closing existing connection
if (eventSource.value) {
eventSource.value.close();
}
}
loading.value = true;
result.value = '';
// Construct the SSE URL
// Assuming the backend endpoint is /api/ai/query or similar.
// We use a relative path so it works if served from the same domain.
// Adjust this URL based on actual backend route.
const url = `/degree/chat?q=${encodeURIComponent(query.value)}`;
try {
const es = new EventSource(url);
eventSource.value = es;
es.onopen = () => {
console.log('Connection opened');
};
es.onmessage = (event) => {
const eventData = event.data.trim();
if (eventData === '[DONE]') {
loading.value = false;
es.close();
return;
}
try {
const data = JSON.parse(event.data);
// 处理流式内容
let chunk = '';
if (data.content) chunk = data.content;
else if (data.markdown) chunk = data.markdown;
else if (data.chunk) chunk = data.chunk;
else if (typeof data === 'string') chunk = data;
if (chunk) {
// 保持原始文本,不对 markdown 符号进行手动转义处理
// marked 会处理大部分情况
result.value += chunk;
}
// 处理状态更新
if (data.step || data.message) {
// 可以根据需要处理状态,比如更新进度条等
// 目前主要依赖流式内容展示
}
} catch (e) {
// 非 JSON 内容直接追加
if (eventData && eventData !== '[DONE]') {
result.value += event.data;
}
}
};
es.onerror = (err) => {
console.error('SSE Error:', err);
loading.value = false;
es.close();
// 如果之前已经有结果,就保持现状;否则给出简单提示
if (!result.value) {
result.value = '查询过程出现异常,未能获取到数据';
}
};
// Listen for a specific 'done' event if the backend sends one
es.addEventListener('done', () => {
if (bufferRow.value && (bufferRow.value.total != null || bufferRow.value.peak != null || bufferRow.value.flat != null || bufferRow.value.valley != null)) {
pushRow(bufferRow.value);
bufferRow.value = null;
}
if (!result.value) {
result.value = '未查询到数据';
}
es.close();
loading.value = false;
});
} catch (err) {
console.error('Failed to create EventSource:', err);
loading.value = false;
ElementPlus.ElMessage.error('无法建立连接');
}
};
const stopGeneration = () => {
if (eventSource.value) {
eventSource.value.close();
eventSource.value = null;
}
loading.value = false;
ElementPlus.ElMessage.info('已停止生成');
};
onMounted(() => {
// 生成二维码
const qrEl = document.getElementById('qrcode');
if (qrEl) {
// 清空可能存在的旧内容
qrEl.innerHTML = '';
new QRCode(qrEl, {
text: window.location.href,
width: 256, // 生成高分辨率图片
height: 256,
colorDark: "#000000",
colorLight: "#ffffff",
correctLevel: QRCode.CorrectLevel.M // 中等纠错等级,平衡密度和可靠性
});
}
});
return {
query,
loading,
result,
renderedResult,
examples,
isMobile,
handleSearch,
setExample,
stopGeneration
};
}
});
app.use(ElementPlus);
app.mount('#app');