/**
 * ShopXO 适配器
 * 
 * ShopXO是国内流行的开源PHP商城系统
 * 支持从 ShopXO 免费版/付费版 迁移到 LiteMall
 * 
 * 关键表:
 *   goods → 商品
 *   goods_category → 分类
 *   user → 用户
 *   goods_spec_base → SKU规格
 */

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

const TABLE_MAP = {
  'goods': 'products',
  'goods_category': 'categories',
  'user': 'users',
};

const FIELD_MAP = {
  products: {
    id: 'id',
    title: 'name',
    simple_desc: 'description',
    seo_keywords: 'seo_keywords',
    price: 'price',
    min_price: null,
    max_price: null,
    original_price: 'original_price',
    inventory: 'stock',
    sales_count: 'sales',
    images: { target: 'image', transform: v => Array.isArray(v) ? v[0] : (typeof v === 'string' ? v.split(',')[0] : v) },
    photo_count: null,
    is_home_recommended: { target: 'is_recommend', transform: v => v === 1 ? 1 : 0 },
    is_shelves: { target: 'status', transform: v => v === 1 ? 1 : 0 },
    sort: 'sort',
    category_id: 'category_id',
    add_time: { target: 'created_at', transform: v => v ? new Date(v * 1000).toISOString() : null },
    up_time: { target: 'updated_at', transform: v => v ? new Date(v * 1000).toISOString() : null },
  },
  
  categories: {
    id: 'id',
    pid: 'pid',
    name: 'name',
    sort: 'sort',
    is_enable: { target: 'status', transform: v => v === 1 ? 1 : 0 },
    icon: 'icon',
  },
  
  users: {
    id: 'id',
    nickname: 'nickname',
    mobile: 'phone',
    avatar: 'avatar',
    level_id: 'level_id',
    balance: 'balance',
    integral: 'points',
    status: 'status',
    add_time: { target: 'created_at', transform: v => v ? new Date(v * 1000).toISOString() : null },
    login_time: { target: 'updated_at', transform: v => v ? new Date(v * 1000).toISOString() : null },
  },
};

class ShopXOAdapter extends PlatformAdapter {
  constructor() {
    super({
      name: 'shopxo',
      label: 'ShopXO 免费版/付费版',
      version: '1.0',
      description: '支持ShopXO开源版商品/分类/用户数据迁移',
      icon: '🛍️',
      formats: ['sql', 'json'],
    });
    
    this.tableIdentifiers = [
      'shopxo_goods',
      'goods_category',
      'shopxo_user',
      'CREATE TABLE IF NOT EXISTS \\`goods\\`',
    ];
  }

  detect(input) {
    const content = input.content || '';
    if (!content) return 0;
    
    let score = 0;
    
    if (input.type === 'sql') {
      if (content.includes('CREATE TABLE `goods`') || content.includes('INSERT INTO `goods`')) {
        score += 0.3;
      }
      if (content.includes('CREATE TABLE `goods_category`') || content.includes('INSERT INTO `goods_category`')) {
        score += 0.2;
      }
      if (content.includes('CREATE TABLE `user`') && content.includes('mobile') && content.includes('nickname')) {
        score += 0.2;
      }
      // ShopXO特征：goods表有inventory字段（CRMEB叫stock）
      if (content.includes('`inventory`') && content.includes('`goods`')) {
        score += 0.3;
      }
    }
    
    if (input.type === 'json') {
      try {
        const data = JSON.parse(content);
        if (data.products?.[0]?.inventory !== undefined) score += 0.3;
        if (data.products?.[0]?.simple_desc !== undefined) score += 0.2;
      } catch (e) { /* ignore */ }
    }
    
    if (content.includes('"source":"ShopXO"') || content.includes("'source':'ShopXO'")) {
      score = 1;
    }
    
    return Math.min(score, 1);
  }

  async convert(input) {
    if (input.type === 'sql') {
      return this._convertFromSql(input.content);
    } else if (input.type === 'json') {
      return this._convertFromJson(input.content);
    }
    throw new Error('不支持的输入格式');
  }

  _convertFromSql(sqlContent) {
    const data = { products: [], categories: [], users: [] };
    const tables = this._parseSqlTables(sqlContent);

    // 转换分类
    const catRows = tables['goods_category'] || tables['shopxo_goods_category'] || [];
    for (const row of catRows) {
      const cat = {};
      for (const [srcKey, target] of Object.entries(FIELD_MAP.categories)) {
        if (row[srcKey] !== undefined) {
          if (typeof target === 'string') cat[target] = row[srcKey];
          else if (target?.transform) cat[target.target] = target.transform(row[srcKey]);
        }
      }
      data.categories.push(cat);
    }

    // 转换商品
    const prodRows = tables['goods'] || tables['shopxo_goods'] || [];
    for (const row of prodRows) {
      const product = {};
      for (const [srcKey, target] of Object.entries(FIELD_MAP.products)) {
        if (target && row[srcKey] !== undefined) {
          if (typeof target === 'string') product[target] = row[srcKey];
          else if (target.transform) product[target.target] = target.transform(row[srcKey]);
        }
      }
      
      // 处理图片: ShopXO的images可能是逗号分隔
      if (row.images) {
        const imgs = typeof row.images === 'string' ? row.images.split(',') : 
                     Array.isArray(row.images) ? row.images : [];
        if (imgs.length > 0 && !product.image) product.image = imgs[0];
        product.images = imgs.join(',');
      }
      
      // 处理description
      if (!product.description && row.seo_description) {
        product.description = row.seo_description;
      }
      
      data.products.push(product);
    }

    // 转换用户
    const userRows = tables['user'] || tables['shopxo_user'] || [];
    for (const row of userRows) {
      const user = {};
      for (const [srcKey, target] of Object.entries(FIELD_MAP.users)) {
        if (target && row[srcKey] !== undefined) {
          if (typeof target === 'string') user[target] = row[srcKey];
          else if (target.transform) user[target.target] = target.transform(row[srcKey]);
        }
      }
      data.users.push(user);
    }

    return this._buildResult(data);
  }

