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, 'to.user_type': this.Opera.JsonArrayObject };
  }

  // 全部已读
  async read({ id, user_type }) {
    const list = await this.model
      .createQueryBuilder()
      .where('"to" @> :member', { member: JSON.stringify([{ user: parseInt(id), user_type }]) })
      .getMany();
    for (const tag of list) {
      const to = get(tag, 'to', []);
      for (const val of to) {
        if (val.user === parseInt(id)) val.is_read = '1';
      }
      await this.model.update({ id: tag.id }, { to: to });
    }
  }
  /**
   * 发送消息
   * @param id 消息数据id
   */
  async toSendMsg(id) {
    const data = await this.model.createQueryBuilder().where(`id =:id`, { id }).getOne();
    if (!data) return;
    const data_content = get(data, 'content');
    const to = get(data, 'to', []);
    for (const i of to) {
      const target = get(i, 'user');
      const userType = get(i, 'user_type');
      const content = {
        data_id: id,
        content: data_content,
      };
      this.toSendMq(target, userType, content);
    }
  }

  /**
   * 发送mq消息
   * @param target mq接收人
   * @param userType 用户类型
   * @param content 消息对象
   */
  async toSendMq(target, userType: MessageUserType, content) {
    const url = `${this.mqServiceHttpPrefix}/send`;
    const body = { target, userType, content };
    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;
  }
}
