/**
 * [MOCK-ANALYTICS-001] Analytics数据源抽象层
 * AI注意: 这是数据源抽象层，业务组件通过此层获取数据
 * 仅在REACT_APP_USE_MOCK=true时启用Mock
 * 
 * @module services/analyticsDataSource
 * @created 2026-03-19
 */

import { IDataSource, IMockDataSource } from '@/types/datasource';

// ============================================
// 类型定义
// ============================================

export interface MetricData {
  key: string;
  label: string;
  value: number;
  unit: string;
  change: number;
  changeType: 'up' | 'down' | 'neutral';
  icon: string;
  color: string;
}

export interface ChartData {
  date: string;
  sales: number;
  orders: number;
  visitors: number;
  conversion: number;
}

export interface ProductAnalytics {
  id: string;
  productId: string;
  name: string;
  image: string;
  category: string;
  sales: number;
  revenue: number;
  profit: number;
  profitMargin: number;
  views: number;
  conversionRate: number;
  returnRate: number;
  trend: 'up' | 'down' | 'stable';
}

export interface OrderAnalytics {
  id: string;
  orderId: string;
  platform: string;
  status: string;
  amount: number;
  profit: number;
  createdAt: string;
  customerType: 'new' | 'returning';
  shippingCost: number;
  platformFee: number;
}

export interface ProfitAnalytics {
  id: string;
  period: string;
  revenue: number;
  cost: number;
  grossProfit: number;
  netProfit: number;
  margin: number;
  platformFees: number;
  shippingCost: number;
  adSpend: number;
  otherCosts: number;
}

export interface RealtimeMetrics {
  timestamp: string;
  activeUsers: number;
  ordersPerMinute: number;
  revenuePerMinute: number;
  conversionRate: number;
}

export interface AlertRule {
  id: string;
  name: string;
  metric: string;
  condition: '>' | '<' | '=' | '>=' | '<=';
  threshold: number;
  enabled: boolean;
  notifyChannels: string[];
  lastTriggered?: string;
}

export interface Dashboard {
  id: string;
  name: string;
  widgets: Widget[];
  isDefault: boolean;
  createdAt: string;
}

export interface Widget {
  id: string;
  type: 'metric' | 'chart' | 'table' | 'alert';
  title: string;
  config: any;
  position: { x: number; y: number; w: number; h: number };
}

export interface AnalyticsQueryParams {
  startDate?: string;
  endDate?: string;
  shopId?: string;
  platform?: string;
}

export interface AnalyticsData {
  metrics: MetricData[];
  chartData: ChartData[];
  productAnalytics: ProductAnalytics[];
  orderAnalytics: OrderAnalytics[];
  profitAnalytics: ProfitAnalytics[];
  realtimeMetrics: RealtimeMetrics[];
  alertRules: AlertRule[];
  dashboards: Dashboard[];
}

// ============================================
// Analytics专用接口
// ============================================

export interface IAnalyticsDataSource {
  fetchAllData(params?: AnalyticsQueryParams): Promise<AnalyticsData>;
  fetchMetrics(): Promise<MetricData[]>;
  fetchChartData(): Promise<ChartData[]>;
  fetchProductAnalytics(): Promise<ProductAnalytics[]>;
  fetchOrderAnalytics(): Promise<OrderAnalytics[]>;
  fetchProfitAnalytics(): Promise<ProfitAnalytics[]>;
  fetchRealtimeData(): Promise<RealtimeMetrics[]>;
  fetchAlertRules(): Promise<AlertRule[]>;
  fetchDashboards(): Promise<Dashboard[]>;
  createAlertRule(data: Partial<AlertRule>): Promise<AlertRule>;
  updateAlertRule(id: string, data: Partial<AlertRule>): Promise<AlertRule>;
  deleteAlertRule(id: string): Promise<void>;
  toggleAlertRule(id: string, enabled: boolean): Promise<void>;
}

// ============================================
// API实现
// ============================================

class ApiAnalyticsDataSource implements IAnalyticsDataSource {
  async fetchAllData(params?: AnalyticsQueryParams): Promise<AnalyticsData> {
    const [metrics, chartData, productAnalytics, orderAnalytics, profitAnalytics, realtimeMetrics, alertRules, dashboards] = await Promise.all([
      this.fetchMetrics(),
      this.fetchChartData(),
      this.fetchProductAnalytics(),
      this.fetchOrderAnalytics(),
      this.fetchProfitAnalytics(),
      this.fetchRealtimeData(),
      this.fetchAlertRules(),
      this.fetchDashboards(),
    ]);
    return { metrics, chartData, productAnalytics, orderAnalytics, profitAnalytics, realtimeMetrics, alertRules, dashboards };
  }

