const mongoose = require('mongoose')
const bcrypt = require('bcryptjs')

// 用户等级枚举
const UserLevel = {
  NORMAL: 1,     // 普通用户
  VIP: 2,         // VIP用户
  SUPER_VIP: 3    // 超级VIP
}

// 用户状态枚举
const UserStatus = {
  ACTIVE: 'active',      // 活跃
  INACTIVE: 'inactive',  // 非活跃
  BANNED: 'banned'       // 封禁
}

const userSchema = new mongoose.Schema({
  // 基础信息
  username: {
    type: String,
    required: true,
    unique: true,
    trim: true,
    minlength: 3,
    maxlength: 20,
    match: /^[a-zA-Z0-9_]+$/
  },
  password: {
    type: String,
    required: true,
    minlength: 6
  },
  email: {
    type: String,
    sparse: true,
    trim: true,
    lowercase: true,
    match: /^\w+([.-]?\w+)*@\w+([.-]?\w+)*(\.\w{2,3})+$/
  },
  phone: {
    type: String,
    sparse: true,
    trim: true,
    match: /^1[3-9]\d{9}$/
  },

  // 个人信息
  nickname: {
    type: String,
    required: true,
    trim: true,
    maxlength: 20
  },
  avatar: {
    type: String,
    default: ''
  },
  gender: {
    type: String,
    enum: ['male', 'female', 'unknown'],
    default: 'unknown'
  },
  birthday: Date,

  // 账户信息
  points: {
    type: Number,
    default: 0,
    min: 0
  },
  level: {
    type: Number,
    enum: Object.values(UserLevel),
    default: UserLevel.NORMAL
  },
  status: {
    type: String,
    enum: Object.values(UserStatus),
    default: UserStatus.ACTIVE
  },
  balance: {
    type: Number,
    default: 0,
    min: 0
  },

  // 第三方登录
  wechatOpenid: {
    type: String,
    sparse: true
  },
  wechatUnionid: {
    type: String,
    sparse: true
  },

  // 统计信息
  travelCount: {
    type: Number,
    default: 0
  },
  animalAdoptCount: {
    type: Number,
    default: 0
  },
  flowerOrderCount: {
    type: Number,
    default: 0
  },

  // 时间戳
  lastLoginAt: Date,
  createdAt: {
    type: Date,
    default: Date.now
  },
  updatedAt: {
    type: Date,
    default: Date.now
  }
}, {
  timestamps: true,
  toJSON: {
    transform: function(doc, ret) {
      delete ret.password
      delete ret.wechatOpenid
      delete ret.wechatUnionid
      return ret
    }
  }
})

// 索引 (移除与字段定义中 unique: true 和 sparse: true 重复的索引)
userSchema.index({ createdAt: -1 })
userSchema.index({ points: -1 })

// 密码加密中间件
userSchema.pre('save', async function(next) {
  if (!this.isModified('password')) return next()
  
  try {
    const salt = await bcrypt.genSalt(12)
    this.password = await bcrypt.hash(this.password, salt)
    next()
  } catch (error) {
    next(error)
  }
})

// 比较密码方法
userSchema.methods.comparePassword = async function(candidatePassword) {
  return bcrypt.compare(candidatePassword, this.password)
}

// 检查用户状态是否活跃
userSchema.methods.isActive = function() {
  return this.status === UserStatus.ACTIVE
}

// 检查是否为VIP用户
userSchema.methods.isVip = function() {
  return this.level >= UserLevel.VIP
}

// 添加积分
userSchema.methods.addPoints = function(points) {
  this.points += points
  return this.save()
}

// 扣除积分
userSchema.methods.deductPoints = function(points) {
  if (this.points < points) {
    throw new Error('积分不足')
  }
  this.points -= points
  return this.save()
}

// 静态方法：根据用户名查找用户
userSchema.statics.findByUsername = function(username) {
  return this.findOne({ username })
}

// 静态方法：根据邮箱查找用户
userSchema.statics.findByEmail = function(email) {
  return this.findOne({ email })
}

// 静态方法：根据手机号查找用户
userSchema.statics.findByPhone = function(phone) {
  return this.findOne({ phone })
}

// 虚拟字段：用户等级名称
userSchema.virtual('levelName').get(function() {
  const levelNames = {
    [UserLevel.NORMAL]: '普通用户',
    [UserLevel.VIP]: 'VIP用户',
    [UserLevel.SUPER_VIP]: '超级VIP'
  }
  return levelNames[this.level] || '未知'
})

const User = mongoose.model('User', userSchema)

module.exports = {
  User,
  UserLevel,
  UserStatus
}