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

// CRMEB表名 → LiteMall表名 映射
const TABLE_MAP = {
  'eb_store_product': 'products',
  'eb_store_category': 'categories',
  'eb_user': 'users',
  'eb_store_order': 'orders',
  'eb_store_product_attr_value': 'product_skus',
  'eb_store_product_relation': null,
};

// CRMEB字段 → LiteMall字段 映射
const FIELD_MAP = {
  products: {
    id: 'id',
    store_name: 'name',
    store_info: 'subtitle',
    description: 'description',
    keyword: 'seo_keywords',
    price: 'price',
    ot_price: 'original_price',
    cost: 'cost_price',
    stock: 'stock',
    sales: 'sales',
    image: 'image',
    slider_image: 'images',
    cate_id: 'category_id',
    unit_name: 'unit',
    is_show: { target: 'status', transform: (v) => v === 1 ? 1 : 0 },
    is_new: { target: 'is_new', transform: (v) => v === 1 ? 1 : 0 },
    is_hot: { target: 'is_hot', transform: (v) => v === 1 ? 1 : 0 },
    is_best: { target: 'is_recommend', transform: (v) => v === 1 ? 1 : 0 },
    sort: 'sort',
    create_time: 'created_at',
    update_time: 'updated_at',
  },
  categories: {
    id: 'id', pid: 'pid', cate_name: 'name', sort: 'sort',
    is_show: { target: 'status', transform: v => v === 1 ? 1 : 0 },
    pic: 'icon',
    add_time: { target: 'created_at', transform: v => v ? new Date(v * 1000).toISOString() : null },
  },
  users: {
    uid: 'id', nickname: 'nickname', phone: 'phone', avatar: 'avatar',
    level: 'level_id', now_money: 'balance', integral: 'points', experience: 'experience',
    status: 'status',
    add_time: { target: 'created_at', transform: v => v ? new Date(v * 1000).toISOString() : null },
    last_login_time: { target: 'updated_at', transform: v => v ? new Date(v * 1000).toISOString() : null },
  },
  product_skus: {
    id: 'id', product_id: 'product_id', unique: 'sku_code', price: 'price',
    stock: 'stock', image: 'image', suk: 'specs', ot_price: 'original_price', cost: 'cost_price',
  },
};

class CrmeBAdapter extends PlatformAdapter {
  constructor() {
    super({
      name: 'crmeB', label: 'CRMEB 标准版 V6', version: '1.0',
      description: '支持CRMEB标准版及付费版商品/分类/用户数据迁移',
      icon: '🛒', formats: ['sql', 'json'],
    });
  }

  detect(input) {
    const content = input.content || '';
    if (!content) return 0;
    let score = 0;
    const identifiers = ["eb_store_product", "eb_store_category", "eb_user", "eb_wechat_user", "eb_store_product_attr_value"];
    if (input.type === 'sql') {
      for (const id of identifiers) {
        if (content.includes('CREATE TABLE `' + id + '`') || content.includes('INSERT INTO `' + id + '`')) score += 0.3;
      }
      if (score > 0.8) score = 1;
    }
    if (input.type === 'json') {
      try {
        const data = JSON.parse(content);
        if (data.products && data.products[0]?.store_name) score += 0.3;
      } catch (e) { /* ignore */ }
    }
    return Math.min(score, 1);
  }

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

