/**
 * 一键搬家 - 核心迁移引擎
 * 
 * 功能: 商城数据互通，支持导入/导出为通用JSON格式
 * 格式: ZIP包（manifest.json + 业务数据JSON + 媒体文件）
 * 
 * 支持的迁移场景:
 *   LiteMall ↔ LiteMall (自有格式互通)
 *   未来可扩展: CRMEB / 有赞 / 淘宝 / Shopify / WooCommerce
 */

const fs = require('fs');
const path = require('path');
const { get, all, run } = require('../utils/db');

// ========== 通用数据格式定义 ==========

const MIGRATION_VERSION = '1.0.0';
const EXPORT_DIR = path.resolve(__dirname, '..', '..', 'exports');

/**
 * 创建导出目录
 */
function ensureExportDir() {
  if (!fs.existsSync(EXPORT_DIR)) {
    fs.mkdirSync(EXPORT_DIR, { recursive: true });
  }
  return EXPORT_DIR;
}

// ========== 导出引擎 ==========

/**
 * 导出LiteMall数据为通用JSON包
 * @param {Object} options - 导出选项
 * @param {boolean} options.includeProducts - 包含商品
 * @param {boolean} options.includeCategories - 包含分类
 * @param {boolean} options.includeUsers - 包含用户
 * @param {boolean} options.includeOrders - 包含订单
 * @param {boolean} options.includeImages - 包含图片文件
 * @returns {Object} { manifest, data, paths }
 */
async function exportData(options = {}) {
  const {
    includeProducts = true,
    includeCategories = true,
    includeUsers = false,
    includeOrders = false,
    includeImages = false,
  } = options;

  const timestamp = new Date().toISOString();
  const exportId = `export_${Date.now()}`;

  // Manifest - 包的元信息
  const manifest = {
    migrationVersion: MIGRATION_VERSION,
    exportId,
    exportedAt: timestamp,
    source: 'LiteMall',
    sourceVersion: '1.0.0',
    stats: {},
    included: { products: includeProducts, categories: includeCategories, users: includeUsers, orders: includeOrders, images: includeImages },
  };

  const data = {};

  // 导出分类
  if (includeCategories) {
    data.categories = all(`SELECT * FROM categories ORDER BY sort, id`);
    manifest.stats.categories = data.categories.length;
  }

  // 导出商品
  if (includeProducts) {
    const products = all(`SELECT * FROM products ORDER BY id`);
    
    // 商品SKU
    const productIds = products.map(p => p.id);
    let skus = [];
    let images = [];
    if (productIds.length > 0) {
      skus = all(`SELECT * FROM product_skus WHERE product_id IN (${productIds.join(',')})`);
      images = all(`SELECT * FROM product_images WHERE product_id IN (${productIds.join(',')})`);
    }

    data.products = products;
    data.productSkus = skus;
    data.productImages = images;
    manifest.stats.products = products.length;
    manifest.stats.skus = skus.length;
  }

  // 导出用户
  if (includeUsers) {
    data.users = all(`SELECT id, nickname, phone, avatar, level_id, 
      experience, balance, points, status, created_at, updated_at 
      FROM users ORDER BY id`);
    manifest.stats.users = data.users.length;
  }

  // 导出订单
  if (includeOrders) {
    data.orders = all(`SELECT * FROM orders ORDER BY id`);
    data.orderItems = all(`SELECT * FROM order_items ORDER BY id`);
    manifest.stats.orders = data.orders.length;
  }

  manifest.stats.exportedAt = timestamp;

  return { manifest, data };
}

/**
 * 保存导出包到文件
 * @param {Object} exportResult - exportData()的返回值
 * @param {string} filename - 可选的导出文件名
 * @returns {string} 导出文件路径
 */
function saveExportToJson(exportResult, filename = null) {
  ensureExportDir();
  const name = filename || `litemall-export-${Date.now()}.json`;
  const filePath = path.join(EXPORT_DIR, name);
  
  const package_ = {
    manifest: exportResult.manifest,
    data: exportResult.data,
  };
  
  fs.writeFileSync(filePath, JSON.stringify(package_, null, 2), 'utf-8');
  return filePath;
}

// ========== 导入引擎 ==========

/**
 * 验证导入包格式
 */
