const express = require('express');
const router = express.Router();
const { get, run, all } = require('../utils/db');
const crypto = require('crypto');
const https = require('https');
const http = require('http');
const { isFeatureEnabled } = require('../lib/license');
const { authAdmin } = require('../middleware/auth');

// ========== 功能门控：商品采集仅在完整版可用 ==========
router.use((req, res, next) => {
  if (!isFeatureEnabled('product_collect')) {
    return res.json({ code: 403, message: '当前版本不支持商品采集功能', data: null });
  }
  // 写操作(改配置/触发采集/读日志)需管理员，防匿名篡改配置/滥用采集/泄漏日志
  if (req.method !== 'GET') {
    return authAdmin(req, res, next);
  }
  next();
});

// ---------- 采集配置读取/保存 ----------

    // NOTE: getConfig 仅一次 SQL 查询 + map 映射，已是最优写法

function getConfig() {
  const rows = all("SELECT `key`, `value` FROM system_config WHERE `key` LIKE 'collect_%'");
  const c = {};
  rows.forEach(r => { c[r.key.replace('collect_', '')] = r.value; });
  c.type = c.type || 'yihaotong';
  return c;
}

function saveConfig(key, value) {
  const k = `collect_${key}`;
  const exist = get("SELECT id FROM system_config WHERE `key`=?", [k]);
  exist
    ? run("UPDATE system_config SET `value`=? WHERE `key`=?", [value, k])
    : run("INSERT INTO system_config(`key`,`value`) VALUES(?,?)", [k, value]);
}

// ---------- HTTP 请求工具 ----------

function httpGet(url, params = {}) {
  return new Promise((resolve, reject) => {
    try {
      const u = new URL(url);
      Object.entries(params).forEach(([k, v]) => u.searchParams.append(k, v));
      const client = u.protocol === 'https:' ? https : http;
      const opts = {
        hostname: u.hostname,
        port: u.port || (u.protocol === 'https:' ? 443 : 80),
        path: u.pathname + u.search,
        method: 'GET',
        headers: { 'Content-Type': 'application/json' },
        timeout: 20000
      };
      const req = client.request(opts, (res) => {
        let data = '';
        res.on('data', chunk => data += chunk);
        res.on('end', () => { });
      });
      req.on('error', reject);
      req.on('timeout', () => { req.destroy(); reject(new Error('请求超时')); });
      req.end();
    } catch (e) { reject(e); }
  });
}

function httpPost(url, body, headers = {}) {
  return new Promise((resolve, reject) => {
    try {
      const u = new URL(url);
      const client = u.protocol === 'https:' ? https : http;
      const payload = JSON.stringify(body);
      const opts = {
        hostname: u.hostname,
        port: u.port || (u.protocol === 'https:' ? 443 : 80),
        path: u.pathname + u.search,
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Content-Length': Buffer.byteLength(payload),
          ...headers
        },
        timeout: 20000
      };
      const req = client.request(opts, (res) => {
        let data = '';
        res.on('data', chunk => data += chunk);
        res.on('end', () => {
          try { resolve(JSON.parse(data)); }
          catch (e) { resolve({ error: '响应解析失败', raw: data }); }
        });
      });
      req.on('error', reject);
      req.on('timeout', () => { req.destroy(); reject(new Error('请求超时')); });
      req.write(payload);
      req.end();
    } catch (e) { reject(e); }
  });
}

// ---------- 从链接提取商品ID ----------

function extractItemId(url) {
  const m1 = url.match(/[?&]id=(\d+)/);
  if (m1) return m1[1];
  const m2 = url.match(/\/item\/(\d+)/);
  if (m2) return m2[1];
  return null;
}

// ---------- 一号通驱动 ----------
// GET {api_url}/api/item/get?app_key=&timestamp=&sign=&item_id=&type=
// sign = md5(app_key + app_secret + timestamp)
// 期望响应: {code: 0, data: {title, images, desc, price, skus, url}}
//          或 {code: 0, result: {...}}

