const system=require("../../system");
const ServiceBase=require("../sve.base");
const fs=require("fs");
var excel = require('exceljs');
const uuidv4 = require('uuid/v4');
var path= require('path');
class TaskService extends ServiceBase{
  constructor(){
     super(ServiceBase.getDaoName(TaskService));
     //this.appDao=system.getObject("db.appDao");
     this.taskManager=system.getObject("db.taskManager");
     this.emailClient=system.getObject("util.mailClient");
     this.ossClient=system.getObject("util.ossClient");
  }
  async create(qobj){
    var self=this;
    return this.db.transaction(async t=>{
        var task=await  this.dao.create(qobj,t);
        //发布任务事件
        var action="new";
        var taskClassName=task.taskClassName;
        var exp=task.taskexp;
        var msg=action+"_"+taskClassName+"_"+exp;
        await self.taskManager.newTask(msg);
        await self.taskManager.publish("task","newtask");
        return task;
    });
  }
  async restartTasks2(qobj){
    return this.restartTasks(qobj);
  }
  async restartTasks(qobj){
    var self=this;
    var rtn={};
    var tasks=await this.dao.model.findAll({raw:true});
    //清空任务列表
    await this.taskManager.clearlist();
    for(var i=0;i<tasks.length;i++){
      var tmpTask2=tasks[i];
      try {
        (async (tmpTask,that)=>{
          var action="new";
          var taskClassName=tmpTask.taskClassName;
          var exp=tmpTask.taskexp;
          var msg=action+"_"+taskClassName+"_"+exp;
          await that.taskManager.newTask(msg);
          await that.taskManager.publish("task","newtask");
        })(tmpTask2,self);
      } catch (e) {
        rtn=null;
      }
    }
    return rtn;
  }
  async delete(qobj){
    var self=this;
    return this.db.transaction(async t=>{
        var task= await this.dao.model.findOne({where:qobj});
        await  this.dao.delete(task,qobj,t);
        //发布任务事件
        var action="delete";
        var taskName=task.taskClassName;
        var exp=task.taskexp;
        var msg=action+"_"+taskName;
        //发布任务，消息是action_taskClassName
        await this.taskManager.publish("task",msg,null);
        return task;
    });
  }
}
module.exports=TaskService;