  _convertFromJson(jsonContent) {
    let source;
    try { source = JSON.parse(jsonContent); } catch (e) { throw new Error('JSON解析失败'); }
    
    if (source.manifest && source.data) return source;
    
    const data = {
      products: source.products || [],
      categories: source.categories || [],
      users: source.users || [],
      productSkus: source.productSkus || [],
    };
    return this._buildResult(data);
  }

  _buildResult(data) {
    const now = new Date().toISOString();
    for (const p of data.products) { if (!p.created_at) p.created_at = now; if (!p.updated_at) p.updated_at = now; if (!p.status) p.status = 1; }
    for (const c of data.categories) { if (!c.created_at) c.created_at = now; }
    for (const u of data.users) { if (!u.created_at) u.created_at = now; if (!u.password) u.password = '$2b$10$default'; }
    
    // 生成productImages
    const productImages = [];
    for (const p of data.products) {
      let imgList = [];
      const rawImages = p.images || p.slider_image || p.photos || '';
      try { imgList = JSON.parse(rawImages); } catch(e) { imgList = String(rawImages).split(',').filter(Boolean); }
      imgList.forEach((url, idx) => { if (idx > 0 && url) productImages.push({ product_id: p.id, url: url.trim(), type: 0, sort: idx }); });
    }
    data.productImages = productImages;

    return {
      manifest: {
        migrationVersion: '1.0.0',
        exportId: `shopxo_import_${Date.now()}`,
        exportedAt: now,
        source: 'ShopXO',
        sourceVersion: '*',
        adapter: 'shopxo-v1.0',
        stats: {
          products: data.products.length,
          categories: data.categories.length,
          users: data.users.length,
          skus: data.productSkus?.length || 0,
          productImages: productImages.length,
        },
      },
      data,
    };
  }

  _parseSqlTables(sql) {
    const tables = {};
    const insertRegex = /INSERT\s+INTO\s+`?(\w+)`?\s*(?:\([^)]*\))?\s*VALUES\s*(.*?)(?:;|$)/gims;
    
    for (const match of sql.matchAll(insertRegex)) {
      const tableName = match[1];
      if (!tables[tableName]) tables[tableName] = [];
      
      const valuesStr = match[2];
      const rowRegex = /\(([^)]*)\)\s*(?:,|$)/g;
      let rowMatch;
      while ((rowMatch = rowRegex.exec(valuesStr)) !== null) {
        tables[tableName].push(this._parseRow(rowMatch[1]));
      }
    }
    return tables;
  }

  _parseRow(str) {
    const values = this._parseValues(str);
    // 简单按位置转对象，列名从create table获取或使用默认
    const obj = {};
    const keys = ['id', 'title', 'simple_desc', 'images', 'price', 'original_price', 'inventory', 'sales_count', 'is_shelves', 'sort', 'category_id', 'add_time'];
    for (let i = 0; i < keys.length && i < values.length; i++) {
      obj[keys[i]] = values[i];
    }
    return obj;
  }

  _parseValues(str) {
    const values = [];
    let current = '';
    let inString = false;
    let stringChar = '';
    
    for (let i = 0; i < str.length; i++) {
      const ch = str[i];
      if (!inString) {
        if (ch === "'" || ch === '"') { inString = true; stringChar = ch; current += ch; }
        else if (ch === ',') { values.push(current.trim()); current = ''; }
        else { current += ch; }
      } else {
        if (ch === '\\') { current += ch + (str[i + 1] || ''); i++; }
        else if (ch === stringChar) { inString = false; current += ch; }
        else { current += ch; }
      }
    }
    if (current.trim()) values.push(current.trim());
    
    return values.map(v => {
      v = v.trim();
      if ((v.startsWith("'") && v.endsWith("'")) || (v.startsWith('"') && v.endsWith('"'))) {
        return v.slice(1, -1).replace(/\\'/g, "'");
      }
      if (v === 'NULL' || v === '') return null;
      const num = Number(v);
      return isNaN(num) ? v : num;
    });
  }

  getHelp() {
    return `
<h4>从ShopXO导出数据</h4>
<p><b>通过phpMyAdmin/宝塔导出SQL：</b></p>
<ol>
  <li>登录宝塔面板 → 数据库 → 找到ShopXO数据库</li>
  <li>点击"导出" → 选择"自定义" → 勾选 goods, goods_category, user 表</li>
  <li>下载SQL文件，在本页上传</li>
</ol>
    `.trim();
  }

  getFieldMap() { return FIELD_MAP; }
}

module.exports = ShopXOAdapter;
