const system = require("../../../system");
const Dao = require("../../dao.base");

class OrgDao extends Dao {
  constructor() {
    super(Dao.getModelName(OrgDao));
  }

  /**
   * 条件查询
   * @param {} params
   */
  async findUserByOrgId(params) {
    let sql = [];
    sql.push(`SELECT c.ucid,c.ucname,c.uctype,c.saas_id,c.isEnabled,c.created_at,c.updated_at,c.deleted_at
      FROM uc_org a INNER JOIN uc_user_org b ON a.id = b.org_id INNER JOIN uc_user c ON b.user_id = c.id
      WHERE 1=1 and ( c.deleted_at is null or c.deleted_at > NOW() ) `);
    if (params.id) {
      sql.push("AND a.id = :id");
    }
    return await this.customQuery(sql.join(" "), params);
  }

  async all(saas_id, attrs) {
    attrs = attrs || "*";
    var sql = [];
    sql.push("SELECT");
    sql.push(attrs);
    sql.push("FROM uc_org");
    sql.push("WHERE deleted_at IS NULL");
    var params = {};
    if (saas_id) {
      sql.push("AND saas_id = :saas_id");
      params.saas_id = saas_id;
    }
    return this.customQuery(sql.join(" "), params);
  }

  async mapByIds(ids) {
    let result = {};
    if (!ids || ids.length == 0) {
      return result;
    }
    let sql = [];
    sql.push("SELECT");
    sql.push("*");
    sql.push("FROM uc_org");
    sql.push("WHERE id IN (:ids)");

    let list = await this.customQuery(sql.join(" "), {
      ids: ids
    });
    if (!list || list.length == 0) {
      return result;
    }
    for (let item of list) {
      result[item.id] = item;
    }
    return result;
  }

}

module.exports = OrgDao;