/**
 * [MOCK-013] 商品管理模块DataSource
 * AI注意: 这是Mock实现，不是真实业务逻辑
 * 仅在USE_MOCK=true时启用 */

import moment from 'moment';
import { BaseDataSource, DataSourceFactory } from './baseDataSource';

export interface Product {
  id: string;
  sku: string;
  name: string;
  image: string;
  category: string;
  price: number;
  costPrice: number;
  profit: number;
  roi: number;
  stock: number;
  status: 'DRAFT' | 'PRICED' | 'LISTED' | 'SYNCING' | 'LIVE' | 'SYNC_FAILED' | 'OFFLINE';
  platformStatus: Record<string, string>;
  shopId: string;
  shopName: string;
  platform: string;
  createdAt: string;
  updatedAt: string;
}

export interface Shop {
  id: string;
  name: string;
  platform: string;
  status: 'ACTIVE' | 'INACTIVE' | 'SUSPENDED';
  region: string;
  currency: string;
}

export interface ProductFilter {
  keyword?: string;
  status?: string[];
  platform?: string[];
  shop?: string[];
  category?: string[];
  priceRange?: [number, number];
  stockRange?: [number, number];
  roiRange?: [number, number];
  dateRange?: any;
  minProfit?: number;
  minStock?: number;
  searchInDescription?: boolean;
}

export interface ProductSort {
  field: string;
  order: 'ascend' | 'descend' | null;
}

export interface ProductDataSource {
  fetchProducts(filter?: ProductFilter, sort?: ProductSort): Promise<Product[]>;
  getProduct(id: string): Promise<Product | null>;
  createProduct(product: Omit<Product, 'id' | 'createdAt' | 'updatedAt'>): Promise<Product>;
  updateProduct(id: string, product: Partial<Product>): Promise<Product | null>;
  deleteProduct(id: string): Promise<boolean>;
  duplicateProduct(id: string): Promise<Product>;
  updateProductStatus(id: string, status: Product['status']): Promise<Product | null>;
  syncProduct(id: string): Promise<Product | null>;
  fetchShops(): Promise<Shop[]>;
  getPlatformStats(): Promise<Record<string, { total: number; live: number; pending: number; failed: number }>>;
}

const PLATFORMS = [
  'TikTok', 'TikTokFull',
  'Shopee', 'ShopeeFull', 'ShopeeLight',
  'Lazada', 'LazadaFull',
  'TemuFull',
  'Shein', 'SheinHalf',
  'Ozon', 'Yandex', 'AliExpress', 'AliExpressHalf', 'AliExpressPop',
  'Coupang', 'Walmart', 'Wildberries', 'Allegro', 'MercadoLibre',
  'Jumia', 'Joom', 'Amazon', 'Wish', 'Emag', 'Miravia',
  'Daraz', 'Joybuy', 'Alibaba', 'Qoo10', 'Shopify', 'Shoplazza',
  'ShopyyV1', 'ShopyyV2', 'Shopline', 'GreatBoss', 'Other',
  'eBay',
];

const CATEGORIES = ['工业自动化', '电子元器件', '工具设备', '仪器仪表', '安防设备'];

