const express = require('express');
const fs = require('fs');
const path = require('path');
const bcrypt = require('bcrypt');
const bodyParser = require('body-parser');

const app = express();
const PORT = 3000;
const USER_FILE = path.join(__dirname, 'user.json');

// 中间件
app.use(bodyParser.json());

// 初始化用户文件（如果不存在）
if (!fs.existsSync(USER_FILE)) {
    fs.writeFileSync(USER_FILE, JSON.stringify([], null, 2));
}

// 读取用户数据
function readUsers() {
    try {
        const data = fs.readFileSync(USER_FILE, 'utf8');
        return JSON.parse(data);
    } catch (err) {
        console.error('Error reading user file:', err);
        return [];
    }
}

// 写入用户数据
function writeUsers(users) {
    try {
        fs.writeFileSync(USER_FILE, JSON.stringify(users, null, 2));
    } catch (err) {
        console.error('Error writing user file:', err);
    }
}

// 文档路由
app.get("/device", (req, res) => {
    /**
     这个JSON结构包含了以下主要信息：

    设备基本信息（ID、类型、制造商等）

    时间戳（ISO 8601格式）

    定位信息（经纬度、高度、精度、速度和方向）

    电池状态（电量、电压、充电状态和剩余续航）

    车辆状态（点火状态、锁定状态等）

    环境数据（温度和湿度）

    遥测数据（里程、总运行时间、信号强度）

    附加数据（GPS定位类型、可见卫星数等）

    您可以根据实际需求调整字段或添加更多信息。
     */
    res.json({
        "device": {
            "id": "EBike-123456789",
            "type": "electric_bike",
            "manufacturer": "ExampleTech",
            "model": "ET-3000",
            "firmware_version": "1.2.3"
        },
        "timestamp": "2023-05-16T14:30:45Z",
        "location": {
            "latitude": 39.9042,
            "longitude": 116.4074,
            "altitude": 45.2,
            "accuracy": 5.0,
            "speed": 25.5,
            "heading": 180.0
        },
        "battery": {
            "level": 78.5,
            "voltage": 48.2,
            "charging": false,
            "remaining_range": 65.2
        },
        "status": {
            "ignition": true,
            "locked": false,
            "alarm_triggered": false,
            "maintenance_required": false
        },
        "environment": {
            "temperature": 28.5,
            "humidity": 45.0
        },
        "telemetry": {
            "odometer": 1250.3,
            "total_runtime": 3568,
            "signal_strength": 85
        },
        "additional_data": {
            "gps_fix_type": "3D",
            "satellites_in_view": 12,
            "cellular_network": "5G",
            "timestamp_device": "2023-05-16T14:30:45Z"
        }
    })
})
// API文档路由
app.get('/', (req, res) => {
    const apiDocs = {
        description: '用户认证服务API文档',
        endpoints: [
            {
                method: 'POST',
                path: '/signup',
                description: '用户注册',
                requestBody: {
                    username: 'string (必需)',
                    password: 'string (必需)'
                },
                responses: {
                    '201': '用户创建成功',
                    '400': '用户名已存在或缺少用户名/密码'
                }
            },
            {
                method: 'POST',
                path: '/login',
                description: '用户登录',
                requestBody: {
                    username: 'string (必需)',
                    password: 'string (必需)'
                },
                responses: {
                    '200': '登录成功',
                    '400': '缺少用户名/密码',
                    '401': '无效的用户名或密码'
                }
            }
        ],
        note: '所有密码都会经过哈希处理后再存储'
    };

    res.json(apiDocs);
});

app.get("/test", (req, res) => {

    let style = `
        h1{
            color:red;
        }
    `
    let template = `<h1>这里是测试页面</h1>`


    res.write(`<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>TEST UTF-8编码示例</title>
    <style>${style}</style>
</head>
<body>
    ${template}
</body>
</html>`)
})

// 注册路由
app.post('/signup', async (req, res) => {
    const { username, password } = req.body;

    if (!username || !password) {
        return res.status(400).json({ error: 'Username and password are required' });
    }

    const users = readUsers();

    // 检查用户是否已存在
    if (users.some(user => user.username === username)) {
        return res.status(400).json({ error: 'Username already exists' });
    }

    // 哈希密码
    const hashedPassword = await bcrypt.hash(password, 10);

    // 添加新用户
    users.push({
        username,
        password: hashedPassword
    });

    writeUsers(users);

    res.status(201).json({ message: 'User created successfully' });
});

// 登录路由
app.post('/login', async (req, res) => {
    const { username, password } = req.body;

    if (!username || !password) {
        return res.status(400).json({ error: 'Username and password are required' });
    }

    const users = readUsers();
    const user = users.find(user => user.username === username);

    if (!user) {
        return res.status(401).json({ error: 'Invalid username or password' });
    }

    // 验证密码
    const passwordMatch = await bcrypt.compare(password, user.password);

    if (!passwordMatch) {
        return res.status(401).json({ error: 'Invalid username or password' });
    }

    res.json({ message: 'Login successful' });
});

// 启动服务器
app.listen(PORT, () => {
    console.log(`Server is running on http://localhost:${PORT}`);
});