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){
          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 self = this;
  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=null;
        //  if(pathTmp=="/"){
        //    tmp={"path":pathTmp,"components":{
        //      "default":componentFactory("autosubmitorder")
        //    },};
        //  }else{
        //    tmp={"path":pathTmp,"components":{
        //      "default":componentFactory(d.data.data.bizs[k].comname)
        //    },};
        //  }
        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:"",
        currentChatTo:"",
        channelCode:"",
        itemCode:"",
      },
      mutations: {
        increment (state) {
          state.count++
        },
      }
    });
    router.beforeEach((to, from,next) => {
       console.log("enter before...........................");
       //设置当前访问的叶子节点的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: "0px",
          showType:0,
          header_h:40,
          hastop:true,
          catas:[
          ],
          logins:[
          ],
          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,
          openid:"",
          channelCode:"",
          itemCode:"",
        };
      },
      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);
        if(!this.currentPos[this.currentCodePath]){
          $workbench.scrollTop(0);
        }else{
          this.$nextTick(()=>{
              $workbench.scrollTop(this.currentPos[this.currentCodePath]);
          });

        }
      },
      mounted(){   
        var showtype=window.location.search.substr(1).match(new RegExp("(^|&)" + "showtype" + "=([^&]*)(&|$)", "i"));
        if(showtype!= null){
          this.showType=unescape(showtype[2]);
        }
        var itemcode=window.location.search.substr(1).match(new RegExp("(^|&)" + "itemcode" + "=([^&]*)(&|$)", "i"));
        if(itemcode!= null){
          this.$store.state.itemCode=unescape(itemcode[2]);
          this.itemCode = unescape(itemcode[2]);
        }
        var channelcode=window.location.search.substr(1).match(new RegExp("(^|&)" + "channelcode" + "=([^&]*)(&|$)", "i"));
        if(channelcode!= null){
          this.$store.state.channelCode=unescape(channelcode[2]);
          this.channelCode = unescape(channelcode[2]);
        }else{
          this.header_h=0;
          $("#loading").fadeOut();
          this.$message.warning("传递参数channelcode错误");
          this.$router.push("/");
          return false;
        }
        var openid=window.location.search.substr(1).match(new RegExp("(^|&)" + "openid" + "=([^&]*)(&|$)", "i"));
        if(openid!= null){
          this.openid=unescape(openid[2]);
        }else{
          this.header_h=0;
          $("#loading").fadeOut();
          this.$message.warning("传递参数openid错误");
          this.$router.push("/");
          return false;
        }
        this.checkUserInfo();
        if(this.showType==0){
          this.header_h=0;
        }
        var $workbench=$(this.$refs.workbench.$el);
        var winHeight=$(window).height();
        var ch=winHeight-this.header_h;
        this.$store.state.header_height=this.header_h;
        //this.header_h=winHeight;
        $workbench.height(ch);
        $(window).resize(()=>{
          var ch=$(window).height()-this.header_h;
          $workbench.height(ch);
        });
        var $header=$(this.$refs.inmain.$el);
        setTimeout(function(){
            $("#loading").fadeOut();
            if(self.currentUser){
              self.minHeader();
            }
            $header.removeClass("inheader");
            // if(self.currentUser){
            //   $header.removeClass("inheader");
            // }else{
            //   $header.addClass("inheader");
            // }
            //self.minHeader();
            if(localStorage.getItem("logoUrl")){
              self.$store.state.logoUrl=localStorage.getItem("logoUrl");
              self.$store.state.appimgUrl=localStorage.getItem("appimgUrl");
            }
        },1500);
        //this.checkPayState();
        $workbench.scroll(()=>{
          this.currentPos[this.currentCodePath]=$workbench.scrollTop();
          if(this.currentPos[this.currentCodePath]>564){
            $header.hide(100);
          }else{
            $header.show(100);
          }
        });
      },
      methods:{
        toMain:function(){
          if(this.openid && this.channelCode){
            window.location.href="https://boss.gongsibao.com/autosubmithtml5?params="+this.channelCode+'&'+this.openid;
    
          }
        },
        myTm:function(){
          if(this.openid && this.channelCode){
            this.$router.push("/autosubmittrademark");
          }
        },
        swSubmit:function(){
          if(this.openid && this.channelCode){
            this.$router.push("/softwarecrsubmitsw");
          }
        },
        myOrder:function(){
          if(this.openid && this.channelCode){
            this.$router.push("/autosubmitorder");
          }
        },
        aboutus:function(){
          this.$router.push("/sysmag/articledetail/1");
        },
        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);
        },
        checkUserInfo:function(){ 
          var self=this;
          var obj={openid:this.openid,channelCode:this.channelCode};
          if(this.itemCode){
            obj["itemCode"]=this.itemCode;
          }
          this.postReq("/web/userCtl/checkUserInfo",obj).then(function(d){
            console.log("checkUserInfo");
            console.log(d);
            // debugger
            if(d && d.status>=0){
              self.$store.state.currentUser=d.data;
            }else{
              self.header_h=0;
              $("#loading").fadeOut();
              self.$store.state.currentUser={};
              if(d){
                self.$message({
                  message: d.msg,
                  type: 'warning'
                });
              }else{
                self.$message({
                  message: "用户为空",
                  type: 'warning'
                });
              }
              self.$router.push("/");
            }
          });
        },
        onclick:function(){
          if(this.aside_w=="65px"){
            this.aside_w="0px";
          }else{
            this.aside_w="65px";
          }
        },
        hideMenu:function(){
          this.aside_w="0px";
        },
        hideTop:function(){
          this.header_h=0;
          this.hastop=false;
        },
        showTop:function(){
          this.header_h=40;
          this.hastop=true;
        },
        showMenu:function(){
          this.aside_w="65px";
        },
        onMenuSelect:function(index){
          var self=this;
          if(index=="exit"){
            this.onlines=0;
            this.minHeader();
            this.getReq("/web/userCtl/exit",null).then(function(r){
              self.$store.state.currentUser=null;
              //清空session
              //self.showLogin();
              //self.$router.push("/");
              window.location.reload();
            });

          }
          if(index=="home"){
            this.$router.push("/");
            return;
          }
          if(index=="fillmoney"){
            //console.log("xxxxxxxxxxxxxxxxxxxx");
            this.$refs.payselect.show();
          }
          if(index=="fillpersoninfo"){
            self.$router.push("/products/finishpersoninfo/");
            return;
          }

          if(index=="toggleHeader"){
            this.minHeader();
          }else{
            this.$router.push(index);
          }

        },
        minHeader:function(){
          if(!this.isToggle){
            this.header_h=40;
            this.$store.state.header_height=this.header_h;
            //$("#imgapp").attr("style","position:absolute;top:8px;margin-left:-45px;height:35px");
            $(window).trigger("resize");
            this.isToggle=true;
          }else{
            this.header_h=40;
            this.$store.state.header_height=this.header_h;
            //$("#imgapp").attr("style","position:absolute;top:8px;margin-left:-170px;");
            $(window).trigger("resize");
            this.isToggle=false;
          }
        },
        hideHeader:function(){
          if(!this.isToggle){
            this.minHeader();
          }
        },
        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;
          console.log(path);
          console.log(this.currentCodePath);
          return axios.get(path,{params:data,"headers":{"codepath":this.currentCodePath}}).then(function(r){
            console.log(r);
            if(r && r.data && r.data.status==-99){
              self.$store.state.currentUser=null;
              self.hideMask();
              self.hideMenu();
              self.$router.push("/");
              self.$message({
                message: '超时，请重新登录',
                type: 'warning'
              });
              console.log(482);

              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.hideMenu();
              self.$router.push("/");
              self.$message({
                message: '超时，请重新登录',
                type: 'warning'
              });
              console.log(509);
              return null;
            }else{
              return r.data?r.data:null;
            }
          });
        },
      },
    });
  });


});