const SHOPS: Shop[] = [
  { id: 'shop-tiktok-1', name: 'TikTok旗舰店A', platform: 'TikTok', status: 'ACTIVE', region: '中国', currency: 'CNY' },
  { id: 'shop-tiktok-2', name: 'TikTok旗舰店B', platform: 'TikTok', status: 'ACTIVE', region: '美国', currency: 'USD' },
  { id: 'shop-tiktok-3', name: 'TikTok精品店C', platform: 'TikTok', status: 'ACTIVE', region: '欧洲', currency: 'EUR' },
  { id: 'shop-tiktok-4', name: 'TikTok精品店D', platform: 'TikTok', status: 'INACTIVE', region: '东南亚', currency: 'SGD' },
  { id: 'shop-shopee-1', name: 'Shopee官方店A', platform: 'Shopee', status: 'ACTIVE', region: '东南亚', currency: 'SGD' },
  { id: 'shop-shopee-2', name: 'Shopee官方店B', platform: 'Shopee', status: 'ACTIVE', region: '台湾', currency: 'TWD' },
  { id: 'shop-shopee-3', name: 'Shopee旗舰店C', platform: 'Shopee', status: 'ACTIVE', region: '马来西亚', currency: 'MYR' },
  { id: 'shop-shopee-4', name: 'Shopee旗舰店D', platform: 'Shopee', status: 'SUSPENDED', region: '菲律宾', currency: 'PHP' },
  { id: 'shop-lazada-1', name: 'Lazada官方店A', platform: 'Lazada', status: 'ACTIVE', region: '东南亚', currency: 'SGD' },
  { id: 'shop-lazada-2', name: 'Lazada官方店B', platform: 'Lazada', status: 'ACTIVE', region: '泰国', currency: 'THB' },
  { id: 'shop-lazada-3', name: 'Lazada旗舰店C', platform: 'Lazada', status: 'ACTIVE', region: '越南', currency: 'VND' },
  { id: 'shop-amazon-1', name: 'Amazon美国店A', platform: 'Amazon', status: 'ACTIVE', region: '美国', currency: 'USD' },
  { id: 'shop-amazon-2', name: 'Amazon美国店B', platform: 'Amazon', status: 'ACTIVE', region: '美国', currency: 'USD' },
  { id: 'shop-amazon-3', name: 'Amazon欧洲店C', platform: 'Amazon', status: 'ACTIVE', region: '欧洲', currency: 'EUR' },
  { id: 'shop-amazon-4', name: 'Amazon欧洲店D', platform: 'Amazon', status: 'ACTIVE', region: '英国', currency: 'GBP' },
  { id: 'shop-amazon-5', name: 'Amazon日本店E', platform: 'Amazon', status: 'ACTIVE', region: '日本', currency: 'JPY' },
  { id: 'shop-ebay-1', name: 'eBay全球店A', platform: 'eBay', status: 'ACTIVE', region: '全球', currency: 'USD' },
  { id: 'shop-ebay-2', name: 'eBay全球店B', platform: 'eBay', status: 'ACTIVE', region: '欧洲', currency: 'EUR' },
  { id: 'shop-ebay-3', name: 'eBay美国店C', platform: 'eBay', status: 'ACTIVE', region: '美国', currency: 'USD' },
  { id: 'shop-shopify-1', name: 'Shopify独立站A', platform: 'Shopify', status: 'ACTIVE', region: '全球', currency: 'USD' },
  { id: 'shop-shopify-2', name: 'Shopify独立站B', platform: 'Shopify', status: 'ACTIVE', region: '欧洲', currency: 'EUR' },
  { id: 'shop-shopify-3', name: 'Shopify独立站C', platform: 'Shopify', status: 'ACTIVE', region: '亚洲', currency: 'CNY' },
  { id: 'shop-temu-1', name: 'Temu旗舰店A', platform: 'Temu', status: 'ACTIVE', region: '美国', currency: 'USD' },
  { id: 'shop-temu-2', name: 'Temu旗舰店B', platform: 'Temu', status: 'ACTIVE', region: '欧洲', currency: 'EUR' },
  { id: 'shop-temu-3', name: 'Temu旗舰店C', platform: 'Temu', status: 'ACTIVE', region: '澳大利亚', currency: 'AUD' },
  { id: 'shop-shein-1', name: 'SHEIN官方店A', platform: 'Shein', status: 'ACTIVE', region: '全球', currency: 'USD' },
  { id: 'shop-shein-2', name: 'SHEIN官方店B', platform: 'Shein', status: 'ACTIVE', region: '欧洲', currency: 'EUR' },
  { id: 'shop-shein-3', name: 'SHEIN官方店C', platform: 'Shein', status: 'ACTIVE', region: '中东', currency: 'AED' },
  { id: 'shop-ozon-1', name: 'Ozon旗舰店A', platform: 'Ozon', status: 'ACTIVE', region: '俄罗斯', currency: 'RUB' },
  { id: 'shop-ali-1', name: '速卖通旗舰店A', platform: 'AliExpress', status: 'ACTIVE', region: '全球', currency: 'USD' },
  { id: 'shop-walmart-1', name: 'Walmart旗舰店A', platform: 'Walmart', status: 'ACTIVE', region: '美国', currency: 'USD' },
];

