// 风控服务
import { generateFutureData, futuresList } from '../utils/mockData';

// 获取止损建议
export const fetchStopLossAdvice = async (symbol: string) => {
  // 模拟API请求延迟
  await new Promise(resolve => setTimeout(resolve, 300));
  const future = futuresList.find(item => item.code === symbol);
  if (!future) {
    throw new Error('品种不存在');
  }
  const data = generateFutureData(symbol, future.name);
  
  return {
    stop_loss_price: data.tradingAdvice.stopLoss,
    strategy: ['固定止损', '移动止损', '波动率止损'][Math.floor(Math.random() * 3)],
    reasoning: `基于${data.volatility}波动率和${data.riskLevel}风险等级，建议设置止损位在${data.tradingAdvice.stopLoss.toFixed(2)}`
  };
};

// 获取仓位建议
export const fetchPositionAdvice = async (capital: number, risk_tolerance: string, symbols: string[]) => {
  // 模拟API请求延迟
  await new Promise(resolve => setTimeout(resolve, 400));
  
  // 根据风险承受能力计算仓位比例
  const riskMultiplier = risk_tolerance === 'high' ? 0.05 : risk_tolerance === 'medium' ? 0.03 : 0.01;
  
  const positions = symbols.map(symbol => {
    const future = futuresList.find(item => item.code === symbol);
    if (!future) return null;
    
    const positionPercentage = +(Math.random() * 20 + 5).toFixed(2);
    const positionAmount = capital * positionPercentage / 100;
    
    return {
      symbol,
      percentage: positionPercentage,
      amount: positionAmount,
      reasoning: `基于${risk_tolerance}风险承受能力，建议配置${positionPercentage}%的仓位`
    };
  }).filter(Boolean);
  
  return { positions };
};

// 获取换月预警
export const fetchRolloverAlerts = async () => {
  // 模拟API请求延迟
  await new Promise(resolve => setTimeout(resolve, 200));
  
  const alerts = [
    { symbol: 'RB', expiration_date: '2026-05-15', days_left: 15, recommendation: '建议开始移仓' },
    { symbol: 'SC', expiration_date: '2026-06-20', days_left: 30, recommendation: '关注换月' },
    { symbol: 'CU', expiration_date: '2026-04-20', days_left: 5, recommendation: '紧急移仓' },
    { symbol: 'MA', expiration_date: '2026-05-10', days_left: 10, recommendation: '建议移仓' }
  ];
  
  return alerts;
};

// 获取风险评估
export const fetchRiskAssessment = async (symbol: string) => {
  // 模拟API请求延迟
  await new Promise(resolve => setTimeout(resolve, 300));
  const future = futuresList.find(item => item.code === symbol);
  if (!future) {
    throw new Error('品种不存在');
  }
  
  const riskLevel = ['低', '中等', '高'][Math.floor(Math.random() * 3)];
  const volatility = +(Math.random() * 10 + 5).toFixed(2);
  const liquidity = +(Math.random() * 50 + 50).toFixed(2);
  
  return {
    risk_level: riskLevel,
    volatility: volatility,
    liquidity: liquidity,
    reasoning: `该品种风险等级为${riskLevel}，波动率为${volatility}%，流动性良好，适合${riskLevel === '高' ? '激进' : riskLevel === '中等' ? '稳健' : '保守'}型投资者`
  };
};