/**
 * 一键搬家 - 迁移API路由
 * 挂载路径: /api/admin/migration
 */
const express = require('express');
const fs = require('fs');
const path = require('path');
const { authAdmin } = require('../middleware/auth');
const { get, all, run } = require('../utils/db');
const migration = require('../lib/migration');
const adapters = require('../lib/migration/adapters');
const imageMigrator = require('../lib/migration/image-migrator');

function getImgCount(str) {
  if (!str) return 0;
  return str.split(',').filter(Boolean).length;
}

const router = express.Router();

// ========== 导出 ==========

/**
 * POST /api/admin/migration/export
 * 导出商城数据
 * Body: { includeProducts, includeCategories, includeUsers, includeOrders }
 */
router.post('/export', authAdmin, async (req, res) => {
  try {
    const {
      includeProducts = true,
      includeCategories = true,
      includeUsers = false,
      includeOrders = false,
    } = req.body;

    const exportResult = await migration.exportData({
      includeProducts,
      includeCategories,
      includeUsers,
      includeOrders,
    });

    const filename = `litemall-export-${Date.now()}.json`;
    const filePath = migration.saveExportToJson(exportResult, filename);

    // 记录日志
    run(`INSERT INTO migration_logs (type, status, source_platform, stats, options, file_path, created_at) VALUES (?,?,?,?,?,?,?)`,
      ['export', 'success', 'LiteMall', JSON.stringify(exportResult.manifest.stats),
       JSON.stringify(req.body), filePath, new Date().toISOString()]);

    res.json({
      code: 0,
      message: '导出成功',
      data: {
        filename,
        filePath,
        stats: exportResult.manifest.stats,
        downloadUrl: `/api/admin/migration/download/${filename}`,
      }
    });
  } catch (err) {
    console.error('[迁移] 导出失败:', err.message);
    res.json({ code: 1, message: '导出失败: ' + err.message });
  }
});

/**
 * GET /api/admin/migration/download/:filename
 * 下载导出文件
 */
router.get('/download/:filename', authAdmin, (req, res) => {
  const filename = req.params.filename;
  // 安全检查：防止路径穿越
  if (filename.includes('..') || filename.includes('/')) {
    return res.json({ code: 1, message: '非法的文件名' });
  }
  
  const filePath = path.join(migration.EXPORT_DIR, filename);
  if (!fs.existsSync(filePath)) {
    return res.json({ code: 1, message: '文件不存在' });
  }

  res.download(filePath, filename);
});

// ========== 导入预览 ==========

/**
 * POST /api/admin/migration/preview
 * 预览导入数据（不上传文件，粘贴JSON内容）
 * Body: { content: "JSON字符串" }
 */
router.post('/preview', authAdmin, async (req, res) => {
  try {
    let package_;
    if (req.body.content) {
      package_ = JSON.parse(req.body.content);
    } else if (req.body.jsonData) {
      package_ = req.body.jsonData;
    } else {
      return res.json({ code: 1, message: '请提供导入数据' });
    }

    const preview = await migration.previewImport(package_);
    if (preview.error) {
      return res.json({ code: 1, message: preview.error });
    }

    res.json({
      code: 0,
      message: '预览成功',
      data: preview,
    });
  } catch (err) {
    res.json({ code: 1, message: '预览失败: ' + err.message });
  }
});

// ========== 导入执行 ==========

/**
 * POST /api/admin/migration/import
 * 执行导入
 * Body: { content: "JSON字符串", conflictStrategy, importCategories, importProducts, importUsers }
 */