const MOCK_PRODUCTS: Product[] = [
  {
    id: '1',
    sku: 'TP-TEMP-001',
    name: '工业温度传感器 Pro',
    image: 'https://via.placeholder.com/80x80?text=Product',
    category: '工业自动化',
    price: 89.99,
    costPrice: 45.00,
    profit: 44.99,
    roi: 99.98,
    stock: 256,
    status: 'LIVE',
    platformStatus: { Amazon: 'LIVE', eBay: 'LIVE', Shopee: 'PENDING' },
    shopId: 'shop-amazon-1',
    shopName: 'Amazon美国店',
    platform: 'Amazon',
    createdAt: '2025-12-15',
    updatedAt: '2026-03-18',
  },
  {
    id: '2',
    sku: 'TP-PRES-002',
    name: '压力传感器 Digital',
    image: 'https://via.placeholder.com/80x80?text=Product',
    category: '工业自动化',
    price: 129.99,
    costPrice: 65.00,
    profit: 64.99,
    roi: 99.98,
    stock: 128,
    status: 'DRAFT',
    platformStatus: {},
    shopId: 'shop-tiktok-1',
    shopName: 'TikTok旗舰店',
    platform: 'TikTok',
    createdAt: '2026-03-10',
    updatedAt: '2026-03-10',
  },
  {
    id: '3',
    sku: 'TP-FLOW-003',
    name: '流量计 Ultra',
    image: 'https://via.placeholder.com/80x80?text=Product',
    category: '仪器仪表',
    price: 299.99,
    costPrice: 150.00,
    profit: 149.99,
    roi: 99.99,
    stock: 64,
    status: 'PRICED',
    platformStatus: {},
    shopId: 'shop-shopee-1',
    shopName: 'Shopee官方店',
    platform: 'Shopee',
    createdAt: '2026-03-15',
    updatedAt: '2026-03-16',
  },
  {
    id: '4',
    sku: 'TP-MOTR-004',
    name: '步进电机 57型',
    image: 'https://via.placeholder.com/80x80?text=Product',
    category: '工业自动化',
    price: 59.99,
    costPrice: 30.00,
    profit: 29.99,
    roi: 99.97,
    stock: 512,
    status: 'LISTED',
    platformStatus: { Amazon: 'LISTED' },
    shopId: 'shop-amazon-2',
    shopName: 'Amazon欧洲店',
    platform: 'Amazon',
    createdAt: '2026-03-01',
    updatedAt: '2026-03-17',
  },
  {
    id: '5',
    sku: 'TP-CTRL-005',
    name: 'PLC控制器 Mini',
    image: 'https://via.placeholder.com/80x80?text=Product',
    category: '工业自动化',
    price: 199.99,
    costPrice: 100.00,
    profit: 99.99,
    roi: 99.99,
    stock: 32,
    status: 'SYNCING',
    platformStatus: { Amazon: 'SYNCING', eBay: 'SYNCING' },
    shopId: 'shop-ebay-1',
    shopName: 'eBay全球店',
    platform: 'eBay',
    createdAt: '2026-03-18',
    updatedAt: '2026-03-18',
  },
  {
    id: '6',
    sku: 'TP-SENS-006',
    name: '光电传感器',
    image: 'https://via.placeholder.com/80x80?text=Product',
    category: '工业自动化',
    price: 39.99,
    costPrice: 20.00,
    profit: 19.99,
    roi: 99.95,
    stock: 0,
    status: 'SYNC_FAILED',
    platformStatus: { Amazon: 'FAILED' },
    shopId: 'shop-temu-1',
    shopName: 'Temu旗舰店',
    platform: 'Temu',
    createdAt: '2026-03-05',
    updatedAt: '2026-03-18',
  },
  {
    id: '7',
    sku: 'TP-VALV-007',
    name: '电磁阀 24V',
    image: 'https://via.placeholder.com/80x80?text=Product',
    category: '工具设备',
    price: 79.99,
    costPrice: 40.00,
    profit: 39.99,
    roi: 99.98,
    stock: 200,
    status: 'OFFLINE',
    platformStatus: { Amazon: 'OFFLINE', eBay: 'OFFLINE' },
    shopId: 'shop-shein-1',
    shopName: 'SHEIN官方店',
    platform: 'Shein',
    createdAt: '2025-11-20',
    updatedAt: '2026-02-28',
  },
];

