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={};
  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":"/","components":{
             "default":componentFactory("patentychomepage")
           },};
         }else{
           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,
    });
    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...........................");
       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);
         }
       }
       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,
          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,
          sbzch:"",
          activeIndex: '1',
        };
      },
      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;
        console.log(self.currentUser, "=========self.currentUser======");
        //检查登录状态 TODO WANGKUN
        this.checkLogin(this.checkcallback);
        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();
            $("#app").css("visibility","visible");
            if(self.currentUser){
              self.minHeader();
            }
            if(self.currentUser){
              $header.removeClass("inheader");
            }else{
              $header.addClass("inheader");
            }
            //self.hide();
            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:{
        handleSelect(key, keyPath) {
          if(key=="1"){
            this.$router.push("/patentsimplesearch");
          }
          if(key=="2"){
            this.$router.push("/patentadvancedsearch");
          }
        },
        checkcallback:function(currentUser){
          var self=this;
          if(currentUser) {
            var url = location.href;
            console.log(url);
            var arrUrl = url.split("?");
            var params = arrUrl[1];
            if(params){
              console.log(params);
              this.sbzch=params;
              var notice=params;
              var pm = params.split("=");
              var pa = pm[0];
              if(pa=="applynum"){
                this.activeIndex="";
                self.$router.push("/patentdetail?"+params);
              }else{
                self.$router.push("/patentsimplesearch");
              }
            }else{
              setTimeout(()=>{
                self.$router.push("/patentsimplesearch");
              },500);
            }
          }
          this.hideMenu();
        },
        aboutus:function(){
          this.$router.push("/sysmag/articledetail/1");
        },
        onlinechange:function(n){
          this.onlines=n;
        },
        checkPayState(){
          var self=this;
          console.log("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
          console.log(localStorage["tradekey"]);
          if(localStorage["tradekey"]!=null){
            var ts=localStorage["tradekey"].split("_");
            var tradeKey=ts[0];
            var startTime=Number(ts[1]);
            console.log(localStorage["tradekey"]);
            setTimeout(function(){
              var inth= setInterval(function () {
                //按照tradekey去服务端检查是否存在trade，如果没有就检查订单是否已经付款，如果没有付款
                //返回下单到现在已经过去的时间，如果过去了1个小时
                console.log("start check.......");
                if(!localStorage["tradekey"])
                {
                  window.clearInterval(inth);
                  return;
                }
                self.postReq("/web/tradeCtl/checkPayState",{idkey:tradeKey}).then(d=>{
                   console.log("xxxxxxxxxxxxxxxxxxxxxx");
                   console.log(d.data);
                   if(d.data){
                     //更新页面余额
                     self.$store.state.currentUser["accountBalance"]=d.data.accountBalance;
                     localStorage.removeItem("tradekey");
                     clearInterval(inth);
                     //提示宝币余额已经更新
                     self.$refs.payselect.close();
                     self.$message({
                       message: '兑换成功，宝币余额已经更新',
                       type: 'success',
                     });
                   }else{
                     var passTime=(new Date().getTime()-startTime)/1000;
                     var p=Math.round((passTime/300)*100);
                     self.$nextTick(()=>{
                       self.$refs.payselect.updateProgress(p);
                     });
                     console.log("passed seconds "+passTime);
                     if(passTime>300){//超过5分钟未支付，重新回到选择支付页面
                       self.$refs.payselect.updateProgress(100);
                       localStorage.removeItem("tradekey");
                       clearInterval(inth);
                       //关闭订单，重新下单
                       self.postReq("/web/tradeCtl/closeOrder",{idkey:tradeKey}).then(d=>{
                        console.log("超时........已经关闭订单")
                       });
                     }
                   }
                });
              },3000);
            },5000)
          }
        },
        showMask(){
          var self=this;
          setTimeout((function(){
            self.loading=true;
          }),10);
        },
        hideMask(){
          var self=this;
          setTimeout((function(){
            self.loading=false;
          }),500);
        },
        exitLogin:function(){
          var self=this;
          this.getReq("/web/userCtl/exit",null).then(function(r){
            self.$store.state.currentUser=null;
            //清空session
            //self.showLogin();
            //self.$router.push("/");
            window.location.reload();
          });
        },
        checkLogin:function(cbk){
          var self=this;
          this.getReq("/web/userCtl/checkLogin",{}).then(function(d){
            console.log("page===========================checkLogin===================d=>");
            console.log(d);
            if(d && d.status==0) {
              var currentUser = d.data;
              //修改样式header
              self.$store.state.currentUser=d.data;
              if(cbk){
                console.log("page===========================callback===================d=>");
                return cbk(currentUser);
              }
              /* TODO WANGKUN*/
              //关闭
              if(self.hintLogin){
                self.hintLogin.close();
              }
            }else{
               self.$router.push("/");
            }
          });
        },
        showLogin:function(){
          const h = this.$createElement;
          var $wxsaoma=$(this.$refs.wxsaoma.$el);
          $wxsaoma.hide(100);
          var self=this;
          this.hideMenu();
        },
        onclick:function(){
          if(this.aside_w=="65px"){
            this.aside_w="0px";
          }else{
            this.aside_w="65px";
          }
        },
        hideMenu:function(){
          this.aside_w="0px";
        },
        showMenu:function(){
          this.aside_w="65px";
        },
        onselect:function(k){
          if(k=="login"){
             this.showLogin();
          }
          if(k=="exit"){
             this.hintLogin.close();
          }
        },
        onMenuSelect:function(index){
          var self=this;
          console.log("main.........."+index);
          if(index=="exit"){
            this.onlines=0;
            this.minHeader();
            this.getReq("/web/userCtl/exit",null).then(function(r){
              self.$store.state.currentUser=null;
              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=60;
            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=60;
            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();
          }
        },
        hideHeader2:function(){
          var $header=$(this.$refs.inmain.$el);
          $header.hide();

        },
        showHeader2:function(){
          var $header=$(this.$refs.inmain.$el);
          $header.show();
        },
        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}}).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'
              // });
              // 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){
          var self=this;
          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'
              // });
              // self.showLogin();
              return null;
            }else{
              return r.data?r.data:null;
            }
          });
        },
      },
    });
  });


});
