'use strict'; const assert = require('assert'); const { trimData } = require('naf-core').Util; const _ = require('lodash'); const { ObjectId } = require('mongoose').Types; const { CrudService } = require('naf-framework-mongoose/lib/service'); const { BusinessError, ErrorCode } = require('naf-core').Error; class HeadteacherService extends CrudService { constructor(ctx) { super(ctx, 'headteacher'); this.model = this.ctx.model.Headteacher; this.umodel = this.ctx.model.User; this.yjy = this.ctx.model.Yjyconnect; } async query(filter, { skip, limit, sort, desc, projection } = {}) { // 处理排序 if (sort && _.isString(sort)) { sort = { [sort]: desc ? -1 : 1 }; } else if (sort && _.isArray(sort)) { sort = sort.map(f => ({ [f]: desc ? -1 : 1 })).reduce((p, c) => ({ ...p, ...c }), {}); } let rs = await this.model.find(trimData(filter), projection, { skip, limit, sort }).lean(); if (rs.length > 0) rs = JSON.parse(JSON.stringify(rs)); const ids = rs.map(i => ObjectId(i._id).toString()); const users = await this.umodel.find({ uid: ids }).lean(); const uids = users.map(i => ObjectId(i._id).toString()); const yjyUsers = await this.yjy.find({ suid: uids }).lean(); for (const i of rs) { const { _id: did } = i; i.id = did; const user = users.find(f => ObjectId(did).equals(f.uid)); if (!user) { i.is_bind = false; continue; } const yjyUser = yjyUsers.find(f => ObjectId(user._id).equals(f.suid)); if (yjyUser) i.is_bind = true; else i.is_bind = false; } return rs; } async create(data) { const { name, mobile } = data; const user = await this.umodel.findOne({ mobile }); if (user) { throw new BusinessError(ErrorCode.DATA_EXIST, '电话已经存在'); } const res = await this.model.create(data); const newdata = { name, mobile, type: '1', uid: res.id }; newdata.passwd = { secret: '12345678' }; await this.umodel.create(newdata); return await this.model.findById(res.id || res._id); } async update({ id }, data) { const { name, mobile, openid } = data; // 修改后的手机号查找是否已存在 const have_mobile = await this.umodel.count({ mobile, uid: { $ne: id } }); if (have_mobile > 0) throw new BusinessError(ErrorCode.DATA_EXIST, '电话已经存在'); const res = await this.model.update({ _id: ObjectId(id) }, data); if (res) { const _user = await this.umodel.findOne({ uid: id, type: '1' }); if (_user) { _user.mobile = mobile; _user.name = name; if (openid) { _user.openid = openid; } _user.save(); } } return res; } async delete({ id }) { await this.model.findByIdAndDelete(id); await this.umodel.deleteOne({ uid: id, type: '1' }); return 'deleted'; } } module.exports = HeadteacherService;