SqlManagerModal.jsx 27.5 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 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712
import React, { useState, useEffect, useRef } from 'react'
import {
  Modal, Table, Button, Space, Form, Input, Tag, Popconfirm,
  message, Empty, Tooltip, Divider, Tabs, Switch, Select, Badge,
  DatePicker, Upload,
} from 'antd'
import {
  PlusOutlined, DeleteOutlined, EditOutlined, ImportOutlined,
  SearchOutlined, SaveOutlined, MailOutlined, ClockCircleOutlined,
  SettingOutlined, PlayCircleOutlined, CheckCircleOutlined,
  CloseCircleOutlined, UploadOutlined,
} from '@ant-design/icons'
import dayjs from 'dayjs'
import request from '../utils/request'
import { extractVariables, parseVariables, CONDITION_TYPES } from './ConditionPanel'
import SendMailModal from './SendMailModal'

const { TextArea } = Input
const { RangePicker } = DatePicker

// cron预设
const CRON_PRESETS = [
  { label: '每天 08:00', value: '0 8 * * *' },
  { label: '每天 10:00', value: '0 10 * * *' },
  { label: '每天 14:00', value: '0 14 * * *' },
  { label: '每周一 09:00', value: '0 9 * * 1' },
  { label: '每月1号 09:00', value: '0 9 1 * *' },
  { label: '工作日 10:00', value: '0 10 * * 1-5' },
]

// 动态日期变量提示
const DATE_VARIABLES = [
  { key: 'TODAY', desc: '当天' },
  { key: 'YESTERDAY', desc: '昨天' },
  { key: 'THIS_MONTH_START', desc: '本月1号' },
  { key: 'THIS_MONTH_END', desc: '本月末' },
  { key: 'LAST_MONTH_START', desc: '上月1号' },
  { key: 'LAST_MONTH_END', desc: '上月末' },
  { key: 'THIS_YEAR', desc: '今年' },
  { key: 'THIS_YEAR_START', desc: '今年1月1号' },
  { key: 'LAST_YEAR', desc: '去年' },
]

// 验证逗号分隔的多个邮箱
const validateEmails = (rule, value) => {
  if (!value || !value.trim()) return Promise.resolve()
  const emails = value.split(',').map(e => e.trim()).filter(e => e)
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  const invalid = emails.find(e => !emailRegex.test(e))
  if (invalid) return Promise.reject(new Error(`邮箱格式不正确: ${invalid}`))
  return Promise.resolve()
}