  async fetchMetrics(): Promise<MetricData[]> {
    const response = await fetch('/api/v1/analytics/metrics');
    const result = await response.json();
    return result.data;
  }

  async fetchChartData(): Promise<ChartData[]> {
    const response = await fetch('/api/v1/analytics/chart');
    const result = await response.json();
    return result.data;
  }

  async fetchProductAnalytics(): Promise<ProductAnalytics[]> {
    const response = await fetch('/api/v1/analytics/products');
    const result = await response.json();
    return result.data;
  }

  async fetchOrderAnalytics(): Promise<OrderAnalytics[]> {
    const response = await fetch('/api/v1/analytics/orders');
    const result = await response.json();
    return result.data;
  }

  async fetchProfitAnalytics(): Promise<ProfitAnalytics[]> {
    const response = await fetch('/api/v1/analytics/profit');
    const result = await response.json();
    return result.data;
  }

  async fetchRealtimeData(): Promise<RealtimeMetrics[]> {
    const response = await fetch('/api/v1/analytics/realtime');
    const result = await response.json();
    return result.data;
  }

  async fetchAlertRules(): Promise<AlertRule[]> {
    const response = await fetch('/api/v1/analytics/alerts');
    const result = await response.json();
    return result.data;
  }

  async fetchDashboards(): Promise<Dashboard[]> {
    const response = await fetch('/api/v1/analytics/dashboards');
    const result = await response.json();
    return result.data;
  }

  async createAlertRule(data: Partial<AlertRule>): Promise<AlertRule> {
    const response = await fetch('/api/v1/analytics/alerts', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(data),
    });
    const result = await response.json();
    return result.data;
  }

  async updateAlertRule(id: string, data: Partial<AlertRule>): Promise<AlertRule> {
    const response = await fetch(`/api/v1/analytics/alerts/${id}`, {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(data),
    });
    const result = await response.json();
    return result.data;
  }

  async deleteAlertRule(id: string): Promise<void> {
    await fetch(`/api/v1/analytics/alerts/${id}`, { method: 'DELETE' });
  }

  async toggleAlertRule(id: string, enabled: boolean): Promise<void> {
    await fetch(`/api/v1/analytics/alerts/${id}/toggle`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ enabled }),
    });
  }
}

// ============================================
// Mock实现
// ============================================

/**
 * [MOCK] Analytics Mock数据源
 * AI注意: 这是Mock实现，不是真实业务逻辑
 * 仅在REACT_APP_USE_MOCK=true时启用
 */
class MockAnalyticsDataSource implements IAnalyticsDataSource, IMockDataSource {
  readonly __MOCK__ = true as const;
  readonly __MOCK_NAME__ = 'MockAnalyticsDataSource';

  private mockMetrics: MetricData[] = [
    { key: '1', label: '总销售额', value: 1285000, unit: '¥', change: 12.5, changeType: 'up', icon: 'DollarOutlined', color: '#52c41a' },
    { key: '2', label: '订单数量', value: 3256, unit: '单', change: 8.3, changeType: 'up', icon: 'ShoppingCartOutlined', color: '#1890ff' },
    { key: '3', label: '访客数量', value: 45680, unit: '人', change: -2.1, changeType: 'down', icon: 'TeamOutlined', color: '#722ed1' },
    { key: '4', label: '转化率', value: 7.12, unit: '%', change: 0.5, changeType: 'up', icon: 'FundOutlined', color: '#fa8c16' },
    { key: '5', label: '平均客单价', value: 394.5, unit: '¥', change: 3.8, changeType: 'up', icon: 'BarChartOutlined', color: '#13c2c2' },
    { key: '6', label: '净利润', value: 285600, unit: '¥', change: 15.2, changeType: 'up', icon: 'LineChartOutlined', color: '#eb2f96' },
  ];

  private mockAlertRules: AlertRule[] = [
    { id: '1', name: '销售额下降告警', metric: 'daily_revenue', condition: '<', threshold: 30000, enabled: true, notifyChannels: ['email', 'sms'], lastTriggered: '2026-03-17 08:00:00' },
    { id: '2', name: '转化率过低告警', metric: 'conversion_rate', condition: '<', threshold: 5, enabled: true, notifyChannels: ['email'], lastTriggered: '2026-03-16 14:30:00' },
    { id: '3', name: '库存不足告警', metric: 'inventory_level', condition: '<', threshold: 100, enabled: true, notifyChannels: ['email', 'app'], lastTriggered: '2026-03-18 09:00:00' },
    { id: '4', name: '退货率过高告警', metric: 'return_rate', condition: '>', threshold: 10, enabled: false, notifyChannels: ['email'], lastTriggered: undefined },
  ];

