
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 {
            h5UserId:"jjjjjfffff",
            isYD: "",
            aside_w: "66px",
            header_h:60,
            //currentUser:null,
            loading:false,
            menu_h:0,
            collapse:true,
            isToggle:false,
            items:[
                    ],
            currentPos:{},
            onlines:0,
            mitems:[
              {"code":"waitsignyd","text":"待签","icon":"fa fa-clock-o"},
              {"code":"signedyd","text":"已签","icon":"fa fa-check-circle-o"},
              // {"code":"emy","text":"我的","icon":"fa fa-user-circle"},
            ],
            apk:"wxf616c0a459d66081",
          };
        },
        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;
         
          this.$refs.bottommenu.hidemenu();

          var cb = self.getHashParameter("cb");
  
          var uid = self.getHashParameter("uid") || "";
          var ecid = self.getHashParameter("ecid");
          var ecidcache = localStorage.getItem("ecid");

		      localStorage.setItem('uid', uid);
          
          if(ecid && ecid != 'null' && ecid != "undefined") {
            var idx = ecid.indexOf("#/");
            if(idx > 0) {
              ecid = Number(ecid.substr(0, idx));
            }
          } else if(ecidcache && ecidcache != 'null' && ecidcache != "undefined") {
            ecid = ecidcache;
          } else {
            ecid = ""
          }
          console.log(ecid, "------------------------------------------- ecid 2121321321231");
          localStorage.setItem('ecid', ecid);
          console.log(self.currentUser, "-----------currentUser-----");
          setTimeout(function(){
              $("#loading").fadeOut();
              /*处理小程序链接*/
              if(self.currentUser){
                if(cb) {
                  self.$router.push({
                    path: "/ecompany/signedyd",
                    replace: true
                  });
                } else {
                   self.$router.push({
                     path: "/ecompany/signinfoyd",
                     replace: true
                   });
                }
              }
          },3000);
        },
        methods:{
          menuclick(code){
            if(code=="waitsign"){
                this.$router.push({path:"/ecompany/waitsignyd",query:{from:"mobile"}});
                return;
            }
            if(code=="signed"){
              this.$router.push({path:"/ecompany/signedyd",query:{from:"mobile"}});
              return;
            }
          },
          showmenu(){
             this.$refs.bottommenu.showmenu();
          },
          hidemenu() {
             this.$refs.bottommenu.hidemenu();
          },
          loginSuccess(obj) {
            var self = this;
            self.$router.push({
                path: "/ecompany/signinfoyd",
                replace: true
            });
            $("#idtitle").text("薪必果电子签约平台");
          },
          showMask(){
            var self=this;
            setTimeout((function(){
              self.loading=true;
            }),10);
          },
          hideMask(){
            var self=this;
            setTimeout((function(){
              self.loading=false;
            }),500);
          },
          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){
                // 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){
                return r.data?r.data:null;
  
            });
          },
          checkPayState(){
  
          },
          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;
                }
              }
          }
        },
      });
    });
  
  
  });
  