axios.get("/vue/comp/base").then(function(res){
  $.base64.utf8encode = true;
  if(res.data){
    res.data.forEach(function(comp){
      var obj=eval("("+comp+")");
      Vue.component(obj.vname,obj);
    });
  }
  console.log("load base component finished...");
  function buildPromise(compath){
     return Promise.resolve(new Promise(function(resolve,reject){
       //异步加载组件
       axios.get(compath).then(function(res){
          console.log(compath);
          var obj=eval("("+res.data+")");
          resolve(obj);
       }).catch(function(reason){
         console.log(reason)
       })
     }));
  }
  function componentFactory(comname){
    var compath="/vue/comp/"+comname;
    var tmpFunc=function(){
      return buildPromise(compath);
    }
    return tmpFunc;
  }
  window.componentFactory=componentFactory;
  Vue.mixin({
    props:["modelName"],
    computed:Vuex.mapState({
      currentUser:state=>{
        return  state.currentUser;
      },
      codePath:state=>{
         return state.currentCodePath;
      },
      ctlName:function(){
         return this.modelName+"Ctl";
      },
      header_height:state=>{
         return state.header_height;
      },
      socketClient:state=>{
         return state.socketClient;
      },
    }),
    methods:{
      getUrl(md){
        return "web/"+this.ctlName+"/"+md;
      },
    }
  });

  var routes=[];
  var codepaths={};
  var mapTile={};
  var mapRouterEntry={};
  console.log("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx=======================");
  axios.get("/web/metaCtl/getRouteConfigWithoutProduct").then(d=>{
    console.log("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx=======================");
    console.log(d.data.data.bizs);
    Object.keys(d.data.data.bizs).map((k)=>{
      //path是路由，静态的路由
      var pathTmp=d.data.data.bizs[k].path;
      var codepath=d.data.data.bizs[k].codepath;
       if(!d.data.data.bizs[k].isDynamicRoute){//如果不忽略静态路由
         var tmp={"path":pathTmp,"components":{ }};
         var vname=d.data.data.bizs[k].comname;
         //设置要显示的rouer-view的名字
         tmp.components[pathTmp]=componentFactory(d.data.data.bizs[k].comname);
         mapTile[pathTmp]=d.data.data.bizs[k].title;
        //  var tmp={"path":pathTmp,"components":{
        //   "default":componentFactory(d.data.data.bizs[k].comname)
        // },};
         routes.push(tmp);
         mapRouterEntry[pathTmp]=tmp;
       }
       codepaths[pathTmp]=codepath;//暂存每个叶子节点对应的codepath
    });
    //元数据分析时会为每个叶子节点动态生成codepath,按照code生成从根开始的路径
    console.log(JSON.stringify(codepaths));
    var router=new VueRouter({
      routes:routes,
    });
    router.mapTile=mapTile;
    router.mapRouterEntry=mapRouterEntry;
    const store = new Vuex.Store({
      state: {
        count: 1,
        products:d.data.data.ps,
        currentCodePath:"",
        currentUser:null,
        curSelRow:{},
        header_height:"200",
        socketClient:null,
        logoUrl:"",
        appimgUrl:"",
        currentChatTo:"",
      },
      mutations: {
        increment (state) {
          state.count++
        },
      }
    });
    router.beforeEach((to, from,next) => {
       console.log("enter before...........................");
       //设置当前访问的叶子节点的codepath
       //对于静态路由按照路由条目，获取codepath
       //对于工具产品，按照去掉最后一个数字后的路径去获取codepath,要求
       //配置工具类产品的path时，路径要按照products/code(组件名字来设置)
       //--可以添加静态路由，再次映射到产品，比如实现平台功能
       var keyCodePath=to.path;
       console.log(keyCodePath);
       if(keyCodePath=="" || keyCodePath=="/"){
           keyCodePath="/"
       }else{
         var indexTmp=keyCodePath.lastIndexOf("/");
         var laststr=keyCodePath.substring(indexTmp+1);
         console.log(laststr);
         if(!isNaN(laststr)){
           keyCodePath=keyCodePath.substring(0,indexTmp);
         }
         console.log("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
         console.log(keyCodePath);
         console.log(to);
       }

       store.state.currentCodePath=codepaths[keyCodePath];

       if(!codepaths[keyCodePath]){
         //解决静态:id路由配置的问题
         keyCodePath=keyCodePath+"/:id";
         store.state.currentCodePath=codepaths[keyCodePath];
       }
       console.log("store.state.currentCodePath");
       console.log(store.state.currentCodePath);
       next();
    });
    var app = new Vue({
      el:"#app",
      router:router,
      store:store,
      data:function(){
        return {
          biz:"bpoadmin",
          systemTitle:"薪必果系统",
          loginUrl:"",
          currentDomain:"",
          catas:[

          ],
          loading:false,
          items:[
          ],
          logins:[
            // {"icon":"fa fa-home","title":"首页","type":"text",key:"login","isOnGrid":true},
            {"icon":"el-icon-arrow-right","title":"专利检索","type":"text",key:"login","isOnGrid":true},
            {"icon":"el-icon-arrow-right","title":"专利分析","type":"text",key:"login","isOnGrid":true},
            {"icon":"el-icon-arrow-right","title":"专利竞争分析","type":"text",key:"login","isOnGrid":true},
          ],
          editableTabs2:[
          ],
          editableTabsValue2:'/',
          isShowMenu:"true",
        };
      },
      computed: Vuex.mapState({
        currentCodePath:state=>{
          return  state.currentCodePath;
        },
        currentUser:state=>{
          return  state.currentUser;
        },
        logoUrl:state=>{
          return  state.logoUrl;
        },
        appimgUrl:state=>{
          return  state.appimgUrl;
        },
      }),
      created(){

      },
      updated(){

      },
      mounted(){
        this.getDomain();
        this.hidetabs();
        var self=this;
        //检查登录状态
        this.checkLogin(()=>{
          self.showtabs();
          setTimeout(()=>{
            console.log("xxxxxxxxxxxxxxxxxxxxxxxxxx");
            if(this.$refs.leftmenu){
              console.log("xxxxxxxxxxxxxxxxxxxxxxxxxx=====");
              this.$refs.leftmenu.fetchMetaData();
            }
            console.log(self.currentUser, "----------------------------");

            if(self.biz == 'bpohhr' || self.biz == 'bpogsb') {
                self.pushx({
                  title:"首页",
                  name:"/hhrhome",
                });
             
            } else if (self.biz == 'bpoent') {
              self.pushx({
                title:"首页",
                name:"/enthome",
              });
            } else {
              console.log(location.href, "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
              self.pushx({
                title:"首页",
                name:"/adminhome",
              });
            }
          },100);
        });

        $("#app").css("visibility","visible");
      },
      methods:{
        getDomain(){
          var harr = window.location.href.split("//");
      
          var host = window.location.host;
          this.currentHost = host;
          console.log(host, "------------host---------------");

          var arr = host.split(".");
          if(arr && arr[0] && arr[0].indexOf("bpo") > -1) {
            this.biz = arr[0];
          }
          console.log(this.biz, "------------this.biz---------------");

          this.loginUrl = harr[0] + "//" + host + "/login" + this.biz;
          if(this.biz == "bpohhr" || this.biz == "bpogsb" ) {
            this.systemTitle = '薪必果合伙人系统';
            this.loginUrl = harr[0] + "//" + host + "/loginbpohhr";
          } else if(this.biz == "bpoent") {
            this.systemTitle = '薪必果企业系统';
          } else {
            this.systemTitle = '薪必果管理系统';
          }
          $(".systitle").text(this.systemTitle);
        },
        showtabs:function(){
          $(".el-tabs__nav-scroll").show();
          $(".el-tabs--border-card > .el-tabs__header").css("border-bottom","solid 1px #eee");
        },
        hidetabs:function(){
          $(".el-tabs__nav-scroll").hide();
          $(".el-tabs--border-card > .el-tabs__header").css("border-bottom","none");
        },
        pushx:function(to){
          var rp = to.replace || false;
          if(!to.notab) {
            let exittabs = this.editableTabs2.filter(tab => tab.name == to.name);
            if(exittabs.length>0){
              this.editableTabsValue2 =  to.name;
              this.$nextTick(()=>{
               // this.$router.push(to.name);
                if(to.params){
                  this.$router.push({path:to.name,query:to.params,replace: rp});
                }else{
                  this.$router.push({path:to.name,replace: rp});
                }
              });
              return;
            }
            this.editableTabs2.push({
              title: to.title,
              name:  to.name,
            })
            this.editableTabsValue2 = to.name;
          }
          this.$nextTick(()=>{
            //this.$router.push(to.name);
            if(to.params){
              this.$router.push({path:to.name,query:to.params,replace: rp});
            }else{
              this.$router.push({path:to.name,replace: rp});
            }
          });
        },
        tabclick:function(tab){
          console.log(tab.name);
          this.editableTabsValue2 =  tab.name;
          if(tab.name=="home"){
            this.$router.push("/");
          }else{
            console.log("================mmmmmmmmmmmmmmmmmmmmmmmmmmmmm===============");
            console.log(JSON.stringify(this.editableTabs2));
            console.log(tab.name);
            this.$router.push(tab.name);
          }
          
        },
        // addTab(to){
        //   this.editableTabs2.push({
        //     title: to.title,
        //     name:  to.name,
        //   });
        //   this.editableTabsValue2 =  to.name;
        // },
        removetab:function(targetName){
          console.log("removeTab");
          if(targetName!="/home" || targetName!="/"){
              let tabs = this.editableTabs2;
              let activeName = this.editableTabsValue2;
              if (activeName === targetName) {
                tabs.forEach((tab, index) => {
                  console.log();
                  if (tab.name === targetName) {
                    let nextTab = tabs[index + 1] || tabs[index - 1];
                    if (nextTab) {
                      activeName = nextTab.name;
                    }
                  }
                });
            }
            this.editableTabsValue2 = activeName;
            this.editableTabs2 = tabs.filter(tab => tab.name !== targetName);
            this.tabclick({name:activeName});
          }else{
            return false;
          }
        
        },
        showMask(){
          var self=this;
          setTimeout((function(){
            self.loading=true;
          }),10);
        },
        hideMask(){
          var self=this;
          setTimeout((function(){
            self.loading=false;
          }),500);
        },
        checkLogin:function(cbk){
          var self=this;
          this.getReq("/web/userCtl/checkLogin",{}).then(function(d){
            if(d && d.status==0){
              self.$store.state.currentUser=d.data;
              console.log(d.data.isAdmin);

              if(cbk){
                self.showtabs();
                cbk();
              }
              //修改样式header
              console.log(this.currentUser, "------------------ this.currentUser")
            } else {
              setTimeout(() => {
                console.log(self.currentUser, "-/---------------------------");
                if(!self.currentUser) {
                  window.location = self.loginUrl;
                }
              },300);
            }

            if(self.$refs.topmenu){
              console.log("xxxxxxxxxxxxxxxxxxxxxxxxxx=====");
              self.$refs.topmenu.fetchMetaData();
            }
          });
        },
        showLogin:function(){

        },
        hideLogin:function(){

        },
        usercenter:function() {
          this.pushx({
            title:"个人中心",
            name:"/usercenter"
          });
        },
        onselect:function(k){
          console.log(k);
          var self=this;
          if(k=="register"){
            this.pushx({
              title:"注册",
              name:"/register"
            });
          }
          if(k=="login"){
            this.pushx({
              title:"登录",
              name:"/login"
            });
          }
          if(k=="exit"){
            this.getReq("/web/userCtl/exit",null).then(function(r){
              self.$store.state.currentUser=null;
              self.$nextTick(()=>{
                window.location.reload();
              });
            
            });
          }
        },
        onMenuSelect:function(index){
           var self=this;
           console.log("main.........."+index);
           if(index=="home"){
            this.editableTabsValue2 = "/";
            this.$router.push("/");
          }else{
            var title=this.$router.mapTile[index];
            // var to=index.substring(1);
             this.pushx({
              title:title,
              name:index
            });
          }
         
        },
        formatItem:function(t,label){
           if(t){
             if(!label && t.src){//表示当前是image元素
               if(this.currentUser){
                 return this.currentUser.imgUrl;
               }
               return t.src;
             }else{
               return label;
             }
           }
        },
        getReq(path,data){
          var self=this;
          return axios.get(path,{params:data,"headers":{"codepath":this.currentCodePath}}).then(function(r){
            if(r && r.data && r.data.status==-99){
              self.$store.state.currentUser=null;
              self.hideMask();
              self.$router.push("/");
              return null;
            }else{
              if(r.data && r.data.bizmsg && r.data.bizmsg!="empty"){
                self.$message({
                  message: r.data.bizmsg,
                  type: 'warning'
                });
              }
              return r.data?r.data:null;;
            }
          });
        },
        postReq(path,data){
          return axios.post(path,data,{"headers":{'codepath': this.currentCodePath}}).then(function(r){
            if(r && r.data && r.data.status==-99){
              self.$store.state.currentUser=null;
              self.hideMask();
              self.$router.push("/");
              self.showLogin();
              return null;
            }else{
              return r.data?r.data:null;
            }
          });
        },
      },
    });
  });
});