export class ProductDataSourceImpl extends BaseDataSource implements ProductDataSource {
  private products: Product[] = MOCK_PRODUCTS;

  async fetchProducts(filter?: ProductFilter, sort?: ProductSort): Promise<Product[]> {
    try {
      await this.delay(300);
      let filtered = [...this.products];

      // 应用筛选条件
      if (filter) {
        if (filter.keyword) {
          const keywordLower = filter.keyword.toLowerCase();
          filtered = filtered.filter(product => 
            product.name.toLowerCase().includes(keywordLower) || 
            product.sku.toLowerCase().includes(keywordLower)
          );
        }

        if (filter.status && filter.status.length > 0) {
          filtered = filtered.filter(product => filter.status!.includes(product.status));
        }

        if (filter.category && filter.category.length > 0) {
          filtered = filtered.filter(product => filter.category!.includes(product.category));
        }

        if (filter.shop && filter.shop.length > 0) {
          filtered = filtered.filter(product => filter.shop!.includes(product.shopId));
        }

        if (filter.priceRange) {
          const [min, max] = filter.priceRange;
          filtered = filtered.filter(product => product.price >= min && product.price <= max);
        }

        if (filter.stockRange) {
          const [min, max] = filter.stockRange;
          filtered = filtered.filter(product => product.stock >= min && product.stock <= max);
        }

        if (filter.roiRange) {
          const [min, max] = filter.roiRange;
          filtered = filtered.filter(product => product.roi >= min && product.roi <= max);
        }

        if (filter.minProfit !== undefined) {
          filtered = filtered.filter(product => product.profit >= filter.minProfit!);
        }

        if (filter.minStock !== undefined) {
          filtered = filtered.filter(product => product.stock >= filter.minStock!);
        }
      }

      // 应用排序
      if (sort && sort.field) {
        filtered.sort((a, b) => {
          const field = sort.field as keyof Product;
          const aValue = a[field];
          const bValue = b[field];
          
          if (sort.order === 'ascend') {
            return aValue > bValue ? 1 : -1;
          } else {
            return aValue < bValue ? 1 : -1;
          }
        });
      }

      return filtered;
    } catch (error) {
      return this.handleError(error, []);
    }
  }

  async getProduct(id: string): Promise<Product | null> {
    try {
      await this.delay(200);
      const product = this.products.find(p => p.id === id);
      return product || null;
    } catch (error) {
      return this.handleError(error, null);
    }
  }

  async createProduct(product: Omit<Product, 'id' | 'createdAt' | 'updatedAt'>): Promise<Product> {
    try {
      await this.delay(500);
      const newProduct: Product = {
        ...product,
        id: `${Date.now()}`,
        createdAt: moment().format('YYYY-MM-DD'),
        updatedAt: moment().format('YYYY-MM-DD'),
      };
      this.products.unshift(newProduct);
      return newProduct;
    } catch (error) {
      throw error;
    }
  }