function validateImportPackage(package_) {
  if (!package_.manifest) {
    return { valid: false, error: '缺少manifest元信息' };
  }
  if (!package_.data) {
    return { valid: false, error: '缺少数据内容' };
  }
  if (!package_.manifest.migrationVersion) {
    return { valid: false, error: '缺少版本号' };
  }
  return { valid: true };
}

/**
 * 预览导入数据（不实际写入）
 */
async function previewImport(package_) {
  const validation = validateImportPackage(package_);
  if (!validation.valid) return validation;

  const data = package_.data;
  const categories = data.categories || [];
  const products = data.products || [];
  const users = data.users || [];
  const orders = data.orders || [];

  // 检查冲突
  const existingSkus = new Set(
    (all(`SELECT sku_code FROM product_skus`) || []).map(r => r.sku_code)
  );
  const existingProductIds = new Set(
    (all(`SELECT id FROM products`) || []).map(r => r.id)
  );

  const conflictProducts = products.filter(p => existingProductIds.has(p.id));
  const newProducts = products.filter(p => !existingProductIds.has(p.id));

  return {
    preview: true,
    stats: {
      categories: categories.length,
      products: products.length,
      newProducts: newProducts.length,
      conflictProducts: conflictProducts.length,
      users: users.length,
      orders: orders.length,
    },
    samples: {
      categories: categories.slice(0, 5).map(c => ({ id: c.id, name: c.name })),
      products: products.slice(0, 5).map(p => ({ id: p.id, name: p.name, price: p.price })),
    },
    conflicts: conflictProducts.slice(0, 10).map(p => ({ id: p.id, name: p.name })),
  };
}

/**
 * 执行数据导入
 * @param {Object} package_ - 导入包 { manifest, data }
 * @param {Object} options - 导入选项
 * @param {string} options.conflictStrategy - skip保留现有/overwrite覆盖/rename重命名
 * @param {boolean} options.importCategories - 导入分类
 * @param {boolean} options.importProducts - 导入商品
 * @param {boolean} options.importUsers - 导入用户
 * @param {boolean} options.importOrders - 导入订单
 * @returns {Object} 导入结果
 */
