const express = require('express');
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
const router = express.Router();

// 导入数据库连接（假设从主服务器文件导入）
// 这里暂时用模拟数据，待数据库连接修复后更新
let pool = null;

// 设置数据库连接池（将从主服务器导入）
function setPool(dbPool) {
  pool = dbPool;
}

// JWT中间件验证
const authenticateToken = (req, res, next) => {
  const authHeader = req.headers['authorization'];
  const token = authHeader && authHeader.split(' ')[1];

  if (!token) {
    return res.status(401).json({ 
      success: false, 
      message: '访问令牌缺失',
      code: 'TOKEN_MISSING'
    });
  }

  jwt.verify(token, process.env.JWT_SECRET, (err, user) => {
    if (err) {
      return res.status(403).json({ 
        success: false, 
        message: '访问令牌无效或已过期',
        code: 'TOKEN_INVALID'
      });
    }
    req.user = user;
    next();
  });
};

// 权限检查中间件
const checkPermission = (requiredPermission) => {
  return async (req, res, next) => {
    try {
      if (!pool) {
        return res.status(500).json({
          success: false,
          message: '数据库连接不可用',
          code: 'DB_UNAVAILABLE'
        });
      }

      // 查询用户权限
      const [permissions] = await pool.execute(`
        SELECT p.name as permission_name 
        FROM users u
        JOIN user_roles ur ON u.id = ur.user_id
        JOIN role_permissions rp ON ur.role_id = rp.role_id
        JOIN permissions p ON rp.permission_id = p.id
        WHERE u.id = ?
      `, [req.user.userId]);

      const userPermissions = permissions.map(p => p.permission_name);
      
      if (!userPermissions.includes(requiredPermission)) {
        return res.status(403).json({
          success: false,
          message: '权限不足',
          code: 'INSUFFICIENT_PERMISSION',
          required: requiredPermission
        });
      }

      req.userPermissions = userPermissions;
      next();
    } catch (error) {
      console.error('权限检查错误:', error);
      res.status(500).json({
        success: false,
        message: '权限检查失败',
        code: 'PERMISSION_CHECK_ERROR'
      });
    }
  };
};

// 用户注册
router.post('/register', async (req, res) => {
  try {
    const { username, email, phone, password, real_name, user_type } = req.body;

    // 输入验证
    if (!username || !password || !user_type) {
      return res.status(400).json({
        success: false,
        message: '用户名、密码和用户类型为必填项',
        code: 'MISSING_REQUIRED_FIELDS'
      });
    }

    if (!pool) {
      return res.status(500).json({
        success: false,
        message: '数据库连接不可用，请稍后重试',
        code: 'DB_UNAVAILABLE'
      });
    }

    // 检查用户名是否已存在
    const [existingUsers] = await pool.execute(
      'SELECT id FROM users WHERE username = ? OR email = ? OR phone = ?',
      [username, email || null, phone || null]
    );

    if (existingUsers.length > 0) {
      return res.status(409).json({
        success: false,
        message: '用户名、邮箱或手机号已存在',
        code: 'USER_EXISTS'
      });
    }

    // 密码加密
    const saltRounds = 10;
    const password_hash = await bcrypt.hash(password, saltRounds);

    // 插入新用户
    const [result] = await pool.execute(
      'INSERT INTO users (username, email, phone, password_hash, real_name, user_type) VALUES (?, ?, ?, ?, ?, ?)',
      [username, email || null, phone || null, password_hash, real_name || null, user_type]
    );

    res.status(201).json({
      success: true,
      message: '用户注册成功',
      data: {
        userId: result.insertId,
        username,
        user_type
      }
    });

  } catch (error) {
    console.error('用户注册错误:', error);
    res.status(500).json({
      success: false,
      message: '注册失败，请稍后重试',
      code: 'REGISTRATION_ERROR'
    });
  }
});

