const User = require('../models/User')
const Solution = require('../models/Solution')
const Group = require('../models/Group')
const logger = require('../utils/logger')
const { generatePwd } = require('../utils/helper')

const preload = async (ctx, next) => {
  const uid = ctx.params.uid
  const user = await User.findOne({ uid }).exec()
  if (user == null) ctx.throw(400, 'No such a user')
  ctx.state.user = user
  return next()
}

// 查询所有用户
const find = async (ctx) => {
  const list = await User.find({}).exec()
  ctx.body = {
    list
  }
}

// 查询用户具体信息
const findOne = async (ctx) => {
  const uid = ctx.query.uid
  const [user, solved, unsolved] = await Promise.all([
    User
      .findOne({ uid })
      .select('-_id -pwd')
      .exec(),
    Solution
      .find({ uid, judge: 3 })
      .distinct('pid')
      .exec(),
    Solution
      .find({ uid, judge: {$ne: 3} })
      .distinct('pid')
      .exec()
  ])

  let group = []
  const process = user.gid.map((gid, index) => {
    return Group.findOne({gid}).exec()
      .then((gid) => {
        group.push(gid.title)
      })
  })
  await Promise.all(process)

  ctx.body = {
    user,
    solved,
    unsolved,
    group
  }
}

// 注册
const create = async (ctx) => {
  if (!ctx.request.body.pwd || ctx.request.body.pwd.length <= 5) {
    ctx.throw(400, 'the length of the password must be greater than 5')
  }
  const user = new User({
    uid: ctx.request.body.uid,
    nick: ctx.request.body.nick,
    pwd: generatePwd(ctx.request.body.pwd)
  })
  // 将objectid转换为用户创建时间(可以不用)
  // user.create = moment(objectIdToTimestamp(user._id)).format('YYYY-MM-DD HH:mm:ss')
  const doc = await User.findOne({ uid: user.uid }).exec()
  if (doc) {
    ctx.throw(400, '用户名已被占用!')
  }
  try {
    await user.save()
  } catch (err) {
    ctx.throw(400, err.message)
  }

  ctx.body = {}
}

// 修改用户信息
const update = async (ctx) => {
  const opt = ctx.request.body
  const user = ctx.state.user
  const fileds = ['nick', 'motto', 'school', 'mail']
  fileds.forEach((filed) => {
    user[filed] = opt[filed]
  })
  if (opt.newPwd) {
    user.pwd = generatePwd(opt.newPwd)
  }

  try {
    await user.save()
    logger.info(`One user is updated" ${user.uid}`)
  } catch (e) {
    ctx.throw(400, e.message)
  }

  ctx.body = {
    success: true,
    uid: user.uid
  }
}

module.exports = {
  preload,
  find,
  findOne,
  create,
  update
}

@@ -120,16 +120,52 @@
 Group')%0A
+const config = require('../config')%0A
 const lo
@@ -248,16 +248,71 @@
 helper')
+%0Aconst %7B isAdmin, isRoot %7D = require('../utils/helper')
 %0A%0Aconst 
@@ -528,12 +528,11 @@
 / %E6%9F%A5%E8%AF%A2
-%E6%89%80%E6%9C%89
 %E7%94%A8%E6%88%B7
+%E7%BB%84
 %0Acon
@@ -550,32 +550,222 @@
 sync (ctx) =%3E %7B%0A
+  const filter = %7B%7D%0A  if (ctx.query.privilege && ctx.query.privilege === 'admin') %7B%0A    filter.privilege = %7B%0A      $in: %5Bconfig.privilege.Root + '', config.privilege.Teacher + ''%5D%0A    %7D%0A  %7D%0A
   const list = a
@@ -783,17 +783,14 @@
 ind(
-%7B%7D).exec(
+filter
 )%0A  
@@ -1319,18 +1319,51 @@
 en((
-gid
+item
 ) =%3E %7B%0A
+        console.log(item.title)%0A
     
@@ -1377,19 +1377,20 @@
 up.push(
-gid
+item
 .title)%0A
@@ -2182,32 +2182,362 @@
 sync (ctx) =%3E %7B%0A
+  if (!isAdmin(ctx.session.profile) && ctx.session.profile.uid !== ctx.state.user.uid) %7B%0A    ctx.throw(400, 'You do not have permission to change this user information!')%0A  %7D%0A  if (ctx.state.user.uid === 'admin' && !isRoot(ctx.session.profile)) %7B%0A    ctx.throw(400, %22You do not have permission to change Root's information!%22)%0A  %7D%0A
   const opt = ct

add query adminList