const express = require('express');
const puppeteer = require('puppeteer');
const cors = require('cors');
const sharp = require('sharp');
const fs = require('fs');
const os = require('os');
const path = require('path');


const app = express();
const port = 3000;

app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: false }))

app.post('/screenshot', async (req, res) => {
    const { html } = req.body;

    try {
        const browser = await puppeteer.launch();
        const page = await browser.newPage();
        await page.setContent(html);
        const screenshotBuffer = await page.screenshot({ fullPage: true });
        await browser.close();

        // 压缩截图
        const compressedScreenshotBuffer = await sharp(screenshotBuffer)
            .resize({ width: 800 }) // 调整宽度为800像素，可以根据需要进行修改
            .toBuffer();

        // 保存截图到本地文件系统的 temp 文件夹中
        const fileName = `screenshot_${Date.now()}.png`;
        const filePath = path.join(__dirname, 'temp', fileName);
        fs.writeFileSync(filePath, compressedScreenshotBuffer);

        // 构建图片的网络地址
        const imageUrl = `http://${getLocalIP()}:${port}/temp/${fileName}`;

        res.send(imageUrl);
    } catch (error) {
        console.error('生成截图失败：', error);
        res.status(500).send('生成截图失败');
    }
});

app.listen(port, () => {
    console.log(`服务器部署在了` + getLocalIP() + `:${port}`);
});

// 获取本地 IP 地址
function getLocalIP() {
    const interfaces = os.networkInterfaces();
    for (const interfaceName in interfaces) {
        const interface = interfaces[interfaceName];
        for (const iface of interface) {
            if (iface.family === 'IPv4' && !iface.internal) {
                return iface.address;
            }
        }
    }
    return 'localhost';
}