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

// 中间件将在服务器启动时设置
let authenticateToken = (req, res, next) => {
  return res.status(500).json({
    success: false,
    message: '认证中间件未初始化',
    code: 'AUTH_NOT_INITIALIZED'
  });
};

let checkPermission = (permission) => {
  return (req, res, next) => {
    return res.status(500).json({
      success: false,
      message: '权限中间件未初始化',
      code: 'PERMISSION_NOT_INITIALIZED'
    });
  };
};

let pool = null;

// 设置中间件和数据库连接（从主服务器导入）
function setMiddleware(auth, permission, dbPool) {
  authenticateToken = auth;
  checkPermission = permission;
  pool = dbPool;
}

// 获取用户列表
router.get('/', authenticateToken, checkPermission('user_manage'), async (req, res) => {
  try {
    const { page = 1, limit = 10, user_type, status, search } = req.query;
    const offset = (page - 1) * limit;

    if (!pool) {
      // 数据库不可用时返回模拟数据
      const mockUsers = [
        {
          id: 1,
          username: 'admin',
          email: 'admin@xlxumu.com',
          real_name: '系统管理员',
          user_type: 'admin',
          status: 1,
          last_login: '2024-01-01 10:00:00',
          created_at: '2024-01-01 00:00:00'
        },
        {
          id: 2,
          username: 'farmer001',
          email: 'farmer001@example.com',
          real_name: '张三',
          user_type: 'farmer',
          status: 1,
          last_login: '2024-01-02 08:30:00',
          created_at: '2024-01-01 01:00:00'
        }
      ];

      return res.json({
        success: true,
        data: {
          users: mockUsers,
          pagination: {
            total: mockUsers.length,
            page: parseInt(page),
            limit: parseInt(limit),
            pages: Math.ceil(mockUsers.length / limit)
          }
        }
      });
    }

    // 构建查询条件
    let whereClause = '1=1';
    let queryParams = [];

    if (user_type) {
      whereClause += ' AND user_type = ?';
      queryParams.push(user_type);
    }

    if (status !== undefined) {
      whereClause += ' AND status = ?';
      queryParams.push(parseInt(status));
    }

    if (search) {
      whereClause += ' AND (username LIKE ? OR real_name LIKE ? OR email LIKE ?)';
      const searchTerm = `%${search}%`;
      queryParams.push(searchTerm, searchTerm, searchTerm);
    }

    // 获取总数
    const [countResult] = await pool.execute(
      `SELECT COUNT(*) as total FROM users WHERE ${whereClause}`,
      queryParams
    );
    const total = countResult[0].total;

    // 获取用户列表
    const [users] = await pool.execute(
      `SELECT id, username, email, phone, real_name, user_type, status, last_login, created_at 
       FROM users 
       WHERE ${whereClause} 
       ORDER BY created_at DESC 
       LIMIT ? OFFSET ?`,
      [...queryParams, parseInt(limit), offset]
    );

    res.json({
      success: true,
      data: {
        users,
        pagination: {
          total,
          page: parseInt(page),
          limit: parseInt(limit),
          pages: Math.ceil(total / limit)
        }
      }
    });

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

// 获取用户详情
router.get('/:id', authenticateToken, checkPermission('user_manage'), async (req, res) => {
  try {
    const userId = req.params.id;

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

    // 获取用户基本信息
    const [users] = await pool.execute(
      'SELECT id, username, email, phone, real_name, user_type, status, last_login, created_at FROM users WHERE id = ?',
      [userId]
    );

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

    // 获取用户角色
    const [roles] = await pool.execute(`
      SELECT r.id, r.name, r.description
      FROM user_roles ur
      JOIN roles r ON ur.role_id = r.id
      WHERE ur.user_id = ?
    `, [userId]);

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

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

// 创建用户
router.post('/', authenticateToken, checkPermission('user_manage'), async (req, res) => {
  try {
    const { username, email, phone, password, real_name, user_type, role_ids } = 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 connection = await pool.getConnection();
    await connection.beginTransaction();

    try {
      // 插入用户
      const [userResult] = await connection.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]
      );

      const newUserId = userResult.insertId;

      // 分配角色
      if (role_ids && role_ids.length > 0) {
        for (const roleId of role_ids) {
          await connection.execute(
            'INSERT INTO user_roles (user_id, role_id) VALUES (?, ?)',
            [newUserId, roleId]
          );
        }
      }

      await connection.commit();
      connection.release();

      res.status(201).json({
        success: true,
        message: '用户创建成功',
        data: {
          userId: newUserId,
          username,
          user_type
        }
      });

    } catch (error) {
      await connection.rollback();
      connection.release();
      throw error;
    }

  } catch (error) {
    console.error('创建用户错误:', error);
    res.status(500).json({
      success: false,
      message: '创建用户失败',
      code: 'CREATE_USER_ERROR'
    });
  }
});

// 更新用户
router.put('/:id', authenticateToken, checkPermission('user_manage'), async (req, res) => {
  try {
    const userId = req.params.id;
    const { email, phone, real_name, status, role_ids } = req.body;

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

    // 检查用户是否存在
    const [users] = await pool.execute('SELECT id FROM users WHERE id = ?', [userId]);
    if (users.length === 0) {
      return res.status(404).json({
        success: false,
        message: '用户不存在',
        code: 'USER_NOT_FOUND'
      });
    }

    // 检查邮箱和手机号是否被其他用户使用
    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'
        });
      }
    }

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

    try {
      // 更新用户基本信息
      await connection.execute(
        'UPDATE users SET email = ?, phone = ?, real_name = ?, status = ? WHERE id = ?',
        [email || null, phone || null, real_name || null, status !== undefined ? status : 1, userId]
      );

      // 更新用户角色
      if (role_ids !== undefined) {
        // 删除现有角色
        await connection.execute('DELETE FROM user_roles WHERE user_id = ?', [userId]);
        
        // 添加新角色
        if (role_ids.length > 0) {
          for (const roleId of role_ids) {
            await connection.execute(
              'INSERT INTO user_roles (user_id, role_id) VALUES (?, ?)',
              [userId, roleId]
            );
          }
        }
      }

      await connection.commit();
      connection.release();

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

    } catch (error) {
      await connection.rollback();
      connection.release();
      throw error;
    }

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

// 删除用户
router.delete('/:id', authenticateToken, checkPermission('user_manage'), async (req, res) => {
  try {
    const userId = req.params.id;

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

    // 检查是否是当前用户
    if (parseInt(userId) === req.user.userId) {
      return res.status(400).json({
        success: false,
        message: '不能删除当前登录用户',
        code: 'CANNOT_DELETE_SELF'
      });
    }

    // 检查用户是否存在
    const [users] = await pool.execute('SELECT id FROM users WHERE id = ?', [userId]);
    if (users.length === 0) {
      return res.status(404).json({
        success: false,
        message: '用户不存在',
        code: 'USER_NOT_FOUND'
      });
    }

    // 删除用户（级联删除用户角色关联）
    await pool.execute('DELETE FROM users WHERE id = ?', [userId]);

    res.json({
      success: true,
      message: '用户删除成功'
    });

  } catch (error) {
    console.error('删除用户错误:', error);
    res.status(500).json({
      success: false,
      message: '删除用户失败',
      code: 'DELETE_USER_ERROR'
    });
  }
});

// 重置用户密码
router.post('/:id/reset-password', authenticateToken, checkPermission('user_manage'), async (req, res) => {
  try {
    const userId = req.params.id;
    const { new_password } = req.body;

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

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

    // 检查用户是否存在
    const [users] = await pool.execute('SELECT id FROM users WHERE id = ?', [userId]);
    if (users.length === 0) {
      return res.status(404).json({
        success: false,
        message: '用户不存在',
        code: 'USER_NOT_FOUND'
      });
    }

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

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

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

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

// 获取所有角色（用于分配角色）
router.get('/roles/list', authenticateToken, checkPermission('user_manage'), async (req, res) => {
  try {
    if (!pool) {
      // 数据库不可用时返回模拟数据
      const mockRoles = [
        { id: 1, name: 'admin', description: '系统管理员' },
        { id: 2, name: 'farmer', description: '养殖户' },
        { id: 3, name: 'banker', description: '银行职员' },
        { id: 4, name: 'insurer', description: '保险员' },
        { id: 5, name: 'government', description: '政府监管人员' },
        { id: 6, name: 'trader', description: '交易员' }
      ];

      return res.json({
        success: true,
        data: mockRoles
      });
    }

    const [roles] = await pool.execute('SELECT id, name, description FROM roles ORDER BY id');
    
    res.json({
      success: true,
      data: roles
    });

  } catch (error) {
    console.error('获取角色列表错误:', error);
    res.status(500).json({
      success: false,
      message: '获取角色列表失败',
      code: 'GET_ROLES_ERROR'
    });
  }
});

module.exports = {
  router,
  setMiddleware
};