const system = require("../../system");
const ServiceBase = require("../sve.base");
const moment = require("moment");
class EcompanyworkService extends ServiceBase {
   constructor() {
      super(ServiceBase.getDaoName(EcompanyworkService));
      this.ecompanyDao = system.getObject("db.ecompanyDao");
   }
   async getById(id) {
      var info = await this.dao.model.findOne({where:{id:id}, raw: true});
      if(info && info.ecompanyId) {
         info.ecompany = await this.ecompanyDao.findById(info.ecompanyId);
         if (info.ecompany) {
            info.ecompanyName = info.ecompany.name;
         }
      }
      this.handleDate(info, ["beginDate", "endDate"], "YYYY-MM-DD", -8);
      info.price = system.f2y(info.price);
      info.payPrice = system.f2y(info.payPrice);
      return info;
   }

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

      var where = {};

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

      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 page = await this.getPageList(currentPage, pageSize, where, orderby);
      if (page && page.rows) {
         for (var row of page.rows) {
            this.handleDate(row, ["created_at", "updated_at"]);
            this.handleDate(row, ["beginDate", "endDate"], "YYYY-MM-DD", -8);
            row.price = system.f2y(row.price);
            row.payPrice = system.f2y(row.payPrice);
         }
         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.ecompanyId || 0);
      }
      var companyMap = await this.ecompanyDao.findMapByIds(companyIds, " id, name, contractMobile ");
      for (var item of list) {
        item.ecompany = companyMap["id_" + (item.ecompanyId || 0)] || {};
      }
    }
}
module.exports = EcompanyworkService;