const express = require('express');
const { createProxyMiddleware } = require('http-proxy-middleware');
const path = require('path');

const app = express();
const PORT = 8081;

// CORS 中间件
app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
  res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
  if (req.method === 'OPTIONS') {
    return res.sendStatus(200);
  }
  next();
});

// 专用代理：牛只行情数据 (ad.yunmainiu.com)
// 必须放在通用的 /api 代理之前
app.use('/api/cattle-market-data', createProxyMiddleware({
  target: 'https://ad.yunmainiu.com',
  changeOrigin: true,
  secure: false,
  pathRewrite: {
    '^/': '/api/cattle-data',
  },
  onProxyReq: (proxyReq, req, res) => {
    console.log(`[牛只行情代理] ${req.method} ${req.url} -> https://ad.yunmainiu.com/api/cattle-data`);
    // 伪装请求头，防止被反爬或校验
    proxyReq.setHeader('Host', 'ad.yunmainiu.com');
    proxyReq.setHeader('Referer', 'https://ad.yunmainiu.com/');
    proxyReq.setHeader('User-Agent', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36');
  },
  onProxyRes: (proxyRes, req, res) => {
    console.log(`[牛只行情代理响应] 状态码: ${proxyRes.statusCode}`);
    // 允许跨域：覆盖目标服务器的 CORS 设置
    delete proxyRes.headers['access-control-allow-origin'];
    proxyRes.headers['Access-Control-Allow-Origin'] = '*';
  }
}));

// API 代理：必须在静态文件服务之前，将 /api 请求代理到 cattletrack.aiotagro.com
app.use('/api', createProxyMiddleware({
  // 注意：app.use('/api') 会剥离 '/api' 前缀，所以 req.url 变成了 '/login'
  // 我们将 target 设置为根域名，并通过 pathRewrite 手动添加 /api 前缀
  target: 'https://cattletrack.aiotagro.com',
  changeOrigin: true,
  secure: false,
  pathRewrite: {
    '^/': '/api/', // 将 /login 重写为 /api/login
  },
  onProxyReq: (proxyReq, req, res) => {
    // 这里的 req.url 已经被 Express 剥离了 /api 前缀，例如变为 /login
    // pathRewrite 将其变为 /api/login
    // target 是 ...com，所以最终请求 url 是 ...com/api/login
    console.log(`[代理] ${req.method} ${req.originalUrl} -> ${proxyReq.protocol}//${proxyReq.host}${proxyReq.path}`);
    // 确保请求方法正确转发
    proxyReq.method = req.method;
  },
  onProxyRes: (proxyRes, req, res) => {
    console.log(`[代理响应] ${req.method} ${req.url} - 状态码: ${proxyRes.statusCode}`);
  },
  onError: (err, req, res) => {
    console.error('[代理错误]', err);
    res.status(500).json({ error: '代理请求失败', details: err.message });
  }
}));

// 静态文件服务：提供 datav 目录下的文件
app.use(express.static(__dirname));

app.listen(PORT, () => {
  console.log(`服务器已启动: http://127.0.0.1:${PORT}`);
  console.log(`启动时间: ${new Date().toLocaleString()}`);
  console.log(`请访问: http://127.0.0.1:${PORT}/index.html`);
});

