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

// 中间件将在服务器启动时设置
let authenticateToken = null;
let checkPermission = null;
let pool = null;

// 设置中间件和数据库连接（从主服务器导入）
function setMiddleware(auth, permission, dbPool) {
  authenticateToken = auth;
  checkPermission = permission;
  pool = dbPool;
  console.log('✅ Users模块中间件设置完成');
}

// 获取用户列表
router.get('/', 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: 'farmer001',
          phone: '13800138001',
          email: 'farmer001@example.com',
          real_name: '张三',
          user_type: 'farmer',
          status: 1,
          created_at: '2024-01-01 00:00:00'
        },
        {
          id: 2,
          username: 'trader001',
          phone: '13800138002',
          email: 'trader001@example.com',
          real_name: '李四',
          user_type: 'trader',
          status: 1,
          created_at: '2024-01-02 00: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 = 'WHERE deleted_at IS NULL';
    const 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 phone LIKE ?)';
      const searchPattern = `%${search}%`;
      queryParams.push(searchPattern, searchPattern, searchPattern);
    }

    // 查询总数
    const countQuery = `SELECT COUNT(*) as total FROM users ${whereClause}`;
    
    // 查询数据
    const dataQuery = `
      SELECT 
        id, username, phone, email, real_name, user_type, status, 
        last_login_at, created_at, updated_at
      FROM users 
      ${whereClause}
      ORDER BY created_at DESC
      LIMIT ? OFFSET ?
    `;

    const [countResult] = await pool.execute(countQuery, queryParams);
    const [users] = await pool.execute(dataQuery, [...queryParams, parseInt(limit), offset]);

    const total = countResult[0].total;
    const pages = Math.ceil(total / limit);

    res.json({
      success: true,
      data: {
        users,
        pagination: {
          total,
          page: parseInt(page),
          limit: parseInt(limit),
          pages
        }
      }
    });
  } catch (error) {
    console.error('获取用户列表失败:', error);
    res.status(500).json({
      success: false,
      message: '获取用户列表失败',
      code: 'GET_USERS_ERROR'
    });
  }
});

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

    if (!pool) {
      // 数据库不可用时返回模拟数据
      return res.json({
        success: true,
        data: {
          id: parseInt(id),
          username: 'farmer001',
          phone: '13800138001',
          email: 'farmer001@example.com',
          real_name: '张三',
          user_type: 'farmer',
          status: 1,
          address: '内蒙古锡林郭勒盟锡林浩特市',
          created_at: '2024-01-01 00:00:00'
        }
      });
    }

    const [users] = await pool.execute(
      `SELECT 
        id, username, phone, email, real_name, id_card, gender, birthday, 
        address, user_type, status, avatar, last_login_at, created_at, updated_at
      FROM users 
      WHERE id = ? AND deleted_at IS NULL`,
      [id]
    );

    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: 'GET_USER_ERROR'
    });
  }
});

// 创建用户
router.post('/', async (req, res) => {
  try {
    const {
      username,
      phone,
      email,
      password,
      real_name,
      id_card,
      gender,
      birthday,
      address,
      user_type = 'farmer'
    } = req.body;

    // 验证必填字段
    if (!username || !phone || !password) {
      return res.status(400).json({
        success: false,
        message: '缺少必填字段：username, phone, password',
        code: 'MISSING_REQUIRED_FIELDS'
      });
    }

    if (!pool) {
      // 数据库不可用时返回模拟响应
      return res.status(201).json({
        success: true,
        message: '用户创建成功（模拟）',
        data: {
          id: Math.floor(Math.random() * 1000) + 100,
          username,
          phone,
          email,
          real_name,
          user_type,
          status: 1,
          created_at: new Date().toISOString()
        }
      });
    }

    // 检查用户名和手机号是否已存在
    const [existingUsers] = await pool.execute(
      'SELECT id FROM users WHERE (username = ? OR phone = ?) AND deleted_at IS NULL',
      [username, phone]
    );

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

    // 生成密码哈希
    const salt = await bcrypt.genSalt(10);
    const passwordHash = await bcrypt.hash(password, salt);

    // 插入新用户
    const insertQuery = `
      INSERT INTO users (
        username, phone, email, password_hash, salt, real_name, 
        id_card, gender, birthday, address, user_type
      ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    `;

    const [result] = await pool.execute(insertQuery, [
      username, phone, email, passwordHash, salt, real_name,
      id_card, gender, birthday, address, user_type
    ]);

    // 获取新创建的用户信息
    const [newUser] = await pool.execute(
      `SELECT 
        id, username, phone, email, real_name, user_type, status, created_at
      FROM users WHERE id = ?`,
      [result.insertId]
    );

    res.status(201).json({
      success: true,
      message: '用户创建成功',
      data: newUser[0]
    });
  } catch (error) {
    console.error('创建用户失败:', error);
    res.status(500).json({
      success: false,
      message: '创建用户失败',
      code: 'CREATE_USER_ERROR'
    });
  }
});

