var system = require("../../../system")
var settings = require("../../../../config/settings");
const CtlBase = require("../../ctl.base");
var cacheBaseComp = null;
class MetaCtl extends CtlBase {
  constructor() {
    super("common", CtlBase.getServiceName(MetaCtl));
    this.userS = system.getObject("service.auth.userSve");
  }
  //根据查询参数来确定当前会话对应的应用
  async getAppInfo(req) {
    var acckapp = await this.cacheManager["ApiAccessKeyCache"].cache(settings.appKey, null, 3600);
    if(settings.companyKey){//说明单独登录
      acckapp.app.oauthlogin=acckapp.app.oauthlogin.replace("#","&companyKey="+settings.companyKey+"#");
      acckapp.app.oauthreg=acckapp.app.oauthreg.replace("#","&companyKey="+settings.companyKey+"#");
    }
    if (acckapp) {
      var rs = await this.getRsConfig2(null, req);
      var bcom = await this.getBaseComp();
      var rtn = { "paasurl":settings.paasUrl(),"appinfo": escape(JSON.stringify(acckapp.app)), "basecomp": bcom, "rsconfig": escape(JSON.stringify(rs)), "app": acckapp.app };
      req.session.app = acckapp.app;
      return rtn;
    } else {
      return null;
    }
  }
  async getApiDoc(pobj, queryObj, req) {
    var appid = pobj.appid;
    if (appid == settings.platformid) {
      var result = await this.service.getApiDoc(appid);
      return system.getResult(result);
    }
    return system.getResultFail();
  }
  /**
   * 获取页面基础组件
   */
  async getBaseComp() {
    if (cacheBaseComp) {
      return cacheBaseComp;
    }
    cacheBaseComp = await this.service.getBaseComp();
    cacheBaseComp = escape(JSON.stringify(cacheBaseComp));
    return cacheBaseComp;
  }

  //权限 角色+资源节点code+权限字符串,codepath--
  async getUiConfig(pobj,queryObj, req) {
    var bizCode = queryObj.biz;
    var cfg = await this.service.getUiConfig(settings.appKey);
    console.log(cfg);
    var tmpRoleAuthStr = "";
    if (req && req.session && req.session.user) {
      var tmpRoles = [];
      if (req.session.user.Roles) {
        req.session.user.Roles.forEach(r => {
          tmpRoles.push(r.code);
        });
        //按照角色获取权限列表
        var auths = await this.service.findAuthsByRole(tmpRoles, req.session.user.app_id,req.session.user.owner.id);
        var codeauthattrs = auths.map(r => {
          if (r.authstrs && r.authstrs != "") {
            return r.authstrs;
          } else {
            return "";
          }
        });
        tmpRoleAuthStr = codeauthattrs.join(",");
      }

    }
    //获取当前登录人的角色，进而获取权限，进而合并工具栏目
    var toolbar = [];

    const bizConfigData = cfg.config["bizs"][bizCode];
    console.log(bizCode);
    Object.keys(bizConfigData.config.auth).map(k => {
      //只要有权限就添加
      if (req.session.user && req.session.user.isAdmin) {
        toolbar = toolbar.concat(bizConfigData.config.auth[k]);
      } else {
        if (tmpRoleAuthStr.indexOf(k) >= 0) {
          toolbar = toolbar.concat(bizConfigData.config.auth[k]);
        }
      }
    })
    bizConfigData.config.toolbar = toolbar;
    return system.getResultSuccess(bizConfigData.config);
  }

