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");
    this.authS = system.getObject("service.auth.authSve");
 

  }
  async getApiDoc(pobj, queryObj, req) {
    var appid = pobj.appid;
    var docUrl = pobj.doc;
    if (appid == settings.platformid) {
      var result = await this.service.getApiDoc(appid);
      return system.getResult(result);
    } else {
      var result = await this.service.getApiDocRemote(appid, docUrl);
      return system.getResult(result);
    }
    return system.getResultFail();
  }
  //根据查询参数来确定当前会话对应的应用
  async getAppInfo(req) {
    var appkey = req.query.appKey;
    var companyKey=req.query.companyKey;
    if (!appkey) {
      appkey = settings.appKey;
       //为了查询权限
       req.tocompanyid=settings.platformcompanyid;
    }
    var app = await this.appS.getApp(appkey);
    var rs = await this.getRsConfig2(null, req);
    var company= req.session.company? req.session.company:null;
    var tocompany=req.session.tocompany? req.session.tocompany:null;
    
    if(!tocompany && companyKey){//说明自主登录或注册
      tocompany=await this.comS.findOne({companykey:companyKey});
      req.session.tocompany=tocompany;
    }
   
    var companystr=company?escape(JSON.stringify(company)):escape(JSON.stringify({status:-1}));
    var tocompanystr=tocompany?escape(JSON.stringify(tocompany)):escape(JSON.stringify({status:-1}));
    var rtn = { "appinfo": escape(JSON.stringify(app)), "rsconfig": escape(JSON.stringify(rs)), "basecom": this.getBaseComp(), "app": app,"company":companystr,"tocompany":tocompanystr};
    req.session.app = app;
    return rtn;
  }

  getBaseComp() {
    // if (cacheBaseComp) {
    //   return cacheBaseComp;
    // }
    var glob = require("glob");
    var vuePath = settings.basepath + "/app/front/vues/base";
    var baseComps = [];
    var rs = glob.sync(vuePath + "/**/*.vue");
    if (rs) {
      rs.forEach(function (r) {
        var comp = "";
        if (settings.env == "dev") {
          delete require.cache[r];
          comp = require(r).replace(/\n/g, "");
        } else {
          comp = require(r).replace(/\n/g, "");
        }
        baseComps.push(comp);
      });
    }
    cacheBaseComp = escape(JSON.stringify(baseComps));
    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.authS.findAuthsByRole(tmpRoles, req.session.user.app_id,req.tocompanyid);
        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.getResult(bizConfigData.config);
  }

  async getDicConfig(pobj, queryObj, req) {
    var dicKey = queryObj["dicKey"];
    if (req.appid == settings.platformid || (dicKey != "configType" && dicKey != "data_priv")) {
      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.getResult(cfg.config["pdict"][dicKey]);
    } else {
      if (dicKey == "configType" || dicKey == "data_priv") {
        //跨应用调用，先获取访问token,然后访问远程应用,去获取远程应用的配置项
        var app = req.session.app;
        var uiconfigUrl = app.uiconfigUrl;
        var cfg = await this.service.getRemoteUiConfig(req.appkey, uiconfigUrl);
        return system.getResult(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.authS.findAuthsByRole(tmpRoles, req.session.user.app_id,req.tocompanyid);
        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 && r.code.indexOf("tanent") < 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.getResult(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.authS.findAuthsByRole(tmpRoles, req.session.user.app_id,req.tocompanyid);
        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"]);
  }
  async getAppRsConfig(p, q, req) {
    var rs2 = [];
    var cfg = null;
    if (req.appid == settings.platformid) {
      var cfg = await this.service.getUiConfig(settings.appKey);
    } else {
      var app = req.session.app;
      var uiconfigUrl = app.uiconfigUrl;
      var cfg = await this.service.getRemoteUiConfig(req.appkey, uiconfigUrl);
    }
    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.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 (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,req.tocompanyid);
        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.getResult(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.getResult(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.getResult(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;
