const express = require("express");
const bodyParser = require("body-parser");
const jwt = require("jsonwebtoken");
const bcrypt = require("bcrypt"); // 添加 bcrypt 模块
const logoutRouter = require("./routes/logout");
const router = express.Router();
const secretKey = 'wukeyun';

const app = express();
const mysql = require("mysql");
const conn = mysql.createConnection({
  host: "127.0.0.1",
  user: "root",
  password: "wujiahao",
  database: "wukeyun",
  multipleStatements: true
});

app.use(express.static("public"));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

app.all("*", function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Content-Type");
  res.header("Access-Control-Allow-Methods", "*");
  // res.header("Content-Type", "application/json;charset=utf-8");
  res.header("Content-Type", "application/x-www-form-urlencoded")
  next();
});

router.get('/', function(req, res) {
    // 获取 token
    const token = req.cookies.token; // 假设 token 存储在 cookie 中，你也可以根据你的实际情况获取 token

    // 如果 token 存在，验证 token 的有效性
    if (token) {
        jwt.verify(token, secretKey, (err, decoded) => {
            if (err) {
                // 如果验证失败，发送 login.html 页面
                res.sendFile('public/login.html', { root: __dirname });
            } else {
                // 如果验证成功，发送 index.html 页面
                res.sendFile('public/index.html', { root: __dirname });
            }
        });
    } else {
        // 如果没有 token，发送 login.html 页面
        res.sendFile('public/login.html', { root: __dirname });
        console.log('login.html 页面已发送');
    }
});

app.use("/logout", logoutRouter);

app.post("/login", (req, res) => {
  const { userName, passWord } = req.body;

  if (!userName || !passWord) {
    return res.status(400).json({ code: 400, msg: "用户名与密码为必填参数..." });
  }

  // 使用 bcrypt 进行密码验证
  conn.query("SELECT id, userName, passWord, identity FROM user WHERE userName = ?", [userName], (err, results) => {
    if (err) {
      console.error("Database error:", err);
      return res.status(500).json({ code: 500, msg: "数据库错误" });
    }

    if (results.length === 0) {
		console.log(req)
      return res.status(401).json({ code: 404, msg: "用户名或密码错误" });
    }

    const user = results[0];
    bcrypt.compare(passWord, user.passWord, (err, passwordMatch) => {
      if (err) {
        console.error("Bcrypt error:", err);
        return res.status(500).json({ code: 404, msg: "用户名或密码错误" });
      }

      if (!passwordMatch) {
        return res.status(401).json({ code: 404, msg: "用户名或密码错误" });
      }

      const token = jwt.sign(
          { userId: user.id, identity: user.identity, userName: user.userName },
          secretKey,
          { expiresIn: '12h' }
      );
      res.json({ code: 200, msg: "登录成功", token });
    });
  });
});

app.post("/register", (req, res) => {
  const { userName, passWord } = req.body;

  if (!userName || !passWord) {
    return res.status(400).json({ code: 0, msg: "用户名与密码为必传参数..." });
  }

  // 使用 bcrypt 生成加密后的密码
  bcrypt.hash(passWord, 10, (err, hashedPassword) => {
    if (err) {
      console.error("Bcrypt hash error:", err);
      return res.status(500).json({ code: 0, msg: "密码加密错误" });
    }

    const sqlStr = "INSERT INTO user (userName, passWord) VALUES (?, ?)";
    conn.query(sqlStr, [userName, hashedPassword], (err, results) => {
      if (err) {
        console.error("Database error:", err);
        return res.status(500).json({ code: 0, msg: "数据库错误" });
      }

      res.json({ code: 1, msg: "注册成功" });
    });
  });
});

app.post('/verifyToken', (req, res) => {
    const { token } = req.body;

    // 验证 Token 的有效性
    jwt.verify(token, secretKey, (err, decoded) => {
        if (err) {
            res.json({ valid: false });
        } else {
            // 如果 Token 有效，decoded 中包含了 Token 解码后的信息
            res.json({ valid: true, userId: decoded.userId });
        }
    });
});

app.listen(4000, () => {
  console.log("4000端口已经启动。。。");
});
