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

exports.main = async (event) => {
  const {
    id,
    label,
    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 > 1) {
      return {
        success: false,
        msg: "账号重复"
      }
    }

    await db.collection('user').doc(id).update({
      data: {
        username: label,
        remark,
        isAdmin,
      }
    })
    if (data.length === 0) {
      const {
        data: udata
      } = db.collection('user').doc(id).get()
      await db.collection("contract").where({
        username: _.eq(udata.username)
      }).update({
        username: label
      })
    }

    return {
      success: true
    }
  } catch (err) {
    return {
      success: false,
      msg: err.message
    }
  }
}