const express = require('express');
const mysql = require('mysql2');
const cors = require('cors');
const bodyParser = require('body-parser');
const fs = require('fs');
const path = require('path');

// 创建Express应用
const app = express();
const port = 2342;

// 启用CORS和JSON解析
app.use(cors());
app.use(bodyParser.json());

// 创建logs目录(如果不存在)
const logsDir = path.join(__dirname, 'logs');
if (!fs.existsSync(logsDir)) {
    fs.mkdirSync(logsDir);
}

// 简单日志函数
function logToFile(message) {
    const logFile = path.join(logsDir, 'api.log');
    const timestamp = new Date().toISOString();
    fs.appendFileSync(logFile, `${timestamp} - ${message}\n`);
    console.log(`${timestamp} - ${message}`);
}

// 数据库连接配置
const dbConfig = {
    host: 'localhost',
    port: 25342,           // 修改为正确的MySQL端口
    user: 'hongm',         // 替换为您的数据库用户名
    password: 'JsKJeG7CX2WnyArt',     // 替换为您的数据库密码
    database: 'hongm',
    waitForConnections: true,
    connectionLimit: 10,
    queueLimit: 0
};

// 创建数据库连接池
const pool = mysql.createPool(dbConfig);
const promisePool = pool.promise();

// 检查数据库连接
async function checkDbConnection() {
    try {
        const connection = await promisePool.getConnection();
        logToFile('数据库连接成功');
        connection.release();
        return true;
    } catch (error) {
        logToFile(`数据库连接失败: ${error.message}`);
        return false;
    }
}

// 在启动时测试数据库连接
checkDbConnection();

// 创建一个简单的首页响应
app.get('/', (req, res) => {
    res.send('智能教室管理系统API服务正在运行');
});

// 创建一个图片目录路由
app.use('/images', express.static(path.join(__dirname, 'images')));

// API: 用户登录验证
app.post('/api/login', async (req, res) => {
    try {
        logToFile(`收到登录请求: ${JSON.stringify(req.body)}`);
        const { account, password } = req.body;

        if (!account || !password) {
            return res.status(400).json({
                success: false,
                message: '账号和密码不能为空'
            });
        }

        // 查询密码
        const [passwordRows] = await promisePool.query(
            'SELECT password FROM UserPassword WHERE account = ?',
            [account]
        );

        if (passwordRows.length === 0) {
            logToFile(`登录失败: 账号 ${account} 不存在`);
            return res.status(401).json({
                success: false,
                message: '账号不存在'
            });
        }

        const storedPassword = passwordRows[0].password;

        if (password !== storedPassword) {
            logToFile(`登录失败: 账号 ${account} 密码错误`);
            return res.status(401).json({
                success: false,
                message: '密码错误'
            });
        }

        // 查询用户信息
        const [userRows] = await promisePool.query(
            'SELECT * FROM UserText WHERE account = ?',
            [account]
        );

        if (userRows.length === 0) {
            logToFile(`登录异常: 账号 ${account} 存在但用户信息丢失`);
            return res.status(500).json({
                success: false,
                message: '用户信息不存在'
            });
        }

        const user = userRows[0];
        logToFile(`登录成功: 账号 ${account}, 用户名 ${user.nickname}`);

        // 返回成功登录信息和用户数据
        res.json({
            success: true,
            message: '登录成功',
            user: {
                account: user.account,
                nickname: user.nickname,
                email: user.email || '',
                phone: user.phone || '',
                photo: user.photo || 'http://139.155.155.67:2342/images/default_avatar.png',
                category: user.category
            }
        });
    } catch (error) {
        logToFile(`登录错误: ${error.message}`);
        res.status(500).json({
            success: false,
            message: '服务器错误',
            error: error.message
        });
    }
});

// API: 获取用户信息
app.get('/api/user/:account', async (req, res) => {
    try {
        const { account } = req.params;
        logToFile(`获取用户信息请求: 账号 ${account}`);

        // 查询用户信息
        const [userRows] = await promisePool.query(
            'SELECT * FROM UserText WHERE account = ?',
            [account]
        );

        if (userRows.length === 0) {
            logToFile(`获取用户信息失败: 账号 ${account} 不存在`);
            return res.status(404).json({
                success: false,
                message: '用户不存在'
            });
        }

        const user = userRows[0];
        logToFile(`获取用户信息成功: 账号 ${account}, 用户名 ${user.nickname}`);

        // 返回用户数据
        res.json({
            success: true,
            user: {
                account: user.account,
                nickname: user.nickname,
                email: user.email || '',
                phone: user.phone || '',
                photo: user.photo || 'http://139.155.155.67:2342/images/default_avatar.png',
                category: user.category
            }
        });
    } catch (error) {
        logToFile(`获取用户信息错误: ${error.message}`);
        res.status(500).json({
            success: false,
            message: '服务器错误',
            error: error.message
        });
    }
});