router.post('/import', authAdmin, async (req, res) => {
  try {
    let package_;
    
    // 支持通过适配器转换后再导入
    if (req.body.adapter && req.body.content && req.body.dataType) {
      const adapter = adapters.getAdapter(req.body.adapter);
      if (!adapter) return res.json({ code: 1, message: '不支持的适配器: ' + req.body.adapter });
      const converted = await adapter.convert({ type: req.body.dataType, content: req.body.content });
      package_ = converted;
    } else if (req.body.content) {
      package_ = JSON.parse(req.body.content);
    } else if (req.body.jsonData) {
      package_ = req.body.jsonData;
    } else {
      return res.json({ code: 1, message: '请提供导入数据，或指定适配器+原始数据' });
    }

    // 图片迁移（如果提供了原站地址）
    let imageResult = null;
    if (req.body.downloadImages && req.body.imageBaseUrl && package_.data?.products) {
      try {
        // 先处理相对路径，转为完整URL
        imageMigrator.prepareImageUrls(package_.data.products, req.body.imageBaseUrl);
        
        // 统计需要下载的图片
        let pendingImgs = 0;
        for (const p of package_.data.products) {
          pendingImgs += getImgCount(p.image) + getImgCount(p.images);
        }
        
        // 后台异步下载
        imageMigrator.downloadProductImages(package_.data.products, {
          imageBaseUrl: req.body.imageBaseUrl
        }).then(r => {
          console.log('[迁移] 图片下载完成:', r.downloaded, '张成功,', r.failed, '张失败');
        });
        
        imageResult = { pending: pendingImgs, status: 'downloading' };
      } catch (imgErr) {
        console.error('[迁移] 图片下载启动失败:', imgErr.message);
        imageResult = { error: imgErr.message };
      }
    }

    const result = await migration.importData(package_, {
      conflictStrategy: req.body.conflictStrategy || 'skip',
      importCategories: req.body.importCategories !== false,
      importProducts: req.body.importProducts !== false,
      importUsers: req.body.importUsers !== false,
      importOrders: req.body.importOrders || false,
    });

    if (result.success) {
      res.json({
        code: 0,
        message: '导入完成',
        data: { ...result, imageMigration: imageResult },
      });
    } else {
      res.json({
        code: 1,
        message: '导入失败: ' + (result.error || '未知错误'),
        data: { ...result, imageMigration: imageResult },
      });
    }
  } catch (err) {
    res.json({ code: 1, message: '导入异常: ' + err.message });
  }
});

// ========== 历史记录 ==========

/**
 * GET /api/admin/migration/history
 * 获取迁移历史
 */
router.get('/history', authAdmin, (req, res) => {
  try {
    const limit = parseInt(req.query.limit) || 20;
    const history = migration.getMigrationHistory(limit);
    res.json({
      code: 0,
      data: history,
    });
  } catch (err) {
    res.json({ code: 1, message: err.message });
  }
});

/**
 * GET /api/admin/migration/stats
 * 迁移统计
 */
router.get('/stats', authAdmin, (req, res) => {
  try {
    const stats = migration.getMigrationStats();
    res.json({
      code: 0,
      data: stats,
    });
  } catch (err) {
    res.json({ code: 1, message: err.message });
  }
});

// ========== 文件上传导入 ==========

/**
 * POST /api/admin/migration/images/download
 * 下载导入数据中的商品图片
 */
router.post('/images/download', authAdmin, async (req, res) => {
  try {
    const { products, imageBaseUrl } = req.body;
    if (!products || !Array.isArray(products)) {
      return res.json({ code: 1, message: '请提供商品列表' });
    }
    
    imageMigrator.prepareImageUrls(products, imageBaseUrl || '');
    const result = await imageMigrator.downloadProductImages(products, {
      imageBaseUrl: imageBaseUrl || ''
    });
    
    res.json({
      code: 0,
      message: result.failed === 0 ? '全部图片下载成功' : `${result.downloaded}张成功, ${result.failed}张失败`,
      data: result
    });
  } catch (err) {
    res.json({ code: 1, message: '图片下载失败: ' + err.message });
  }
});

/**
 * POST /api/admin/migration/images/resolve-crmeB
 * 解析CRMEB图片路径（将系统路径转为URL）
 */
router.post('/images/resolve-crmeB', authAdmin, (req, res) => {
  try {
    const { products, domain } = req.body;
    if (!products) return res.json({ code: 1, message: '请提供商品列表' });
    
    const resolved = products.map(p => ({
      ...p,
      image: p.image ? imageMigrator.resolveImageUrl(p.image, domain) : p.image,
      images: p.images ? p.images.split(',').map(i => imageMigrator.resolveImageUrl(i.trim(), domain)).join(',') : p.images,
    }));
    
    res.json({ code: 0, message: '解析完成', data: { count: products.length, samples: resolved.slice(0, 3) } });
  } catch (err) {
    res.json({ code: 1, message: '解析失败: ' + err.message });
  }
});

/**
 * POST /api/admin/migration/upload
 * 上传JSON文件并预览
 */