  async getDicConfig(pobj,queryObj, req) {
    var dicKey = queryObj["dicKey"];
    var cfg = await this.service.getUiConfig(settings.appKey);
    //获取当前登录人的角色，进而获取权限，进而合并工具栏目
    if (dicKey == "data_priv") {
      if (req.session && req.session.user && !req.session.user.isSuper) {
        delete cfg.config["pdict"][dicKey]["company"];
      }
    }

    return system.getResultSuccess(cfg.config["pdict"][dicKey]);
  }
  async findSubSystems(p, q, req) {
    var rtnSubs = [];
    var cfg = await this.service.getUiConfig(settings.appKey);
    var tmpRoleCodepathStr = [];
    if (req && req.session && req.session.user) {
      var tmpRoles = [];
      if (req.session.user.Roles) {
        req.session.user.Roles.forEach(r => {
          tmpRoles.push(r.code);
        });
        //按照角色获取权限列表
        var auths = await this.service.findAuthsByRole(tmpRoles, req.session.user.app_id,req.session.user.owner.id);
        var codepathattrs = auths.map(r => {
          if (r.authstrs && r.authstrs != "") {
            if (r.codepath) {
              var cparr = r.codepath.split("/");
              for (var c of cparr) {
                tmpRoleCodepathStr.push(c);
              }
            }
            return r.codepath;
          } else {
            return "";
          }
        });
        for (var i = 0; i < cfg.config["rstree"].children.length; i++) {
          var r = cfg.config["rstree"].children[i];
          if (r.isSubmenu) {

            if (tmpRoleCodepathStr.indexOf(r.code) >= 0) {
              rtnSubs.push({ subcode: r.code, subtitle: r.label });
            } else {
              if (req.session.user.isAdmin) {

                if (r.code.indexOf("pmg") < 0) {
                  rtnSubs.push({ subcode: r.code, subtitle: r.label });
                } else {
                  if (req.session.user.isSuper) {
                    rtnSubs.push({ subcode: r.code, subtitle: r.label });
                  }
                }

              }


            }
          }
        }
      }

    }
    return system.getResultSuccess(rtnSubs);

  }
  async getRsConfig2(q, req) {
    var rs2 = [];
    console.log("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
    var cfg = await this.service.getUiConfig(settings.appKey);
    console.log("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy");
    var tmpRoleCodepathStr = [];
    if (req && req.session && req.session.user) {

      var tmpRoles = [];
      if (req.session.user.Roles) {
        req.session.user.Roles.forEach(r => {
          tmpRoles.push(r.code);
        });
        //按照角色获取权限列表
        var auths = await this.service.findAuthsByRole(tmpRoles, req.session.user.app_id,req.session.user.owner.id);
        var codepathattrs = auths.map(r => {
          if (r.authstrs && r.authstrs != "") {
            if (r.codepath) {
              var cparr = r.codepath.split("/");
              for (var c of cparr) {
                tmpRoleCodepathStr.push(c);
              }
            }
            return r.codepath;
          } else {
            return "";
          }
        });

      }

    }
    console.log(".....................获取当前登录人的角色，进而获取权限，进而合并工具栏目.getRsConfig");
    //获取当前登录人的角色，进而获取权限，进而合并工具栏目
    for (var i = 0; i < cfg.config["rstree"].children.length; i++) {
      var r = cfg.config["rstree"].children[i];
      console.log(r.code);
      var funcrange = function (n) {
        if (req && req.session && req.session.user) {
          if (req.session.user.isAdmin || req.session.user.isSuper) {
            if (n.codePath.indexOf("pmg") < 0 && req.session.user.isAdmin) {
              n.hidden = false;
            }
            if (n.codePath.indexOf("pmg") >= 0 && req.session.user.isAdmin) {
              n.hidden = true;
            }
            if (n.codePath.indexOf("pmg") >= 0 && req.session.user.isSuper) {
              console.log("isSuperisSuperisSuperisSuperisSuperisSuperisSuperisSuperisSuperisSuper");
              n.hidden = false;
            }
            if (n.codePath.indexOf("pmg") < 0 && req.session.user.isSuper && !req.session.user.isAdmin) {
              console.log("isSuperisSuperisSuperisSuperisSuperisSuperisSuperisSuperisSuperisSuper");
              n.hidden = true;
            }
          } else {
            if (tmpRoleCodepathStr.indexOf(n.code) < 0) {
              if (n.isctl && n.isctl == "no") {
                n.hidden = false;
                console.log(n.code, "no ctl", "show menu");
              } else {
                n.hidden = true;
                console.log(n.code, "no authed", "hide menu");

              }
            } else {
              n.hidden = false;
              console.log(n.code, "authed......", "show menu");
            }
          }
        }
        if (n.children) {
          n.children.forEach((dd) => {
            return funcrange(dd);
          });
        } else {
          if (n.isctl && n.isctl == "no") {
            n.hidden = false;
          }
          return;
        }
      };
      funcrange(r);
    }
    return (cfg.config["rstree"]);
  }
  //每个角色有一个code/codepath的集合
  //只要当前code出现在codepath中，就返回
  //针对叶子节点授权，那么父节点出现在codepath中，所以可以实现父节点返回
  async getRsConfig(q, req) {
    var rs2 = [];
    console.log("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
    var cfg = await this.service.getUiConfig(settings.appKey);
    console.log("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy");
    var tmpRoleCodepathStr = [];
    if (req && req.session && req.session.user) {
      //按照用户查询角色
      // try{
      //   var user= await this.userS.getAuths(req.session.user.id);
      //   var roles=await user.getRoles({raw:true});
      //   console.log(roles);
      // }catch(e){
      //   console.log(e);
      // }
      var tmpRoles = [];
      if (req.session.user.Roles) {
        req.session.user.Roles.forEach(r => {
          tmpRoles.push(r.code);
        });
        //按照角色获取权限列表
        var auths = await this.authS.findAuthsByRole(tmpRoles, req.session.user.app_id);
        var codepathattrs = auths.map(r => {
          if (r.authstrs && r.authstrs != "") {
            if (r.codepath) {
              var cparr = r.codepath.split("/");
              for (var c of cparr) {
                tmpRoleCodepathStr.push(c);
              }
            }
            return r.codepath;
          } else {
            return "";
          }
        });

      }

    }
    console.log(".....................获取当前登录人的角色，进而获取权限，进而合并工具栏目.getRsConfig");
    //获取当前登录人的角色，进而获取权限，进而合并工具栏目
    for (var i = 0; i < cfg.config["rstree"].children.length; i++) {
      var r = cfg.config["rstree"].children[i];
      console.log(r.code);
      var funcrange = function (n) {
        if (req && req.session && req.session.user) {
          if (req.session.user.isAdmin || req.session.user.isSuper) {
            if (n.codePath.indexOf("pmg") < 0 && req.session.user.isAdmin) {
              n.hidden = false;
            }
            if (n.codePath.indexOf("pmg") >= 0 && req.session.user.isAdmin) {
              n.hidden = true;
            }
            if (n.codePath.indexOf("pmg") >= 0 && req.session.user.isSuper) {
              console.log("isSuperisSuperisSuperisSuperisSuperisSuperisSuperisSuperisSuperisSuper");
              n.hidden = false;
            }
            if (n.codePath.indexOf("pmg") < 0 && req.session.user.isSuper && !req.session.user.isAdmin) {
              console.log("isSuperisSuperisSuperisSuperisSuperisSuperisSuperisSuperisSuperisSuper");
              n.hidden = true;
            }
          } else {
            if (tmpRoleCodepathStr.indexOf(n.code) < 0) {
              if (n.isctl && n.isctl == "no") {
                n.hidden = false;
                console.log(n.code, "no ctl", "show menu");
              } else {
                n.hidden = true;
                console.log(n.code, "no authed", "hide menu");

              }
            } else {
              n.hidden = false;
              console.log(n.code, "authed......", "show menu");
            }
          }
        }
        if (n.children) {
          n.children.forEach((dd) => {
            return funcrange(dd);
          });
        } else {
          if (n.isctl && n.isctl == "no") {
            n.hidden = false;
          }
          return;
        }
      };
      funcrange(r);
    }
    return system.getResultSuccess(cfg.config["rstree"]);
  }
  async getRouteConfig() {
    var cfg = await this.service.getUiConfig(settings.appKey);
    //获取当前登录人的角色，进而获取权限，进而合并工具栏目
    var tmp = {};
    tmp.bizs = cfg.config["bizs"];
    //  var products=await this.productS.list(settings.wxconfig.appId);
    //  tmp.ps=await this.productC.addVisitCountData(products);
    return system.getResultSuccess(tmp);
  }
  async getRouteConfigWithoutProduct(q, req) {
    console.log("...............req.hostname.................................................................");
    console.log(req.hostname);
    var cfg = await this.service.getUiConfig(settings.wxconfig.appId);
    //获取当前登录人的角色，进而获取权限，进而合并工具栏目
    var tmp = {};
    tmp.bizs = cfg.config["bizs"];
    if (settings.env == "dev") {
      if (req.hostname.indexOf("igsuper") < 0) {
        tmp.isp = 0;
      } else {
        tmp.isp = 1;
      }
    } else {
      if (req.hostname.indexOf("igirl") < 0) {
        tmp.isp = 0;
      } else {
        tmp.isp = 1;
      }
    }
    return system.getResultSuccess(tmp);
  }
  async getRouteConfigWithoutProduct2(q, req) {
    var tmp = {};
    try {
      console.log(req.hostname);
      var cfg = await this.service.getUiConfig(settings.wxconfig.appId);
      //获取当前登录人的角色，进而获取权限，进而合并工具栏目
      tmp.bizs = cfg.config["bizs"];
      if (settings.env == "dev") {
        if (req.hostname.indexOf("igsuper") < 0) {
          tmp.isp = 0;
        } else {
          tmp.isp = 1;
        }
      } else {
        if (req.hostname.indexOf("igirl") < 0) {
          tmp.isp = 0;
        } else {
          tmp.isp = 1;
        }
      }
    } catch (e) {

    }
    return tmp;
  }
}
module.exports = MetaCtl;