// API: 更新用户邮箱
app.put('/api/user/:account/email', async (req, res) => {
    try {
        const { account } = req.params;
        const { email } = req.body;
        logToFile(`更新用户邮箱请求: 账号 ${account}, 新邮箱 ${email}`);

        // 验证邮箱格式
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        if (!emailRegex.test(email)) {
            logToFile(`更新邮箱失败: 邮箱格式无效 ${email}`);
            return res.status(400).json({
                success: false,
                message: '邮箱格式无效'
            });
        }

        // 检查用户是否存在
        const [userCheck] = await promisePool.query(
            'SELECT account FROM UserText WHERE account = ?',
            [account]
        );

        if (userCheck.length === 0) {
            logToFile(`更新邮箱失败: 账号 ${account} 不存在`);
            return res.status(404).json({
                success: false,
                message: '用户不存在'
            });
        }

        // 更新邮箱
        const [result] = await promisePool.query(
            'UPDATE UserText SET email = ? WHERE account = ?',
            [email, account]
        );

        if (result.affectedRows === 0) {
            logToFile(`更新邮箱失败: 账号 ${account} 无法更新`);
            return res.status(500).json({
                success: false,
                message: '更新邮箱失败'
            });
        }

        logToFile(`更新邮箱成功: 账号 ${account}, 新邮箱 ${email}`);
        res.json({
            success: true,
            message: '邮箱更新成功'
        });
    } catch (error) {
        logToFile(`更新邮箱错误: ${error.message}`);
        res.status(500).json({
            success: false,
            message: '服务器错误',
            error: error.message
        });
    }
});

// API: 用户注册
app.post('/api/register', async (req, res) => {
    try {
        const { account, password, nickname, email, phone, photo } = req.body;
        logToFile(`收到注册请求: ${JSON.stringify(req.body)}`);

        // 验证必填字段
        if (!account || !password || !email) {
            return res.status(400).json({
                success: false,
                message: '账号、密码和邮箱为必填项'
            });
        }

        // 检查账号是否已存在
        const [existingUser] = await promisePool.query(
            'SELECT account FROM UserText WHERE account = ?',
            [account]
        );

        if (existingUser.length > 0) {
            logToFile(`注册失败: 账号 ${account} 已存在`);
            return res.status(400).json({
                success: false,
                message: '账号已存在'
            });
        }

        // 检查邮箱是否已存在
        const [existingEmail] = await promisePool.query(
            'SELECT email FROM UserText WHERE email = ?',
            [email]
        );

        if (existingEmail.length > 0) {
            logToFile(`注册失败: 邮箱 ${email} 已被使用`);
            return res.status(400).json({
                success: false,
                message: '邮箱已被使用'
            });
        }

        // 开始事务
        const connection = await promisePool.getConnection();
        await connection.beginTransaction();

        try {
            // 插入用户基本信息
            await connection.query(
                'INSERT INTO UserText (account, nickname, email, phone, photo, category) VALUES (?, ?, ?, ?, ?, ?)',
                [account, nickname || account, email, phone || null, photo || 'http://139.155.155.67:2342/images/default_avatar.png', 'user']
            );

            // 插入用户密码
            await connection.query(
                'INSERT INTO UserPassword (account, password) VALUES (?, ?)',
                [account, password]
            );

            // 提交事务
            await connection.commit();
            logToFile(`注册成功: 账号 ${account}, 昵称 ${nickname || account}`);

            res.json({
                success: true,
                message: '注册成功',
                user: {
                    account,
                    nickname: nickname || account,
                    email,
                    phone: phone || '',
                    photo: photo || 'http://139.155.155.67:2342/images/default_avatar.png',
                    category: 'user'
                }
            });
        } catch (error) {
            // 回滚事务
            await connection.rollback();
            throw error;
        } finally {
            connection.release();
        }
    } catch (error) {
        logToFile(`注册错误: ${error.message}`);
        res.status(500).json({
            success: false,
            message: '注册失败，请稍后重试',
            error: error.message
        });
    }
});

// 启动服务器
app.listen(port, '0.0.0.0', () => {
    logToFile(`API服务运行在端口 ${port}`);
});