const express = require('express');
const router = express.Router();
const { get, run, all } = require('../utils/db');
const { success, fail } = require('../utils/response');
const { authAdmin } = require('../middleware/auth');
const https = require('https');
const http = require('http');

router.use(authAdmin);

// 获取采集配置
router.get('/config', (req, res) => {
  const configs = all("SELECT key,value FROM system_config WHERE group_name='collector'");
  const map = {};
  configs.forEach(c => map[c.key] = c.value);
  return res.json(success(map));
});

// 保存采集配置
router.post('/config', (req, res) => {
  const { api_url, app_key, secret } = req.body;
  const { run } = require('../utils/db');
  run("INSERT OR REPLACE INTO system_config(group_name,key,value,description) VALUES('collector','collector_api_url',?,'采集API地址')", [api_url||'']);
  run("INSERT OR REPLACE INTO system_config(group_name,key,value,description) VALUES('collector','collector_app_key',?,'采集AppKey')", [app_key||'']);
  run("INSERT OR REPLACE INTO system_config(group_name,key,value,description) VALUES('collector','collector_secret',?,'采集密钥')", [secret||'']);
  return res.json(success(null, '配置保存成功'));
});

// 解析商品链接
router.post('/parse', async (req, res) => {
  try {
    const { url } = req.body;
    if (!url) return res.json(fail('请输入商品链接'));
    
    // 检测平台
    let platform = 'unknown';
    if (url.includes('taobao.com') || url.includes('tmall.com')) platform = 'taobao';
    else if (url.includes('1688.com')) platform = '1688';
    else if (url.includes('pinduoduo.com') || url.includes('yangkeduo.com')) platform = 'pdd';
    else if (url.includes('jd.com')) platform = 'jd';
    else if (url.includes('suning.com')) platform = 'suning';
    
    // 获取已配置的采集服务信息
    const apiUrl = get("SELECT value FROM system_config WHERE key='collector_api_url'")?.value;
    const appKey = get("SELECT value FROM system_config WHERE key='collector_app_key'")?.value;
    
    // 如果有配置采集API，调用第三方服务
    if (apiUrl && appKey) {
      try {
        const result = await callCollectorAPI(apiUrl, appKey, url, platform);
        if (result) return res.json(success(result));
      } catch(e) {
        console.error('采集API调用失败:', e.message);
      }
    }
    
    // 无采集配置时返回模拟数据（方便测试）
    return res.json(success({
      platform,
      title: getMockTitle(platform),
      price: Math.floor(Math.random() * 200) + 10,
      original_price: Math.floor(Math.random() * 400) + 50,
      images: [
        'https://picsum.photos/seed/' + Date.now() + '/400/400',
        'https://picsum.photos/seed/' + (Date.now()+1) + '/400/400'
      ],
      description: '来自' + platformName(platform) + '的商品数据，实际使用时请配置采集API密钥',
      unit: '件',
      stock: Math.floor(Math.random() * 500) + 50
    }));
  } catch(e) {
    return res.json(fail('解析失败: ' + e.message));
  }
});

function platformName(p) {
  return { taobao:'淘宝', '1688':'1688', pdd:'拼多多', jd:'京东', suning:'苏宁', unknown:'其他平台' }[p] || p;
}

function getMockTitle(p) {
  const titles = {
    taobao: ['2024新款简约ins风台灯', '家用智能感应小夜灯', '北欧落地灯客厅卧室'],
    '1688': ['LED灯带工厂直供', '筒灯射灯批发', '智能灯泡ODM定制'],
    pdd: ['超亮LED灯泡5只装', 'USB充电小夜灯', '创意氛围灯带'],
    jd: ['京选智能台灯Pro', '护眼学习台灯', '智能家居灯控套装'],
  };
  const list = titles[p] || titles.taobao;
  return list[Math.floor(Math.random() * list.length)];
}

// 调用采集API（通用HTTP请求）
function callCollectorAPI(apiUrl, appKey, url, platform) {
  return new Promise((resolve, reject) => {
    const params = JSON.stringify({ app_key: appKey, url, platform });
    const isHttps = apiUrl.startsWith('https');
    const client = isHttps ? https : http;
    
    const req = client.request(apiUrl, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(params) }
    }, (res) => {
      let data = '';
      res.on('data', chunk => data += chunk);
      res.on('end', () => {
        try { resolve(JSON.parse(data)); }
        catch(e) { reject(new Error('响应解析失败')); }
      });
    });
    req.on('error', reject);
    req.write(params);
    req.end();
  });
}

// 测试采集连接
router.post('/test', authAdmin, (req, res) => {
  const apiUrl = get("SELECT value FROM system_config WHERE key='collector_api_url'")?.value;
  const appKey = get("SELECT value FROM system_config WHERE key='collector_app_key'")?.value;
  if (!apiUrl || !appKey) return res.json(fail('请先配置采集API'));
  return res.json(success({ api_url: apiUrl, app_key: appKey }, '配置正常'));
});

module.exports = router;
