axios.get("/vue/comp/base",{
  headers:{"access_source":"zqq1571212637509"}
}).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,{
        headers:{"access_source":"zqq1571212637509"}
      }).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={};
  axios.get("/web/metaCtl/getRouteConfig",{
    headers:{"access_source":"zqq1571212637509"}
  }).then(d=>{
    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":{
           "default":componentFactory(d.data.data.bizs[k].comname)
         },};
         routes.push(tmp);
       }
       codepaths[pathTmp]=codepath;//暂存每个叶子节点对应的codepath
    });
    //元数据分析时会为每个叶子节点动态生成codepath,按照code生成从根开始的路径
    console.log(JSON.stringify(codepaths));
    console.log(d.data.data.ps);
    d.data.data.ps.forEach(p=>{
      if(p.code){
        var tmpRoute={"path":"/products/"+p.code+"/:id","components":{
          "default":componentFactory(p.code)
        }};
        routes.push(tmpRoute);
      }
    });
    var router=new VueRouter({
      routes:routes,
      //mode:'history'
  //     scrollBehavior (to, from, savedPosition) {
  //  // return desired position
  //       console.log("xxxxxxxxxxxxxxxxxxxxxxssrollxxxxxxxxxxxxxxxxxxxxxx");
  //       console.log(savedPosition);
  //     },
    });
    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);
       }

       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 {
          aside_w: "66px",
          header_h:60,
          hastop:true,
          catas:[
            {"icon":"el-icon-star-off","title":"我的收藏","type":"text",key:"love","isOnGrid":true},
            {"icon":"el-icon-edit","title":"所有","type":"text",key:"all","isOnGrid":true},
            {"icon":"el-icon-share",title:"商标",type:"text",key:"sb","isOnGrid":true},
            {"icon":"el-icon-edit",title:"ICP",type:"text",key:"icp","isOnGrid":true},
            {"icon":"el-icon-share",title:"工商",type:"text",key:"gs","isOnGrid":true},
            {"icon":"el-icon-share",title:"热门",type:"text",key:"common","isOnGrid":true},
          ],
          logins:[
            {"icon":"el-icon-arrow-right","title":"扫码成为合伙人","type":"text",key:"login","isOnGrid":true},
          ],
          hintLogin:null,
          //currentUser:null,
          loading:false,
          menu_h:0,
          collapse:true,
          isToggle:false,
          items:[
  					{code:"zero",left:"/imgs/i22.png",right:"/imgs/rebot.png"},
  					{code:"one",left:"/imgs/i21.png",right:"/imgs/rebot.png"},
  					{code:"two",left:"/imgs/i2.png",right:"/imgs/rebot.png"},
  				],
          currentPos:{},
          onlines:0,
        };
      },
      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(){
        var $workbench=$(this.$refs.workbench.$el);
        console.log("scrollllllllllllllllllllllllllllllllllllllllllllllll");
        if(!this.currentPos[this.currentCodePath]){
          $workbench.scrollTop(0);
        }else{
          this.$nextTick(()=>{
              console.log(this.currentPos[this.currentCodePath]);
              $workbench.scrollTop(this.currentPos[this.currentCodePath]);
          });

        }
      },
      mounted(){
        var self=this;
        var $workbench=$(this.$refs.workbench.$el);
        var winHeight=$(window).height();
        var ch=winHeight-this.header_h;
        this.$store.state.header_height=this.header_h;
        $workbench.height(ch);
        $(window).resize(()=>{
          var ch=$(window).height()-this.header_h;
          $workbench.height(ch);
        });
        setTimeout(function(){
            $("#loading").fadeOut();
            if(localStorage.getItem("logoUrl")){
              self.$store.state.logoUrl=localStorage.getItem("logoUrl");
              self.$store.state.appimgUrl=localStorage.getItem("appimgUrl");
            }
        },1500);
        $workbench.scroll(()=>{
          this.currentPos[this.currentCodePath]=$workbench.scrollTop();
        });
        this.$router.push("/sysmag/allfqtm");
      },
      methods:{
        onlinechange:function(n){
          this.onlines=n;
        },
        showMask(){
          var self=this;
          setTimeout((function(){
            self.loading=true;
          }),10);
        },
        hideMask(){
          var self=this;
          setTimeout((function(){
            self.loading=false;
          }),500);
        },

        onclick:function(){
          if(this.aside_w=="65px"){
            this.aside_w="0px";
          }else{
            this.aside_w="65px";
          }
        },
        
        hideTop:function(){
          this.header_h=0;
          this.hastop=false;
        },
        showTop:function(){
          this.header_h=60;
          this.hastop=true;
        },
        
        onselect:function(k){
          if(k=="login"){
             this.showLogin();
          }
          if(k=="exit"){
             this.hintLogin.close();
          }
        },
        handleClick(tab,e){
          console.log(tab,e);
        },
        formatItem:function(t,label){
           if(t){
             if(!label && t.src){//表示当前是image元素
               if(this.currentUser){
                 return this.currentUser.imgUrl;
               }
               return t.src;
             }else{
               if(t.code=="smallmoney"){
                 return label;
               }
               return label;
             }
           }
        },
        getReq(path,data){
          var self=this;
          return axios.get(path,{params:data,"headers":{"codepath":this.currentCodePath,"access_source":"zqq1571212637509"}}).then(function(r){
            if(r && r.data && r.data.status==-99){
              // self.$store.state.currentUser=null;
              // self.hideMask();
              // self.hideMenu();
              // self.$router.push("/sysmag/allfqtm");
              // self.$message({
              //   message: '扫码成为合伙人',
              //   type: 'warning'
              // });
              // self.showLogin();

              // 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,"access_source":"zqq1571212637509"}}).then(function(r){
            if(r && r.data && r.data.status==-99){
              // self.$store.state.currentUser=null;
              // self.hideMask();
              // self.hideMenu();
              // self.$router.push("/sysmag/allfqtm");
              // self.$message({
              //   message: '扫码成为合伙人',
              //   type: 'warning'
              // });
              // self.showLogin();
              // return null;
            }else{
              return r.data?r.data:null;
            }
          });
        },
      },
    });
  });


});
