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

  async delByUserId(user_id, t) {
    var sql = "DELETE FROM uc_user_role WHERE user_id = :user_id";
    await this.customUpdate(sql, {
      user_id: user_id
    }, t) || [];
  }

  async listByUserId(user_id, attrs, t) {
    attrs = attrs || "*";
    var sql = "SELECT " + attrs + " FROM uc_user_role WHERE user_id = :user_id";
    return await this.customQuery(sql, {
      user_id: user_id
    }, t) || [];
  }

  async findUserRoles(user_id) {
    var sql = [];
    sql.push("SELECT");
    sql.push("t2.`id`, t2.`code`, t2.`name`");
    sql.push("FROM uc_user_role t1")
    sql.push("INNER JOIN uc_role t2 ON t1.`role_id` = t2.`id`");
    sql.push("WHERE t1.`user_id` = :user_id");
    return await this.customQuery(sql.join(" "), {
      user_id: user_id
    }) || [];
  }

  async mapByUserIds(userIds) {
    let result = {};
    let sql = [];
    sql.push("SELECT");
    sql.push("user_id, role_id");
    sql.push("FROM uc_user_role");
    sql.push("WHERE user_id IN (:userIds)");
    sql.push("GROUP BY user_id, role_id");

    let list = await this.customQuery(sql.join(" "), {userIds: userIds});
    if (!list || list.length == 0) {
      return {};
    }

    for (let item of list) {
      let roleIds = result[item.user_id];
      if (!roleIds) {
        roleIds = [];
      }
      roleIds.push(item.role_id);
      result[item.user_id] = roleIds;
    }
    return result;
  }


  async mapByUserIds2(userIds) {
    let result = {};
    let sql = [];
    sql.push("SELECT");
    sql.push("t2.id, t1.user_id, t2.`code`, t2.`name`");
    sql.push("FROM uc_user_role t1")
    sql.push("INNER JOIN uc_role t2 ON t1.`role_id` = t2.`id`");
    sql.push("WHERE t1.`user_id` IN (:userIds)");

    let list = await this.customQuery(sql.join(" "), {userIds: userIds});
    if (!list || list.length == 0) {
      return {};
    }
    for (let item of list) {
      let roles = result[item.user_id] || [];
      roles.push(item);
      result[item.user_id] = roles;
    }
    return result;
  }
}
module.exports = UserroleDao;