/* === 产品净值指标页面 === */
/* global React, useToast, LineChart */
const { useState, useEffect } = React;

function PageOperationIndicator() {
  const toast = useToast();
  
  // 当前活动tab
  const [activeTab, setActiveTab] = useState('calculate'); // 'calculate' | 'sync' | 'strategy-calculate' | 'strategy-sync'
  
  // 数据状态
  const [productList, setProductList] = useState([]);
  const [summaryList, setSummaryList] = useState([]); // wrtb_info_indicator 数据
  const [historyList, setHistoryList] = useState([]); // wrtb_info_indicator_history 数据
  const [selectedProduct, setSelectedProduct] = useState(null);
  const [timeSeries, setTimeSeries] = useState([]);
  const [loading, setLoading] = useState(false);
  const [calculating, setCalculating] = useState(false);
  
  // 筛选条件
  const [filterProductId, setFilterProductId] = useState('');
  const [filterDate, setFilterDate] = useState('');
  const [resetAll, setResetAll] = useState(false);
  
  // 分页状态 - 指标计算
  const [pagination, setPagination] = useState({
    page: 1,
    pageSize: 20,
    total: 0,
    totalPages: 1
  });
  
  // 分页状态 - 指标同步
  const [summaryPagination, setSummaryPagination] = useState({
    page: 1,
    pageSize: 20,
    total: 0,
    totalPages: 1
  });

  // 获取产品列表（从wrtb_info_product表获取全部产品）
  const fetchProductList = async () => {
    try {
      const data = await window.apiFetch('/api/info-products/all/list');
      if (data.data) {
        setProductList(data.data.map(p => ({
          productId: p.productId,
          productName: p.productName
        })));
      }
    } catch (error) {
      console.error('获取产品列表失败:', error);
      toast.push('获取产品列表失败', 'error');
    }
  };

  // 获取指标汇总（wrtb_info_indicator）
  const fetchSummary = async (productId = null, page = summaryPagination.page, pageSize = summaryPagination.pageSize) => {
    try {
      let url = '/api/indicators/summary';
      const params = new URLSearchParams();
      const targetProductId = productId !== null ? productId : filterProductId;
      if (targetProductId && targetProductId !== 'all' && targetProductId !== '') {
        params.append('product_id', targetProductId);
      }
      params.append('page', page);
      params.append('page_size', pageSize);
      const queryString = params.toString();
      if (queryString) {
        url += '?' + queryString;
      }
      const data = await window.apiFetch(url);
      if (data.data) {
        setSummaryList(data.data);
        // 更新分页信息
        setSummaryPagination({
          page: data.page || 1,
          pageSize: data.page_size || 20,
          total: data.total || 0,
          totalPages: data.total_pages || 1
        });
      }
    } catch (error) {
      console.error('获取指标汇总失败:', error);
      toast.push('获取指标汇总失败', 'error');
    }
  };

  // 获取指标历史列表（wrtb_info_indicator_history）
  const fetchHistoryList = async (productId = null, page = pagination.page, pageSize = pagination.pageSize) => {
    try {
      // 根据tab选择不同的API：净值指标用/indicators，策略指标用/strategy-indicators
      const isStrategyTab = activeTab === 'strategy-calculate';
      let url = isStrategyTab ? '/api/strategy-indicators/history/list' : '/api/indicators/history/list';
      const params = new URLSearchParams();
      const targetProductId = productId !== null && productId !== undefined ? productId : filterProductId;
      console.log('fetchHistoryList called:', { productId, filterProductId, targetProductId, page, pageSize, isStrategyTab, url });
      if (targetProductId && targetProductId !== 'all' && targetProductId !== '') {
        params.append('product_id', targetProductId);
      }
      if (filterDate) {
        params.append('date', filterDate);
      }
      params.append('page', page);
      params.append('page_size', pageSize);
      const queryString = params.toString();
      if (queryString) {
        url += '?' + queryString;
      }
      console.log('Fetching URL:', url);
      const data = await window.apiFetch(url);
      if (data.data) {
        setHistoryList(data.data);
        // 更新分页信息
        setPagination({
          page: data.page || 1,
          pageSize: data.page_size || 20,
          total: data.total || 0,
          totalPages: data.total_pages || 1
        });
      }
    } catch (error) {
      console.error('获取指标历史失败:', error);
      toast.push('获取指标历史失败', 'error');
    }
  };

  // 获取时序数据（用于图表展示）
  const fetchTimeSeries = async (productId) => {
    try {
      const data = await window.apiFetch(`/api/indicators/history/${productId}`);
      if (data.data) {
        setTimeSeries(data.data);
      }
    } catch (error) {
      console.error('获取时序数据失败:', error);
      toast.push('获取时序数据失败', 'error');
    }
  };

  // 计算指标
  const calculateIndicator = async () => {
    setCalculating(true);
    try {
      let url = '/api/indicators/calculate/batch';
      let options = {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        }
      };
      
      const params = new URLSearchParams();
      if (filterProductId && filterProductId !== 'all') {
        url = `/api/indicators/calculate/${filterProductId}`;
      }
      if (filterDate) {
        params.append('end_date', filterDate);
      }
      if (resetAll) {
        params.append('reset_all', 'true');
      }
      
      const queryString = params.toString();
      if (queryString) {
        url += '?' + queryString;
      }
      
      const data = await window.apiFetch(url, options);
      if (data.success) {
        toast.push(data.message || '计算完成', 'success');
        await fetchHistoryList();
        await fetchSummary();
        if (selectedProduct) {
          await fetchTimeSeries(selectedProduct.productId);
        }
      } else {
        toast.push(data.message || '计算失败', 'error');
      }
    } catch (error) {
      console.error('计算指标失败:', error);
      toast.push('计算指标失败: ' + (error.message || '未知错误'), 'error');
    } finally {
      setCalculating(false);
    }
  };

  // 同步指标到汇总表
  const syncIndicator = async () => {
    setCalculating(true);
    try {
      let url = '/api/indicators/sync/batch';
      let options = {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        }
      };
      
      if (filterProductId && filterProductId !== 'all') {
        url = `/api/indicators/sync/${filterProductId}`;
      }
      
      const data = await window.apiFetch(url, options);
      if (data.success) {
        toast.push(`同步完成，成功 ${data.success_count} 条`, 'success');
        await fetchSummary();
      } else {
        toast.push(data.message || '同步失败', 'error');
      }
    } catch (error) {
      console.error('同步指标失败:', error);
      toast.push('同步指标失败: ' + (error.message || '未知错误'), 'error');
    } finally {
      setCalculating(false);
    }
  };

  // 计算策略指标
  const calculateStrategyIndicator = async () => {
    setCalculating(true);
    try {
      let url = '/api/strategy-indicators/calculate/batch';
      let options = {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        }
      };
      
      const params = new URLSearchParams();
      if (filterProductId && filterProductId !== 'all') {
        url = `/api/strategy-indicators/calculate/${filterProductId}`;
      }
      if (filterDate) {
        params.append('end_date', filterDate);
      }
      if (resetAll) {
        params.append('reset_all', 'true');
      }
      
      const queryString = params.toString();
      if (queryString) {
        url += '?' + queryString;
      }
      
      const data = await window.apiFetch(url, options);
      if (data.success) {
        toast.push(data.message || '策略指标计算完成', 'success');
        await fetchHistoryList();
        await fetchSummary();
      } else {
        toast.push(data.message || '策略指标计算失败', 'error');
      }
    } catch (error) {
      console.error('计算策略指标失败:', error);
      toast.push('计算策略指标失败: ' + (error.message || '未知错误'), 'error');
    } finally {
      setCalculating(false);
    }
  };

  // 同步策略指标到汇总表
  const syncStrategyIndicator = async () => {
    setCalculating(true);
    try {
      let url = '/api/strategy-indicators/sync/batch';
      let options = {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        }
      };
      
      if (filterProductId && filterProductId !== 'all') {
        url = `/api/strategy-indicators/sync/${filterProductId}`;
      }
      
      const data = await window.apiFetch(url, options);
      if (data.success) {
        toast.push(`策略指标同步完成，成功 ${data.success_count} 条`, 'success');
        await fetchSummary();
      } else {
        toast.push(data.message || '策略指标同步失败', 'error');
      }
    } catch (error) {
      console.error('同步策略指标失败:', error);
      toast.push('同步策略指标失败: ' + (error.message || '未知错误'), 'error');
    } finally {
      setCalculating(false);
    }
  };

  // 初始化
  useEffect(() => {
    fetchProductList();
    fetchSummary();
    fetchHistoryList();
  }, []);

  // 选择产品
  const selectProduct = async (item) => {
    setSelectedProduct(item);
    await fetchTimeSeries(item.productId);
  };

  // 格式化百分比
  const formatPct = (value) => {
    if (value === null || value === undefined) return '-';
    return (value * 100).toFixed(2) + '%';
  };

  // 格式化数值
  const formatNum = (value, decimals = 4) => {
    if (value === null || value === undefined) return '-';
    return value.toFixed(decimals);
  };

  // 获取值的样式
  const getValueClass = (value, inverse = false) => {
    if (value === null || value === undefined) return '';
    if (value > 0) {
      return inverse ? 'num danger' : 'num';
    } else if (value < 0) {
      return inverse ? 'num' : 'num danger';
    }
    return 'num';
  };

  // 渲染tab内容
  const renderTabContent = () => {
    if (activeTab === 'calculate') {
      return (
        <div className="card">
          <div className="card-header">
            <h3>指标历史数据</h3>
            <span style={{ fontSize: 13, color: 'var(--fg-3)' }}>(数据来源: wrtb_info_indicator_history)</span>
          </div>
          <div className="card-body">
            <div className="batch-table-wrapper">
              <table className="batch-table">
                <thead>
                  <tr>
                    <th>产品ID</th>
                    <th>产品名称</th>
                    <th>统计日期</th>
                    <th>最新净值</th>
                    <th>累计收益</th>
                    <th>年化收益</th>
                    <th>当前回撤</th>
                    <th>最大回撤</th>
                    <th>年化波动</th>
                    <th>夏普比率</th>
                    <th>卡玛比率</th>
                  </tr>
                </thead>
                <tbody>
                  {historyList.length === 0 ? (
                    <tr>
                      <td colSpan="11" className="empty-state">
                        暂无数据，请先计算指标
                      </td>
                    </tr>
                  ) : (
                    historyList.map((item) => (
                      <tr
                        key={`${item.product_id}-${item.date}`}
                        onClick={() => selectProduct({ productId: item.product_id, productName: item.product_name })}
                        style={{
                          cursor: 'pointer',
                          background: selectedProduct?.productId === item.product_id ? 'var(--bg)' : 'transparent'
                        }}
                      >
                        <td style={{ fontWeight: 500 }}>{item.product_id}</td>
                        <td>{item.product_name || '-'}</td>
                        <td>{item.date || '-'}</td>
                        <td className="num">{formatNum(item.latest_nav, 4)}</td>
                        <td className={getValueClass(item.cumulative_return)}>{formatPct(item.cumulative_return)}</td>
                        <td className={getValueClass(item.annual_return)}>{formatPct(item.annual_return)}</td>
                        <td className={getValueClass(item.current_drawdown, true)}>{formatPct(item.current_drawdown)}</td>
                        <td className={getValueClass(item.max_drawdown, true)}>{formatPct(item.max_drawdown)}</td>
                        <td className="num">{formatPct(item.annual_volatility)}</td>
                        <td className="num">{formatNum(item.sharpe, 2)}</td>
                        <td className="num">{formatNum(item.calmar, 2)}</td>
                      </tr>
                    ))
                  )}
                </tbody>
              </table>
            </div>
            
            {/* 分页控件 */}
            {historyList.length > 0 && (
              <div className="pagination-container">
                <div className="pagination-info">
                  共 {pagination.total} 条记录，当前第 {pagination.page} / {pagination.totalPages} 页
                </div>
                <div className="pagination-controls">
                  <button
                    className="pagination-btn"
                    onClick={() => fetchHistoryList(null, Math.max(1, pagination.page - 1))}
                    disabled={pagination.page <= 1}
                  >
                    上一页
                  </button>
                  <span className="pagination-current">
                    第 {pagination.page} 页
                  </span>
                  <button
                    className="pagination-btn"
                    onClick={() => fetchHistoryList(null, Math.min(pagination.totalPages, pagination.page + 1))}
                    disabled={pagination.page >= pagination.totalPages}
                  >
                    下一页
                  </button>
                  <div className="pagination-page-size">
                    <span>每页</span>
                    <select
                      value={pagination.pageSize}
                      onChange={(e) => {
                        const newPageSize = parseInt(e.target.value);
                        setPagination(prev => ({ ...prev, pageSize: newPageSize, page: 1 }));
                        fetchHistoryList(null, 1, newPageSize);
                      }}
                    >
                      <option value={10}>10</option>
                      <option value={20}>20</option>
                      <option value={50}>50</option>
                      <option value={100}>100</option>
                    </select>
                    <span>条</span>
                  </div>
                </div>
              </div>
            )}
          </div>
        </div>
      );
    } else if (activeTab === 'sync') {
      return (
        <div className="card">
          <div className="card-header">
            <h3>指标汇总数据</h3>
            <span style={{ fontSize: 13, color: 'var(--fg-3)' }}>(数据来源: wrtb_info_indicator)</span>
          </div>
          <div className="card-body">
            <div className="batch-table-wrapper">
              <table className="batch-table">
                <thead>
                  <tr>
                    <th>产品ID</th>
                    <th>产品名称</th>
                    <th>最新日期</th>
                    <th>最新净值</th>
                    <th>累计收益</th>
                    <th>年化收益</th>
                    <th>当前回撤</th>
                    <th>最大回撤</th>
                    <th>年化波动</th>
                    <th>夏普比率</th>
                    <th>卡玛比率</th>
                    <th>操作</th>
                  </tr>
                </thead>
                <tbody>
                  {summaryList.length === 0 ? (
                    <tr>
                      <td colSpan="12" className="empty-state">
                        暂无数据，请先同步指标
                      </td>
                    </tr>
                  ) : (
                    summaryList.map((item) => (
                      <tr
                        key={item.product_id}
                        onClick={() => selectProduct({ productId: item.product_id, productName: item.product_name })}
                        style={{
                          cursor: 'pointer',
                          background: selectedProduct?.productId === item.product_id ? 'var(--bg)' : 'transparent'
                        }}
                      >
                        <td style={{ fontWeight: 500 }}>{item.product_id}</td>
                        <td>{item.product_name || '-'}</td>
                        <td>{item.latest_date || '-'}</td>
                        <td className="num">{formatNum(item.latest_nav, 4)}</td>
                        <td className={getValueClass(item.cumulative_return)}>{formatPct(item.cumulative_return)}</td>
                        <td className={getValueClass(item.annual_return)}>{formatPct(item.annual_return)}</td>
                        <td className={getValueClass(item.current_drawdown, true)}>{formatPct(item.current_drawdown)}</td>
                        <td className={getValueClass(item.max_drawdown, true)}>{formatPct(item.max_drawdown)}</td>
                        <td className="num">{formatPct(item.annual_volatility)}</td>
                        <td className="num">{formatNum(item.sharpe, 2)}</td>
                        <td className="num">{formatNum(item.calmar, 2)}</td>
                        <td>
                          <button
                            className="btn btn-sm"
                            onClick={(e) => {
                              e.stopPropagation();
                              setFilterProductId(item.product_id);
                              syncIndicator();
                            }}
                            disabled={calculating}
                          >
                            重同步
                          </button>
                        </td>
                      </tr>
                    ))
                  )}
                </tbody>
              </table>
            </div>
            
            {/* 分页控件 */}
            {summaryList.length > 0 && (
              <div className="pagination-container">
                <div className="pagination-info">
                  共 {summaryPagination.total} 条记录，当前第 {summaryPagination.page} / {summaryPagination.totalPages} 页
                </div>
                <div className="pagination-controls">
                  <button
                    className="pagination-btn"
                    onClick={() => fetchSummary(null, Math.max(1, summaryPagination.page - 1))}
                    disabled={summaryPagination.page <= 1}
                  >
                    上一页
                  </button>
                  <span className="pagination-current">
                    第 {summaryPagination.page} 页
                  </span>
                  <button
                    className="pagination-btn"
                    onClick={() => fetchSummary(null, Math.min(summaryPagination.totalPages, summaryPagination.page + 1))}
                    disabled={summaryPagination.page >= summaryPagination.totalPages}
                  >
                    下一页
                  </button>
                  <div className="pagination-page-size">
                    <span>每页</span>
                    <select
                      value={summaryPagination.pageSize}
                      onChange={(e) => {
                        const newPageSize = parseInt(e.target.value);
                        setSummaryPagination(prev => ({ ...prev, pageSize: newPageSize, page: 1 }));
                        fetchSummary(null, 1, newPageSize);
                      }}
                    >
                      <option value={10}>10</option>
                      <option value={20}>20</option>
                      <option value={50}>50</option>
                      <option value={100}>100</option>
                    </select>
                    <span>条</span>
                  </div>
                </div>
              </div>
            )}
          </div>
        </div>
      );
    } else if (activeTab === 'strategy-calculate') {
      return (
        <div className="card">
          <div className="card-header">
            <h3>策略指标历史数据</h3>
            <span style={{ fontSize: 13, color: 'var(--fg-3)' }}>(数据来源: wrtb_info_indicator_history)</span>
          </div>
          <div className="card-body">
            <div className="batch-table-wrapper">
              <table className="batch-table">
                <thead>
                  <tr>
                    <th>产品ID</th>
                    <th>产品名称</th>
                    <th>统计日期</th>
                    <th>单期最大调仓</th>
                    <th>累计调仓幅度</th>
                    <th>策略集中度HHI</th>
                    <th>平均现金仓位</th>
                    <th>最新现金仓位</th>
                  </tr>
                </thead>
                <tbody>
                  {historyList.length === 0 ? (
                    <tr>
                      <td colSpan="8" className="empty-state">
                        暂无数据，请先计算策略指标
                      </td>
                    </tr>
                  ) : (
                    historyList.map((item) => (
                      <tr
                        key={`${item.product_id}-${item.date}`}
                        onClick={() => selectProduct({ productId: item.product_id, productName: item.product_name })}
                        style={{
                          cursor: 'pointer',
                          background: selectedProduct?.productId === item.product_id ? 'var(--bg)' : 'transparent'
                        }}
                      >
                        <td style={{ fontWeight: 500 }}>{item.product_id}</td>
                        <td>{item.product_name || '-'}</td>
                        <td>{item.date || '-'}</td>
                        <td className="num">{formatPct(item.max_single_adjustment)}</td>
                        <td className="num">{formatPct(item.cumulative_turnover)}</td>
                        <td className="num">{formatNum(item.hhi, 4)}</td>
                        <td className="num">{formatPct(item.average_cash_weight)}</td>
                        <td className="num">{formatPct(item.latest_cash_weight)}</td>
                      </tr>
                    ))
                  )}
                </tbody>
              </table>
            </div>
            
            {/* 分页控件 */}
            {historyList.length > 0 && (
              <div className="pagination-container">
                <div className="pagination-info">
                  共 {pagination.total} 条记录，当前第 {pagination.page} / {pagination.totalPages} 页
                </div>
                <div className="pagination-controls">
                  <button
                    className="pagination-btn"
                    onClick={() => fetchHistoryList(null, Math.max(1, pagination.page - 1))}
                    disabled={pagination.page <= 1}
                  >
                    上一页
                  </button>
                  <span className="pagination-current">
                    第 {pagination.page} 页
                  </span>
                  <button
                    className="pagination-btn"
                    onClick={() => fetchHistoryList(null, Math.min(pagination.totalPages, pagination.page + 1))}
                    disabled={pagination.page >= pagination.totalPages}
                  >
                    下一页
                  </button>
                  <div className="pagination-page-size">
                    <span>每页</span>
                    <select
                      value={pagination.pageSize}
                      onChange={(e) => {
                        const newPageSize = parseInt(e.target.value);
                        setPagination(prev => ({ ...prev, pageSize: newPageSize, page: 1 }));
                        fetchHistoryList(null, 1, newPageSize);
                      }}
                    >
                      <option value={10}>10</option>
                      <option value={20}>20</option>
                      <option value={50}>50</option>
                      <option value={100}>100</option>
                    </select>
                    <span>条</span>
                  </div>
                </div>
              </div>
            )}
          </div>
        </div>
      );
    } else {
      return (
        <div className="card">
          <div className="card-header">
            <h3>策略指标汇总数据</h3>
            <span style={{ fontSize: 13, color: 'var(--fg-3)' }}>(数据来源: wrtb_info_indicator)</span>
          </div>
          <div className="card-body">
            <div className="batch-table-wrapper">
              <table className="batch-table">
                <thead>
                  <tr>
                    <th>产品ID</th>
                    <th>产品名称</th>
                    <th>最新日期</th>
                    <th>单期最大调仓</th>
                    <th>累计调仓幅度</th>
                    <th>策略集中度HHI</th>
                    <th>平均现金仓位</th>
                    <th>最新现金仓位</th>
                    <th>操作</th>
                  </tr>
                </thead>
                <tbody>
                  {summaryList.length === 0 ? (
                    <tr>
                      <td colSpan="9" className="empty-state">
                        暂无数据，请先同步策略指标
                      </td>
                    </tr>
                  ) : (
                    summaryList.map((item) => (
                      <tr
                        key={item.product_id}
                        onClick={() => selectProduct({ productId: item.product_id, productName: item.product_name })}
                        style={{
                          cursor: 'pointer',
                          background: selectedProduct?.productId === item.product_id ? 'var(--bg)' : 'transparent'
                        }}
                      >
                        <td style={{ fontWeight: 500 }}>{item.product_id}</td>
                        <td>{item.product_name || '-'}</td>
                        <td>{item.latest_date || '-'}</td>
                        <td className="num">{formatPct(item.max_single_adjustment)}</td>
                        <td className="num">{formatPct(item.cumulative_turnover)}</td>
                        <td className="num">{formatNum(item.hhi, 4)}</td>
                        <td className="num">{formatPct(item.average_cash_weight)}</td>
                        <td className="num">{formatPct(item.latest_cash_weight)}</td>
                        <td>
                          <button
                            className="btn btn-sm"
                            onClick={(e) => {
                              e.stopPropagation();
                              setFilterProductId(item.product_id);
                              syncStrategyIndicator();
                            }}
                            disabled={calculating}
                          >
                            重同步
                          </button>
                        </td>
                      </tr>
                    ))
                  )}
                </tbody>
              </table>
            </div>
            
            {/* 分页控件 */}
            {summaryList.length > 0 && (
              <div className="pagination-container">
                <div className="pagination-info">
                  共 {summaryPagination.total} 条记录，当前第 {summaryPagination.page} / {summaryPagination.totalPages} 页
                </div>
                <div className="pagination-controls">
                  <button
                    className="pagination-btn"
                    onClick={() => fetchSummary(null, Math.max(1, summaryPagination.page - 1))}
                    disabled={summaryPagination.page <= 1}
                  >
                    上一页
                  </button>
                  <span className="pagination-current">
                    第 {summaryPagination.page} 页
                  </span>
                  <button
                    className="pagination-btn"
                    onClick={() => fetchSummary(null, Math.min(summaryPagination.totalPages, summaryPagination.page + 1))}
                    disabled={summaryPagination.page >= summaryPagination.totalPages}
                  >
                    下一页
                  </button>
                  <div className="pagination-page-size">
                    <span>每页</span>
                    <select
                      value={summaryPagination.pageSize}
                      onChange={(e) => {
                        const newPageSize = parseInt(e.target.value);
                        setSummaryPagination(prev => ({ ...prev, pageSize: newPageSize, page: 1 }));
                        fetchSummary(null, 1, newPageSize);
                      }}
                    >
                      <option value={10}>10</option>
                      <option value={20}>20</option>
                      <option value={50}>50</option>
                      <option value={100}>100</option>
                    </select>
                    <span>条</span>
                  </div>
                </div>
              </div>
            )}
          </div>
        </div>
      );
    }
  };

  return (
    <div className="page-operation">
      {/* 操作栏 */}
      <div className="card operation-header-card" style={{ marginBottom: 16 }}>
        {/* Tab切换 */}
        <div className="tab-container">
          <button
            className={`tab-btn ${activeTab === 'calculate' ? 'active' : ''}`}
            onClick={() => {
              setActiveTab('calculate');
              fetchHistoryList();
            }}
          >
            净值指标计算
          </button>
          <button
            className={`tab-btn ${activeTab === 'sync' ? 'active' : ''}`}
            onClick={() => {
              setActiveTab('sync');
              fetchSummary();
            }}
          >
            净值指标同步
          </button>
          <button
            className={`tab-btn ${activeTab === 'strategy-calculate' ? 'active' : ''}`}
            onClick={() => {
              setActiveTab('strategy-calculate');
              fetchHistoryList();
            }}
          >
            策略指标计算
          </button>
          <button
            className={`tab-btn ${activeTab === 'strategy-sync' ? 'active' : ''}`}
            onClick={() => {
              setActiveTab('strategy-sync');
              fetchSummary();
            }}
          >
            策略指标同步
          </button>
        </div>

        {/* 筛选条件 */}
        <div className="filter-row" style={{ padding: '16px' }}>
          {/* 产品选择 */}
          <div className="filter-item">
            <label>产品列表</label>
            <select 
              className="input"
              value={filterProductId}
              onChange={(e) => {
                const newProductId = e.target.value;
                setFilterProductId(newProductId);
                if (activeTab === 'calculate') {
                  setPagination(prev => ({ ...prev, page: 1 }));
                  fetchHistoryList(newProductId, 1);
                } else {
                  setSummaryPagination(prev => ({ ...prev, page: 1 }));
                  fetchSummary(newProductId, 1);
                }
              }}
            >
              <option value="all">全部产品</option>
              {productList.map(p => (
                <option key={p.productId} value={p.productId}>
                  {p.productId} - {p.productName}
                </option>
              ))}
            </select>
          </div>
          
          {/* 净值日期（仅指标计算tab显示） */}
          {activeTab === 'calculate' && (
            <div className="filter-item">
              <label>净值日期</label>
              <div className="date-picker-wrapper">
                <input
                  type="date"
                  className="input date-picker"
                  value={filterDate}
                  onChange={(e) => {
                    setFilterDate(e.target.value);
                    setPagination(prev => ({ ...prev, page: 1 }));
                    fetchHistoryList(null, 1);
                  }}
                  placeholder="选择日期"
                />
                <span className="date-picker-icon">📅</span>
              </div>
            </div>
          )}
          
          {/* 重置复选框（仅指标计算和策略指标计算tab显示） */}
          {(activeTab === 'calculate' || activeTab === 'strategy-calculate') && (
            <div className="filter-item checkbox-wrap">
              <input
                type="checkbox"
                id="resetAll"
                checked={resetAll}
                onChange={(e) => setResetAll(e.target.checked)}
              />
              <label htmlFor="resetAll">数据全部重置</label>
              <span className="hint">(删除历史数据，重新计算所有日期)</span>
            </div>
          )}
          
          {/* 操作按钮 */}
          <div style={{ display: 'flex', gap: 12 }}>
            <button
              className="btn"
              onClick={() => {
                if (activeTab === 'calculate' || activeTab === 'strategy-calculate') {
                  setPagination(prev => ({ ...prev, page: 1 }));
                  fetchHistoryList(null, 1);
                } else {
                  setSummaryPagination(prev => ({ ...prev, page: 1 }));
                  fetchSummary(null, 1);
                }
              }}
            >
              查询
            </button>
            {activeTab === 'calculate' ? (
              <button
                className="btn btn-primary"
                onClick={calculateIndicator}
                disabled={calculating}
              >
                {calculating ? '计算中...' : '计算指标'}
              </button>
            ) : activeTab === 'sync' ? (
              <button
                className="btn btn-primary"
                onClick={syncIndicator}
                disabled={calculating}
              >
                {calculating ? '同步中...' : '同步指标'}
              </button>
            ) : activeTab === 'strategy-calculate' ? (
              <button
                className="btn btn-primary"
                onClick={calculateStrategyIndicator}
                disabled={calculating}
              >
                {calculating ? '计算中...' : '计算策略指标'}
              </button>
            ) : (
              <button
                className="btn btn-primary"
                onClick={syncStrategyIndicator}
                disabled={calculating}
              >
                {calculating ? '同步中...' : '同步策略指标'}
              </button>
            )}
          </div>
        </div>
      </div>

      {/* Tab内容 */}
      {renderTabContent()}

      {/* 时序数据展示 */}
      {selectedProduct && timeSeries.length > 0 && (
        <div style={{ marginTop: 16 }}>
          <div className="card">
            <div className="card-header">
              <h3>{selectedProduct.productId} - 时序指标</h3>
            </div>
            <div className="card-body">
              {/* 净值曲线 */}
              <div style={{ marginBottom: 24 }}>
                <h4 style={{ marginBottom: 12, fontSize: 14, color: 'var(--fg-2)' }}>净值曲线</h4>
                <LineChart
                  series={[
                    {
                      name: '净值',
                      color: '#0f5cff',
                      data: timeSeries.map(d => d.latest_nav)
                    }
                  ]}
                  dates={timeSeries.map(d => d.date)}
                  height={180}
                  format="nav"
                  showXLabels={true}
                />
              </div>

              {/* 回撤曲线 */}
              <div style={{ marginBottom: 24 }}>
                <h4 style={{ marginBottom: 12, fontSize: 14, color: 'var(--fg-2)' }}>回撤曲线</h4>
                <LineChart
                  series={[
                    {
                      name: '当前回撤',
                      color: '#e53e3e',
                      data: timeSeries.map(d => d.current_drawdown)
                    },
                    {
                      name: '最大回撤',
                      color: '#d69e2e',
                      data: timeSeries.map(d => d.max_drawdown)
                    }
                  ]}
                  dates={timeSeries.map(d => d.date)}
                  height={180}
                  format="pct"
                  showXLabels={true}
                />
              </div>

              {/* 收益曲线 */}
              <div style={{ marginBottom: 24 }}>
                <h4 style={{ marginBottom: 12, fontSize: 14, color: 'var(--fg-2)' }}>收益曲线</h4>
                <LineChart
                  series={[
                    {
                      name: '累计收益',
                      color: '#38a169',
                      data: timeSeries.map(d => d.cumulative_return)
                    }
                  ]}
                  dates={timeSeries.map(d => d.date)}
                  height={180}
                  format="pct"
                  showXLabels={true}
                />
              </div>

              {/* 风险指标 */}
              <div>
                <h4 style={{ marginBottom: 12, fontSize: 14, color: 'var(--fg-2)' }}>风险指标</h4>
                <LineChart
                  series={[
                    {
                      name: '年化波动',
                      color: '#dd6b20',
                      data: timeSeries.map(d => d.annual_volatility)
                    },
                    {
                      name: '夏普比率',
                      color: '#3182ce',
                      data: timeSeries.map(d => d.sharpe)
                    },
                    {
                      name: '卡玛比率',
                      color: '#2f855a',
                      data: timeSeries.map(d => d.calmar)
                    }
                  ]}
                  dates={timeSeries.map(d => d.date)}
                  height={180}
                  format="num"
                  showXLabels={true}
                />
              </div>
            </div>
          </div>
        </div>
      )}

      {/* 温馨提示 - 计算逻辑说明 */}
      <div className="card" style={{ marginTop: 16 }}>
        <div className="card-body" style={{ padding: '12px 16px', background: 'var(--bg-secondary)', borderRadius: '8px' }}>
          <div style={{ fontSize: 13, color: 'var(--fg-3)' }}>
            <strong>温馨提示：</strong>
            <div style={{ margin: '8px 0 0 0', lineHeight: '1.6' }}>
              <p><strong>指标计算：</strong></p>
              <ul style={{ margin: '4px 0 0 20px', padding: 0 }}>
                <li>如果产品选择"全部"且日期为空：计算所有产品，从历史数据最后日期到当前日期</li>
                <li>如果选择特定产品：仅计算该产品的指标</li>
                <li>如果选择日期：计算指定日期的数据</li>
                <li>如果勾选"数据全部重置"：删除历史数据，从产品最早日期重新计算到当前</li>
              </ul>
              <p style={{ marginTop: 8 }}><strong>指标同步：</strong></p>
              <ul style={{ margin: '4px 0 0 20px', padding: 0 }}>
                <li>将 wrtb_info_indicator_history 表中的最新数据同步到 wrtb_info_indicator 表</li>
                <li>支持按产品筛选，同步单个产品或全部产品</li>
              </ul>
              <p style={{ marginTop: 8 }}><strong>数据来源：</strong></p>
              <ul style={{ margin: '4px 0 0 20px', padding: 0 }}>
                <li><code>wrtb_info_indicator_history</code>：产品每日指标历史数据（时序数据）</li>
                <li><code>wrtb_info_indicator</code>：产品最新指标汇总数据</li>
              </ul>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

window.PageOperationIndicator = PageOperationIndicator;