// 用户登录
router.post('/login', async (req, res) => {
  try {
    const { username, password } = req.body;

    if (!username || !password) {
      return res.status(400).json({
        success: false,
        message: '用户名和密码为必填项',
        code: 'MISSING_CREDENTIALS'
      });
    }

    if (!pool) {
      // 数据库不可用时返回模拟数据（用于测试）
      if (username === 'admin' && password === 'admin123') {
        const token = jwt.sign(
          { userId: 1, username: 'admin', user_type: 'admin' },
          process.env.JWT_SECRET,
          { expiresIn: process.env.JWT_EXPIRES_IN || '24h' }
        );

        return res.json({
          success: true,
          message: '登录成功（测试模式）',
          data: {
            token,
            user: {
              id: 1,
              username: 'admin',
              user_type: 'admin',
              real_name: '系统管理员'
            }
          }
        });
      } else {
        return res.status(401).json({
          success: false,
          message: '用户名或密码错误',
          code: 'INVALID_CREDENTIALS'
        });
      }
    }

    // 检查数据库连接是否可用
    try {
      await pool.execute('SELECT 1');
    } catch (dbError) {
      // 数据库连接失败，使用测试模式
      if (username === 'admin' && password === 'admin123') {
        const token = jwt.sign(
          { userId: 1, username: 'admin', user_type: 'admin' },
          process.env.JWT_SECRET,
          { expiresIn: process.env.JWT_EXPIRES_IN || '24h' }
        );

        return res.json({
          success: true,
          message: '登录成功（测试模式 - 数据库不可用）',
          data: {
            token,
            user: {
              id: 1,
              username: 'admin',
              user_type: 'admin',
              real_name: '系统管理员'
            }
          }
        });
      } else {
        return res.status(401).json({
          success: false,
          message: '用户名或密码错误（测试模式）',
          code: 'INVALID_CREDENTIALS'
        });
      }
    }

    // 查询用户
    const [users] = await pool.execute(
      'SELECT id, username, password_hash, user_type, real_name, status FROM users WHERE username = ?',
      [username]
    );

    if (users.length === 0) {
      return res.status(401).json({
        success: false,
        message: '用户名或密码错误',
        code: 'INVALID_CREDENTIALS'
      });
    }

    const user = users[0];

    // 检查用户状态
    if (user.status === 0) {
      return res.status(403).json({
        success: false,
        message: '用户账号已被禁用',
        code: 'ACCOUNT_DISABLED'
      });
    }

    // 验证密码
    const isPasswordValid = await bcrypt.compare(password, user.password_hash);
    if (!isPasswordValid) {
      return res.status(401).json({
        success: false,
        message: '用户名或密码错误',
        code: 'INVALID_CREDENTIALS'
      });
    }

    // 生成JWT令牌
    const token = jwt.sign(
      { 
        userId: user.id, 
        username: user.username, 
        user_type: user.user_type 
      },
      process.env.JWT_SECRET,
      { expiresIn: process.env.JWT_EXPIRES_IN || '24h' }
    );

    // 更新最后登录时间
    await pool.execute(
      'UPDATE users SET last_login = CURRENT_TIMESTAMP WHERE id = ?',
      [user.id]
    );

    res.json({
      success: true,
      message: '登录成功',
      data: {
        token,
        user: {
          id: user.id,
          username: user.username,
          user_type: user.user_type,
          real_name: user.real_name
        }
      }
    });

  } catch (error) {
    console.error('用户登录错误:', error);
    res.status(500).json({
      success: false,
      message: '登录失败，请稍后重试',
      code: 'LOGIN_ERROR'
    });
  }
});

// 获取当前用户信息
router.get('/profile', authenticateToken, async (req, res) => {
  try {
    if (!pool) {
      // 数据库不可用时返回模拟数据
      return res.json({
        success: true,
        data: {
          id: req.user.userId,
          username: req.user.username,
          user_type: req.user.user_type,
          real_name: '系统管理员',
          email: 'admin@xlxumu.com',
          status: 1
        }
      });
    }

    // 检查数据库连接
    try {
      await pool.execute('SELECT 1');
    } catch (dbError) {
      // 数据库连接失败，返回模拟数据
      return res.json({
        success: true,
        data: {
          id: req.user.userId,
          username: req.user.username,
          user_type: req.user.user_type,
          real_name: '系统管理员',
          email: 'admin@xlxumu.com',
          status: 1
        }
      });
    }

    const [users] = await pool.execute(
      'SELECT id, username, email, phone, real_name, user_type, status, last_login, created_at FROM users WHERE id = ?',
      [req.user.userId]
    );

    if (users.length === 0) {
      return res.status(404).json({
        success: false,
        message: '用户不存在',
        code: 'USER_NOT_FOUND'
      });
    }

    res.json({
      success: true,
      data: users[0]
    });

  } catch (error) {
    console.error('获取用户信息错误:', error);
    res.status(500).json({
      success: false,
      message: '获取用户信息失败',
      code: 'PROFILE_ERROR'
    });
  }
});

