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);
    });
  }

  function buildPromise(compath){
     return Promise.resolve(new Promise(function(resolve,reject){
       //异步加载组件
       axios.get(compath).then(function(res){
          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").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生成从根开始的路径
    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,
    });
    const store = new Vuex.Store({
      state: {
        count: 1,
        products:d.data.data.ps,
        currentCodePath:"",
        currentUser:null,
        curSelRow:{},
        header_height:"200",
        socketClient:null,
        logoUrl:"",
        appimgUrl:"",
      },
      mutations: {
        increment (state) {
          state.count++
        },
      }
    });
    router.beforeEach((to, from,next) => {

       //设置当前访问的叶子节点的codepath
       //对于静态路由按照路由条目，获取codepath
       //对于工具产品，按照去掉最后一个数字后的路径去获取codepath,要求
       //配置工具类产品的path时，路径要按照products/code(组件名字来设置)
       //--可以添加静态路由，再次映射到产品，比如实现平台功能
       var keyCodePath=to.path;
       if(keyCodePath=="" || keyCodePath=="/"){
           keyCodePath="/"
       } else {
         var indexTmp=keyCodePath.lastIndexOf("/");
         var laststr=keyCodePath.substring(indexTmp+1);
         if(!isNaN(laststr)){
           keyCodePath=keyCodePath.substring(0,indexTmp);
         }
       }

       store.state.currentCodePath=codepaths[keyCodePath];
       if(!codepaths[keyCodePath]){
         //解决静态:id路由配置的问题
         keyCodePath=keyCodePath+"/:id";
         store.state.currentCodePath=codepaths[keyCodePath];
       }
       next();
    });
    var app = new Vue({
      el:"#app",
      router:router,
      store:store,
      data:function(){
        return {
          aside_w: "66px",
          header_h:60,
          //currentUser:null,
          loading:false,
          apk:"wxf616c0a459d66081",
          loginForm:{},
        };
      },
      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(){
        if (window.history && window.history.pushState) {
          window.addEventListener('popstate', function() {
            wx.miniProgram.navigateBack({delta: 1});
            wx.miniProgram.postMessage({ data: '我要后退' });
          }, false);
        }
    
        var self=this;
        console.log(self.currentUser, "-----------currentUser-----");
        this.checkLogin((isLogin)=>{
          $("#loading").fadeOut();
          console.log(isLogin, self.currentUser, "------------cb----self.currentUser------------");
          if(isLogin) {
            self.$router.push({
              path: "/bpostat/bpostatindex",
              replace: true
            });
          }
        });
      },
      methods:{
        checkLogin(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);
              //修改样式header
              console.log(self.currentUser, "------------------ this.currentUser")
              if(cbk){
                cbk(true);
              }
            } else {
              if(cbk){
                cbk(false);
              }
            }

          });
        },
        statlogin() {
          var self = this;
          var loginForm = this.loginForm || {};
          if(!loginForm.userName || !loginForm.userName.trim()) {
            self.$message.warning("请输入账户");
            return;
          }

          if(!loginForm.password || !loginForm.password.trim()) {
            self.$message.warning("请输入密码");
            return;
          }

          self.$root.postReq("/web/userCtl/loginstat", loginForm).then(function(d){
            if(d.status==0) {
              // self.$root.pushx({nane:"/home", notab:true});
              self.$store.state.currentUser=d.data;
              self.$router.push({
                path: "/bpostat/bpostatindex",
                replace: true
              });
            }  else {
                self.$message.warning(d.msg || "登录失败, 请稍候重试");
            }
          });
        },
        menuclick(code){
          // if(code=="waitsign"){
          //     this.$router.push({path:"/ecompany/waitsign",query:{from:"mobile"}});
          //     return;
          // }
        },
        showMask(){
          var self=this;
          setTimeout((function(){
            self.loading=true;
          }),10);
        },
        hideMask(){
          var self=this;
          setTimeout((function(){
            self.loading=false;
          }),500);
        },
        showmenu(){
       },
       hidemenu(){
       },
        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}}).then(function(r){
              return r.data?r.data:null;;

          });
        },
        postReq(path,data){
          return axios.post(path,data,{"headers":{'codepath': this.currentCodePath}}).then(function(r){
              return r.data?r.data:null;

          });
        },
        getHashParameter(key) {
           var hrefurl=location.href;
           if(window.location.href.indexOf("from=singlemessage#")!=-1){
             hrefurl=hrefurl.replace("from=singlemessage#","").replace("mobile?","mobile#");
           }
           if(window.location.href.indexOf("from=singlemessage&isappinstalled=0#")!=-1){
             hrefurl=hrefurl.replace("from=singlemessage&isappinstalled=0#","").replace("mobile?","mobile#");
           }
           var reg = new RegExp("(^|&)" + key + "=([^&]*)(&|$)", "i");
           var index=hrefurl.indexOf("?");
           if(index!=-1){
              var searchStr=hrefurl.substr(index);
              var r = searchStr.substr(1).match(reg);
              if (r != null) {
                var x = unescape(r[2]);
                return decodeURI(x);
              } else {
                return null;
              }
            }
        }
      },
    });
  });


});
