/**
 * 拼多多 适配器
 * 
 * 支持从拼多多商家后台导出的CSV数据迁移到LiteMall
 * 
 * 导入方式:
 *   1. 拼多多商家后台 → 商品管理 → 导出商品数据 → CSV
 *   2. JSON格式
 */

const PlatformAdapter = require('../adapter');

class PinduoduoAdapter extends PlatformAdapter {
  constructor() {
    super({
      name: 'pinduoduo',
      label: '拼多多',
      version: '1.0',
      description: '从拼多多商家后台导入商品数据（支持CSV导出格式）',
      icon: '🔴',
      formats: ['csv', 'json'],
    });
    
    // 拼多多CSV字段 → LiteMall字段映射
    this.csvFieldMap = {
      // 商品名称
      '商品名称': 'name',
      'goods_name': 'name',
      'name': 'name',
      'goodsName': 'name',
      
      // 价格
      '商品价格': { target: 'price', transform: v => parseFloat(v) || 0 },
      '单买价': { target: 'price', transform: v => parseFloat(v) || 0 },
      '拼单价': { target: 'original_price', transform: v => parseFloat(v) || 0 },
      '原价': { target: 'original_price', transform: v => parseFloat(v) || 0 },
      'market_price': { target: 'original_price', transform: v => parseFloat(v) || 0 },
      'min_group_price': { target: 'original_price', transform: v => parseFloat(v) || 0 },
      'price': { target: 'price', transform: v => parseFloat(v) || 0 },
      
      // 成本价
      '成本价': { target: 'cost_price', transform: v => parseFloat(v) || 0 },
      'cost_price': { target: 'cost_price', transform: v => parseFloat(v) || 0 },
      
      // 库存
      '库存': { target: 'stock', transform: v => parseInt(v) || 0 },
      '库存数量': { target: 'stock', transform: v => parseInt(v) || 0 },
      'quantity': { target: 'stock', transform: v => parseInt(v) || 0 },
      'stock': { target: 'stock', transform: v => parseInt(v) || 0 },
      
      // 销量
      '已售': { target: 'sales', transform: v => parseInt(v) || 0 },
      '销量': { target: 'sales', transform: v => parseInt(v) || 0 },
      'sold_quantity': { target: 'sales', transform: v => parseInt(v) || 0 },
      'sales': { target: 'sales', transform: v => parseInt(v) || 0 },
      
      // 图片
      '商品主图': { target: 'image', transform: v => (v || '').split('|')[0] || (v || '').split(',')[0] },
      '主图链接': { target: 'image', transform: v => (v || '').split('|')[0] || (v || '').split(',')[0] },
      '主图': { target: 'image', transform: v => (v || '').split('|')[0] || (v || '').split(',')[0] },
      '缩略图': { target: 'image', transform: v => (v || '').split('|')[0] },
      'thumb_url': { target: 'image', transform: v => (v || '').split('|')[0] },
      
      '商品轮播图': { target: 'images', transform: v => (v || '').replace(/\|/g, ',').replace(/【/g, '').replace(/】/g, ',') },
      'banner': { target: 'images', transform: v => (v || '').replace(/\|/g, ',') },
      
      // 分类
      '分类ID': 'category_id',
      '商品分类': 'category_id',
      'cat_id': 'category_id',
      'category_id': 'category_id',
      
      // 描述
      '商品描述': 'description',
      '详情': 'description',
      'goods_desc': 'description',
      'description': 'description',
      
      // 规格/单位
      '单位': 'unit',
      'sku': null,
      
      // ID
      '商品ID': 'id',
      'goods_id': 'id',
      'id': 'id',
    };
  }

  detect(input) {
    const content = input.content || '';
    if (!content) return 0;
    let score = 0;
    
    if (input.type === 'csv') {
      const firstLine = content.split('\n')[0] || '';
      const pddSignals = ['商品名称', '商品价格', '拼单价', '单买价', '商品主图', 
                          'goods_name', 'min_group_price', '已售'];
      for (const sig of pddSignals) {
        if (firstLine.includes(sig)) {
          score += 0.15;
        }
      }
      // 拼多多CSV特征：同时包含"拼单价"和"单买价"
      if (firstLine.includes('拼单价') || firstLine.includes('单买价')) {
        score += 0.3;
      }
    }
    
    if (input.type === 'json') {
      try {
        const data = JSON.parse(content);
        if (data.source === 'pinduoduo' || data.source === '拼多多') score = 1;
        if (Array.isArray(data) && data[0]?.min_group_price !== undefined) score += 0.3;
        if (Array.isArray(data) && data[0]?.goods_name && data[0]?.min_group_price) score += 0.3;
      } catch (e) { /* ignore */ }
    }
    
    return Math.min(score, 1);
  }

  async convert(input) {
    if (input.type === 'csv') return this._convertFromCsv(input.content);
    if (input.type === 'json') return this._convertFromJson(input.content);
    throw new Error('不支持的格式: ' + input.type + '，仅支持csv和json');
  }

