const system = require('../../../system');
const ServiceBase = require('../../sve.base');
class MsgHistoryService extends ServiceBase {
  constructor() {
    super(ServiceBase.getDaoName(MsgHistoryService));
    this.msgnoticeDao = system.getObject('db.msg.msgnoticeDao');
    this.userDao = system.getObject('db.auth.userDao');
    this.redisClient = system.getObject('util.redisClient');
  }
  async saveMsg(msg) {
    const self = this;
    console.log('save msg ', msg);
    // 事务
    await this.db.transaction(async (t) => {
      // 1.保存聊天信息
      msg = await self.dao.create(msg, t);
      // 2.保存好友信息
      await self.msgnoticeDao.saveNotice(msg, t);
    });
    return msg;
  }

  async pushBusinessLicenseMsg(senderId, targetId, businessLicenseId) {
    if (!businessLicenseId) {
      return 0;
    }
    const notice = await this.msgnoticeDao.findOne({ fromId: senderId, toId: targetId });
    if (notice && notice.businessLicense_id == businessLicenseId) {
      return 0;
    }

    const senderUser = await this.userDao.findById(senderId);
    const targetUser = await this.userDao.findById(targetId);

    const senderChannel = `${senderUser.app_id}￥${senderUser.id}`;
    const targetChannel = `${targetUser.app_id}￥${targetUser.id}`;

    const sender = `${senderUser.app_id}￥${senderUser.id}￥${senderUser.headUrl}`;
    const target = `${targetUser.app_id}￥${targetUser.id}￥${targetUser.headUrl}`;
    const msg = {
      msgType: 'mryzLicense',
      sender,
      senderId,
      target,
      targetId,
      content: businessLicense_id,
      isRead: false,
      businessLicense_id,
    };

    const obj = await this.saveMsg(msg);

    const bl = await this.businesslicenseDao.findById(businessLicense_id);
    msg.businessLicense = bl;
    msg.id = obj.id;
    msg.created_at = obj.created_at;

    this.redisClient.publish(senderChannel, JSON.stringify(msg));
    this.redisClient.publish(targetChannel, JSON.stringify(msg));
    return 1;
  }

  async getChatList(senderId, targetId, maxId, pageSize) {
    const sql = 'SELECT * FROM `msghistory` WHERE id < :maxId AND ((senderId = :senderId AND targetId = :targetId) OR (targetId = :senderId AND senderId = :targetId)) ORDER BY id DESC LIMIT :pageSize ';
    const params = { senderId, targetId, maxId, pageSize };
    const list = await this.dao.customQuery(sql, params);

    if (!list || list.length == 0) {
      return [];
    }

    const licenseIds = [];
    const msgIds = [];
    list.forEach((item) => {
      if (item.msgType == 'mryzLicense') {
        licenseIds.push(Number(item.businessLicense_id));
      }
      msgIds.push(item.id);
    });
    if (licenseIds.length > 0) {
      const licenseSql = `SELECT * FROM yz_business_license WHERE id IN (${licenseIds.join(',')}) `;
      const licenseList = await this.businesslicenseDao.customQuery(licenseSql);

      const licenseMap = [];
      licenseList.forEach((item) => {
        licenseMap[`id${item.id}`] = item;
      });
      list.forEach((item) => {
        if (item.msgType == 'mryzLicense') {
          item.businessLicense = licenseMap[`id${item.businessLicense_id}`];
        }
      });
    }

    const self = this;
    setTimeout(() => {
      self.setRead(senderId, targetId, list);
    }, 1000);
    return list;
  }

  async setRead(senderId, targetId, list) {
    if (!list || list.length == 0) {
      return;
    }

    const target = await this.userDao.findById(targetId);
    if (!target) {
      return;
    }
    const pushIds = [];
    for (const item of list) {
      if (item.isRead || senderId != item.targetId) {
        continue;
      }
      pushIds.push(item.id);
    }

    if (pushIds.length == 0) {
      return;
    }

    this.dao.updateByWhere({ isRead: true }, { where: { id: { [this.db.Op.in]: pushIds } } });
    const channel = `${target.app_id}￥${target.id}`;
    const rs = await this.redisClient.publish(channel, JSON.stringify({ type: 'readmsg', data: pushIds }));
    console.log(rs, '------------------------------------------ publish result ');
  }

  async readMsg(userId, id) {
    const msg = await this.dao.findById(id);
    if (!msg || userId != msg.targetId) {
      return 0;
    }
    msg.isRead = true;
    await msg.save();

    const user = await this.userDao.findById(msg.senderId);
    if (!user) {
      return 0;
    }
    const channel = `${user.app_id}￥${user.id}`;
    return await this.redisClient.publish(channel, JSON.stringify({ type: 'readmsg', data: [msg.id] }));
  }
}
module.exports = MsgHistoryService;