  async updateProduct(id: string, product: Partial<Product>): Promise<Product | null> {
    try {
      await this.delay(300);
      const index = this.products.findIndex(p => p.id === id);
      if (index === -1) {
        return null;
      }
      
      this.products[index] = {
        ...this.products[index],
        ...product,
        updatedAt: moment().format('YYYY-MM-DD'),
      };
      
      return this.products[index];
    } catch (error) {
      return this.handleError(error, null);
    }
  }

  async deleteProduct(id: string): Promise<boolean> {
    try {
      await this.delay(200);
      const initialLength = this.products.length;
      this.products = this.products.filter(p => p.id !== id);
      return this.products.length < initialLength;
    } catch (error) {
      return this.handleError(error, false);
    }
  }

  async duplicateProduct(id: string): Promise<Product> {
    try {
      await this.delay(500);
      const originalProduct = this.products.find(p => p.id === id);
      if (!originalProduct) {
        throw new Error('Product not found');
      }
      
      const newProduct: Product = {
        ...originalProduct,
        id: `${Date.now()}`,
        sku: `${originalProduct.sku}-COPY`,
        name: `${originalProduct.name} (复制)`,
        status: 'DRAFT',
        platformStatus: {},
        createdAt: moment().format('YYYY-MM-DD'),
        updatedAt: moment().format('YYYY-MM-DD'),
      };
      
      this.products.unshift(newProduct);
      return newProduct;
    } catch (error) {
      throw error;
    }
  }

  async updateProductStatus(id: string, status: Product['status']): Promise<Product | null> {
    return this.updateProduct(id, { status });
  }

  async syncProduct(id: string): Promise<Product | null> {
    try {
      // 先设置为同步中
      await this.updateProductStatus(id, 'SYNCING');
      
      // 模拟同步过程
      await this.delay(2000);
      
      // 随机决定同步是否成功
      const success = Math.random() > 0.3;
      const status = success ? 'LIVE' : 'SYNC_FAILED';
      
      return this.updateProductStatus(id, status);
    } catch (error) {
      console.error('Failed to sync product:', error);
      return this.updateProductStatus(id, 'SYNC_FAILED');
    }
  }

  async fetchShops(): Promise<Shop[]> {
    try {
      await this.delay(200);
      return SHOPS;
    } catch (error) {
      return this.handleError(error, []);
    }
  }

  async getPlatformStats(): Promise<Record<string, { total: number; live: number; pending: number; failed: number }>> {
    try {
      await this.delay(300);
      const stats: Record<string, { total: number; live: number; pending: number; failed: number }> = {
        all: { total: this.products.length, live: 0, pending: 0, failed: 0 },
        unpublished: { total: 0, live: 0, pending: 0, failed: 0 },
      };
      
      PLATFORMS.forEach(platform => {
        stats[platform] = { total: 0, live: 0, pending: 0, failed: 0 };
      });
      
      this.products.forEach(product => {
        const platforms = Object.keys(product.platformStatus);
        if (platforms.length === 0) {
          stats.unpublished.total++;
        }
        platforms.forEach(platform => {
          if (!stats[platform]) {
            stats[platform] = { total: 0, live: 0, pending: 0, failed: 0 };
          }
          stats[platform].total++;
          const status = product.platformStatus[platform];
          if (status === 'LIVE') {
            stats[platform].live++;
            stats.all.live++;
          } else if (status === 'PENDING' || status === 'SYNCING' || status === 'LISTED') {
            stats[platform].pending++;
            stats.all.pending++;
          } else if (status === 'FAILED' || status === 'SYNC_FAILED') {
            stats[platform].failed++;
            stats.all.failed++;
          }
        });
      });
      
      return stats;
    } catch (error) {
      return this.handleError(error, {
        all: { total: 0, live: 0, pending: 0, failed: 0 },
        unpublished: { total: 0, live: 0, pending: 0, failed: 0 },
      });
    }
  }
}

export const productDataSource = new ProductDataSourceImpl();
DataSourceFactory.register('product', productDataSource);