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) {
    var self = this;
    console.log("save msg ", msg);
    // 事务
    await this.db.transaction(async function (t){
        // 1.保存聊天信息
        msg = await self.dao.create(msg, t);
        // 2.保存好友信息
        await self.msgnoticeDao.saveNotice(msg, t);
    });
    return msg;
  }

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

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

    var senderChannel = senderUser.app_id + "￥" + senderUser.id;
    var targetChannel = targetUser.app_id + "￥" + targetUser.id;

    var sender = senderUser.app_id + "￥" + senderUser.id + "￥" + senderUser.headUrl;
    var target = targetUser.app_id + "￥" + targetUser.id + "￥" + targetUser.headUrl;
    var msg = {
      msgType: "mryzLicense",
      sender:sender,
      senderId:senderId,
      target:target,
      targetId:targetId,
      content:businessLicense_id,
      isRead:false,
      businessLicense_id:businessLicense_id
    }

    var obj = await this.saveMsg(msg);

    var 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) {
    let 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 "
    let params = {senderId:senderId, targetId: targetId, maxId: maxId, pageSize: pageSize};
    var list = await this.dao.customQuery(sql, params);

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

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

      var licenseMap = [];
      licenseList.forEach(item => {
        licenseMap["id" + item.id] = item;
      });
      list.forEach(item => {
        if(item.msgType == 'mryzLicense') {
          item.businessLicense = licenseMap['id' + item.businessLicense_id];
        }
      });
    }

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

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

    var target = await this.userDao.findById(targetId);
    if(!target) {
      return;
    }
    var pushIds = [];
    for(var 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}}});
    var channel = target.app_id + "￥" + target.id;
    var rs = await this.redisClient.publish(channel, JSON.stringify({type:"readmsg", data : pushIds}));
    console.log(rs, "------------------------------------------ publish result ");
  }

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

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