  _convertFromSql(sqlContent) {
    const data = { products: [], categories: [], users: [], productSkus: [], productAttrs: [], productSpecs: [] };
    const tables = this._parseSqlTables(sqlContent);
    const now = new Date().toISOString();

    const tableKeys = Object.keys(tables);
    
    for (const tableName of tableKeys) {
      const rows = tables[tableName];
      if (!rows || rows.length === 0) continue;
      
      // 从第一行看有哪些列，智能判断这是什么表
      const firstRow = rows[0];
      const columns = Object.keys(firstRow || {});
      const colStr = columns.join(',');
      
      // 判断是否为商品表：必须包含store_name关键字段（不含price/stock等通用字段避免误判）
      const isProductTable = columns.includes('store_name');
        
      // 判断是否为分类表：有cate_name关键字段
      const isCategoryTable = columns.includes('cate_name');
      
      // 判断是否为用户表：有uid/nickname关键字段
      const isUserTable = columns.includes('uid') && (columns.includes('nickname') || columns.includes('phone'));
      
      // 判断是否为SKU表（排除订单/用户/杂项表避免误判）
      const isOrderLike = tableName.includes('order') || tableName.includes('cart_info');
      const isSkuTable = !isOrderLike && (columns.includes('suk')
        || (columns.includes('unique') && columns.includes('product_id') && columns.includes('price'))
        || (columns.includes('product_id') && columns.includes('price') && columns.includes('stock')
          && (tableName.includes('attr_value') || tableName.includes('sku'))));
      
      // 判断是否为规格属性定义表（CRMEB的eb_store_product_attr）
      const isAttrTable = columns.includes('attr_name') && columns.includes('attr_values') && columns.includes('product_id');
      
      // DEBUG: 记录各表分类情况
      if (isProductTable || isCategoryTable || isUserTable || isSkuTable) {
        console.log('[CRMEB] 表:', tableName, '=>', 
          isCategoryTable?'分类':isProductTable?'商品':isUserTable?'用户':'SKU',
          '列数:', columns.length, '行数:', rows.length);
        if (isSkuTable) console.log('[CRMEB] SKU表列名:', colStr);
      }

      // 分类
      if (isCategoryTable) {
        for (const row of rows) {
          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]);
            }
          }
          if (cat.name) data.categories.push(cat);
        }
      }
      // 商品
      else if (isProductTable) {
        if (rows.length > 0) {
          console.log('[CRMEB] 产品列名:', Object.keys(rows[0]).join(','));
          console.log('[CRMEB] 有description列:', Object.keys(rows[0]).includes('description'));
          if (rows[0].description) console.log('[CRMEB] description值:', String(rows[0].description).slice(0,100));
        }
        for (const row of rows) {
          const product = { status: 1, unit: '件', created_at: now, updated_at: now };
          for (const [srcKey, target] of Object.entries(FIELD_MAP.products)) {
            if (row[srcKey] !== undefined) {
              if (typeof target === 'string') product[target] = row[srcKey];
              else if (target.transform) product[target.target] = target.transform(row[srcKey]);
            }
          }
          if (row.slider_image) {
            try {
              const parsed = JSON.parse(row.slider_image);
              product.images = Array.isArray(parsed) ? JSON.stringify(parsed) : row.slider_image;
            } catch {
              product.images = String(row.slider_image).replace(/\[|\]/g, '').split(',').filter(Boolean);
              product.images = JSON.stringify(product.images);
            }
          }
          if (product.name) data.products.push(product);
        }
      }
      // 用户
      else if (isUserTable) {
        console.log('[CRMEB] 找到用户表:', tableName, '行数:', rows.length);
        for (const row of rows) {
          const user = { status: 1, created_at: now, updated_at: now, password: '$2b$10$default' };
          for (const [srcKey, target] of Object.entries(FIELD_MAP.users)) {
            if (row[srcKey] !== undefined) {
              if (typeof target === 'string') user[target] = row[srcKey];
              else if (target.transform) user[target.target] = target.transform(row[srcKey]);
            }
          }
          if (user.nickname || user.phone) data.users.push(user);
        }
      }
      // 规格属性定义表（CRMEB的eb_store_product_attr）
      if (isAttrTable) {
        for (const row of rows) {
          let values = [];
          try { values = JSON.parse(row.attr_values); } catch(e) { values = String(row.attr_values).split(',').filter(Boolean); }
          if (!Array.isArray(values)) values = [String(row.attr_values)];
          data.productSpecs.push({
            product_id: row.product_id,
            name: row.attr_name,
            spec_values: JSON.stringify(values),
            sort: row.sort || 0
          });
        }
        continue;
      }
      
      // SKU
      else if (isSkuTable) {
        for (const row of rows) {
          const sku = {};
          for (const [srcKey, target] of Object.entries(FIELD_MAP.product_skus)) {
            if (row[srcKey] !== undefined) {
              if (typeof target === 'string') sku[target] = row[srcKey];
              else if (target.transform) sku[target.target] = target.transform(row[srcKey]);
            }
          }
          // 处理specs：保持结构化JSON格式（前端PC版需JSON.parse匹配SKU）
          if (sku.specs) {
            let raw = String(sku.specs).trim();
            // 如果是平铺格式 "红色,128G" → 通过attr表还原为结构化JSON
            if (!raw.startsWith('[')) {
              const prodSpecs = data.productSpecs.filter(a => Number(a.product_id) === Number(row.product_id));
              const vals = raw.split(',').map(v => v.trim()).filter(Boolean);
              if (prodSpecs.length > 0 && vals.length === prodSpecs.length) {
                const jsonSpecs = prodSpecs.map((s, i) => ({ name: s.name, value: vals[i] }));
                raw = JSON.stringify(jsonSpecs);
              } else {
                raw = JSON.stringify(vals.map(v => ({ name: '规格', value: v })));
              }
            }
            sku.specs = raw;
          }
          if (sku.product_id) data.productSkus.push(sku);
        }
      }
    }
    
    // DEBUG: SKU统计
    console.log('[CRMEB] 总SKU数:', data.productSkus.length);
    if (data.productSkus.length > 0) {
      const samplePrices = data.productSkus.slice(0,5).map(s => s.price);
      console.log('[CRMEB] 前5个SKU价格:', JSON.stringify(samplePrices));
    } else {
      console.log('[CRMEB] ⚠️ 没有找到SKU数据！');
    }
    
    // DEBUG: 产品图片格式
    if (data.products.length > 0) {
      console.log('[CRMEB] 首产品images:', data.products[0].images?.slice(0,100));
    }

    return this._buildResult(data, now);
  }

  _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 || [],
      productSpecs: source.productSpecs || [],
    };
    return this._buildResult(data, new Date().toISOString());
  }

  _buildResult(data, now) {
    // 给没有手机号的用户补一个虚拟手机号
    let phoneIdx = 1;
    for (const u of data.users) {
      if (!u.password) u.password = '$2b$10$default';
      if (!u.phone || u.phone === 'undefined') {
        u.phone = 'mig_' + (phoneIdx++) + '@litemall.com';
      }
      if (!u.nickname) u.nickname = '用户' + phoneIdx;
    }
    
    // 从商品images字段生成 productImages（详情图独立表）
    const productImages = [];
    for (const p of data.products) {
      let imgList = [];
      if (p.images) {
        try { imgList = JSON.parse(p.images); } catch(e) { imgList = String(p.images).split(','); }
      }
      // 跳过第一张（第一张是商品主图image字段，product_images用于额外详情图）
      imgList.forEach((url, idx) => {
        if (idx > 0 && url) {
          productImages.push({ product_id: p.id, url: url.trim(), type: 0, sort: idx });
        }
      });
      // 如果images只有一张且image字段为空，则取第一张
      if (imgList.length === 1 && p.image) {
        productImages.push({ product_id: p.id, url: p.image.trim(), type: 0, sort: 0 });
      }
    }

    return {
      manifest: {
        migrationVersion: '1.0.0',
        exportId: 'crmeB_import_' + Date.now(),
        exportedAt: now, source: 'CRMEB', sourceVersion: 'V6', adapter: 'crmeB-v1.0',
        stats: { products: data.products.length, categories: data.categories.length, users: data.users.length, skus: data.productSkus.length, productImages: productImages.length, productSpecs: data.productSpecs?.length || 0 },
      },
      data: { products: data.products, categories: data.categories, users: data.users, productSkus: data.productSkus, productImages, productSpecs: data.productSpecs || [] },
    };
  }

  // ====== SQL解析器（兼容各种导出格式）======

  _parseSqlTables(sql) {
    const tables = {};
    
    // 1. 收集所有CREATE TABLE的列信息
    const createStmts = {};
    const createRegex = /CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?`?(\w+)`?\s*\(([\s\S]*?)\)\s*(?:ENGINE|DEFAULT|;|$)/gim;
    let cm;
    while ((cm = createRegex.exec(sql)) !== null) {
      createStmts[cm[1]] = cm[2];
    }

    // 2. 从CREATE TABLE提取列名
    const getColumns = (def) => {
      if (!def) return [];
      const cols = [];
      // 按行拆分
      const lines = def.split(/\n|\r\n/);
      if (lines.length === 1) {
        // 整行格式: `id` int, `name` varchar(255)
        const parts = def.split(',');
        for (const p of parts) {
          const m = p.trim().match(/^`?(\w+)`?\s+/);
          if (m) cols.push(m[1]);
        }
      } else {
        for (const line of lines) {
          const t = line.trim();
          if (/^(INDEX|KEY|UNIQUE|PRIMARY|CONSTRAINT|FOREIGN|CHECK|\s*$)/i.test(t)) continue;
          const m = t.match(/^\s*`?(\w+)`?\s+/);
          if (m) cols.push(m[1]);
        }
      }
      return cols;
    };

    // 3. 解析INSERT语句
    const insRegex = /INSERT\s+(?:IGNORE\s+)?INTO\s+`?(\w+)`?\s*(?:\(([^)]+)\))?\s*VALUES\s*/gim;
    let im;
    while ((im = insRegex.exec(sql)) !== null) {
      const tn = im[1];
      if (!tables[tn]) tables[tn] = [];
      
      let cols = [];
      if (im[2]) cols = im[2].split(',').map(c => c.trim().replace(/^`(.+)`$/, '$1'));
      else cols = getColumns(createStmts[tn]);
      
      let rem = sql.substring(im.index + im[0].length);
      
      while (rem.length > 0) {
        rem = rem.trimStart();
        if (rem[0] !== '(') break;
        
        const parsed = this._parseRow(rem);
        if (!parsed) break;
        
        const obj = {};
        for (let i = 0; i < cols.length && i < parsed.values.length; i++) {
          obj[cols[i]] = parsed.values[i];
        }
        tables[tn].push(obj);
        
        rem = rem.substring(parsed.idx).trimStart();
        if (rem[0] === ',') rem = rem.substring(1);
        else if (rem[0] === ';') break;
        else break;
      }
    }
    return tables;
  }

  _parseRow(str) {
    if (str[0] !== '(') return null;
    const vals = [];
    let cur = '', depth = 0, inStr = false, ch = '', i = 0;
    for (i = 0; i < str.length; i++) {
      ch = str[i];
      if (inStr) {
        if (ch === '\\' && i+1 < str.length) { cur += ch + str[++i]; }
        else if (ch === inStr) { inStr = false; cur += ch; }
        else { cur += ch; }
      } else {
        if (ch === '(') { if (depth++ === 0) continue; cur += ch; }
        else if (ch === ')') { if (--depth === 0) { vals.push(cur.trim()); break; } cur += ch; }
        else if (ch === "," && depth === 1) { vals.push(cur.trim()); cur = ''; }
        else if (ch === "'" || ch === '"') { inStr = ch; cur += ch; }
        else { cur += ch; }
      }
    }
    return {
      values: vals.map(v => {
        v = v.trim();
        if ((v.startsWith("'") && v.endsWith("'")) || (v.startsWith('"') && v.endsWith('"')))
          return v.slice(1,-1).replace(/\\'/g,"'").replace(/\\"/g,'"').replace(/\\\\/g,'\\');
        if (v === 'NULL' || v === '') return null;
        const n = Number(v);
        return isNaN(n) ? v : n;
      }),
      idx: i + 1
    };
  }

  getHelp() {
    return '从CRMEB导出: 宝塔面板 → 数据库 → 导出SQL';
  }

  getFieldMap() { return FIELD_MAP; }
}

module.exports = CrmeBAdapter;
