const TaskBase = require("../task.base");
const system = require("../../system");
const logCtl = system.getObject("web.oplogCtl");

class JobApplyStatusTask extends TaskBase {
  constructor() {
    super(TaskBase.getServiceName(JobApplyStatusTask));
    this.ejobapplySve = system.getObject("service.ejobapplySve");
    this.ejobSve = system.getObject("service.ejobSve");
    this.ejobtimesSve = system.getObject("service.ejobtimesSve");
  }
  async subDoTask() {
    console.log("begin do job status ----------------------------------- ");
    await this.doStatus();
    console.log("end do job status ----------------------------------- ");
  }

  async saveApply(apply, status, statusName) {
    apply.status = status;
    apply.statusName = statusName;
    await apply.save();
  }

  async doOne(id) {
    var apply = await this.ejobapplySve.findById(id);
    var jobTime = await this.ejobtimesSve.findJobTime(apply.ejob_id) || {};
    if (!jobTime.begin || !jobTime.end) {
      return;
    }
    var begin = jobTime.begin.getTime();
    var end = jobTime.end.getTime();
    var now = new Date().getTime();
    // 0:待审核,1:待签约,2:已签约, 3:进行中, 4:已完成, 5:已撤销, 6:已驳回, 7:已失效
    if (apply.status == '0') {
      // 0:待审核 处理
      if (now < begin) {
        return;
      } else if(now >= begin) {
        // 改为 7:已失效
        await this.saveApply(apply, '7', '已失效'); 
      }
    } else if (apply.status == '1') {
      // 1:待签约 处理
      if (now < begin) {
        return;
      } else {
        await this.saveApply(apply, '7', '已失效');
      }
    } else if (apply.status == '2') {
      // 1. 已签约 处理
      if (now < begin) {
        return; 
      } else if (now >= begin && now < end) {
        await this.saveApply(apply, '3', '进行中');
      } else {
        await this.saveApply(apply, '4', '已完成');
      }
    } else if (apply.stauts == '3') {
      // 3:进行中 处理
      if (now < begin) {
        await this.saveApply(apply, '2', '已签约');
      } else if (now >= begin && now < end) {
        return;
      } else {
        await this.saveApply(apply, '4', '已完成');
      }
    }
  }

  async doStatus() {
    var ids = await this.ejobapplySve.getIdsByStatus(['0', '1', '2', '3']);
    console.log(ids, "-------------------------------- ids");
    if (!ids || ids.length == 0) {
      return;
    }
    for (var id of ids) {
      try {
        await this.doOne(id);
      } catch (error) {
        console.log(error);
        logCtl.info({
          optitle:"职位状态任务执行异常, apply_id is = " + id,
          op:"base/db/JobApplyStatusTask.js",
          content:"" + error.stack,
          clientIp:""
        });
      }
    }
  }
}
module.exports = JobApplyStatusTask;