var system=require("../../system")
var settings=require("../../../config/settings");
const CtlBase = require("../ctl.base");
class MetaCtl extends CtlBase{
   constructor(){
     super(CtlBase.getServiceName(MetaCtl));
     this.userS=system.getObject("service.userSve");
     this.authS=system.getObject("service.authSve");
   }
   //权限 角色+资源节点code+权限字符串,codepath--
   async getUiConfig(queryObj,req){
     var bizCode=queryObj.biz;
     var cfg=await this.service.getUiConfig(settings.wxconfig.appId);
     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.companyid);
          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.getResult2(bizConfigData.config,null);
   }
  
   async getDicConfig(queryObj,req){
     var dicKey=queryObj["dicKey"];
     var cfg=await this.service.getUiConfig(settings.wxconfig.appId);
     //获取当前登录人的角色，进而获取权限，进而合并工具栏目
     if(dicKey=="data_priv"){
      if(req.session && req.session.user && !req.session.user.isSuper){
       delete cfg.config["pdict"][dicKey]["company"];
      }
     }
    
     return system.getResult2(cfg.config["pdict"][dicKey],null);
   }
   async findSubSystems(q,req){
     var rtnSubs=[];
    var cfg=await this.service.getUiConfig(settings.wxconfig.appId);
    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.companyid);
         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});
                  }
                  
                }
              }
          }
         }
       }
      
    }
    return system.getResult2(rtnSubs,null);

   }
   async getRsConfig2(q,req){
    var rs2=[];
     console.log("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
    var cfg=await this.service.getUiConfig(settings.wxconfig.appId);
    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.company_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.wxconfig.appId);
     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.company_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.getResult2(cfg.config["rstree"],null);
   }
   async getRouteConfig(){
     var cfg=await this.service.getUiConfig(settings.wxconfig.appId);
     //获取当前登录人的角色，进而获取权限，进而合并工具栏目
     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.getResult2(tmp,null);
   }
   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.getResult2(tmp,null);
   }
   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;
