var Server=require('socket.io');
var System = require('../base/system');
var redisClient=System.getObject("util.redisClient");
const logCtl=System.getObject("web.oplogCtl");
const notifyCtl=System.getObject("web.socketNotifyCtl");
const msgHistoryService=System.getObject("service.msghistorySve");
class MsgHandler{
  constructor(server,client){
    this.server=server;
    this.client=client;
    this.init();
  }
  notifyClient(ukchannel,msg){
    var msgH={msgType:"system",sender:"s￥s￥s￥s",target:msg.to,content:msg.content};
    msgHistoryService.create(msgH).then((m)=>{
      redisClient.publish(ukchannel,JSON.stringify(msg));
    }).catch(e=>{
        console.log(e);
        logCtl.info({
           optitle:"socket.server.js->notifyClient接口调用异常error:",
           op:"chatmsg",
           content:e.stack,
           clientIp:null,
           agent:"",
         });

    });
  }
  init(){
    var self=this;
    //转发通信消息
    this.client.on("chatmsg",msg=>{
      const from=msg.from;
      const to=msg.to;
      const msgContent=msg.content;
      var arrs=to.split("￥");
      var tochannel=arrs[0]+"￥"+arrs[1];
      //发布消息
      //持久化消息
      var msgH={msgType:"single",sender:msg.from,target:msg.to,content:msg.content};
      msgHistoryService.create(msgH).then((m)=>{
        redisClient.publish(tochannel,JSON.stringify(msg));
      }).catch(e=>{
          console.log(e);
          logCtl.info({
             optitle:"socket.server.js->发布消息->持久化消息接口调用异常error:",
  					 op:"chatmsg",
  					 content:e,
  					 clientIp:null,
  					 agent:"",
  				 });
      });
      //self.server.users[to].emit("chatmsg",msg);
    });

    this.client.on("mryzmsg", async msg=>{
      try {
        const from=msg.from;
        const to=msg.to;
        const msgContent=msg.content;
        var fromArrs = from.split("￥");
        var toArrs=to.split("￥");

        var fromId = Number(fromArrs[1]);
        var toId = Number(toArrs[1]);

        var fromChannel = fromArrs[0]+"￥"+fromArrs[1];
        var toChannel = toArrs[0]+"￥"+toArrs[1];

        // 消息对象
        var msgH = {
          msgType:msg.msgType || "mryzSingle",
          sender:from,
          senderId:fromId,
          target:msg.to,
          targetId:toId,
          content:msgContent,
          isRead:false,
          businessLicense_id:msg.businessLicense_id || 0,
        };
        msgH = await msgHistoryService.saveMsg(msgH);
        redisClient.publish(fromChannel, JSON.stringify(msgH));
        if(fromChannel != toChannel) {
          redisClient.publish(toChannel, JSON.stringify(msgH));
        }
      } catch (e) {
        console.error(e);
        logCtl.info({
           optitle:"socket.server.js->发布每日易照消息->持久化每日易照消息接口调用异常error:",
           op:"mryzmsg",
           content:e,
           clientIp:null,
           agent:"",
         });
      }
      //self.server.users[to].emit("chatmsg",msg);
    });

    //响应消息处理
    this.client.on("replymsg",(msg,fn)=>{
      var p=null;
      var invokeObj= System.getObject("web."+msg.cls);
      console.log(invokeObj);
			if(invokeObj[msg.method]){
				p=invokeObj[msg.method].apply(invokeObj,[msg.data]);
			}
      p.then(r=>{
				fn(r);
			}).then(()=>{
        logCtl.info({
           optitle:"socket.server.js->响应消息处理->接口调用info:",
					 op:msg.cls+"/"+msg.method,
					 content:JSON.stringify(msg.data),
					 clientIp:null,
					 agent:"",
				 });
      }).catch(err=>{
        logCtl.error({
           optitle:"socket.server.js->响应消息处理->接口调用异常error:",
					 op:msg.cls+"/"+msg.method,
					 content:JSON.stringify(msg.data),
					 clientIp:null,
					 agent:"",
				 });
      })
    });
  }

}
class SocketServer{
   constructor(httpServer){
     this.server=Server(httpServer,{
       serveClient: false,
     });
     this.users={};
     this.init();
     this.onlines=0;
   }
   init(){
     var self=this;
     //挂载到web应用的控制器
     notifyCtl.setSocketServer(self);
     //订阅广播频道
     redisClient.subscribe("brc",self);
     //中间件可以在链接事件发出前调用一次
     this.server.use((socket,next)=>{
       next();
     });
     this.server.on('connection', function(client){
        console.log("connection.....socket");
        //链接登录事件
        client.on('login', function(data){
          console.log("login...........................................................success");
          console.log(data);
          console.log(client.remoteAddress);
          var uk=data.appid+"￥"+data.id;
          client.uk=uk;
          client.uid=data.id;
          client.username=data.nickName;
          client.appname=data.appname;
          client.appkey=data.appkey;
          client.sex=data.sex;
          client.imgUrl=data.imgUrl;
          self.users[uk]=new MsgHandler(self,client);
          //订阅uk私人频道
          var ss = redisClient.subscribe(uk,self);
          //加入redisClient列表
          redisClient.sadd("onlineset"+"￥"+data.appkey,[uk+"￥"+data.nickName+"￥"+data.imgUrl]).then(n=>{
            //当前在线
            self.onlines=n;
            redisClient.publish("brc",JSON.stringify({"type":"online","content":n}));
          });
        });
        //链接断开事件
        client.on('disconnect', async function(r){
          console.log("connection.........................................dismiss.............");
          if(client.uk) {
             await redisClient.srem("onlineset"+"￥"+client.appkey,client.uk+"￥"+client.username+"￥"+client.imgUrl);
             await redisClient.publish("brc",JSON.stringify({"type":"online","content":(self.onlines--)}));
             delete self.users[client.uk];
             redisClient.unsubscribe(client.uk);
             //redisClient.unsubscribe("brc");
             console.log(client.uk+"￥"+client.username+"￥"+client.imgUrl);
          }
        });
     });
   }
}
module.exports=SocketServer;
