import { Config, Provide } from '@midwayjs/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import { Message } from '../../entity/system/message.entity';
import { BaseServiceV2 } from '../../frame/BaseServiceV2';
import { MessageUserType } from '../../public/var';
import Axios from 'axios';
import { get, omit } from 'lodash';

@Provide()
export class MessageService extends BaseServiceV2 {
  @InjectEntityModel(Message)
  model: Repository<Message>;
  @Config('modulesConfig.mq')
  mqServiceHttpPrefix: any;
  getQueryColumnsOpera() {
    return { 'to.user': this.Opera.JsonArrayObject, 'to.is_read': this.Opera.JsonArrayObject };
  }
  /**
   * 发送mq消息
   * @param target mq接收人
   * @param userType 用户类型
   * @param data_id 消息数据id
   */
  async toSendMq(target, userType: MessageUserType, data_id) {
    const url = `${this.mqServiceHttpPrefix}/send`;
    const body = { target, userType, data_id };
    try {
      await Axios.post(url, body, { responseType: 'json' });
    } catch (error) {
      console.log(error);
    }
  }

  /**
   * 剃除非当前用户外的数据
   * @param data 消息数据列表
   * @param user 用户id
   */
  deleteOtherUserInfo(data, user) {
    const nd = [];
    for (const i of data) {
      let to = get(i, 'to', []);
      const ndo = omit(i, ['to']);
      to = to.filter(f => f.user === user || f.user === parseInt(user));
      ndo.to = to;
      nd.push(ndo);
    }
    return nd;
  }
}