export default function SqlManagerModal({ open, onClose, onLoadSql, currentSql, currentConditions, connId, currentScriptId, onScriptIdChange }) {
  const [scripts, setScripts] = useState([])
  const [loading, setLoading] = useState(false)
  const [searchKeyword, setSearchKeyword] = useState('')
  // 详情/编辑弹窗
  const [detailOpen, setDetailOpen] = useState(false)
  const [detailForm] = Form.useForm()
  const [editingId, setEditingId] = useState(null)
  const [activeTab, setActiveTab] = useState('basic')
  // 脚本维度的参数编辑
  const [scriptConditions, setScriptConditions] = useState([])
  // 手动发送邮件弹窗
  const [sendMailOpen, setSendMailOpen] = useState(false)
  const [sendMailScript, setSendMailScript] = useState(null)

  useEffect(() => {
    if (open) loadScripts()
  }, [open])

  const loadScripts = async () => {
    setLoading(true)
    const res = await request.get('/sql-manage')
    if (res.success) setScripts(res.data)
    setLoading(false)
  }

  // 打开"保存当前SQL"
  const handleOpenSave = () => {
    setEditingId(null)
    setActiveTab('basic')
    // 从当前编辑器的SQL解析参数,并带入当前值
    const parsedConds = currentConditions && currentConditions.length > 0
      ? currentConditions
      : parseVariables(currentSql || '', [])
    setScriptConditions(parsedConds)

    detailForm.resetFields()
    // 用 setTimeout 确保 form 已准备好再设值
    setTimeout(() => {
      detailForm.setFieldsValue({
        sql: currentSql || '',
        schedulerEnabled: false,
      })
    }, 0)
    setDetailOpen(true)
  }

  // 编辑已有脚本
  const handleEdit = (record) => {
    setEditingId(record.id)
    setActiveTab('basic')
    // 使用脚本保存的 conditions
    setScriptConditions(record.conditions || [])

    detailForm.resetFields()
    setTimeout(() => {
      detailForm.setFieldsValue({
        name: record.name,
        purpose: record.purpose || '',
        usedBy: record.usedBy || '',
        category: record.category || '',
        sql: record.sql,
        recipientEmails: record.recipientEmails || '',
        emailSubject: record.emailSubject || '',
        cronExpression: record.cronExpression || '',
        schedulerEnabled: record.schedulerEnabled || false,
      })
    }, 0)
    setDetailOpen(true)
  }

  // 序列化conditions中的dayjs对象为字符串
  const serializeConditions = (conds) => {
    return conds.map(c => {
      const safe = { ...c }
      if (safe.value && dayjs.isDayjs(safe.value)) safe.value = safe.value.format('YYYY-MM-DD')
      if (safe.valueStart && dayjs.isDayjs(safe.valueStart)) safe.valueStart = safe.valueStart.format('YYYY-MM-DD')
      if (safe.valueEnd && dayjs.isDayjs(safe.valueEnd)) safe.valueEnd = safe.valueEnd.format('YYYY-MM-DD')
      return safe
    })
  }

  // 保存脚本
  const handleSave = async () => {
    try {
      const values = await detailForm.validateFields()
      const safeConditions = serializeConditions(scriptConditions)
      setScriptConditions(safeConditions)  // 更新本地为安全格式
      const payload = {
        ...values,
        conditions: safeConditions,
        connId,
      }

      if (editingId) {
        const res = await request.put(`/sql-manage/${editingId}`, payload)
        if (res.success) {
          message.success('脚本更新成功')
          // 如果当前正在使用这个脚本,同步参数到编辑器
          if (currentScriptId === editingId) {
            onLoadSql({ ...payload, id: editingId, conditions: safeConditions })
          }
          setDetailOpen(false)
          loadScripts()
        } else {
          message.error(res.message)
        }
      } else {
        const res = await request.post('/sql-manage', payload)
        if (res.success) {
          message.success('脚本保存成功')
          // 新保存的脚本,设置为当前脚本
          if (onScriptIdChange) onScriptIdChange(res.data.id)
          setDetailOpen(false)
          loadScripts()
        } else {
          message.error(res.message)
        }
      }
    } catch {
      // 表单验证失败
    }
  }

  // 删除脚本
  const handleDelete = async (id) => {
    await request.delete(`/sql-manage/${id}`)
    message.success('已删除')
    if (currentScriptId === id && onScriptIdChange) onScriptIdChange(null)
    loadScripts()
  }

  // 打开手动发送邮件弹窗
  const handleOpenSendMail = (record) => {
    setSendMailScript(record)
    setSendMailOpen(true)
  }

  // 手动触发执行
  const handleManualRun = async (record) => {
    const res = await request.post(`/sql-manage/${record.id}/run`)
    if (res.success) {
      message.success('任务已触发执行,请稍候查看执行结果')
      setTimeout(() => loadScripts(), 3000)
    } else {
      message.error(res.message)
    }
  }

  // 加载脚本到编辑器
  const handleLoad = (record) => {
    onLoadSql(record)
    if (onScriptIdChange) onScriptIdChange(record.id)
    onClose()
  }

  // ====== 参数编辑逻辑 ======

  // 从当前编辑弹窗中的SQL解析参数
  const handleParseConditionsInDetail = () => {
    const sql = detailForm.getFieldValue('sql') || ''
    const vars = extractVariables(sql)
    if (vars.length === 0) {
      message.info('未在SQL中发现 {{变量名}} 占位符')
      return
    }
    // 合并已有值
    const newConds = parseVariables(sql, scriptConditions)
    setScriptConditions(newConds)
    setActiveTab('params')
    message.success(`解析到 ${vars.length} 个条件参数`)
  }

  // 更新单个参数
  const updateScriptCondition = (index, updates) => {
    const newConds = [...scriptConditions]
    newConds[index] = { ...newConds[index], ...updates }
    setScriptConditions(newConds)
  }

  // Excel导入
  const handleExcelImportInDetail = (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) {
          updateScriptCondition(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 renderParamValueInput = (cond, index) => {
    switch (cond.type) {
      case 'exact':
        return <Input size="small" placeholder="请输入值" value={cond.value} onChange={e => updateScriptCondition(index, { value: e.target.value })} style={{ width: 200 }} />
      case 'fuzzy':
        return <Input size="small" placeholder="模糊关键词" value={cond.value} onChange={e => updateScriptCondition(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) updateScriptCondition(index, { valueStart: dates[0], valueEnd: dates[1] })
              else updateScriptCondition(index, { valueStart: '', valueEnd: '' })
            }}
            style={{ width: 260 }}
          />
        )
      case 'datemonth':
        return <DatePicker size="small" picker="month" value={cond.value ? dayjs(cond.value) : null} onChange={d => updateScriptCondition(index, { value: d })} style={{ width: 200 }} />
      case 'dateyear':
        return <DatePicker size="small" picker="year" value={cond.value ? dayjs(cond.value) : null} onChange={d => updateScriptCondition(index, { value: d })} style={{ width: 200 }} />
      case 'dateday':
        return <DatePicker size="small" value={cond.value ? dayjs(cond.value) : null} onChange={d => updateScriptCondition(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 => updateScriptCondition(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 }
                })
                updateScriptCondition(index, { dictOptions: opts })
              }
            }}>配置字典</Button>
          </Space>
        )
      case 'excel_import':
        return (
          <Space size={4}>
            <Upload accept=".xlsx,.xls,.csv" showUploadList={false} beforeUpload={(file) => handleExcelImportInDetail(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 => updateScriptCondition(index, { value: e.target.value })} style={{ width: 200 }} />
    }
  }

  // 搜索过滤
  const filteredScripts = scripts.filter(s => {
    if (!searchKeyword) return true
    const kw = searchKeyword.toLowerCase()
    return (
      (s.name || '').toLowerCase().includes(kw) ||
      (s.purpose || '').toLowerCase().includes(kw) ||
      (s.usedBy || '').toLowerCase().includes(kw) ||
      (s.category || '').toLowerCase().includes(kw)
    )
  })

  // 格式化条件值为可显示的字符串
  const formatCondValue = (val) => {
    if (!val) return ''
    if (dayjs.isDayjs(val)) return val.format('YYYY-MM-DD')
    return String(val)
  }

  // 条件值渲染
  const renderConditionTags = (conditions) => {
    if (!conditions || conditions.length === 0) return <span style={{ color: '#999' }}>无参数</span>
    return (
      <Space size={4} wrap>
        {conditions.map((c, i) => (
          <Tag key={i} style={{ fontSize: 11 }}>
            {c.name}({c.type}) = {c.type === 'excel_import'
              ? `[${(c.importedValues || []).length}条]`
              : formatCondValue(c.value) || formatCondValue(c.valueStart) || '(未填)'}
          </Tag>
        ))}
      </Space>
    )
  }

  const columns = [
    {
      title: '脚本名称',
      dataIndex: 'name',
      key: 'name',
      width: 150,
      ellipsis: true,
      render: (text) => <span style={{ fontWeight: 600 }}>{text}</span>,
    },
    {
      title: '分类',
      dataIndex: 'category',
      key: 'category',
      width: 80,
      ellipsis: true,
      render: (text) => text ? <Tag color="blue">{text}</Tag> : '-',
    },
    {
      title: '参数',
      key: 'conditions',
      width: 160,
      render: (_, record) => renderConditionTags(record.conditions),
    },
    {
      title: '定时',
      key: 'scheduler',
      width: 90,
      render: (_, record) => {
        if (!record.cronExpression) return <span style={{ color: '#999' }}>未配置</span>
        return (
          <Space size={4}>
            <Badge status={record.schedulerEnabled ? 'success' : 'default'} />
            <span style={{ fontSize: 12 }}>{record.cronExpression}</span>
          </Space>
        )
      },
    },
    {
      title: '上次执行',
      key: 'lastRun',
      width: 120,
      render: (_, record) => {
        if (!record.lastRunAt) return <span style={{ color: '#999' }}>-</span>
        const statusIcon = record.lastRunStatus === 'success'
          ? <CheckCircleOutlined style={{ color: '#52c41a' }} />
          : <CloseCircleOutlined style={{ color: '#ff4d4f' }} />
        return (
          <Tooltip title={record.lastRunMessage}>
            <Space size={4}>
              {statusIcon}
              <span style={{ fontSize: 11, color: '#999' }}>
                {new Date(record.lastRunAt).toLocaleString()}
              </span>
            </Space>
          </Tooltip>
        )
      },
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      render: (_, record) => (
        <Space size={4}>
          <Tooltip title="加载到编辑器">
            <Button type="link" size="small" icon={<ImportOutlined />} onClick={() => handleLoad(record)}>
              加载
            </Button>
          </Tooltip>
          <Tooltip title="编辑脚本配置">
            <Button type="link" size="small" icon={<EditOutlined />} onClick={() => handleEdit(record)} />
          </Tooltip>
          <Tooltip title="手动发送邮件">
            <Button type="link" size="small" icon={<MailOutlined />} onClick={() => handleOpenSendMail(record)} />
          </Tooltip>
          {record.cronExpression && (
            <Tooltip title="手动触发执行">
              <Button type="link" size="small" icon={<PlayCircleOutlined />} onClick={() => handleManualRun(record)} />
            </Tooltip>
          )}
          <Popconfirm title="确定删除该脚本?" onConfirm={() => handleDelete(record.id)}>
            <Button type="link" size="small" danger icon={<DeleteOutlined />} />
          </Popconfirm>
        </Space>
      ),
    },
  ]

  return (
    <>
      <Modal
        title="SQL脚本管理"
        open={open}
        onCancel={onClose}
        width={1000}
        footer={
          <Space>
            <Button onClick={onClose}>关闭</Button>
          </Space>
        }
      >
        {/* 工具栏 */}
        <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 12 }}>
          <Space>
            <Button
              type="primary"
              icon={<SaveOutlined />}
              onClick={handleOpenSave}
              disabled={!currentSql || !currentSql.trim()}
            >
              保存当前SQL
            </Button>
          </Space>
          <Input
            placeholder="搜索脚本..."
            prefix={<SearchOutlined />}
            size="small"
            value={searchKeyword}
            onChange={e => setSearchKeyword(e.target.value)}
            style={{ width: 200 }}
            allowClear
          />
        </div>

        <Table
          dataSource={filteredScripts}
          columns={columns}
          rowKey="id"
          size="small"
          loading={loading}
          pagination={{ pageSize: 10, showSizeChanger: false, showTotal: t => `共 ${t} 条` }}
          locale={{
            emptyText: (
              <Empty description="暂无保存的脚本" style={{ padding: '20px 0' }}>
                <Button type="primary" size="small" onClick={handleOpenSave}>
                  保存当前SQL
                </Button>
              </Empty>
            ),
          }}
          expandable={{
            rowExpandable: () => true,
            expandedRowRender: (record) => (
              <div style={{ padding: '8px 0' }}>
                <pre style={{
                  background: '#f5f5f5', padding: 12, borderRadius: 6,
                  fontSize: 12, fontFamily: 'Menlo, Monaco, Consolas, monospace',
                  maxHeight: 200, overflow: 'auto', whiteSpace: 'pre-wrap', wordBreak: 'break-all',
                }}>
                  {record.sql}
                </pre>
                {record.recipientEmails && (
                  <div style={{ marginTop: 8, fontSize: 12, color: '#666' }}>
                    <MailOutlined style={{ marginRight: 4 }} />
                    收件人: {record.recipientEmails}
                  </div>
                )}
              </div>
            ),
          }}
        />
      </Modal>

      {/* 保存/编辑详情弹窗 - 含参数/邮件/定时四个Tab */}
      <Modal
        title={editingId ? '编辑脚本配置' : '保存SQL脚本'}
        open={detailOpen}
        onCancel={() => setDetailOpen(false)}
        onOk={handleSave}
        okText="保存"
        cancelText="取消"
        width={720}
      >
        <Form form={detailForm} layout="vertical" style={{ marginTop: 16 }}>
          <Tabs activeKey={activeTab} onChange={setActiveTab} items={[
            {
              key: 'basic',
              label: <span><SettingOutlined /> 基本信息</span>,
              children: (
                <>
                  <div style={{ display: 'flex', gap: 12 }}>
                    <Form.Item name="name" label="脚本名称" rules={[{ required: true, message: '请输入脚本名称' }]} style={{ flex: 1 }}>
                      <Input placeholder="例如:月度终端支付明细" />
                    </Form.Item>
                    <Form.Item name="category" label="分类" style={{ flex: 1 }}>
                      <Input placeholder="例如:月常态、合规" />
                    </Form.Item>
                  </div>
                  <div style={{ display: 'flex', gap: 12 }}>
                    <Form.Item name="purpose" label="用途描述" style={{ flex: 2 }}>
                      <Input placeholder="例如:导出指定月份的终端支付明细数据" />
                    </Form.Item>
                    <Form.Item name="usedBy" label="使用人" style={{ flex: 1 }}>
                      <Input placeholder="例如:仕雄" />
                    </Form.Item>
                  </div>
                  <Form.Item name="sql" label="SQL内容" rules={[{ required: true, message: 'SQL内容不能为空' }]}>
                    <TextArea
                      rows={6}
                      placeholder="SQL脚本内容"
                      style={{ fontFamily: 'Menlo, Monaco, Consolas, monospace', fontSize: 12 }}
                    />
                  </Form.Item>
                  <div style={{ textAlign: 'right', marginBottom: 8 }}>
                    <Button size="small" icon={<SearchOutlined />} onClick={handleParseConditionsInDetail}>
                      从SQL解析参数
                    </Button>
                  </div>
                  {scriptConditions.length > 0 && (
                    <div style={{
                      padding: '10px 12px', background: '#f6ffed', border: '1px solid #b7eb8f',
                      borderRadius: 6,
                    }}>
                      <div style={{ fontSize: 13, fontWeight: 600, marginBottom: 6, color: '#389e0d' }}>
                        已解析 {scriptConditions.length} 个参数,可在"参数配置"Tab中编辑详细值:
                      </div>
                      {renderConditionTags(scriptConditions)}
                    </div>
                  )}
                </>
              ),
            },
            {
              key: 'params',
              label: <span><SearchOutlined /> 参数配置</span>,
              children: (
                <>
                  {scriptConditions.length === 0 ? (
                    <Empty description="未配置参数。请在SQL中使用 {{变量名}} 定义条件,然后点击从SQL解析参数" style={{ padding: '30px 0' }}>
                      <Button size="small" icon={<SearchOutlined />} onClick={handleParseConditionsInDetail}>
                        从SQL解析参数
                      </Button>
                    </Empty>
                  ) : (
                    <div style={{ maxHeight: '50vh', overflowY: 'auto' }}>
                      {scriptConditions.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 => updateScriptCondition(index, { type: t })}
                            options={CONDITION_TYPES}
                            style={{ width: 140 }}
                          />
                          <div style={{ flex: 1, minWidth: 200 }}>
                            {renderParamValueInput(cond, index)}
                          </div>
                          <Popconfirm title="删除该参数?" onConfirm={() => {
                            setScriptConditions(scriptConditions.filter((_, i) => i !== index))
                          }}>
                            <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_变量名}}'} 表示结束日期。
                  </div>
                  <div style={{ marginTop: 8, fontSize: 12, color: '#1890ff' }}>
                    参数值支持动态日期变量:
                    <Space size={4} wrap style={{ marginLeft: 8 }}>
                      {DATE_VARIABLES.map(v => (
                        <Tag key={v.key} color="geekblue">{v.key}={v.desc}</Tag>
                      ))}
                    </Space>
                  </div>
                </>
              ),
            },
            {
              key: 'email',
              label: <span><MailOutlined /> 邮件配置</span>,
              children: (
                <>
                  <div style={{
                    padding: '10px 12px', background: '#fff7e6', border: '1px solid #ffd591',
                    borderRadius: 6, marginBottom: 16, fontSize: 12, color: '#d46b08',
                  }}>
                    邮件发送依赖全局SMTP配置,请先在工具栏"邮件配置"中完成SMTP设置。每个脚本可单独配置收件人和邮件主题。
                  </div>
                  <Form.Item
                    name="recipientEmails"
                    label="收件人邮箱"
                    tooltip="多个收件人用英文逗号分隔,支持群发"
                    rules={[{ validator: validateEmails }]}
                  >
                    <Input placeholder="例如:zhangsan@company.com,lisi@company.com" />
                  </Form.Item>
                  <Form.Item name="emailSubject" label="邮件主题" tooltip="为空则自动生成:[SQL报表] 脚本名称 - 日期">
                    <Input placeholder="例如:月度终端支付明细报表(自定义)" />
                  </Form.Item>
                  <div style={{ color: '#999', fontSize: 12 }}>
                    邮件将自动附带Excel附件,包含查询结果数据。
                  </div>
                </>
              ),
            },
            {
              key: 'scheduler',
              label: <span><ClockCircleOutlined /> 定时配置</span>,
              children: (
                <>
                  <Form.Item name="schedulerEnabled" label="启用定时执行" valuePropName="checked">
                    <Switch checkedChildren="开" unCheckedChildren="关" />
                  </Form.Item>
                  <Form.Item name="cronExpression" label="执行时间(cron表达式)">
                    <Input placeholder="例如:0 10 * * *(每天10:00)" />
                  </Form.Item>
                  <div style={{ marginBottom: 16 }}>
                    <div style={{ fontSize: 13, fontWeight: 600, marginBottom: 8 }}>快捷选择:</div>
                    <Space wrap>
                      {CRON_PRESETS.map(p => (
                        <Button
                          key={p.value}
                          size="small"
                          onClick={() => detailForm.setFieldsValue({ cronExpression: p.value })}
                        >
                          {p.label}
                        </Button>
                      ))}
                    </Space>
                  </div>
                  <Divider style={{ margin: '12px 0' }} />
                  <div>
                    <div style={{ fontSize: 13, fontWeight: 600, marginBottom: 8 }}>参数支持动态日期变量:</div>
                    <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
                      {DATE_VARIABLES.map(v => (
                        <Tag key={v.key} color="geekblue">
                          {v.key}{v.desc}
                        </Tag>
                      ))}
                    </div>
                    <div style={{ color: '#999', fontSize: 12, marginTop: 8 }}>
                      在参数值中填入以上关键字,执行时会自动替换为对应日期。例如参数值填 TODAY,执行时自动替换为当天日期。
                    </div>
                  </div>
                </>
              ),
            },
          ]} />
        </Form>
      </Modal>
      {/* 发送邮件弹窗 */}
      <SendMailModal
        open={sendMailOpen}
        onClose={() => setSendMailOpen(false)}
        script={sendMailScript}
        onSent={() => loadScripts()}
      />
    </>
  )
}