  _convertFromCsv(csvContent) {
    const products = [];
    const lines = csvContent.split('\n').filter(l => l.trim());
    if (lines.length < 2) throw new Error('CSV数据至少需要标题行+1行数据');
    
    // 检测分隔符
    const firstLine = lines[0];
    const delimiter = firstLine.includes('\t') ? '\t' : ',';
    
    // 解析标题行
    const headers = this._parseCsvLine(firstLine, delimiter);
    
    // 建立映射
    const fieldIndex = {};
    for (let i = 0; i < headers.length; i++) {
      const h = headers[i].trim();
      if (this.csvFieldMap[h]) {
        fieldIndex[i] = this.csvFieldMap[h];
      }
    }
    
    // 解析数据行
    for (let rowIdx = 1; rowIdx < lines.length; rowIdx++) {
      const values = this._parseCsvLine(lines[rowIdx], delimiter);
      const product = {
        status: 1,
        unit: '件',
        stock: 0,
        price: 0,
        created_at: new Date().toISOString(),
        updated_at: new Date().toISOString(),
      };
      
      for (let i = 0; i < values.length; i++) {
        const mapping = fieldIndex[i];
        if (!mapping) continue;
        const value = values[i]?.trim() || '';
        
        if (typeof mapping === 'string') {
          if (mapping) product[mapping] = value;
        } else if (mapping.transform) {
          product[mapping.target] = mapping.transform(value);
        }
      }
      
      if (product.images && !product.image) {
        const parts = product.images.split(',').filter(Boolean);
        product.image = parts[0] || '';
      }
      
      if (product.name) {
        products.push(product);
      }
    }
    
    const now = new Date().toISOString();
    return {
      manifest: {
        migrationVersion: '1.0.0',
        exportId: `pinduoduo_import_${Date.now()}`,
        exportedAt: now,
        source: '拼多多',
        adapter: 'pinduoduo-v1.0',
        stats: { products: products.length, categories: 0, users: 0 },
      },
      data: { products, categories: [], users: [], productSkus: [], productImages: [] },
    };
  }

  _convertFromJson(jsonContent) {
    let source;
    try { source = JSON.parse(jsonContent); } catch (e) { throw new Error('JSON解析失败'); }
    if (source.manifest && source.data) return source;
    
    const products = Array.isArray(source) ? source : (source.products || []);
    const now = new Date().toISOString();
    
    const mapped = products.map(p => ({
      id: p.goods_id || p.id,
      name: p.goods_name || p.name || '未命名商品',
      price: parseFloat(p.min_group_price || p.price || p.single_price || 0),
      original_price: parseFloat(p.market_price || p.original_price || 0),
      cost_price: parseFloat(p.cost_price || 0),
      stock: parseInt(p.quantity || p.stock || 0),
      sales: parseInt(p.sold_quantity || p.sales || 0),
      image: typeof p.thumb_url === 'string' ? p.thumb_url :
             (typeof p.image === 'string' ? p.image.split('|')[0] : ''),
      images: typeof p.banner === 'string' ? p.banner.replace(/\|/g, ',') :
              (typeof p.images === 'string' ? p.images.replace(/\|/g, ',') : ''),
      category_id: p.cat_id || p.category_id || '',
      description: p.goods_desc || p.description || '',
      status: p.status !== undefined ? p.status : 1,
      unit: '件',
      created_at: now,
      updated_at: now,
    }));
    
    return {
      manifest: {
        migrationVersion: '1.0.0',
        exportId: `pinduoduo_import_${Date.now()}`,
        exportedAt: now, source: '拼多多', adapter: 'pinduoduo-v1.0',
        stats: { products: mapped.length, categories: 0, users: 0 },
      },
      data: { products: mapped, categories: [], users: [], productSkus: [], productImages: [] },
    };
  }

  _parseCsvLine(line, delimiter) {
    const result = [];
    let current = '';
    let inQuotes = false;
    
    for (let i = 0; i < line.length; i++) {
      const ch = line[i];
      if (inQuotes) {
        if (ch === '"') {
          if (line[i + 1] === '"') { current += '"'; i++; }
          else { inQuotes = false; }
        } else {
          current += ch;
        }
      } else {
        if (ch === '"') { inQuotes = true; }
        else if (ch === delimiter) { result.push(current); current = ''; }
        else { current += ch; }
      }
    }
    result.push(current);
    return result;
  }

  getHelp() {
    return `
<h4>从拼多多导出数据</h4>

<p><b>方式一：拼多多商家后台导出（推荐）</b></p>
<ol>
  <li>登录拼多多商家后台（mms.pinduoduo.com）</li>
  <li>商品管理 → 商品列表 → 点击"导出"</li>
  <li>选择导出的商品 → 点击"导出CSV"</li>
  <li>下载CSV文件，在本页上传导入</li>
</ol>

<p><b>方式二：通过拼多多开放平台API</b></p>
<ol>
  <li>对接拼多多开放平台，调用 goods.list.get 接口</li>
  <li>将返回的JSON数据转为标准格式导入</li>
</ol>

<p><b>支持导入的字段：</b></p>
<ul>
  <li>✅ 商品名称</li>
  <li>✅ 拼单价 / 单买价</li>
  <li>✅ 库存数量</li>
  <li>✅ 主图 / 轮播图</li>
  <li>✅ 已售数量</li>
  <li>✅ 商品描述</li>
  <li>✅ 分类ID</li>
</ul>

<p><b>注意：</b></p>
<ul>
  <li>拼多多CSV通常用逗号分隔，系统自动识别</li>
  <li>部分图片链接可能带有时效，建议尽快导入</li>
  <li>等迁移后重新上传图片到本商城</li>
</ul>
    `.trim();
  }

  getFieldMap() { return this.csvFieldMap; }
}

module.exports = PinduoduoAdapter;
