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 wxContext = cloud.getWXContext() const openid = wxContext.OPENID const { action } = event if (action === 'bind') { const { device_id } = event.data if (!device_id) return { code: -1, message: '缺少设备ID' } const existBind = await db.collection('bindings').where({ openid, status: 'active' }).count() if (existBind.total > 0) { const exist = await db.collection('bindings').where({ openid, status: 'active' }).get() return { code: 2001, message: '已绑定设备', data: { device_id: exist.data[0].device_id } } } await db.collection('bindings').add({ data: { openid, device_id, status: 'active', bind_time: db.serverDate() } }) const subExist = await db.collection('subscriptions').where({ openid, status: 'active' }).count() if (subExist.total === 0) { await db.collection('subscriptions').add({ data: { openid, plan_type: 'trial', status: 'active', start_time: db.serverDate(), end_time: new Date(Date.now() + 7 * 24 * 3600 * 1000), remaining_days: 7 } }) } return { code: 0, data: { device_id, bind_token: 'bt_' + Date.now(), subscription: { plan_type: 'trial', remaining_days: 7 } } } } if (action === 'unbind') { await db.collection('bindings').where({ openid, status: 'active' }).update({ data: { status: 'inactive' } }) return { code: 0, data: {} } } if (action === 'list') { const bindings = await db.collection('bindings').where({ openid, status: 'active' }).get() const devices = bindings.data.map(b => ({ device_id: b.device_id, name: '我的光面膜', status: 'online', bind_time: b.bind_time })) return { code: 0, data: { devices, total: devices.length } } } if (action === 'detail') { const { device_id } = event.data const bindings = await db.collection('bindings').where({ openid, device_id, status: 'active' }).get() if (bindings.data.length === 0) return { code: -1, message: '设备未绑定' } const b = bindings.data[0] return { code: 0, data: { device_id: b.device_id, name: '我的光面膜', firmware_version: '1.0.0', battery_level: 85, status: 'online', bind_time: b.bind_time } } } return { code: -1, message: '未知操作' } }