const system = require("../../system");
const ServiceBase = require("../sve.base");
const moment = require("moment");
class EcompanyworkloadService extends ServiceBase {
   constructor() {
      super(ServiceBase.getDaoName(EcompanyworkloadService));
      this.ecompanyDao = system.getObject("db.ecompanyDao");
   }
   async getById(id) {
      var info = await this.dao.model.findOne({where:{id:id}, raw: true});
      if(info && info.ecompany_id) {
         info.ecompany = await this.ecompanyDao.findById(info.ecompany_id);
         if (info.ecompany) {
            info.ecompanyName = info.ecompany.name;
         }
      }
      return info;
   }

   async pageByCondition(params) {
      var currentPage = Number(params.currentPage || 0);
      var pageSize = Number(params.pageSize || 10);

      var where = {};

      if (params.ecompany_id) {
         where.ecompany_id = params.ecompany_id;
      }

      var beginMonth = Number(params.beginMonth || 0);
      var endMonth = Number(params.endMonth || 0);
      if (beginMonth && endMonth) {
         whereObj.month = {
            [this.db.Op.between]: [beginMonth, endMonth]
         };
      } else if (beginMonth && !endMonth) {
         whereObj.month = {
            [this.db.Op.gte]: beginMonth
         };
      } else if (!beginMonth && endMonth) {
         whereObj.month = {
            [this.db.Op.lte]: endMonth
         };
      }

      var orderby = [
         ["id", 'desc']
      ];

      var attributes = ["id", "ecompany_id", "name", "month", "url", "created_at", "updated_at"];
      var page = await this.getPageList(currentPage, pageSize, where, orderby, attributes);
      if (page && page.rows) {
         for (var row of page.rows) {
            this.handleDate(row, ["created_at", "updated_at"]);
         }
         await this.setCompany(page.rows);
      }
      return page;
   }

   async setCompany(list) {
      if (!list || list.length == 0) {
        return;
      }
  
      var companyIds = [];
      for (var item of list) {
        companyIds.push(item.ecompany_id || 0);
      }
      var companyMap = await this.ecompanyDao.findMapByIds(companyIds, " id, name, contractMobile ");
      for (var item of list) {
        item.ecompany = companyMap["id_" + (item.ecompany_id || 0)];
      }
    }
}
module.exports = EcompanyworkloadService;