const UserMySQL = require('../../models/UserMySQL');
const { AppError } = require('../../utils/errors');

class UserService {
  // 获取用户详情
  static async getUserProfile(userId) {
    try {
      const user = await UserMySQL.findById(userId);
      if (!user) {
        throw new AppError('用户不存在', 404);
      }
      return UserMySQL.sanitize(user);
    } catch (error) {
      throw error;
    }
  }

  // 更新用户信息
  static async updateUserProfile(userId, updateData) {
    try {
      const allowedFields = ['nickname', 'avatar', 'gender', 'birthday', 'phone', 'email'];
      const filteredUpdates = {};

      // 过滤允许更新的字段
      Object.keys(updateData).forEach(key => {
        if (allowedFields.includes(key) && updateData[key] !== undefined) {
          filteredUpdates[key] = updateData[key];
        }
      });

      if (Object.keys(filteredUpdates).length === 0) {
        throw new AppError('没有有效的更新字段', 400);
      }

      // 检查邮箱是否已被其他用户使用
      if (filteredUpdates.email) {
        const emailExists = await UserMySQL.isEmailExists(filteredUpdates.email, userId);
        if (emailExists) {
          throw new AppError('邮箱已被其他用户使用', 400);
        }
      }

      // 检查手机号是否已被其他用户使用
      if (filteredUpdates.phone) {
        const phoneExists = await UserMySQL.isPhoneExists(filteredUpdates.phone, userId);
        if (phoneExists) {
          throw new AppError('手机号已被其他用户使用', 400);
        }
      }

      const success = await UserMySQL.update(userId, filteredUpdates);
      if (!success) {
        throw new AppError('更新用户信息失败', 500);
      }

      // 返回更新后的用户信息
      return await this.getUserProfile(userId);
    } catch (error) {
      throw error;
    }
  }

  // 搜索用户（管理员功能）
  static async searchUsers(searchParams) {
    try {
      const { keyword, userType, page = 1, pageSize = 10 } = searchParams;
      const offset = (page - 1) * pageSize;

      let sql = `
        SELECT id, username, user_type, real_name, avatar_url, email, phone, 
               created_at, updated_at, status
        FROM users 
        WHERE 1=1
      `;
      const params = [];

      if (keyword) {
        sql += ` AND (
          username LIKE ? OR 
          real_name LIKE ? OR 
          email LIKE ? OR 
          phone LIKE ?
        )`;
        const likeKeyword = `%${keyword}%`;
        params.push(likeKeyword, likeKeyword, likeKeyword, likeKeyword);
      }

      if (userType) {
        sql += ' AND user_type = ?';
        params.push(userType);
      }

      // 获取总数
      const countSql = `SELECT COUNT(*) as total FROM (${sql}) as count_query`;
      const countResult = await UserMySQL.query(countSql, params);
      const total = countResult[0].total;

      // 添加分页和排序
      sql += ` ORDER BY created_at DESC LIMIT ${parseInt(pageSize)} OFFSET ${parseInt(offset)}`;

      const users = await UserMySQL.query(sql, params);
      
      return {
        users: users.map(user => UserMySQL.sanitize(user)),
        pagination: {
          page: parseInt(page),
          pageSize: parseInt(pageSize),
          total: parseInt(total),
          totalPages: Math.ceil(total / pageSize)
        }
      };
    } catch (error) {
      throw error;
    }
  }

  // 获取用户统计信息（管理员功能）
  static async getUserStatistics() {
    try {
      const sql = `
        SELECT 
          COUNT(*) as total_users,
          COUNT(CASE WHEN user_type = 'farmer' THEN 1 END) as farmers,
          COUNT(CASE WHEN user_type = 'merchant' THEN 1 END) as merchants,
          COUNT(CASE WHEN user_type = 'admin' THEN 1 END) as admins,
          COUNT(CASE WHEN status = 'active' THEN 1 END) as active_users,
          COUNT(CASE WHEN status = 'inactive' THEN 1 END) as inactive_users,
          DATE(created_at) as date
        FROM users 
        GROUP BY DATE(created_at)
        ORDER BY date DESC
        LIMIT 30
      `;

      const stats = await UserMySQL.query(sql);
      return stats;
    } catch (error) {
      throw error;
    }
  }

  // 批量操作用户状态（管理员功能）
  static async batchUpdateUserStatus(userIds, status) {
    try {
      if (!['active', 'inactive'].includes(status)) {
        throw new AppError('无效的状态值', 400);
      }

      if (!userIds || userIds.length === 0) {
        throw new AppError('请选择要操作的用户', 400);
      }

      const placeholders = userIds.map(() => '?').join(',');
      const sql = `UPDATE users SET status = ?, updated_at = NOW() WHERE id IN (${placeholders})`;
      
      const result = await UserMySQL.query(sql, [status, ...userIds]);
      return result.affectedRows;
    } catch (error) {
      throw error;
    }
  }
}

module.exports = UserService;