const system=require("../system")
class TaskBase{
  constructor(className){
     this.redisClient=system.getObject("util.redisClient");
     this.restS=system.getObject("util.restClient");
     this.serviceName=className;
     this.isThrough=false;
     this.isDaemon=false;
     this.TASK_CHANNEL="k8stask";
  }
  async subBeforeTask(params){
      console.log("前置操作......",this.serviceName);
  }
  async beforeTask(params){
     var self=this;
     //订阅任务频道
     await  this.redisClient.subscribe(this.TASK_CHANNEL);
     //频道事件处理函数
     this.redisClient.subclient.on("message", async function (channel, message) {
         if(channel==self.TASK_CHANNEL){
          await self.taskHandle(channel, message);
         }
     });
    await this.subBeforeTask(params);
  }
  async taskHandle(channel, message){
     await this.subTaskHandle(channel, message);
  }
  async subTaskHandle(channel, message){
      console.log(channel, message);
  }
  async subPostTask(params){
    console.log("后置操作......",this.serviceName);
  }
  async postTask(params){
    await this.subPostTask();
    this.redisClient.client.quit();
    this.redisClient.subclient.quit();
 }
  async doTask(params){
    try {
      await this.beforeTask(params);
      if(!this.isThrough){
        await this.subDoTask(params);
        if(this.isDaemon){
          var http = require('http');
          var server = http.createServer((req,res) => {
               this.reqHandler(req,res);
          })
          server.listen(process.env.TASK_PORT);//监听端口号是3000的服务器
          console.log("is listenning........on "+process.env.TASK_PORT);
        }else{
          await this.postTask(params);
        }
      
      }
    } catch (e) {
      await  this.redisClient.unsubscribe(this.TASK_CHANNEL);
      console.log(e);
      //日志记录
      console.log(JSON.stringify({
        optitle:this.serviceName+"，任务执行存在错误",
        op:"base/db/task.base.js",
        content:"",
        clientIp:"",
        status:"error"
      }));
    }
  }
  async subReqHandler(req,res){
      //设置 HTTP 头部，状态码是 200，文件类型是 html，字符集是 utf-8
      res.writeHead(200,{"Content-Type":"text/html;charset='utf-8'"});
      res.write('<h1>Node.js</h1>');
  }
  async reqHandler(req,res){
     await this.subReqHandler(req,res);
     res.end('Hello World\\n');
  }
  async subDoTask(params){
    throw new Error("请在子类中重写此方法进行操作业务逻辑............................!");
  }
  static getServiceName(ClassObj){
    return ClassObj["name"];
  }
  async apiCallWithAk(url,params){
    var acck="task";
    //按照访问token
    var restResult=await this.restS.execPostWithAK(params,url,acck);
    console.log("restResultrestResultrestResultrestResultrestResultrestResultrestResultrestResult");
    console.log(restResult);
    if(restResult){
       return restResult;
    }
    return null;
  }

  sleep(milliSeconds) { 
    var startTime = new Date().getTime(); 
    while (new Date().getTime() < startTime + milliSeconds);
  }
}
module.exports=TaskBase;
