const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()
const _ = db.command

// 云函数入口函数
exports.main = async (event, context) => {
  const { action, data } = event
  const wxContext = cloud.getWXContext()
  const openid = wxContext.OPENID

  switch (action) {
    case 'save':
      return saveUserData(openid, data)
    case 'read':
      return readUserData(openid)
    default:
      return {
        code: 400,
        message: '不支持的操作类型'
      }
  }
}

// 存储用户数据
async function saveUserData(openid, data) {
  try {
    const userDataCollection = db.collection('userData')
    const existingUser = await userDataCollection.where({
      _openid: openid
    }).get()

    if (existingUser.data.length > 0) {
      // 如果用户数据已存在，则更新数据
      await userDataCollection.doc(existingUser.data[0]._id).update({
        data: {
          ...data
        }
      })
      return {
        code: 200,
        message: '用户数据更新成功'
      }
    } else {
      // 如果用户数据不存在，则插入新数据
      await userDataCollection.add({
        data: {
          _openid: openid,
          ...data
        }
      })
      return {
        code: 200,
        message: '用户数据插入成功'
      }
    }
  } catch (error) {
    return {
      code: 500,
      message: '存储用户数据失败',
      error
    }
  }
}

// 读取用户数据
async function readUserData(openid) {
  try {
    const userDataCollection = db.collection('userData')
    const result = await userDataCollection.where({
      _openid: openid
    }).get()

    if (result.data.length > 0) {
      return {
        code: 200,
        message: '用户数据读取成功',
        data: result.data[0]
      }
    } else {
      return {
        code: 404,
        message: '未找到用户数据'
      }
    }
  } catch (error) {
    return {
      code: 500,
      message: '读取用户数据失败',
      error
    }
  }
}