import { Provide } from '@midwayjs/decorator'; import { InjectEntityModel } from '@midwayjs/typegoose'; import { ReturnModelType } from '@typegoose/typegoose'; import { BaseService } from 'free-midway-component'; import { Group } from '../entity/group.entity'; import { Types } from 'mongoose'; import { get, isNumber, omit } from 'lodash'; import { Chat } from '../entity/chat.entity'; const ObjectId = Types.ObjectId; type modelType = ReturnModelType; @Provide() export class GroupService extends BaseService { @InjectEntityModel(Group) model: modelType; @InjectEntityModel(Chat) chatModel: ReturnModelType; /** * 根据群组id,分页查询病人(只有名字) * @param id 群组id * @param skip 分页 * @param limit 分页 */ async findPaitentByGroupId(id: string, skip: number, limit: number) { const pipes: any[] = [ { $match: { _id: new ObjectId(id) } }, { $project: { patients: 1 } }, { $unwind: '$patients' }, { $project: { patient: { $toObjectId: '$patients' } } }, { $lookup: { from: 'patient', localField: 'patient', foreignField: '_id', as: 'info', }, }, { $unwind: '$info' }, { $replaceRoot: { newRoot: '$info' } }, { $project: { name: 1, icon: 1 } }, ]; if (isNumber(skip) && skip > -1) pipes.push({ $skip: skip }); if (isNumber(limit) && limit > 0) pipes.push({ $limit: limit }); const result = await this.model.aggregate(pipes); return result; } /** * 根据患者id,查询患者所在的所有群组及医生简信(只有名字,头像) * @param id 患者id * @param skip 分页 * @param limit 分页 */ async findDoctorByPatientId(id: string, skip?: number, limit?: number) { const result = await this.model.find({ patients: id }, 'name content doctor', { skip, limit }).populate('doctor', 'name').lean(); const afterDealList = result.map(i => { const obj: any = omit(i, ['doctor']); obj.doctorName = get(i, 'doctor.name'); obj.doctorIcon = get(i, 'doctor.icon'); return obj; }); return afterDealList; } /** * 患者查群组列表时,返回患者的每个群组未读信息数量 * @param groupList 群组列表 * @param paitentId 患者id */ async checkNotRead(groupList: Array, paitentId: string) { for (const g of groupList) { const group = get(g, '_id'); const notRead = await this.chatModel.count({ group, speaker: { $ne: paitentId }, not_read: 1 }); const latestChat = await this.chatModel.findOne({ group, patient: paitentId }, null, { sort: { 'meta.createdAt': -1 } }); g['notRead'] = notRead; g['chat'] = latestChat; } return groupList; } }