var Server = require('socket.io');
var system = require('../base/system');
var redisClient = system.getObject("util.redisClient");
const redisAdapter = require('socket.io-redis');
const uuidv4 = require('uuid/v4');
// const notifyCtl = system.getObject("web.socketNotifyCtl");
// const msgHistoryService = system.getObject("service.msghistorySve");
class RoomSet {
  constructor(server, client) {
    this.roomset = [];//房间集
    this.memberset = [];//人员集
    this.init();
  }
  init () {
    var self = this
    redisClient.smembers("roomset").then(rs => {
      //初始化房间集
      self.roomset = rs
    });
    redisClient.smembers("memberset").then(rs => {
      //初始化人员集
      self.memberset = rs
    });
  }
  /**
   * 按照房间名查看人员
   */
  async clientsByRoom (roomname) {
    let rlst = await redisClient.get(roomname)
    return rlst
  }
  /**
   * 查看所有当前在线人数
   */
  async allmembers () {
    return this.memberset
  }
  async allrooms () {
    return this.roomset
  }
}
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);
    });
  }
  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);
      });
      //self.server.users[to].emit("chatmsg",msg);
    });

    //响应消息处理
    this.client.on("replymsg", (msg, fn) => {
      var p = null;
      var invokeObj = system.getObject("web." + msg.pkgname + "." + msg.cls);
      if (invokeObj[msg.method]) {
        p = invokeObj[msg.method].apply(invokeObj, [msg.data]);
      }
      p.then(r => {
        fn(r);
      }).then(() => {
        console.log("call success")
      }).catch(err => {
        console.log(err)
      })
    });
  }

}
class SocketServer {
  constructor(httpServer) {
    this.server = Server(httpServer, {
      serveClient: false,
      cookie: true
    });
    // this.server.adapter(redisAdapter({ pubClient: redisClient.client, subClient: redisClient.subclient }));
    this.server.engine.generateId = (req) => {
      // console.log(req.headers)
      return "custom:id:" + this.getUUID(); // custom id must be unique
    }
    this.users = {}//缓存所有客户端处理器
    this.uinfos = {}//缓存用户信息
    this.socketidMap = {}
    this.rooms = {}
    this.init()
  }
  getUUID () {
    var uuid = uuidv4();
    var u = uuid.replace(/\-/g, "");
    return u;
  }
  init () {
    var self = this;
    this.server.on('connection', function (client) {
      console.log("connection.....socket");
      client.on("login", (d) => {
        let uname = d.userName
        let nickName = d.nickName ? d.nickName : uname
        let headUrl = d.headUrl ? d.headUrl : 'https://gsb-zc.oss-cn-beijing.aliyuncs.com/zc_picUrl344116000745887092020814.jpg'
        let id = d.id
        let encuk = {
          companyid: d.company.id,
          userid: id,
          userName: uname,
          nickName: nickName,
          headUrl: headUrl
        }
        // let str = system.encriptByDes(JSON.stringify(encuk))
        //console.log('encstr', str)
        let uk = uname + "_" + id + "_" + d.company.id
        let ukencstr = system.encriptByDes(JSON.stringify(uk))

        //保存所有的客户端的消息处理器
        self.users[ukencstr] = new MsgHandler(self, client)
        self.uinfos[ukencstr] = encuk
        self.socketidMap[client.id] = ukencstr
        //订阅uk私人频道房间
        var ss = redisClient.subscribe(ukencstr, self);
        //缓存房间到set,缓存所有房间
        //缓存房间中的所有人
      })
      // //
      // self.of('/').adapter.clients((err, clients) => {
      //   console.log(clients); // an array containing all connected socket ids
      // });
      //链接断开事件
      client.on('disconnect', async function (r) {
        console.log("connection.........................................dismiss.............", client.id, r);
        let ukencstr = self.socketidMap[client.id]
        delete self.users[ukencstr]
        delete self.uinfos[ukencstr]
        delete self.socketidMap[client.id]
      });
    });
  }

}
module.exports = SocketServer;