  private mockDashboards: Dashboard[] = [
    { id: '1', name: '默认看板', widgets: [], isDefault: true, createdAt: '2026-01-01' },
    { id: '2', name: '销售分析看板', widgets: [], isDefault: false, createdAt: '2026-02-15' },
    { id: '3', name: '利润监控看板', widgets: [], isDefault: false, createdAt: '2026-03-01' },
  ];

  async fetchAllData(params?: AnalyticsQueryParams): Promise<AnalyticsData> {
    await this.simulateDelay(300);
    const [metrics, chartData, productAnalytics, orderAnalytics, profitAnalytics, realtimeMetrics, alertRules, dashboards] = await Promise.all([
      this.fetchMetrics(),
      this.fetchChartData(),
      this.fetchProductAnalytics(),
      this.fetchOrderAnalytics(),
      this.fetchProfitAnalytics(),
      this.fetchRealtimeData(),
      this.fetchAlertRules(),
      this.fetchDashboards(),
    ]);
    return { metrics, chartData, productAnalytics, orderAnalytics, profitAnalytics, realtimeMetrics, alertRules, dashboards };
  }

  async fetchMetrics(): Promise<MetricData[]> {
    await this.simulateDelay(200);
    return [...this.mockMetrics];
  }

  async fetchChartData(): Promise<ChartData[]> {
    await this.simulateDelay(300);
    return Array.from({ length: 30 }, (_, i) => ({
      date: `2026-03-${String(i + 1).padStart(2, '0')}`,
      sales: Math.floor(Math.random() * 50000) + 30000,
      orders: Math.floor(Math.random() * 200) + 100,
      visitors: Math.floor(Math.random() * 2000) + 1000,
      conversion: parseFloat((Math.random() * 5 + 5).toFixed(2)),
    }));
  }

  async fetchProductAnalytics(): Promise<ProductAnalytics[]> {
    await this.simulateDelay(250);
    return [
      { id: '1', productId: 'PROD-001', name: 'Wireless Bluetooth Headphones', image: 'https://via.placeholder.com/60', category: 'Electronics', sales: 1250, revenue: 62500, profit: 18750, profitMargin: 30, views: 15000, conversionRate: 8.3, returnRate: 2.1, trend: 'up' },
      { id: '2', productId: 'PROD-002', name: 'Smart Watch Series 5', image: 'https://via.placeholder.com/60', category: 'Electronics', sales: 890, revenue: 178000, profit: 44500, profitMargin: 25, views: 12000, conversionRate: 7.4, returnRate: 3.2, trend: 'up' },
      { id: '3', productId: 'PROD-003', name: 'Portable Charger 20000mAh', image: 'https://via.placeholder.com/60', category: 'Electronics', sales: 2100, revenue: 42000, profit: 12600, profitMargin: 30, views: 25000, conversionRate: 8.4, returnRate: 1.8, trend: 'stable' },
      { id: '4', productId: 'PROD-004', name: 'Laptop Stand Aluminum', image: 'https://via.placeholder.com/60', category: 'Accessories', sales: 650, revenue: 32500, profit: 9750, profitMargin: 30, views: 8000, conversionRate: 8.1, returnRate: 2.5, trend: 'down' },
      { id: '5', productId: 'PROD-005', name: 'USB-C Hub 7-in-1', image: 'https://via.placeholder.com/60', category: 'Accessories', sales: 980, revenue: 49000, profit: 14700, profitMargin: 30, views: 11000, conversionRate: 8.9, returnRate: 2.0, trend: 'up' },
    ];
  }

  async fetchOrderAnalytics(): Promise<OrderAnalytics[]> {
    await this.simulateDelay(200);
    return [
      { id: '1', orderId: 'ORD-2026-001', platform: 'AMAZON', status: 'COMPLETED', amount: 299.99, profit: 89.99, createdAt: '2026-03-18 10:30:00', customerType: 'returning', shippingCost: 15, platformFee: 45 },
      { id: '2', orderId: 'ORD-2026-002', platform: 'EBAY', status: 'COMPLETED', amount: 159.99, profit: 47.99, createdAt: '2026-03-18 09:15:00', customerType: 'new', shippingCost: 12, platformFee: 24 },
      { id: '3', orderId: 'ORD-2026-003', platform: 'SHOPIFY', status: 'SHIPPED', amount: 499.99, profit: 149.99, createdAt: '2026-03-18 08:45:00', customerType: 'returning', shippingCost: 20, platformFee: 0 },
      { id: '4', orderId: 'ORD-2026-004', platform: 'SHOPEE', status: 'PENDING', amount: 89.99, profit: 26.99, createdAt: '2026-03-18 08:00:00', customerType: 'new', shippingCost: 8, platformFee: 13.5 },
      { id: '5', orderId: 'ORD-2026-005', platform: 'LAZADA', status: 'COMPLETED', amount: 199.99, profit: 59.99, createdAt: '2026-03-17 16:30:00', customerType: 'returning', shippingCost: 15, platformFee: 30 },
    ];
  }