async function importData(package_, options = {}) {
  const validation = validateImportPackage(package_);
  if (!validation.valid) return validation;

  const {
    conflictStrategy = 'skip',
    importCategories = true,
    importProducts = true,
    importUsers = true,
    importOrders = false,
  } = options;

  const data = package_.data;
  const results = {
    success: true,
    imported: { categories: 0, products: 0, users: 0, orders: 0, skus: 0, images: 0 },
    skipped: { categories: 0, products: 0 },
    errors: [],
  };

  // 开始事务
  const beginTransaction = () => {
    run('PRAGMA foreign_keys = OFF');
    run('BEGIN TRANSACTION');
  };
  const commitTransaction = () => {
    run('COMMIT');
    run('PRAGMA foreign_keys = ON');
  };
  const rollbackTransaction = () => {
    run('ROLLBACK');
    run('PRAGMA foreign_keys = ON');
  };

  try {
    beginTransaction();

    // 1. 导入分类（并记录ID映射，用于修正商品的category_id）
    const catIdMap = {}; // {旧分类ID: 新分类ID}
    if (importCategories && data.categories) {
      const maxCat = get('SELECT MAX(id) as max FROM categories');
      let catId = Math.max((maxCat?.max || 0) + 1, 200);
      
      for (const cat of data.categories) {
        const oldId = cat.id;
        const newId = catId++;
        if (oldId) catIdMap[oldId] = newId;
        
        // 关键修复：pid必须用新ID映射，否则子分类的父ID指向旧分类
        const mappedPid = (cat.pid && catIdMap[cat.pid]) ? catIdMap[cat.pid] : (cat.pid || 0);
        run(`INSERT INTO categories (id, name, pid, sort, status, created_at) VALUES (?,?,?,?,?,?)`,
          [newId, cat.name, mappedPid, cat.sort || 0, cat.status || 1, cat.created_at || new Date().toISOString()]);
        results.imported.categories++;
      }
    }

    // 2. 导入商品（category_id用映射修正）
    if (importProducts && data.products) {
      const maxProd = get('SELECT MAX(id) as max FROM products');
      let prodId = Math.max((maxProd?.max || 0) + 1, 300);
      const idMap = {}; // 旧商品ID → 新商品ID
      
      for (const product of data.products) {
        const oldId = product.id;
        const newId = prodId++;
        if (oldId) idMap[oldId] = newId;
        
        // 修正category_id
        let catId = null;
        if (product.category_id && catIdMap[product.category_id]) {
          catId = catIdMap[product.category_id];
        }
        
        // 判断是否有SKU
        const skus4Product = (data.productSkus || []).filter(s => s.product_id === oldId);
        const hasSkus = skus4Product.length > 0;
        const specType = hasSkus ? 1 : 0;
        
        // 有SKU的产品：用第一个有效SKU的价格作为产品基准价（前端直接显示这个价）
        let displayPrice = Number(product.price) || 0;
        let displayOrigPrice = Number(product.original_price) || 0;
        let displayStock = Number(product.stock) || 0;
        if (hasSkus) {
          const validSku = skus4Product.find(s => Number(s.price) > 0);
          if (validSku) {
            displayPrice = Number(validSku.price);
            if (Number(validSku.original_price) > 0) displayOrigPrice = Number(validSku.original_price);
            if (Number(validSku.stock) >= 0) displayStock = Number(validSku.stock);
          }
        }
        
        run(`INSERT INTO products (id, name, price, original_price, stock, sales,
          description, category_id, image, images, spec_type, status, is_hot, is_new, is_recommend,
          sort, unit, created_at, updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
          [newId, product.name, displayPrice, displayOrigPrice,
          displayStock, product.sales || 0, product.description || '', catId,
          product.image || '', product.images || '', specType,
          product.status || 1, product.is_hot || 0, product.is_new || 0,
          product.is_recommend || 0, product.sort || 0,
          product.unit || '件', product.created_at || new Date().toISOString(),
          new Date().toISOString()]);
        results.imported.products++;
        
        // 导入SKU（修正product_id），过滤价格为null/0的脏数据
        if (hasSkus) {
          for (const sku of skus4Product) {
            const skuPrice = Number(sku.price);
            if (!skuPrice || skuPrice <= 0) {
              console.log('[搬家] 跳过价格为0/null的SKU: 产品=' + oldId + ' SKU=' + (sku.sku_code || ''));
              continue;
            }
            run(`INSERT INTO product_skus (product_id, sku_code, price, stock, image, specs, original_price) VALUES (?,?,?,?,?,?,?)`,
              [newId, sku.sku_code || '', skuPrice, Number(sku.stock) || 0,
              sku.image || '', sku.specs || '', Number(sku.original_price) || 0]);
            results.imported.skus++;
          }
        } else {
          // 无SKU的产品：自动生成一条默认SKU，价格和库存从产品取
          run(`INSERT INTO product_skus (product_id, sku_code, price, stock, specs) VALUES (?,?,?,?,?)`,
            [newId, 'default', Number(product.price) || 0, Number(product.stock) || 0, '[]']);
          results.imported.skus++;
        }
        
        // 导入商品图片到product_images表
        if (data.productImages) {
          const imgs = data.productImages.filter(i => i.product_id === oldId);
          for (const img of imgs) {
            run(`INSERT INTO product_images (product_id, url, type, sort) VALUES (?,?,?,?)`,
              [newId, img.url || '', img.type || 0, img.sort || 0]);
            results.imported.images++;
          }
        }
      }
      // 导入规格属性定义
      if (data.productSpecs && data.productSpecs.length > 0) {
        for (const spec of data.productSpecs) {
          const newProductId = idMap[spec.product_id];
          if (newProductId) {
            run(`INSERT INTO product_specs (product_id, name, spec_values, sort) VALUES (?,?,?,?)`,
              [newProductId, spec.name, spec.spec_values || '[]', spec.sort || 0]);
          }
        }
      }
    }

    // 3. 导入用户
    if (importUsers && data.users) {
      const maxUser = get('SELECT MAX(id) as max FROM users');
      let nextId = Math.max((maxUser?.max || 0) + 1, 500);
      
      for (const user of data.users) {
        // 用手机号去重
        if (user.phone) {
          const dup = get('SELECT id FROM users WHERE phone = ?', [user.phone]);
          if (dup) { user.phone = user.phone + "_mig_" + nextId; }
        }
        
        run(`INSERT INTO users (id, nickname, phone, avatar, level_id,
          balance, points, experience, status, password, created_at, updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)`,
          [nextId++, user.nickname || '用户' + nextId, user.phone, user.avatar, user.level_id || 0,
          user.balance || 0, user.points || 0, user.experience || 0,
          user.status || 1, user.password || '$2b$10$default',
          user.created_at || new Date().toISOString(), new Date().toISOString()]);
        results.imported.users++;
      }
    }

    commitTransaction();

    // 记录迁移日志
    run(`INSERT INTO migration_logs (type, status, stats, options, created_at) VALUES (?,?,?,?,?)`,
      ['import', 'success', JSON.stringify(results.imported), JSON.stringify(options), new Date().toISOString()]);

  } catch (err) {
    rollbackTransaction();
    results.success = false;
    results.error = err.message;
    results.errors.push(err.message);
    
    run(`INSERT INTO migration_logs (type, status, stats, options, error, created_at) VALUES (?,?,?,?,?,?)`,
      ['import', 'failed', '{}', JSON.stringify(options), err.message, new Date().toISOString()]);
  }

  return results;
}

// ========== 平台适配器接口 ==========

/**
 * 平台适配器基类
 * 继承此类以实现特定平台的导入
 */
class PlatformAdapter {
  constructor(name, label) {
    this.name = name;
    this.label = label;
  }

  /** 检测文件/数据是否匹配此平台格式 */
  detect(input) { return false; }

  /** 将平台格式转换为LiteMall通用格式 */
  async convert(input) { throw new Error('未实现convert()'); }

  /** 获取此平台支持的格式说明 */
  getFormatHelp() { return ''; }
}

/**
 * CRMEB数据适配器
 * 从CRMEB的SQL/CSV/JSON格式转换到LiteMall格式
 */
class CrmeBAdapter extends PlatformAdapter {
  constructor() {
    super('crmeB', 'CRMEB标准版');
  }
}

/**
 * 通用CSV适配器
 * 从标准CSV格式导入（如淘宝助手导出）
 */
class CsvAdapter extends PlatformAdapter {
  constructor() {
    super('csv', '通用CSV（淘宝助手/拼多多商家版）');
  }
}

// ========== 平台检测 ==========

/**
 * 检测导入包来自哪个平台
 */
function detectPlatform(package_) {
  const manifest = package_.manifest || {};
  if (manifest.source === 'LiteMall') return 'LiteMall';
  if (manifest.source && manifest.source.includes('CRMEB')) return 'CRMEB';
  if (manifest.source && manifest.source.includes('Shopify')) return 'Shopify';
  return 'Generic';
}

// ========== 迁移历史 ==========

/**
 * 获取迁移历史
 */
function getMigrationHistory(limit = 20) {
  return all(`SELECT * FROM migration_logs ORDER BY id DESC LIMIT ?`, [limit]);
}

/**
 * 获取迁移统计
 */
function getMigrationStats() {
  const imports = all(`SELECT status, COUNT(*) as count FROM migration_logs WHERE type='import' GROUP BY status`);
  const exports = all(`SELECT status, COUNT(*) as count FROM migration_logs WHERE type='export' GROUP BY status`);
  const totalImported = get(`SELECT json_extract(stats, '$.products') as products, json_extract(stats, '$.users') as users FROM migration_logs WHERE type='import' AND status='success' ORDER BY id DESC LIMIT 1`);
  
  const exportDir = ensureExportDir();
  const files = fs.readdirSync(EXPORT_DIR).filter(f => f.endsWith('.json') || f.endsWith('.zip'));
  
  return {
    imports,
    exports,
    lastImport: totalImported,
    exportFiles: files.length,
    exportDir: EXPORT_DIR,
  };
}

module.exports = {
  // 核心
  exportData,
  saveExportToJson,
  importData,
  previewImport,
  validateImportPackage,
  
  // 检测
  detectPlatform,
  
  // 平台适配器
  PlatformAdapter,
  CrmeBAdapter,
  CsvAdapter,
  
  // 历史
  getMigrationHistory,
  getMigrationStats,
  
  // 常量
  EXPORT_DIR,
  MIGRATION_VERSION,
};