router.post('/upload', authAdmin, (req, res) => {
  // 如果express有文件上传中间件则用
  // 这里用base64方式传入
  try {
    const { filename, content } = req.body;
    if (!content) return res.json({ code: 1, message: '请提供文件内容' });
    
    const package_ = JSON.parse(content);
    const source = migration.detectPlatform(package_);
    
    res.json({
      code: 0,
      message: '文件解析成功',
      data: { source, filename, size: content.length }
    });
  } catch (err) {
    res.json({ code: 1, message: '文件解析失败: ' + err.message });
  }
});

// ========== 平台适配器 ==========

/**
 * GET /api/admin/migration/formats
 * 获取支持的格式/适配器列表
 */
router.get('/formats', authAdmin, (req, res) => {
  const allAdapters = adapters.getAllAdapters();
  res.json({
    code: 0,
    data: {
      exportFormats: [
        { id: 'litemall-json', name: 'LiteMall标准JSON', description: '通用的JSON格式，可用于LiteMall之间迁移' },
      ],
      importFormats: allAdapters.map(a => ({
        id: a.name, name: a.label, description: a.description,
        icon: a.icon, adapter: a.name, formats: a.formats,
      })),
      futureFormats: [],
    }
  });
});

/**
 * GET /api/admin/migration/adapters
 * 获取所有平台适配器
 */
router.get('/adapters', authAdmin, (req, res) => {
  res.json({ code: 0, data: adapters.getAllAdapters() });
});

/**
 * POST /api/admin/migration/adapters/detect
 * 自动检测数据来自哪个平台
 */
router.post('/adapters/detect', authAdmin, (req, res) => {
  try {
    const { type, content } = req.body;
    if (!content) return res.json({ code: 1, message: '请提供数据内容' });
    const result = adapters.detectAdapter({ type: type || 'json', content });
    if (result) {
      res.json({
        code: 0, message: '检测到平台: ' + result.adapter.label,
        data: { name: result.adapter.name, label: result.adapter.label, score: result.score },
      });
    } else {
      res.json({ code: 1, message: '未能识别数据来源平台', data: null });
    }
  } catch (err) {
    res.json({ code: 1, message: '检测失败: ' + err.message });
  }
});

/**
 * POST /api/admin/migration/adapters/convert
 * 使用指定适配器转换数据
 */
router.post('/adapters/convert', authAdmin, async (req, res) => {
  try {
    const { adapter: adapterName, type, content } = req.body;
    if (!adapterName || !content) {
      return res.json({ code: 1, message: '请提供适配器名称和数据内容' });
    }
    const adapter = adapters.getAdapter(adapterName);
    if (!adapter) return res.json({ code: 1, message: '不支持的适配器: ' + adapterName });
    
    const result = await adapter.convert({ type: type || 'json', content });
    res.json({
      code: 0, message: '转换成功',
      data: {
        manifest: result.manifest,
        preview: await migration.previewImport(result),
        data: result.data,
      }
    });
  } catch (err) {
    res.json({ code: 1, message: '转换失败: ' + err.message });
  }
});

/**
 * GET /api/admin/migration/adapters/:name/help
 * 获取适配器帮助
 */
router.get('/adapters/:name/help', authAdmin, (req, res) => {
  const adapter = adapters.getAdapter(req.params.name);
  if (!adapter) return res.json({ code: 1, message: '未找到适配器' });
  res.json({
    code: 0,
    data: {
      name: adapter.name, label: adapter.label,
      help: adapter.getHelp(),
      fieldMap: adapter.getFieldMap(),
    }
  });
});

/**
 * POST /api/admin/migration/upload-xlsx
 * 上传xlsx文件（base64编码）并转换为商品数据
 */
router.post('/upload-xlsx', authAdmin, async (req, res) => {
  try {
    const { content } = req.body;
    if (!content) return res.json({ code: 1, message: '请提供文件内容' });

    const buf = Buffer.from(content, 'base64');
    const adapter = adapters.getAdapter('crmeB-xlsx');
    const result = await adapter.convert({ type: 'xlsx', content: buf });
    
    res.json({
      code: 0,
      message: '解析成功，共' + result.data.products.length + '个商品',
      data: {
        manifest: result.manifest,
        preview: result.manifest.stats,
        data: result.data,
      }
    });
  } catch (err) {
    res.json({ code: 1, message: '解析失败: ' + err.message });
  }
});

module.exports = router;
