var Service = require('Service');
var utils = require('utils');
var ScheduledTask = require('../../dao/scheduled_task');
var util = require('util');

/**
 * 修改
 */
var Update = function() { 
  Service.call(this);
};

util.inherits(Update, Service);

module.exports = Update;

/**
 * 处理服务请求
 * @param  {Object} req 服务请求对象
 * @param  {Object} res 服务响应对象
 */
Update.prototype.process =  function(req, res) {
  if(!req.id) {
    this.onLogicError(1, '请提供任务编号！');
    return;
  }
  if(!utils.isInt(req.id)) {
    this.onLogicError(2, '请提供正确的任务编号！');
    return;
  }
  if(!req.name) {
    this.onLogicError(2, '请提供任务名称！');
    return;
  }
  /*if(!req.taskService) {
    this.onLogicError(7, '请提供服务路径！');
    return;
  }*/
  if(!req.type) {
    this.onLogicError(3, '请提供任务类型！');
    return;
  }
  if(!req.exeTime) {
    this.onLogicError(4, '请提供执行时间！');
    return;
  }
  if(req.type==1 || req.type=='1') {
    if(!req.periodType) {
      this.onLogicError(5, '请提供周期类型！');
      return;
    }
    if(req.periodType!='day' && !req.periodRange) {
      this.onLogicError(5, '请提供周期间隔！');
      return;
    }
    if(!req.startDate) {
      this.onLogicError(5, '请提供开始时间！');
      return;
    }
    req.startDate = utils.strToDate(req.startDate + ':00');
    if(req.endDate) {
      req.endDate = utils.strToDate(req.endDate + ':00');
      if(req.startDate>req.endDate) {
        this.onLogicError(6, '开始时间不能晚于结束时间！');
        return;
      }
    }
  }
  
  var self = this;
  var dao = new ScheduledTask(this);
  dao.query({where: '(name=? or service=?) and id<>'+req.id
    +' and org_id='+req.session.orgId,
    params:[req.name, req.taskService]}, function(rows) {
    if(rows.length>0) {
      self.onLogicError(8, '任务已存在！');
      return;
    }
    var task = {};
    task.name = req.name;
    task.type = req.type;
    //task.service = req.taskService;
    if(req.exeTime) task.exe_time = req.exeTime + ':00';
    if(task.type==1) {
      if(req.periodType) task.period_type = req.periodType;
      if(req.periodRange) task.period_range = req.periodRange;
      if(req.startDate) task.start_date = req.startDate;
      if(req.endDate) task.end_date = req.endDate;
    }

    dao.update(task, {where: 'id='+req.id+' and org_id='+req.session.orgId}, function() {
      dao.query({where: 'id='+req.id+' and org_id='+req.session.orgId}, function(rows2) {
        if(rows2.length==0) {
          self.end(res);
          return;
        }
        var taskNew = rows2[0];
        if(taskNew.status==0) {
          global.server.scheduleTaskManager.tasks[taskNew.id] = taskNew;
        }
        self.end(res);
      });
    });
  });
};