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

exports.main = async (event) => {
  const {
    label,
    password,
    remark,
    isAdmin
  } = event.data

  try {
    const db = cloud.database();
    const _ = db.command
    const {
      data
    } = await db.collection('user').where({
      username: _.eq(label)
    }).get()
    if (data.length !== 0) {
      return {
        success: false,
        msg: "用户名重复"
      }
    }

    await db.collection('user').add({
      data: {
        username: label,
        password,
        remark,
        isAdmin,
        createDate: new Date()
      }
    })
    return {
      success: true
    }
  } catch (err) {
    return {
      success: false,
      msg: err.message
    }
  }
}