ConditionPanel.jsx
11.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
import React, { useState, useRef } from 'react'
import { Modal, Button, Select, Input, DatePicker, Tag, Space, Upload, message, Popconfirm, Empty } from 'antd'
import { UploadOutlined, DeleteOutlined, PlusOutlined } from '@ant-design/icons'
import dayjs from 'dayjs'
const { RangePicker } = DatePicker
export const CONDITION_TYPES = [
{ value: 'exact', label: '精准匹配' },
{ value: 'fuzzy', label: '模糊查询' },
{ value: 'daterange', label: '日期区间' },
{ value: 'datemonth', label: '日期按月' },
{ value: 'dateyear', label: '日期按年' },
{ value: 'dateday', label: '日期按天' },
{ value: 'dictionary', label: '字典下拉' },
{ value: 'excel_import', label: 'Excel导入(IN)' },
]
/**
* 从SQL中提取 {{变量名}} 占位符
*/
export function extractVariables(sql) {
const regex = /\{\{(\w+)\}\}/g
const vars = []
let match
while ((match = regex.exec(sql)) !== null) {
if (!vars.includes(match[1])) {
vars.push(match[1])
}
}
return vars
}
/**
* 根据条件配置,将SQL中的占位符替换为实际值
*/
export function buildSql(sql, conditions) {
let result = sql
for (const cond of conditions) {
const placeholder = `{{${cond.name}}}`
const replacement = buildReplacement(cond)
result = result.replaceAll(placeholder, replacement)
}
return result
}
function buildReplacement(cond) {
const { type, value, valueStart, valueEnd, importedValues, dictOptions } = cond
switch (type) {
case 'exact':
return value ? `'${value}'` : "''"
case 'fuzzy':
return value ? `'%${value}%'` : "'%%'"
case 'daterange':
return valueStart ? `'${dayjs(valueStart).format('YYYY-MM-DD')}'` : "'2024-01-01'"
case 'datemonth':
return value ? `'${dayjs(value).format('YYYY-MM')}'` : "'2024-01'"
case 'dateyear':
return value ? `'${dayjs(value).format('YYYY')}'` : "'2024'"
case 'dateday':
return value ? `'${dayjs(value).format('YYYY-MM-DD')}'` : "'2024-01-01'"
case 'dictionary':
return value ? `'${value}'` : "''"
case 'excel_import':
if (importedValues && importedValues.length > 0) {
const quoted = importedValues.map(v => `'${v}'`).join(',')
return quoted
}
return "''"
default:
return value ? `'${value}'` : "''"
}
}
/**
* 处理日期区间中的结束日期占位符
* 约定:{{end_xxx}} 对应 xxx 的日期区间结束值
*/
export function buildSqlWithDateRange(sql, conditions) {
let result = sql
for (const cond of conditions) {
const placeholder = `{{${cond.name}}}`
const replacement = buildReplacement(cond)
result = result.replaceAll(placeholder, replacement)
// 处理日期区间结束占位符 {{end_xxx}}
if (cond.type === 'daterange' && cond.valueEnd) {
const endPlaceholder = `{{end_${cond.name}}}`
const endReplacement = `'${dayjs(cond.valueEnd).format('YYYY-MM-DD')}'`
result = result.replaceAll(endPlaceholder, endReplacement)
}
}
return result
}
/**
* 解析SQL变量并智能推断类型
*/
export function parseVariables(sqlText, existingConditions) {
const vars = extractVariables(sqlText)
if (vars.length === 0) return []
return vars.map(name => {
const existing = existingConditions.find(c => c.name === name)
if (existing) return existing
let type = 'exact'
const lower = name.toLowerCase()
if (lower.includes('name') || lower.includes('名称') || lower.includes('名')) {
type = 'fuzzy'
} else if (lower.includes('date') || lower.includes('日期') || lower.includes('时间') || lower.includes('time')) {
type = 'dateday'
} else if (lower.includes('month') || lower.includes('月')) {
type = 'datemonth'
} else if (lower.includes('year') || lower.includes('年')) {
type = 'dateyear'
}
return { name, type, value: '', valueStart: '', valueEnd: '', importedValues: [], dictOptions: [] }
})
}
export default function ConditionModal({ open, onClose, conditions, onConditionsChange, sqlText, onParse }) {
const updateCondition = (index, updates) => {
const newConds = [...conditions]
newConds[index] = { ...newConds[index], ...updates }
onConditionsChange(newConds)
}
const handleExcelImport = (index, file) => {
const reader = new FileReader()
reader.onload = async (e) => {
const base64 = e.target.result.split(',')[1]
try {
const response = await fetch('/api/export/import', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ fileData: base64, fileName: file.name }),
})
const res = await response.json()
if (res.success) {
updateCondition(index, { importedValues: res.data.values })
message.success(`成功导入 ${res.data.count} 条数据`)
} else {
message.error(res.message)
}
} catch (err) {
message.error('导入失败: ' + err.message)
}
}
reader.readAsDataURL(file)
return false
}
const renderValueInput = (cond, index) => {
switch (cond.type) {
case 'exact':
return (
<Input
size="small"
placeholder="请输入值"
value={cond.value}
onChange={e => updateCondition(index, { value: e.target.value })}
style={{ width: 200 }}
/>
)
case 'fuzzy':
return (
<Input
size="small"
placeholder="模糊关键词"
value={cond.value}
onChange={e => updateCondition(index, { value: e.target.value })}
style={{ width: 200 }}
/>
)
case 'daterange':
return (
<RangePicker
size="small"
value={cond.valueStart && cond.valueEnd ? [dayjs(cond.valueStart), dayjs(cond.valueEnd)] : null}
onChange={dates => {
if (dates) {
updateCondition(index, { valueStart: dates[0], valueEnd: dates[1] })
} else {
updateCondition(index, { valueStart: '', valueEnd: '' })
}
}}
style={{ width: 260 }}
/>
)
case 'datemonth':
return (
<DatePicker
size="small"
picker="month"
value={cond.value ? dayjs(cond.value) : null}
onChange={d => updateCondition(index, { value: d })}
style={{ width: 200 }}
/>
)
case 'dateyear':
return (
<DatePicker
size="small"
picker="year"
value={cond.value ? dayjs(cond.value) : null}
onChange={d => updateCondition(index, { value: d })}
style={{ width: 200 }}
/>
)
case 'dateday':
return (
<DatePicker
size="small"
value={cond.value ? dayjs(cond.value) : null}
onChange={d => updateCondition(index, { value: d })}
style={{ width: 200 }}
/>
)
case 'dictionary':
return (
<Space direction="vertical" size={4} style={{ width: 240 }}>
<Select
size="small"
placeholder="请选择"
value={cond.value || undefined}
onChange={v => updateCondition(index, { value: v })}
options={cond.dictOptions || []}
style={{ width: '100%' }}
allowClear
/>
<Button
size="small"
type="dashed"
onClick={() => {
const input = prompt('输入字典项,格式:标签:值,每行一个\n例如:\n启用:1\n停用:0')
if (input) {
const opts = input.split('\n').filter(s => s.trim()).map(s => {
const [label, value] = s.split(':').map(p => p.trim())
return { label: label || value, value: value || label }
})
updateCondition(index, { dictOptions: opts })
}
}}
>
配置字典
</Button>
</Space>
)
case 'excel_import':
return (
<Space size={4}>
<Upload
accept=".xlsx,.xls,.csv"
showUploadList={false}
beforeUpload={(file) => handleExcelImport(index, file)}
>
<Button size="small" icon={<UploadOutlined />}>导入Excel</Button>
</Upload>
{cond.importedValues && cond.importedValues.length > 0 && (
<Tag color="blue">{cond.importedValues.length} 条</Tag>
)}
</Space>
)
default:
return (
<Input
size="small"
placeholder="请输入值"
value={cond.value}
onChange={e => updateCondition(index, { value: e.target.value })}
style={{ width: 200 }}
/>
)
}
}
return (
<Modal
title="查询条件配置"
open={open}
onCancel={onClose}
width={720}
footer={
<Space>
<Button onClick={onParse} icon={<PlusOutlined />}>
重新解析条件
</Button>
<Button type="primary" onClick={onClose}>
确定
</Button>
</Space>
}
>
{conditions.length === 0 ? (
<Empty
description={
<span>
未配置条件。请在SQL中使用 {'{{变量名}}'} 定义条件,<br />
然后点击工具栏的"解析条件"按钮自动识别
</span>
}
style={{ padding: '30px 0' }}
/>
) : (
<div style={{ maxHeight: '60vh', overflowY: 'auto' }}>
{conditions.map((cond, index) => (
<div
key={cond.name}
style={{
display: 'flex',
alignItems: 'center',
gap: 8,
padding: '10px 12px',
borderBottom: '1px solid #f0f0f0',
flexWrap: 'wrap',
}}
>
<Tag color="blue" style={{ minWidth: 90, textAlign: 'center' }}>{cond.name}</Tag>
<Select
size="small"
value={cond.type}
onChange={t => updateCondition(index, { type: t })}
options={CONDITION_TYPES}
style={{ width: 140 }}
/>
<div style={{ flex: 1, minWidth: 200 }}>
{renderValueInput(cond, index)}
</div>
<Popconfirm title="删除该条件?" onConfirm={() => {
const newConds = conditions.filter((_, i) => i !== index)
onConditionsChange(newConds)
}}>
<Button size="small" type="text" danger icon={<DeleteOutlined />} />
</Popconfirm>
</div>
))}
</div>
)}
<div style={{ marginTop: 12, padding: '8px 12px', background: '#f6f6f6', borderRadius: 6, fontSize: 12, color: '#888' }}>
提示:日期区间类型需在SQL中使用 {'{{end_变量名}}'} 表示结束日期,例如 {'{{start_date}}'} 和 {'{{end_start_date}}'}
</div>
</Modal>
)
}