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

exports.main = async (event) => {
  const {
    id,
    name,
    type,
    files,
    username
  } = event.data
  try {
    const db = cloud.database({
      throwOnNotFound: false
    });
    const doc = db.collection('contract').doc(id)
    const {
      data
    } = await doc.get()
    const fileList = []
    data.fileIds.forEach(id => {
      if (!files.includes(id)) {
        fileList.push(id)
      }
    })
    if (fileList.length > 0) {
      cloud.deleteFile({
        fileList
      })
    }
    await doc.update({
      data: {
        username,
        name,
        type,
        fileIds: files,
      }
    })
    return {
      success: true
    }
  } catch (err) {
    return {
      success: false,
      msg: err.message
    }
  }
}