const system=require("../../system");
const Dao=require("../dao.base");
const moment = require("moment");
class EjobtimesDao extends Dao{
  constructor(){
    super(Dao.getModelName(EjobtimesDao));
  }

  async findMapByJobIds(jobIds, timePatten) {
    var result = [];
    if(!jobIds || jobIds.length == 0) {
      return result;
    }

    timePatten = timePatten || "YYYY.MM.DD";

    var sql = "SELECT * FROM c_ejob_times where ejob_id IN (:jobIds) ";
    var list = await this.customQuery(sql, {jobIds:jobIds});
    if(!list || list.length == 0) {
      return result;
    }

    for(var item of list) {
      var key = "ejobId_" + item.ejob_id;
      var lst = result[key];
      if(!lst) {
        lst = [];
      }
      item.begin_at = moment(item.begin_at).format(timePatten);
      item.end_at = moment(item.end_at).format(timePatten);
      lst.push(item);
      result[key] = lst;
    }
    return result;
  }

  async findByTime(companyId, begin, end) {
    if(!companyId) {
      return [];
    }
    var where = {ecompany_id: companyId};
    var and = [];
    if(begin && end) {  
      where.end_at = {
        [this.db.Op.gte]: begin + " 00:00:00"
      };
      where.begin_at = {
        [this.db.Op.lte]: end + " 23:59:59"
      };
    } else if(begin && !end) {
      where.begin_at = {
        [this.db.Op.lte]: begin + " 23:59:59"
      };
      where.end_at = {
        [this.db.Op.gte]: begin + " 00:00:00"
      };
    } else if(!begin && end) {
      where.begin_at = {
        [this.db.Op.lte]: end + " 23:59:59"
      };
      where.end_at = {
        [this.db.Op.gte]: end + " 00:00:00"
      };
    }
    
    var result = await this.model.findAll({where:where,attributes:["ejob_id"]});
    var ids = [];
    for(var item of result) {
      if(ids.indexOf(item.ejob_id) == -1) {
        ids.push(item.ejob_id);
      }
    }
    return ids;
  }

  async findJobTime(jobId) {
    var sql = "SELECT MIN(begin_at) AS begin, MAX(end_at) AS end FROM `c_ejob_times` WHERE ejob_id = " + jobId;
    var list = await this.customQuery(sql);
    if(!list || list.length == 0) {
      return {};
    }

    return list[0];
  }
}
module.exports=EjobtimesDao;
