/* === Rule Strategy Page === */

let _globalBizTypeCache = [];
async function loadBizTypes(force = false) {
  if (!force && _globalBizTypeCache.length > 0) return _globalBizTypeCache;
  try {
    const list = await window.apiFetch('/api/rule/biz-type/list');
    _globalBizTypeCache = list.map(item => ({ value: item.code, label: item.name }));
    return _globalBizTypeCache;
  } catch (e) {
    console.error('加载业务类型失败:', e);
    return [];
  }
}
function getBizTypeLabel(code) {
  const found = _globalBizTypeCache.find(b => b.value === code);
  return found ? found.label : code;
}

function RuleBizTypePanel() {
  const [list, setList] = React.useState([]);
  const [showModal, setShowModal] = React.useState(false);
  const [editing, setEditing] = React.useState(null);
  const [form, setForm] = React.useState({ code: '', name: '', remark: '', sort: 0, status: 1 });

  const fetchList = async () => {
    const data = await window.apiFetch('/api/rule/biz-type/list?include_disabled=true');
    setList(data);
  };

  React.useEffect(() => { fetchList(); }, []);

  const resetForm = () => { setForm({ code: '', name: '', remark: '', sort: 0, status: 1, short_circuit: 1 }); };

  const openAdd = () => { resetForm(); setEditing(null); setShowModal(true); };

  const openEdit = (row) => {
    setEditing(row);
    setForm({ code: row.code, name: row.name, remark: row.remark || '', sort: row.sort, status: row.status, short_circuit: (row.short_circuit ?? 1) });
    setShowModal(true);
  };

  const handleSave = async () => {
    if (!form.code || !form.name) { alert('请输入编码和名称'); return; }
    try {
      if (editing) {
        await window.apiFetch(`/api/rule/biz-type/${editing.id}`, { method: 'PUT', body: JSON.stringify(form) });
      } else {
        await window.apiFetch('/api/rule/biz-type/add', { method: 'POST', body: JSON.stringify(form) });
      }
      setShowModal(false);
      fetchList();
    } catch (e) { alert(e.message || '保存失败'); }
  };

  const handleDelete = async (id) => {
    if (!confirm('确定删除？删除后使用该分组的规则将无法匹配到分组名称')) return;
    try {
      await window.apiFetch(`/api/rule/biz-type/${id}`, { method: 'DELETE' });
      fetchList();
    } catch (e) { alert('删除失败'); }
  };

  return (
    <div>
      <div className="search-bar">
        <div className="spacer" />
        <button className="btn btn-primary" onClick={openAdd}>新增分组</button>
      </div>

      <div className="batch-table-wrapper">
        <table className="batch-table">
          <thead>
            <tr>
              <th style={{width:80}}>排序</th>
              <th style={{width:150}}>分组编码</th>
              <th style={{width:150}}>分组名称</th>
              <th>备注</th>
              <th style={{width:80}}>状态</th>
              <th style={{width:180}}>操作</th>
            </tr>
          </thead>
          <tbody>
            {list.map(row => (
              <tr key={row.id}>
                <td>{row.sort}</td>
                <td><code>{row.code}</code></td>
                <td>{row.name}</td>
                <td className="muted">{row.remark || '-'}</td>
                <td>
                  <span className={`status status-${row.status === 1 ? 'active' : 'disabled'}`}>
                    {row.status === 1 ? '启用' : '禁用'}
                  </span>
                </td>
                <td>
                  <div className="action-btns">
                    <button className="btn-link" onClick={() => openEdit(row)}>编辑</button>
                    <button className="btn-link danger" onClick={() => handleDelete(row.id)}>删除</button>
                  </div>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {showModal && (
        <div className="drawer-backdrop" onClick={() => setShowModal(false)}>
          <div className="drawer rule-drawer" onClick={e => e.stopPropagation()}>
            <div className="drawer-header">
              <div className="drawer-title">{editing ? '编辑' : '新增'}规则分组</div>
              <button className="drawer-close" onClick={() => setShowModal(false)}>×</button>
            </div>
            <div className="drawer-body">
              <div className="form-grid">
                <div className="form-group">
                  <label>分组编码 <span className="required">*</span></label>
                  <input className="input" value={form.code} onChange={e => setForm({...form, code: e.target.value})} placeholder="如: product_drawdown" />
                </div>
                <div className="form-group">
                  <label>分组名称 <span className="required">*</span></label>
                  <input className="input" value={form.name} onChange={e => setForm({...form, name: e.target.value})} placeholder="如: 产品最大回撤" />
                </div>
              </div>
              <div className="form-group">
                <label>备注</label>
                <input className="input" value={form.remark} onChange={e => setForm({...form, remark: e.target.value})} placeholder="说明这个分组的用途" />
              </div>
              <div className="form-grid">
                <div className="form-group">
                  <label>排序号</label>
                  <input type="number" className="input" value={form.sort} onChange={e => setForm({...form, sort: parseInt(e.target.value)||0})} />
                </div>
                <div className="form-group">
                  <label>状态</label>
                  <select className="select" value={form.status} onChange={e => setForm({...form, status: parseInt(e.target.value)})}>
                    <option value={1}>启用</option>
                    <option value={0}>禁用</option>
                  </select>
                </div>
              </div>
              <div className="checkbox-row">
                <label className="checkbox">
                  <input type="checkbox" checked={form.short_circuit === 1}
                    onChange={e => setForm({...form, short_circuit: e.target.checked ? 1 : 0})} />
                  <span />
                  <strong>短路执行</strong>（命中即停，不勾选则本分组下所有规则都会完整校验）
                </label>
              </div>
            </div>
            <div className="drawer-footer">
              <button className="btn btn-secondary" onClick={() => setShowModal(false)}>取消</button>
              <button className="btn btn-primary" onClick={handleSave}>保存</button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

function RuleConfigPanel() {
  const [rules, setRules] = React.useState([]);
  const [showModal, setShowModal] = React.useState(false);
  const [editingRule, setEditingRule] = React.useState(null);
  const [searchKeyword, setSearchKeyword] = React.useState('');

  const fetchRules = async () => {
    try {
      const data = await window.apiFetch('/api/rule/config/list');
      setRules(data);
    } catch (error) {
      console.error('获取规则列表失败:', error);
    }
  };

  React.useEffect(() => {
    fetchRules();
  }, []);

  const handleDelete = async (ruleId) => {
    if (!confirm('确定要删除这条规则吗？')) return;
    try {
      await window.apiFetch(`/api/rule/config/${ruleId}`, { method: 'DELETE' });
      fetchRules();
    } catch (error) {
      console.error('删除规则失败:', error);
    }
  };

  const handleToggleStatus = async (rule) => {
    const endpoint = rule.status === 1 ? 'disable' : 'enable';
    try {
      await window.apiFetch(`/api/rule/config/${rule.id}/${endpoint}`, { method: 'POST' });
      fetchRules();
    } catch (error) {
      console.error('切换状态失败:', error);
    }
  };

  const filteredRules = rules.filter(rule =>
    rule.rule_name.includes(searchKeyword) || rule.rule_code.includes(searchKeyword)
  );

  return (
    <div className="rule-config-panel">
      <div className="search-bar">
        <input
          type="text"
          className="input"
          placeholder="搜索规则名称或编码..."
          value={searchKeyword}
          onChange={(e) => setSearchKeyword(e.target.value)}
        />
        <button className="btn btn-primary" onClick={() => { setEditingRule(null); setShowModal(true); }}>
          新增规则
        </button>
      </div>

      <div className="batch-table-wrapper">
        <table className="batch-table">
          <thead>
            <tr>
              <th>规则编码</th>
              <th>规则名称</th>
              <th>业务类型</th>
              <th>规则表达式</th>
              <th>状态</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            {filteredRules.map(rule => (
              <tr key={rule.id}>
                <td><code>{rule.rule_code}</code></td>
                <td>{rule.rule_name}</td>
                <td>{getBizTypeLabel(rule.biz_type)}</td>
                <td><code>{rule.rule_expr}</code></td>
                <td>
                  <span className={`status status-${rule.status === 1 ? 'active' : 'disabled'}`}>
                    {rule.status === 1 ? '启用' : '禁用'}
                  </span>
                </td>
                <td>
                  <div className="action-btns">
                    <button className="btn-link" onClick={() => { setEditingRule(rule); setShowModal(true); }}>编辑</button>
                    <button className="btn-link" onClick={() => handleToggleStatus(rule)}>
                      {rule.status === 1 ? '禁用' : '启用'}
                    </button>
                    <button className="btn-link danger" onClick={() => handleDelete(rule.id)}>删除</button>
                  </div>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {showModal && (
        <RuleConfigModal
          rule={editingRule}
          onClose={() => setShowModal(false)}
          onSuccess={() => { setShowModal(false); fetchRules(); }}
        />
      )}
    </div>
  );
}

function RuleConfigModal({ rule, onClose, onSuccess }) {
  const [formData, setFormData] = React.useState({
    rule_code: rule?.rule_code || '',
    rule_name: rule?.rule_name || '',
    rule_expr: rule?.rule_expr || '',
    biz_type: rule?.biz_type || 'product_drawdown',
    status: rule?.status ?? 1,
    short_circuit: rule?.short_circuit ?? 1,
    remark: rule?.remark || '',
  });

  const handleSubmit = async () => {
    try {
      const url = rule ? `/api/rule/config/${rule.id}` : '/api/rule/config/add';
      const method = rule ? 'PUT' : 'POST';

      await fetch(url, {
        method,
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(formData),
      });
      onSuccess();
    } catch (error) {
      console.error('保存规则失败:', error);
    }
  };

  return (
    <div className="drawer-backdrop" onClick={onClose}>
      <div className="drawer rule-drawer" onClick={(e) => e.stopPropagation()}>
        <div className="drawer-header">
          <div className="drawer-title">{rule ? '编辑规则' : '新增规则'}</div>
          <button className="drawer-close" onClick={onClose}>×</button>
        </div>
        <div className="drawer-body">
          <div className="drawer-section">
            <div className="drawer-section-title">基本信息</div>
            <div className="form-grid">
              <div className="form-group">
                <label>规则编码 <span className="required">*</span></label>
                <input
                  type="text"
                  className="input"
                  value={formData.rule_code}
                  onChange={(e) => setFormData({ ...formData, rule_code: e.target.value })}
                  required
                  disabled={!!rule}
                />
              </div>
              <div className="form-group">
                <label>规则名称 <span className="required">*</span></label>
                <input
                  type="text"
                  className="input"
                  value={formData.rule_name}
                  onChange={(e) => setFormData({ ...formData, rule_name: e.target.value })}
                  required
                />
              </div>
            </div>
            <div className="form-grid">
              <div className="form-group">
                <label>业务类型 <span className="required">*</span></label>
                <select
                  className="input"
                  value={formData.biz_type}
                  onChange={(e) => setFormData({ ...formData, biz_type: e.target.value })}
                  required
                >
                  {_globalBizTypeCache.map(opt => (
                    <option key={opt.value} value={opt.value}>{opt.label}</option>
                  ))}
                </select>
              </div>
              <div className="form-group">
                <label>状态</label>
                <select
                  className="input"
                  value={formData.status}
                  onChange={(e) => setFormData({ ...formData, status: parseInt(e.target.value) })}
                >
                  <option value="1">启用</option>
                  <option value="0">禁用</option>
                </select>
              </div>
            </div>
          </div>
          <div className="drawer-section">
            <div className="drawer-section-title">规则配置</div>
            <div className="form-group">
              <label>规则表达式 <span className="required">*</span></label>
              <textarea
                className="input"
                rows="3"
                value={formData.rule_expr}
                onChange={(e) => setFormData({ ...formData, rule_expr: e.target.value })}
                placeholder="例如: max_drawdown > 5"
                required
              />
            </div>
            <div className="form-group">
              <label>备注</label>
              <textarea
                className="input"
                rows="2"
                value={formData.remark}
                onChange={(e) => setFormData({ ...formData, remark: e.target.value })}
              />
            </div>
            <div className="checkbox-row">
              <label className="checkbox">
                <input type="checkbox" checked={formData.short_circuit === 1}
                  onChange={e => setFormData({...formData, short_circuit: e.target.checked ? 1 : 0})} />
                <span />
                <strong>短路执行</strong>（本规则命中后立即终止不再校验后续规则）
              </label>
            </div>
          </div>
        </div>
        <div className="drawer-footer">
          <button className="btn btn-ghost" onClick={onClose}>取消</button>
          <button className="btn btn-primary" onClick={handleSubmit}>保存</button>
        </div>
      </div>
    </div>
  );
}

function MetricManagementPanel() {
  const [metrics, setMetrics] = React.useState([]);
  const [showModal, setShowModal] = React.useState(false);

  const fetchMetrics = async () => {
    try {
      const data = await window.apiFetch('/api/rule/metric/list');
      setMetrics(data);
    } catch (error) {
      console.error('获取指标列表失败:', error);
    }
  };

  React.useEffect(() => {
    fetchMetrics();
  }, []);

  const handleDelete = async (metricId) => {
    if (!confirm('确定要删除这个指标吗？')) return;
    try {
      await window.apiFetch(`/api/rule/metric/${metricId}`, { method: 'DELETE' });
      fetchMetrics();
    } catch (error) {
      console.error('删除指标失败:', error);
    }
  };

  return (
    <div className="metric-panel">
      <div className="search-bar">
        <h3>指标管理</h3>
        <button className="btn btn-primary" onClick={() => setShowModal(true)}>
          新增指标
        </button>
      </div>

      <div className="batch-table-wrapper">
        <table className="batch-table">
          <thead>
            <tr>
              <th>指标编码</th>
              <th>指标名称</th>
              <th>业务类型</th>
              <th>取值字段</th>
              <th>备注</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            {metrics.map(metric => (
              <tr key={metric.id}>
                <td><code>{metric.metric_code}</code></td>
                <td>{metric.metric_name}</td>
                <td>{getBizTypeLabel(metric.biz_type) || metric.biz_type}</td>
                <td><code>{metric.value_field}</code></td>
                <td>{metric.remark || '-'}</td>
                <td>
                  <button className="btn-link danger" onClick={() => handleDelete(metric.id)}>删除</button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {showModal && (
        <MetricModal
          onClose={() => setShowModal(false)}
          onSuccess={() => { setShowModal(false); fetchMetrics(); }}
        />
      )}
    </div>
  );
}

function MetricModal({ onClose, onSuccess }) {
  const [formData, setFormData] = React.useState({
    metric_code: '',
    metric_name: '',
    biz_type: 'product_drawdown',
    value_field: '',
    remark: '',
  });

  const handleSubmit = async () => {
    try {
      await window.apiFetch('/api/rule/metric/add', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(formData),
      });
      onSuccess();
    } catch (error) {
      console.error('保存指标失败:', error);
    }
  };

  return (
    <div className="drawer-backdrop" onClick={onClose}>
      <div className="drawer rule-drawer" onClick={(e) => e.stopPropagation()}>
        <div className="drawer-header">
          <div className="drawer-title">新增指标</div>
          <button className="drawer-close" onClick={onClose}>×</button>
        </div>
        <div className="drawer-body">
          <div className="form-grid">
            <div className="form-group">
              <label>指标编码 <span className="required">*</span></label>
              <input
                type="text"
                className="input"
                value={formData.metric_code}
                onChange={(e) => setFormData({ ...formData, metric_code: e.target.value })}
                required
              />
            </div>
            <div className="form-group">
              <label>指标名称 <span className="required">*</span></label>
              <input
                type="text"
                className="input"
                value={formData.metric_name}
                onChange={(e) => setFormData({ ...formData, metric_name: e.target.value })}
                required
              />
            </div>
          </div>
          <div className="form-grid">
            <div className="form-group">
              <label>业务类型 <span className="required">*</span></label>
              <select
                className="input"
                value={formData.biz_type}
                onChange={(e) => setFormData({ ...formData, biz_type: e.target.value })}
                required
              >
                {_globalBizTypeCache.map(opt => (
                  <option key={opt.value} value={opt.value}>{opt.label}</option>
                ))}
              </select>
            </div>
            <div className="form-group">
              <label>取值字段 <span className="required">*</span></label>
              <input
                type="text"
                className="input"
                value={formData.value_field}
                onChange={(e) => setFormData({ ...formData, value_field: e.target.value })}
                placeholder="例如: max_drawdown"
                required
              />
            </div>
          </div>
          <div className="form-group">
            <label>备注</label>
            <textarea
              className="input"
              rows="2"
              value={formData.remark}
              onChange={(e) => setFormData({ ...formData, remark: e.target.value })}
            />
          </div>
        </div>
        <div className="drawer-footer">
          <button className="btn btn-ghost" onClick={onClose}>取消</button>
          <button className="btn btn-primary" onClick={handleSubmit}>保存</button>
        </div>
      </div>
    </div>
  );
}

function RulePagination({ result, onChange }) {
  const maxPage = Math.ceil((result?.total||0) / (result?.page_size||20));
  return (
    <div className="pagination-bar" style={{display:'flex',justifyContent:'space-between',alignItems:'center',marginTop:'12px',padding:'8px 4px',fontSize:'12px'}}>
      <div className="pagination-info" style={{color:'var(--fg-3)'}}>
        共 <b>{result?.total||0}</b> 条记录，当前第 <b>{result?.page||1}</b> / {maxPage||1} 页
      </div>
      <div className="pagination-buttons" style={{display:'flex',gap:'8px'}}>
        <button className="btn btn-ghost" style={{padding:'4px 10px',fontSize:'12px'}}
          onClick={() => onChange((result?.page||1)-1)} disabled={(result?.page||1) <= 1}>上一页</button>
        <button className="btn btn-ghost" style={{padding:'4px 10px',fontSize:'12px'}}
          onClick={() => onChange((result?.page||1)+1)} disabled={(result?.page||1) >= maxPage}>下一页</button>
      </div>
    </div>
  );
}

function EventLogPanel() {
  const [subTab, setSubTab] = React.useState('overview');
  const [page, setPage] = React.useState(1);
  const [result, setResult] = React.useState({ total: 0, items: [] });
  const [filters, setFilters] = React.useState({ biz_type: '', is_hit: '', keyword: '' });
  const [showDetail, setShowDetail] = React.useState(null);

  const fetchList = async (p = 1) => {
    const api = subTab === 'detail' ? '/api/rule/run-detail/list' : '/api/rule/event/list';
    const params = new URLSearchParams({ page: p, page_size: 15 });
    if (filters.biz_type) params.append('biz_type', filters.biz_type);
    if (filters.is_hit !== '') params.append('is_hit', filters.is_hit);
    if (filters.keyword && subTab === 'detail') params.append('rule_code', filters.keyword);
    try {
      const data = await window.apiFetch(`${api}?${params}`);
      setResult(data);
      setPage(p);
    } catch (e) {
      console.error(e);
    }
  };

  React.useEffect(() => {
    fetchList(1);
  }, [subTab, filters]);

  const renderOverview = () => (
    <table className="batch-table">
      <thead>
        <tr>
          <th style={{width:80}}>ID</th>
          <th style={{width:120}}>规则编码</th>
          <th style={{width:120}}>业务编号</th>
          <th style={{width:130}}>业务类型</th>
          <th>触发描述</th>
          <th style={{width:150}}>触发时间</th>
        </tr>
      </thead>
      <tbody>
        {(result.items||[]).length ? (result.items||[]).map(row => (
          <tr key={row.id}>
            <td>{row.id}</td>
            <td><code>{row.rule_code}</code></td>
            <td>{row.biz_no}</td>
            <td>{getBizTypeLabel(row.biz_type)}</td>
            <td style={{maxWidth:320,whiteSpace:'nowrap',overflow:'hidden',textOverflow:'ellipsis'}}>{row.trigger_msg}</td>
            <td>{String(row.trigger_time||'').slice(0,19).replace('T',' ')}</td>
          </tr>
        )) : (
          <tr><td colSpan={6} className="empty-cell">暂无数据</td></tr>
        )}
      </tbody>
    </table>
  );

  const renderDetail = () => (
    <table className="batch-table">
      <thead>
        <tr>
          <th style={{width:60}}>顺序</th>
          <th style={{width:120}}>规则编码</th>
          <th>规则名称</th>
          <th style={{width:90}}>业务编号</th>
          <th style={{width:70}}>是否命中</th>
          <th>触发描述</th>
          <th style={{width:150}}>执行时间</th>
        </tr>
      </thead>
      <tbody>
        {(result.items||[]).length ? (result.items||[]).map(row => (
          <tr key={row.id}>
            <td>{row.sort}</td>
            <td><code>{row.rule_code}</code></td>
            <td>{row.rule_name}</td>
            <td>{row.biz_no}</td>
            <td>
              <span className={`status status-${row.is_hit ? 'active' : 'disabled'}`}
                style={{fontSize:'11px',padding:'1px 6px'}}>{row.is_hit ? '命中' : '未命中'}</span>
            </td>
            <td style={{maxWidth:280,whiteSpace:'nowrap',overflow:'hidden',textOverflow:'ellipsis'}}>{row.trigger_msg}</td>
            <td>{String(row.trigger_time||'').slice(0,19).replace('T',' ')}</td>
          </tr>
        )) : (
          <tr><td colSpan={7} className="empty-cell">暂无数据（需要写规则明细表）</td></tr>
        )}
      </tbody>
    </table>
  );

  return (
    <div className="event-panel">
      <div className="config-tabs-row" style={{display:'flex',gap:'4px',marginBottom:'14px',borderBottom:'1px solid var(--divider)',paddingBottom:'12px'}}>
        {[
          { id: 'overview', label: '事件总览' },
          { id: 'group', label: '分组查询' },
          { id: 'detail', label: '明细查询' },
        ].map(t => (
          <button className={subTab === t.id ? 'tab-btn tab-active' : 'tab-btn'} key={t.id}
            onClick={() => { setSubTab(t.id); }}
            style={{background: subTab === t.id ? 'var(--primary-soft)' : 'transparent',
              color: subTab === t.id ? 'var(--primary)' : 'var(--fg-3)',
              border:'none', borderRadius:'6px', padding:'7px 14px', fontSize:'12px', cursor:'pointer'}}>
            {t.label}
          </button>
        ))}
      </div>

      <div className="search-bar" style={{marginBottom:'12px'}}>
        <div className="filter-group" style={{gap:'8px'}}>
          <select className="input" style={{width:'140px'}} value={filters.biz_type}
            onChange={e => setFilters({...filters, biz_type: e.target.value})}>
            <option value="">全部业务类型</option>
            {_globalBizTypeCache.map(o => (<option key={o.value} value={o.value}>{o.label}</option>))}
          </select>
          <select className="input" style={{width:'100px'}} value={String(filters.is_hit)}
            onChange={e => setFilters({...filters, is_hit: e.target.value})}>
            <option value="">命中状态</option>
            <option value="1">命中</option>
            <option value="0">未命中</option>
          </select>
          {subTab === 'detail' && (
            <input className="input" style={{width:'140px'}} placeholder="规则编码关键词"
              value={filters.keyword} onChange={e => setFilters({...filters, keyword: e.target.value})}
            />
          )}
          <button className="btn btn-primary" style={{padding:'6px 14px'}} onClick={() => fetchList(1)}>
            刷新
          </button>
        </div>
      </div>

      <div className="batch-table-wrapper">
        {subTab === 'overview' && renderOverview()}
        {subTab === 'group' && renderOverview()}
        {subTab === 'detail' && renderDetail()}
        <RulePagination result={result} onChange={(p) => fetchList(p)} />
      </div>
    </div>
  );
}

function JsonEditModal({ jsonData, onClose, onSave }) {
  const [editValue, setEditValue] = React.useState(JSON.stringify(jsonData, null, 2));

  const handleSave = () => {
    try {
      const parsed = JSON.parse(editValue);
      onSave(parsed);
      onClose();
    } catch (err) {
      alert('JSON 格式错误，请检查');
    }
  };

  return (
    <div className="drawer-backdrop" onClick={onClose}>
      <div className="drawer rule-drawer" onClick={(e) => e.stopPropagation()}>
        <div className="drawer-header">
          <div className="drawer-title">编辑测试数据</div>
          <button className="drawer-close" onClick={onClose}>×</button>
        </div>
        <div className="drawer-body">
          <div className="form-group">
            <label>JSON 数据</label>
            <textarea
              className="input json-editor"
              rows="15"
              value={editValue}
              onChange={(e) => setEditValue(e.target.value)}
            />
          </div>
        </div>
        <div className="drawer-footer">
          <button className="btn btn-ghost" onClick={onClose}>取消</button>
          <button className="btn btn-primary" onClick={handleSave}>保存</button>
        </div>
      </div>
    </div>
  );
}

function CombinedRuleTestPanel() {
  const [bizType, setBizType] = React.useState('product_drawdown');
  const [bizNo, setBizNo] = React.useState('PROD001_2025-05-24');
  const [expr, setExpr] = React.useState('max_drawdown > 5');
  const [testData, setTestData] = React.useState({
    prodCode: 'PROD001',
    statDate: '2025-05-24',
    max_drawdown: 6.2,
    yield_rate: 3.5,
    status: 'NORMAL'
  });
  const [showEditModal, setShowEditModal] = React.useState(false);
  const [result, setResult] = React.useState(null);
  const [resultType, setResultType] = React.useState(null);

  const handleTestRule = async () => {
    try {
      const data = await window.apiFetch('/api/rule/execute', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ bizType, bizNo, data: testData }),
      });
      setResult(data);
      setResultType('rule');
    } catch (error) {
      console.error('执行规则失败:', error);
    }
  };

  const handleTestExpr = async () => {
    try {
      const data = await window.apiFetch('/api/rule/test', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ expr, test_data: testData })
      });
      setResult(data);
      setResultType('expr');
    } catch (error) {
      console.error('测试表达式失败:', error);
    }
  };

  const getResultClass = () => {
    if (resultType === 'rule') {
      const hit = result.hit ?? result.triggered;
      if (hit) return 'success';
      if (result.success) return 'info';
      return 'error';
    }
    return result.result ? 'success' : 'info';
  };

  const getBadgeText = () => {
    if (resultType === 'rule') {
      const hit = result.hit ?? result.triggered;
      if (result.hit_count >= 0) {
        return hit ? `命中${result.hit_count}/${result.total_count}条规则` : `共校验${result.total_count}条规则`;
      }
      return hit ? '规则已触发' : '规则未触发';
    }
    return result.result ? 'True' : 'False';
  };

  return (
    <div className="test-panel combined-panel">
      <div className="test-form">
        <div className="form-grid">
          <div className="form-group">
            <label>业务类型 <span className="required">*</span></label>
            <select
              className="input"
              value={bizType}
              onChange={(e) => setBizType(e.target.value)}
            >
              {_globalBizTypeCache.map(opt => (
                <option key={opt.value} value={opt.value}>{opt.label}</option>
              ))}
            </select>
          </div>
          <div className="form-group">
            <label>业务编号 <span className="required">*</span></label>
            <input
              type="text"
              className="input"
              value={bizNo}
              onChange={(e) => setBizNo(e.target.value)}
              placeholder="例如: PROD001_2025-05-24"
            />
          </div>
        </div>

        <div className="form-group">
          <label>测试数据 (JSON)</label>
          <textarea
            className="input json-editor"
            rows="8"
            readOnly
            value={JSON.stringify(testData, null, 2)}
          />
          <div className="form-actions-right">
            <button 
              className="btn btn-secondary" 
              onClick={() => setShowEditModal(true)}
            >
              编辑
            </button>
          </div>
        </div>

        <div className="form-group">
          <label>表达式 <span className="required">*</span></label>
          <input
            type="text"
            className="input expr-input"
            value={expr}
            onChange={(e) => setExpr(e.target.value)}
            placeholder="例如: max_drawdown > 5 and yield_rate < 2"
          />
          <div className="hint">支持 Python 语法：&gt;, &lt;, &gt;=, &lt;=, ==, !=, and, or, not</div>
        </div>

        <div className="button-group">
          <button 
            className="btn btn-primary btn-lg" 
            onClick={handleTestRule}
          >
            测试规则
          </button>
          <button 
            className="btn btn-secondary btn-lg" 
            onClick={handleTestExpr}
          >
            测试表达式
          </button>
        </div>
      </div>

      {result && (
        <div className={`test-result ${getResultClass()}`}>
          <div className="result-header">
            <h4>{resultType === 'rule' ? '规则执行结果' : '表达式测试结果'}</h4>
            <span className={`result-badge ${resultType === 'rule' ? (result.triggered ? 'triggered' : 'not-triggered') : (result.result ? 'true' : 'false')}`}>
              {getBadgeText()}
            </span>
          </div>
          <pre>{JSON.stringify(result, null, 2)}</pre>
        </div>
      )}

      {showEditModal && (
        <JsonEditModal
          jsonData={testData}
          onClose={() => setShowEditModal(false)}
          onSave={(newData) => setTestData(newData)}
        />
      )}

      <div className="tip-section">
        <div className="tip-card">
          <div className="tip-icon">💡</div>
          <div className="tip-content">
            <h4>📖 测试规则 vs 测试表达式</h4>
            <div className="tip-row">
              <div className="tip-item">
                <span className="tip-label">🔹 测试规则</span>
                <p>根据业务类型匹配已配置的规则，执行完整的规则触发流程，返回规则是否被触发以及相关信息。</p>
              </div>
              <div className="tip-item">
                <span className="tip-label">🔹 测试表达式</span>
                <p>仅验证表达式语法和计算结果，不关联规则配置，直接使用页面上的测试数据进行计算。</p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

function RuleHelpPanel() {
  return (
    <div className="help-panel">
      <div className="help-section">
        <h2>📋 规则引擎使用指南</h2>
        <p className="section-desc">本系统提供灵活的规则配置和执行能力，帮助您实现自动化业务规则判断。</p>
      </div>

      <div className="help-card">
        <h3>🎯 核心功能模块</h3>
        
        <div className="module-item">
          <div className="module-icon">📊</div>
          <div className="module-content">
            <h4>指标管理</h4>
            <p>定义业务指标与数据源字段的映射关系，为规则表达式提供数据支持。</p>
            <div className="module-example">
              <span className="example-label">示例：</span>
              <code>max_drawdown → 产品最大回撤字段</code>
            </div>
          </div>
        </div>

        <div className="module-item">
          <div className="module-icon">⚙️</div>
          <div className="module-content">
            <h4>规则配置</h4>
            <p>配置具体的业务规则，包括规则名称、表达式、业务类型等。</p>
            <div className="module-example">
              <span className="example-label">示例：</span>
              <code>max_drawdown > 5 → 触发预警</code>
            </div>
          </div>
        </div>

        <div className="module-item">
          <div className="module-icon">🔍</div>
          <div className="module-content">
            <h4>规则测试</h4>
            <p>测试规则配置和表达式的正确性，支持实时调试。</p>
          </div>
        </div>

        <div className="module-item">
          <div className="module-icon">📝</div>
          <div className="module-content">
            <h4>触发事件日志</h4>
            <p>记录所有规则触发事件，便于追溯和审计。</p>
          </div>
        </div>
      </div>

      <div className="help-card">
        <h3>📦 数据准备要求</h3>
        <ul className="help-list">
          <li><strong>数据格式：</strong>JSON 格式，键名为指标编码，值为对应数值</li>
          <li><strong>必填字段：</strong>根据业务类型配置的指标</li>
          <li><strong>时间字段：</strong>建议包含统计日期（statDate）</li>
        </ul>
        <div className="code-block">
          <pre>{`{
  "prodCode": "PROD001",
  "statDate": "2025-05-24",
  "max_drawdown": 6.2,
  "yield_rate": 3.5,
  "status": "NORMAL"
}`}</pre>
        </div>
      </div>

      <div className="help-card">
        <h3>🚀 API 使用说明</h3>
        
        <div className="api-item">
          <h4>POST /api/rule/execute</h4>
          <p>执行规则引擎，根据业务类型匹配规则并触发</p>
          <div className="api-params">
            <span className="param-label">参数：</span>
            <ul>
              <li><code>bizType</code> - 业务类型</li>
              <li><code>bizNo</code> - 业务编号</li>
              <li><code>data</code> - 测试数据（JSON）</li>
            </ul>
          </div>
        </div>

        <div className="api-item">
          <h4>POST /api/rule/test</h4>
          <p>测试表达式计算结果</p>
          <div className="api-params">
            <span className="param-label">参数：</span>
            <ul>
              <li><code>expr</code> - 表达式字符串</li>
              <li><code>test_data</code> - 测试数据（JSON）</li>
            </ul>
          </div>
        </div>
      </div>

      <div className="help-card">
        <h3>💡 使用场景</h3>
        <div className="scenario-grid">
          <div className="scenario-item">
            <div className="scenario-icon">⚠️</div>
            <div>
              <h5>风险预警</h5>
              <p>产品回撤超过阈值时自动触发预警</p>
            </div>
          </div>
          <div className="scenario-item">
            <div className="scenario-icon">📈</div>
            <div>
              <h5>业绩达标</h5>
              <p>收益率满足条件时触发奖励机制</p>
            </div>
          </div>
          <div className="scenario-item">
            <div className="scenario-icon">🔄</div>
            <div>
              <h5>状态变更</h5>
              <p>满足条件时自动更新产品状态</p>
            </div>
          </div>
        </div>
      </div>

      <div className="help-card">
        <h3>⚙️ RuleAction 可配置动作引擎</h3>
        <p className="section-desc">规则命中后，系统会自动执行预配置的动作列表，支持多动作顺序执行，实现与业务逻辑解耦。</p>

        <div className="module-item">
          <div className="module-icon">🔀</div>
          <div className="module-content">
            <h4>核心原理</h4>
            <p>当规则命中时，系统查询 <code>wrtb_rule_action</code> 配置表，按顺序逐个执行动作：</p>
            <div className="code-block" style={{marginTop:'12px'}}><pre style={{fontSize:'12px'}}>{`┌─────────────────────────────────────────────┐
│  规则命中  ──►  查询动作列表  ──►  顺序执行  │
│                                            │
│  CREATE_EVENT  →  ADD_WATCHLIST  →  ...    │
└─────────────────────────────────────────────┘`}</pre></div>
          </div>
        </div>

        <div className="module-item" style={{marginTop:'16px'}}>
          <div className="module-icon">🔌</div>
          <div className="module-content">
            <h4>支持的动作类型</h4>
            <div className="form-grid" style={{marginTop:'10px',gap:'12px',gridTemplateColumns:'1fr 1fr'}}>
              <div style={{background:'var(--bg)',padding:'10px 12px',borderRadius:'6px'}}>
                <b style={{color:'var(--primary)'}}>CREATE_EVENT</b>
                <p style={{fontSize:'12px',margin:'2px 0 0',color:'var(--fg-3)'}}>写事件日志表（默认向后兼容）</p>
              </div>
              <div style={{background:'var(--bg)',padding:'10px 12px',borderRadius:'6px'}}>
                <b style={{color:'var(--teal)'}}>ADD_WATCHLIST</b>
                <p style={{fontSize:'12px',margin:'2px 0 0',color:'var(--fg-3)'}}>自动新增到观察名单</p>
              </div>
            </div>
          </div>
        </div>

        <div className="module-item" style={{marginTop:'16px'}}>
          <div className="module-icon">📝</div>
          <div className="module-content">
            <h4>配置示例（SQL 插入）</h4>
            <p>给规则配置两个动作，命中后既写事件又加观察名单：</p>
            <div className="code-block" style={{marginTop:'10px'}}><pre style={{fontSize:'12px'}}>{`INSERT INTO wrtb_rule_action (rule_id, action_type, action_config)
VALUES (1, 'CREATE_EVENT', NULL);

INSERT INTO wrtb_rule_action (rule_id, action_type, action_config)
VALUES (1, 'ADD_WATCHLIST', '{"level": "WARN"}');`}</pre></div>
          </div>
        </div>

        <div className="module-item" style={{marginTop:'16px'}}>
          <div className="module-icon">🎯</div>
          <div className="module-content">
            <h4>报文响应示例</h4>
            <p>返回新增加字段 <code>action_count</code> 和 <code>actions</code> 数组便于调试：</p>
            <div className="code-block" style={{marginTop:'10px'}}><pre style={{fontSize:'12px'}}>{`{
  "hit": true,
  "hit_count": 1,
  "total_count": 3,
  "action_count": 2,
  "actions": [
    {"rule_id":1,"action":"CREATE_EVENT","result":{"event_id":123}},
    {"rule_id":1,"action":"ADD_WATCHLIST","result":{"ok":true,"product_id":"xxx"}}
  ]
}`}</pre></div>
          </div>
        </div>

        <div className="module-item" style={{marginTop:'16px'}}>
          <div className="module-icon">💡</div>
          <div className="module-content">
            <h4>Watchlist 字段映射关系</h4>
            <ul className="help-list" style={{marginTop:'8px',fontSize:'12px'}}>
              <li><code>product_id</code>：从测试数据读取 prodCode / product_id / productCode</li>
              <li><code>scene</code>：固定为 rule_engine</li>
              <li><code>driver</code>：命中规则的编码</li>
              <li><code>tag</code>：业务类型编码</li>
              <li><code>level</code> / <code>reason</code>：从动作配置和规则描述读取</li>
            </ul>
          </div>
        </div>

        <div className="module-item" style={{marginTop:'16px'}}>
          <div className="module-icon">⚠️</div>
          <div className="module-content">
            <h4>使用说明与注意事项</h4>
            <ul className="help-list warning" style={{marginTop:'8px',fontSize:'12px'}}>
              <li><strong>兼容模式：</strong>若某规则未配置任何动作，默认执行 CREATE_EVENT（不影响原有逻辑）</li>
              <li><strong>顺序保证：</strong>同一规则的多个动作按表中的顺序执行，可通过控制 insert 顺序控制依赖</li>
              <li><strong>异常隔离：</strong>单个动作失败不影响全局（新动作应幂等设计）</li>
              <li><strong>未来扩展：</strong>支持短信/邮件通知、API 回调等新动作只需加 handler，不改核心执行逻辑</li>
            </ul>
          </div>
        </div>
      </div>

      <div className="help-card">
        <h3>⚠️ 注意事项</h3>
        <ul className="help-list warning">
          <li>表达式使用 Python 语法，支持比较运算符和逻辑运算符</li>
          <li>指标编码需与指标管理中配置的编码一致</li>
          <li>规则触发后会记录到事件日志，可追溯审计</li>
          <li>建议在正式使用前充分测试规则配置</li>
          <li>敏感数据请勿在测试环境中使用真实值</li>
        </ul>
      </div>
    </div>
  );
}

function PageOperationRule() {
  const [activeTab, setActiveTab] = React.useState("config");

  const tabs = [
    { id: "config", label: "规则配置" },
    { id: "metric", label: "指标管理" },
    { id: "biz-type", label: "规则分组" },
    { id: "event", label: "事件日志" },
    { id: "test", label: "规则测试" },
    { id: "help", label: "规则说明" }
  ];

  React.useEffect(() => {
    loadBizTypes();
  }, []);

  return (
    <div className="page-operation">
      <div className="card operation-header-card">
        <div className="tab-container">
          {tabs.map(tab => (
            <button
              key={tab.id}
              className={`tab-btn ${activeTab === tab.id ? "active" : ""}`}
              onClick={() => setActiveTab(tab.id)}
            >
              {tab.label}
            </button>
          ))}
        </div>
        <div className="tab-content">
          {activeTab === "config" && <RuleConfigPanel />}
          {activeTab === "metric" && <MetricManagementPanel />}
          {activeTab === "biz-type" && <RuleBizTypePanel />}
          {activeTab === "event" && <EventLogPanel />}
          {activeTab === "test" && <CombinedRuleTestPanel />}
          {activeTab === "help" && <RuleHelpPanel />}
        </div>
      </div>
    </div>
  );
}
