axios.get("/vue/comp/base").then(function(res){
  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={};
  axios.get("/web/metaCtl/getRouteConfig").then(d=>{
    Object.keys(d.data.data.bizs).map((k)=>{
      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;//暂存每个叶子节点对应的访问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'
    });
    const store = new Vuex.Store({
      state: {
        count: 1,
        products:d.data.data.ps,
        currentCodePath:"",
        currentUser:null,
        curSelRow:{},
        header_height:"200",
        socketClient:null,
      },
      mutations: {
        increment (state) {
          state.count++
        },
      }
    });
    router.beforeEach((to, from,next) => {
       console.log("enter before...........................");
       var keyCodePath=to.path;
       if(keyCodePath==""){
           keyCodePath="/"
       }
       console.log(keyCodePath);
       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:600,
          header_footer_top:260,
          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,
        };
      },
      computed: Vuex.mapState({
        currentCodePath:state=>{
          return  state.currentCodePath;
        },
        currentUser:state=>{
          return  state.currentUser;
        },
      }),
      created(){

      },
      mounted(){
        var self=this;
        //检查登录状态
        this.checkLogin();
        setTimeout(function(){
            $("#loading").fadeOut();
            if(self.currentUser){
              self.minHeader();
            }
            //self.minHeader();
        },500);
        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);
        });
        //this.checkPayState();
      },
      methods:{
        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("超时........已经关闭订单")
                       });
                     }
                   }
                });
              },10000);
            },5000)
          }
        },
        showMask(){
          var self=this;
          setTimeout((function(){
            self.loading=true;
          }),10);
        },
        hideMask(){
          var self=this;
          setTimeout((function(){
            self.loading=false;
          }),500);
        },
        checkLogin:function(){
          var self=this;
          this.getReq("/web/userCtl/checkLogin",{}).then(function(d){
            if(d && d.status==0){
              self.$store.state.currentUser=d.data;
              self.showMenu();
              //关闭
              if(self.hintLogin){
                self.hintLogin.close();
              }
            }
          });
        },
        showLogin:function(){
          const h = this.$createElement;
          var self=this;
          if(!this.hintLogin){
            this.hintLogin=this.$notify({
               title: '扫码登陆',
               message: h('div',{attrs:{id:"login_container"}}),
               duration:0,
               onClose:function(){
                 self.hintLogin=null;
               },
            });
          }
          var obj = new WxLogin({
              self_redirect:false,
              id:"login_container",
              appid:"wx76a324c5d201d1a4",
              scope:"snsapi_login",
              redirect_uri:"http://boss.gongsibao.com/",
              state: "wx76a324c5d201d1a4",
              href: "https://boss.gongsibao.com/css/qr.css"
          });
          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.minHeader();
            this.getReq("/web/userCtl/exit",null).then(function(r){
              self.currentUser=null;
              //清空session
              self.showLogin();
            });
          }
          if(index=="home"){
            this.$router.push("/");
            return;
          }
          if(index=="fillmoney"){
            console.log("xxxxxxxxxxxxxxxxxxxx");
            this.$refs.payselect.show();
          }
          if(index=="toggleHeader"){
            this.minHeader();
          }else{
            this.$router.push(index);
          }

        },
        minHeader:function(){
          if(!this.isToggle){
            this.header_h=45;
            this.$store.state.header_height=this.header_h;
            this.header_footer_top=5;
            $("#imgapp").attr("style","position:absolute;top:8px;margin-left:-45px;height:35px");
            $(window).trigger("resize");
            this.isToggle=true;
          }else{
            this.header_h=600;
            this.$store.state.header_height=this.header_h;
            this.header_footer_top=260;
            $("#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;
          return axios.get(path,{params:data,"headers":{"codepath":this.currentCodePath}}).then(function(r){
            if(r && r.data && r.data.status==-99){
              self.$router.push("/");
              self.$message({
                message: '扫码登录,开启智能助手',
                type: 'warning'
              });
              self.showLogin();
              self.hideMask();
              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.$router.push("/");
              self.$message({
                message: '扫码登录,开启智能助手',
                type: 'warning'
              });
              self.showLogin();
              return null;
            }else{
              return r.data?r.data:null;
            }
          });
        },

      },
    });
  });


});