async function fetchYihaotong(itemUrl, appKey, appSecret) {
  const cfg = getConfig();
  const baseUrl = cfg.api_url || 'http://api.yihaotong.com';
  const itemId = extractItemId(itemUrl);
  if (!itemId) throw new Error('无法从链接解析出商品ID');

  const timestamp = Math.floor(Date.now() / 1000);
  const sign = crypto.createHash('md5').update(appKey + (appSecret || '') + timestamp).digest('hex');

  const result = await httpGet(`${baseUrl}/api/item/get`, {
    app_key: appKey,
    timestamp,
    sign,
    item_id: itemId,
    type: 'taobao'
  });

  const code = result.code ?? -1;
  if (code !== 0 && code !== 200) {
    throw new Error(result.msg || result.message || '一号通接口报错');
  }

  const d = result.data || result.result || result;
  return {
    title: d.title || '',
    images: Array.isArray(d.images) ? d.images : (d.images ? [d.images] : []),
    description: d.desc || d.description || '',
    price: '0.00',
    original_price: d.price || d.original_price || '0.00',
    origin_price: d.price || d.original_price || '0.00',
    specs: formatSkus(d.skus || d.specs || []),
    source_url: d.url || itemUrl
  };
}

// ---------- 99采集驱动 ----------
// GET {api_url}/item/info?apikey=&secret=&item_url=
// 期望响应: {status: 'success', result: {item_title, item_imgs, item_desc, item_price, sku_list, item_url}}

async function fetch99cai(itemUrl, appKey, appSecret) {
  const cfg = getConfig();
  const baseUrl = cfg.api_url || 'https://api.99cai.example.com/api';
  const result = await httpGet(`${baseUrl}/item/info`, {
    apikey: appKey,
    secret: appSecret,
    item_url: itemUrl
  });
  if (result.status !== 'success') {
    throw new Error(result.message || result.msg || '99采集接口返回异常');
  }
  const r = result.result || {};
  return {
    title: r.item_title || '',
    images: r.item_imgs ? r.item_imgs.split(',').filter(Boolean) : [],
    description: r.item_desc || '',
    price: '0.00',
    original_price: r.item_price || '0.00',
    origin_price: r.item_price || '0.00',
    specs: formatSkus(r.sku_list || r.skus || []),
    source_url: r.item_url || itemUrl
  };
}

// ---------- SKU 格式化 ----------

function formatSkus(skus) {
  if (!Array.isArray(skus) || skus.length === 0) {
    return [{ spec_name: '默认', price: '0.00', stock: 999 }];
  }
  return skus.map(s => ({
    spec_name: s.name || s.spec_name || '默认',
    price: s.price || '0.00',
    stock: s.stock || 999,
    sku_id: s.id || s.sku_id || ''
  }));
}

// ---------- 路由 ----------

router.get('/config', (req, res) => {
  res.json({ code: 0, data: getConfig() });
});

router.post('/config', (req, res) => {
  const { type, app_key, app_secret, api_url } = req.body;
  saveConfig('type', type || 'yihaotong');
  saveConfig('app_key', app_key || '');
  saveConfig('app_secret', app_secret || '');
  saveConfig('api_url', api_url || '');
  res.json({ code: 0, message: '配置已保存' });
});

router.post('/execute', async (req, res) => {
  const { content } = req.body;
  if (!content) return res.json({ code: 1, message: '请输入采集内容' });

  const cfg = getConfig();

  try {
    let product;

    if (cfg.type === '99cai') {
      if (!cfg.app_key || !cfg.app_secret) {
        return res.json({ code: 1, message: '99采集需要填写 AppKey 和 AppSecret' });
      }
      product = await fetch99cai(content, cfg.app_key, cfg.app_secret);
    } else {
      if (!cfg.app_key) {
        return res.json({ code: 1, message: '一号通需要填写 AppKey' });
      }
      product = await fetchYihaotong(content, cfg.app_key, cfg.app_secret);
    }

    return res.json({ code: 0, data: product });

  } catch (e) {
    console.error('[采集]', cfg.type, e.message);
    return res.json({
      code: 0,
      data: {
        title: '演示商品 - ' + content.substring(0, 20),
        images: ['data:image/svg+xml,' + encodeURIComponent('<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200"><rect width="200" height="200" fill="#f0f0f0"/><text x="50%" y="50%" text-anchor="middle" dominant-baseline="middle" font-size="14" fill="#999">暂无图片</text></svg>')],
        description: '采集服务暂不可用，返回演示数据（' + e.message + '）',
        price: '0.00',
        original_price: '99.00',
        origin_price: '99.00',
        specs: [{ spec_name: '默认', price: '0.00', stock: 999 }],
        source_url: content
      },
      demo: true,
      message: e.message
    });
  }
});

router.get('/logs', authAdmin, (req, res) => {
  const logs = all("SELECT * FROM operation_logs WHERE module='collect' ORDER BY id DESC LIMIT 20");
  res.json({ code: 0, data: logs });
});

module.exports = { router, fetchYihaotong, fetch99cai, getConfig, formatSkus };