// 更新用户信息
router.put('/profile', authenticateToken, async (req, res) => {
  try {
    const { real_name, email, phone } = req.body;
    const userId = req.user.userId;

    if (!pool) {
      return res.status(500).json({
        success: false,
        message: '数据库连接不可用',
        code: 'DB_UNAVAILABLE'
      });
    }

    // 检查邮箱和手机号是否被其他用户使用
    if (email || phone) {
      const [existingUsers] = await pool.execute(
        'SELECT id FROM users WHERE (email = ? OR phone = ?) AND id != ?',
        [email || null, phone || null, userId]
      );

      if (existingUsers.length > 0) {
        return res.status(409).json({
          success: false,
          message: '邮箱或手机号已被其他用户使用',
          code: 'CONTACT_EXISTS'
        });
      }
    }

    // 更新用户信息
    await pool.execute(
      'UPDATE users SET real_name = ?, email = ?, phone = ? WHERE id = ?',
      [real_name || null, email || null, phone || null, userId]
    );

    res.json({
      success: true,
      message: '用户信息更新成功'
    });

  } catch (error) {
    console.error('更新用户信息错误:', error);
    res.status(500).json({
      success: false,
      message: '更新用户信息失败',
      code: 'UPDATE_PROFILE_ERROR'
    });
  }
});

// 修改密码
router.post('/change-password', authenticateToken, async (req, res) => {
  try {
    const { current_password, new_password } = req.body;
    const userId = req.user.userId;

    if (!current_password || !new_password) {
      return res.status(400).json({
        success: false,
        message: '当前密码和新密码为必填项',
        code: 'MISSING_PASSWORDS'
      });
    }

    if (!pool) {
      return res.status(500).json({
        success: false,
        message: '数据库连接不可用',
        code: 'DB_UNAVAILABLE'
      });
    }

    // 获取当前密码哈希
    const [users] = await pool.execute(
      'SELECT password_hash FROM users WHERE id = ?',
      [userId]
    );

    if (users.length === 0) {
      return res.status(404).json({
        success: false,
        message: '用户不存在',
        code: 'USER_NOT_FOUND'
      });
    }

    // 验证当前密码
    const isCurrentPasswordValid = await bcrypt.compare(current_password, users[0].password_hash);
    if (!isCurrentPasswordValid) {
      return res.status(401).json({
        success: false,
        message: '当前密码错误',
        code: 'INVALID_CURRENT_PASSWORD'
      });
    }

    // 加密新密码
    const saltRounds = 10;
    const new_password_hash = await bcrypt.hash(new_password, saltRounds);

    // 更新密码
    await pool.execute(
      'UPDATE users SET password_hash = ? WHERE id = ?',
      [new_password_hash, userId]
    );

    res.json({
      success: true,
      message: '密码修改成功'
    });

  } catch (error) {
    console.error('修改密码错误:', error);
    res.status(500).json({
      success: false,
      message: '修改密码失败',
      code: 'CHANGE_PASSWORD_ERROR'
    });
  }
});

// 获取用户权限
router.get('/permissions', authenticateToken, async (req, res) => {
  try {
    if (!pool) {
      // 数据库不可用时返回模拟权限数据
      const mockPermissions = ['user_manage', 'cattle_manage', 'data_view', 'system_config'];
      return res.json({
        success: true,
        data: {
          permissions: mockPermissions,
          roles: ['admin']
        }
      });
    }

    // 查询用户角色和权限
    const [results] = await pool.execute(`
      SELECT r.name as role_name, p.name as permission_name, p.module
      FROM users u
      JOIN user_roles ur ON u.id = ur.user_id
      JOIN roles r ON ur.role_id = r.id
      LEFT JOIN role_permissions rp ON r.id = rp.role_id
      LEFT JOIN permissions p ON rp.permission_id = p.id
      WHERE u.id = ?
    `, [req.user.userId]);

    const roles = [...new Set(results.map(r => r.role_name))];
    const permissions = [...new Set(results.filter(r => r.permission_name).map(r => r.permission_name))];

    res.json({
      success: true,
      data: {
        roles,
        permissions
      }
    });

  } catch (error) {
    console.error('获取权限错误:', error);
    res.status(500).json({
      success: false,
      message: '获取权限失败',
      code: 'PERMISSIONS_ERROR'
    });
  }
});

// 登出（主要用于前端清除token，后端不需要处理）
router.post('/logout', authenticateToken, (req, res) => {
  res.json({
    success: true,
    message: '登出成功'
  });
});

// 导出模块
module.exports = {
  router,
  authenticateToken,
  checkPermission,
  setPool
};