  async fetchProfitAnalytics(): Promise<ProfitAnalytics[]> {
    await this.simulateDelay(200);
    return [
      { id: '1', period: '2026-03-18', revenue: 45000, cost: 28000, grossProfit: 17000, netProfit: 12500, margin: 27.8, platformFees: 2500, shippingCost: 1500, adSpend: 800, otherCosts: 200 },
      { id: '2', period: '2026-03-17', revenue: 52000, cost: 32000, grossProfit: 20000, netProfit: 14800, margin: 28.5, platformFees: 2900, shippingCost: 1800, adSpend: 950, otherCosts: 250 },
      { id: '3', period: '2026-03-16', revenue: 48000, cost: 30000, grossProfit: 18000, netProfit: 13200, margin: 27.5, platformFees: 2700, shippingCost: 1650, adSpend: 900, otherCosts: 220 },
      { id: '4', period: '2026-03-15', revenue: 55000, cost: 34000, grossProfit: 21000, netProfit: 15500, margin: 28.2, platformFees: 3100, shippingCost: 1900, adSpend: 1000, otherCosts: 280 },
      { id: '5', period: '2026-03-14', revenue: 42000, cost: 26000, grossProfit: 16000, netProfit: 11800, margin: 28.1, platformFees: 2350, shippingCost: 1400, adSpend: 750, otherCosts: 180 },
    ];
  }

  async fetchRealtimeData(): Promise<RealtimeMetrics[]> {
    await this.simulateDelay(100);
    return Array.from({ length: 10 }, (_, i) => ({
      timestamp: new Date(Date.now() - i * 60000).toISOString(),
      activeUsers: Math.floor(Math.random() * 500) + 200,
      ordersPerMinute: Math.floor(Math.random() * 20) + 5,
      revenuePerMinute: Math.floor(Math.random() * 2000) + 500,
      conversionRate: parseFloat((Math.random() * 3 + 4).toFixed(2)),
    }));
  }

  async fetchAlertRules(): Promise<AlertRule[]> {
    await this.simulateDelay(150);
    return [...this.mockAlertRules];
  }

  async fetchDashboards(): Promise<Dashboard[]> {
    await this.simulateDelay(100);
    return [...this.mockDashboards];
  }

  async createAlertRule(data: Partial<AlertRule>): Promise<AlertRule> {
    await this.simulateDelay(300);
    const newRule: AlertRule = {
      id: `${Date.now()}`,
      name: data.name || '',
      metric: data.metric || '',
      condition: data.condition || '<',
      threshold: data.threshold || 0,
      enabled: data.enabled ?? true,
      notifyChannels: data.notifyChannels || [],
    };
    this.mockAlertRules.push(newRule);
    return newRule;
  }

  async updateAlertRule(id: string, data: Partial<AlertRule>): Promise<AlertRule> {
    await this.simulateDelay(200);
    const index = this.mockAlertRules.findIndex(r => r.id === id);
    if (index === -1) throw new Error('Alert rule not found');
    this.mockAlertRules[index] = { ...this.mockAlertRules[index], ...data };
    return this.mockAlertRules[index];
  }

  async deleteAlertRule(id: string): Promise<void> {
    await this.simulateDelay(150);
    this.mockAlertRules = this.mockAlertRules.filter(r => r.id !== id);
  }

  async toggleAlertRule(id: string, enabled: boolean): Promise<void> {
    await this.simulateDelay(100);
    const index = this.mockAlertRules.findIndex(r => r.id === id);
    if (index !== -1) {
      this.mockAlertRules[index].enabled = enabled;
    }
  }

  private simulateDelay(ms: number): Promise<void> {
    return new Promise(resolve => setTimeout(resolve, ms));
  }
}

// ============================================
// 导出数据源实例
// ============================================

const useMock = process.env.REACT_APP_USE_MOCK === 'true';

export const analyticsDataSource: IAnalyticsDataSource = useMock
  ? new MockAnalyticsDataSource()
  : new ApiAnalyticsDataSource();

export const __MOCK__ = useMock;
export const __DATA_SOURCE_TYPE__ = useMock ? 'mock' : 'api';
