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

  async findMapByIds(ids, attrs) {
    var result = [];
    if(!ids || ids.length == 0) {
      return result;
    }

    attrs = attrs || "*";
    var sql = "SELECT " + attrs + " FROM c_dkcompany where id IN (:ids) ";
    var list = await this.customQuery(sql, {ids:ids});
    if(!list || list.length == 0) {
      return result;
    }

    for(var item of list) {
      result["id_" + item.id] = item;
    }

    return result;
  }

  async idsLikeName(name) {
    var result = [];
    if(!name || !name.trim()) {
      return result;
    }

    var sql = "SELECT id FROM c_dkcompany WHERE name LIKE :name ";
    var list = await this.customQuery(sql, {name : "%" + name + "%"});
    
    if(list) {
      for(var item of list) {
        result.push(item.id);
      }
    }
    return result;
  }

  async findNamesByOwnerIds(ownerIds) {
    var result = [];
    if(!ownerIds || ownerIds.length == 0) {
      return result;
    }
    var sql = "SELECT name FROM c_dkcompany WHERE owner_id IN (:ownerIds) ";
    var list = await this.customQuery(sql, {ownerIds: ownerIds});
    if(!list || list.length == 0) {
      return result;
    }

    for(var item of list) {
      result.push(item.name);
    }
    return result;
  }

  async findIdsByOwnerIds(ownerIds) {
    var result = [];  
    if(!ownerIds || ownerIds.length == 0) {
      return result;
    }
    var sql = "SELECT id FROM c_dkcompany WHERE owner_id IN (:ownerIds) ";
    var list = await this.customQuery(sql, {ownerIds: ownerIds});
    if(!list || list.length == 0) {
      return result;
    }

    for(var item of list) {
      result.push(item.id);
    }
    return result;
  }



  async findMapByNames(names, attrs) {
    var result = [];
    if(!ids || ids.length == 0) {
      return result;
    }

    attrs = attrs || "*";
    var sql = "SELECT " + attrs + " FROM c_dkcompany where name IN (:names) WHERE deleted_at IS NULL ";
    var list = await this.customQuery(sql, {names:names});
    if(!list || list.length == 0) {
      return result;
    }

    for(var item of list) {
      result[item.name] = item;
    }
    return result;
  }

  async suggest(name, ownerIds) {
    if(!name) {
      return [];
    }
    var sql = "SELECT id, name FROM `c_dkcompany` WHERE name LIKE :queryLike AND deleted_at IS NULL ";

    if(ownerIds && ownerIds.length > 0) {
      sql = sql + " AND owner_id IN (:ownerIds) ";
    }
    sql = sql + " ORDER BY id ASC ";
    var list = await this.customQuery(sql, {queryLike: "%" + name + "%", ownerIds: ownerIds});
    return list || [];
  }
}
module.exports = DKcompanyDao;