'use strict'; const assert = require('assert'); const Service = require('egg').Service; class integralService extends Service { constructor(ctx) { super(ctx); this.model = this.ctx.model.Integral; } async create({ openid, name, integral }) { assert(name, '姓名不存在'); assert(openid, 'openid不存在'); assert(integral, '积分不存在'); await this.service.integralLog.create({ openid, name, integral }); try { const res = await this.model.create({ openid, name, integral }); return { errcode: 0, errmsg: 'ok', data: res }; } catch (error) { throw error; } } async update({ id, openid, name, integral }) { assert(id, 'id不存在'); assert(name, '姓名不存在'); assert(openid, 'openid不存在'); assert(integral, '积分不存在'); await this.service.integralLog.create({ openid, name, integral }); try { await this.model.updateOne({ _id: id }, { openid, name, integral }); return { errcode: 0, errmsg: 'ok', data: '' }; } catch (error) { throw error; } } async delete({ id }) { assert(id, 'id不存在'); try { await this.model.deleteOne({ _id: id }); return { errcode: 0, errmsg: 'ok', data: '' }; } catch (error) { throw error; } } async query({ skip, limit, openid, name, integral }) { const filter = {}; const arr = { openid, name, integral }; for (const e in arr) { const data = `{ "${e}": { "$regex": "${arr[e]}" } }`; if (arr[e]) { filter.$or = []; filter.$or.push(JSON.parse(data)); } } try { const total = await this.model.find({ ...filter }); let res; if (skip && limit) { res = await this.model.find({ ...filter }).skip(Number(skip) * Number(limit)).limit(Number(limit)); } else { res = await this.model.find({ ...filter }); } return { errcode: 0, errmsg: 'ok', data: res, total: total.length }; } catch (error) { throw error; } } async increase({ openid, name, integral }) { assert(openid, 'openid不存在'); assert(name, '姓名不存在'); assert(integral, '积分不存在'); try { await this.service.integralLog.create({ openid, name, integral }); const one = await this.model.findOne({ openid }); if (one) { const total = Number(integral) + Number(one.integral); await this.model.updateOne({ openid }, { integral: total }); return { errcode: 0, errmsg: 'ok', data: '' }; } await this.model.create({ openid, name, integral }); return { errcode: 0, errmsg: 'ok', data: '' }; } catch (error) { throw error; } } async reduce({ openid, name, integral }) { assert(openid, 'openid不存在'); assert(name, '姓名不存在'); assert(integral, '积分不存在'); try { const one = await this.model.findOne({ openid }); if (one) { const total = Number(one.integral) - Number(integral); await this.model.updateOne({ openid }, { integral: total }); await this.service.integralLog.create({ openid, name, integral }); return { errcode: 0, errmsg: 'ok', data: '' }; } return { errcode: -1001, errmsg: '未查询到用户', data: '' }; } catch (error) { throw error; } } } module.exports = integralService;