const cloud = require('wx-server-sdk')
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

exports.main = async (event) => {
  const {
    username,
    password
  } = event.data
  const db = cloud.database();
  const _ = db.command
  // 如果云函数所在环境为 abc，则下面的调用就会请求到 abc 环境的数据库
  let user = await db.collection('user').where({
    username: _.eq(username)
  }).get()
  user = user.data[0]
  if (!user || (user.password !== password)) {
    return {
      success: false,
      msg: "用户名或密码错误",
    }
  } else {
    return {
      success: true,
      userInfo: {
        username: user.username,
        isAdmin: user.isAdmin
      }
    }
  }
}