// 更新用户信息
router.put('/:id', async (req, res) => {
  try {
    const { id } = req.params;
    const {
      real_name,
      email,
      gender,
      birthday,
      address,
      avatar
    } = req.body;

    if (!pool) {
      // 数据库不可用时返回模拟响应
      return res.json({
        success: true,
        message: '用户信息更新成功（模拟）',
        data: {
          id: parseInt(id),
          real_name,
          email,
          gender,
          birthday,
          address,
          avatar,
          updated_at: new Date().toISOString()
        }
      });
    }

    // 检查用户是否存在
    const [existingUsers] = await pool.execute(
      'SELECT id FROM users WHERE id = ? AND deleted_at IS NULL',
      [id]
    );

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

    // 更新用户信息
    const updateQuery = `
      UPDATE users 
      SET real_name = ?, email = ?, gender = ?, birthday = ?, 
          address = ?, avatar = ?, updated_at = CURRENT_TIMESTAMP
      WHERE id = ?
    `;

    await pool.execute(updateQuery, [
      real_name, email, gender, birthday, address, avatar, id
    ]);

    // 获取更新后的用户信息
    const [updatedUser] = await pool.execute(
      `SELECT 
        id, username, phone, email, real_name, gender, birthday, 
        address, avatar, user_type, status, updated_at
      FROM users WHERE id = ?`,
      [id]
    );

    res.json({
      success: true,
      message: '用户信息更新成功',
      data: updatedUser[0]
    });
  } catch (error) {
    console.error('更新用户信息失败:', error);
    res.status(500).json({
      success: false,
      message: '更新用户信息失败',
      code: 'UPDATE_USER_ERROR'
    });
  }
});

// 删除用户（软删除）
router.delete('/:id', async (req, res) => {
  try {
    const { id } = req.params;

    if (!pool) {
      // 数据库不可用时返回模拟响应
      return res.json({
        success: true,
        message: '用户删除成功（模拟）'
      });
    }

    // 检查用户是否存在
    const [existingUsers] = await pool.execute(
      'SELECT id FROM users WHERE id = ? AND deleted_at IS NULL',
      [id]
    );

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

    // 软删除用户
    await pool.execute(
      'UPDATE users SET deleted_at = CURRENT_TIMESTAMP WHERE id = ?',
      [id]
    );

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

// 获取用户统计信息
router.get('/stats/overview', async (req, res) => {
  try {
    if (!pool) {
      // 数据库不可用时返回模拟数据
      return res.json({
        success: true,
        data: {
          total_users: 1250,
          active_users: 1180,
          farmers: 850,
          traders: 280,
          consumers: 120,
          new_users_today: 15,
          new_users_this_month: 320
        }
      });
    }

    // 查询用户统计信息
    const [stats] = await pool.execute(`
      SELECT 
        COUNT(*) as total_users,
        SUM(CASE WHEN status = 1 THEN 1 ELSE 0 END) as active_users,
        SUM(CASE WHEN user_type = 'farmer' THEN 1 ELSE 0 END) as farmers,
        SUM(CASE WHEN user_type = 'trader' THEN 1 ELSE 0 END) as traders,
        SUM(CASE WHEN user_type = 'consumer' THEN 1 ELSE 0 END) as consumers,
        SUM(CASE WHEN DATE(created_at) = CURDATE() THEN 1 ELSE 0 END) as new_users_today,
        SUM(CASE WHEN YEAR(created_at) = YEAR(NOW()) AND MONTH(created_at) = MONTH(NOW()) THEN 1 ELSE 0 END) as new_users_this_month
      FROM users 
      WHERE deleted_at IS NULL
    `);

    res.json({
      success: true,
      data: stats[0]
    });
  } catch (error) {
    console.error('获取用户统计信息失败:', error);
    res.status(500).json({
      success: false,
      message: '获取用户统计信息失败',
      code: 'GET_USER_STATS_ERROR'
    });
  }
});

module.exports = {
  router,
  setMiddleware
};