const system = require("../../../system");
const ServiceBase = require("../../sve.base")
const settings = require("../../../../config/settings")
class AuthService extends ServiceBase {
  constructor() {
    super("auth", ServiceBase.getDaoName(AuthService));
    this.pmap = {};
  }

  async add(obj) {
    var saas_id = Number(obj.saas_id || 0);
    var pid = Number(obj.pid || 0);

    if (!saas_id) {
      return system.getResult(null, "请指定saas_id");
    }

    if (pid === 0) {
      // 验证是否存在其他权限
      var exist = await this.findCount({
        where: {
          saas_id: saas_id
        }
      });
      if (exist) {
        return system.getResult(null, "菜单根目录已经存在");
      }
    }

    obj.pid = pid;
    obj.saas_id = saas_id;
    obj.menuType = Number(obj.menuType || 1);
    obj.name = this.trim(obj.name);
    obj.icon = this.trim(obj.icon);
    obj.path = this.trim(obj.path);
    obj.sort = Number(obj.sort || 99);
    var obj = await this.dao.create(obj);
    return system.getResultSuccess();
  }

  async upd(obj) {
    var saas_id = Number(obj.saas_id || 0);
    var pid = Number(obj.pid || 0);
    var id = Number(obj.id || 0);
    if (!id) {
      return system.getResult(null, "菜单不存在");
    }
    var auth = await this.findById(id);
    if (!saas_id) {
      return system.getResult(null, "请指定saas_id");
    }

    if (saas_id != auth.saas_id) {
      return system.getResult(null, "修改失败，权限不足");
    }

    auth.menuType = Number(obj.menuType || 1);
    auth.name = this.trim(obj.name);
    auth.icon = this.trim(obj.icon);
    auth.path = this.trim(obj.path);
    auth.sort = Number(obj.sort || 99);

    await auth.save();
    return system.getResultSuccess();
  }

  async byPid(obj) {
    var list = await this.dao.findAll({
      pid: obj.pid || 0,
    });
    return list;
  }

  async tree() {
    var all = await this.dao.all();

    var pmap = {};
    for (var item of all) {
      var list = pmap[item.pid];
      if (!list) {
        list = [];
      }
      list.push(item);
      pmap[item.pid] = list;
      console.log(item.pid);
    }

    for(var item of all) {
      item.childs = pmap[item.id] || [];
    }

    return system.getResultSuccess(pmap[0]);
  }

  async del(obj) {
    await this.delete({id: obj.id});
    return system.getResultSuccess();
  }
}
module.exports = AuthService;