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")
           },};
          //  tmp={"path":pathTmp,"components":{
          //    "default":componentFactory(d.data.data.bizs[k].comname)
          //  },};
         }else{
           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: "66px",
          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,
          params:[]
        };
      },
      computed: Vuex.mapState({
        currentCodePath:state=>{
          return  state.currentCodePath;
        },
        currentUser:state=>{
          return  state.currentUser;
        },
        logoUrl:state=>{
          return  state.logoUrl;
        },
        appimgUrl:state=>{
          return  state.appimgUrl;
        },
      }),
      created(){
        // console.log("window.location.search");
        // console.log(window.location);
      },
      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(){
        console.log("window.location.search----------------------------------------------");
        console.log(window.location.search);
        var search = window.location.search;
        if(search && search.indexOf("?params=")>=0){
          var strList = search.split("?params=");
          if(strList.length>1){
            var str = strList[1];
            var paramList = str.split("&");
            if(paramList.length==3){
              this.params=paramList
            }
          }else{
            console.log("参数有误。")
          }
          
        }else{
          console.log("参数有误")
        }
        console.log(this.params);
        var self=this;
        // //检查登录状态
        // this.checkLogin(()=>{
        //   this.$refs.sidemenu.fetchMetaData();
        //   this.$refs.socketclient.initSocketClient();

        // });

        //检查用户信息
        if(this.params.length==3 && this.params[2]){
          this.$store.state.channelCode=this.params[0];
          this.$store.state.itemCode=this.params[1];
          this.checkUserInfo();
        }
        
        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();
            }
            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:{
        aboutus:function(){
          this.$router.push("/sysmag/articledetail/1");
        },
        onlinechange:function(n){
          this.onlines=n;
        },
        checkPayState(){
          var self=this;
          if(localStorage["tradekey"]!=null){
            var ts=localStorage["tradekey"].split("_");
            var tradeKey=ts[0];
            var startTime=Number(ts[1]);
            setTimeout(function(){
              var inth= setInterval(function () {
                //按照tradekey去服务端检查是否存在trade，如果没有就检查订单是否已经付款，如果没有付款
                //返回下单到现在已经过去的时间，如果过去了1个小时
                if(!localStorage["tradekey"])
                {
                  window.clearInterval(inth);
                  return;
                }
                self.postReq("/web/tradeCtl/checkPayState",{idkey:tradeKey}).then(d=>{
                   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);
                     });
                     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);
        },
        checkLogin:function(cbk){
          var self=this;
          this.getReq("/web/userCtl/checkUserInfo",{openid:this.params[2]}).then(function(d){
            console.log("checkUserInfo");
            console.log(d);
            // debugger
            if(d && d.status=="0"){
              //修改样式header
              self.$store.state.currentUser=d.data;
              if(cbk){
                cbk();
              }
              // self.$router.push("/automaticsubmit")
            }else{
              self.$store.state.currentUser={};
              if(d){
                self.$message({
                  message: d.msg,
                  type: 'warning'
                });
              }else{
                self.$message({
                  message: "用户为空",
                  type: 'warning'
                });
              }
            }
          });
          // this.getReq("/web/userCtl/checkLogin",{}).then(function(d){
          //   if(d && d.status==0){
          //     if(cbk){
          //       cbk();
          //     }
          //     //修改样式header
          //     self.$store.state.currentUser=d.data;
          //     self.showMenu();
          //     if(d.data.originTarget && d.data.originTarget!=""){
          //       //如果扫码登录时函有来源动作，那么先调转到来源动作
          //       self.$router.push("/uc/msgs");
          //     }else{
          //         if((self.codePath && self.codePath=="/") || (self.codePath=="toolroot/platformop/papp/homepage")){
          //           self.$router.push("/workbench");
          //         }
          //     }
          //   }
          // });
        },
        checkUserInfo:function(){ 
          var self=this;
          this.postReq("/web/userCtl/checkUserInfo",{openid:this.params[2],channelCode:this.params[0],itemCode:this.params[1]}).then(function(d){
            console.log("checkUserInfo");
            console.log(d);
            // debugger
            if(d && d.status>=0){
              self.$store.state.currentUser=d.data;
            }else{
              self.$store.state.currentUser={};
              if(d){
                self.$message({
                  message: d.msg,
                  type: 'warning'
                });
              }else{
                self.$message({
                  message: "用户为空",
                  type: 'warning'
                });
              }
            }
          });
        },
        showLogin:function(){
          const h = this.$createElement;
          var $wxsaoma=$(this.$refs.wxsaoma.$el);
          $wxsaoma.hide(100);
          var self=this;
          if(!this.hintLogin){
            this.hintLogin=this.$notify({
               title: '扫码作为合伙人登录',
               message: h('div',{attrs:{id:"login_container"}}),
               duration:1800000,
               showClose: false,
               onClose:function(){
                 self.hintLogin=null;
                 $wxsaoma.show(100);
               },
            });
          }
          var obj = new WxLogin({
              self_rect: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";
        },
        hideTop:function(){
          this.header_h=0;
          this.hastop=false;
        },
        showTop:function(){
          this.header_h=40;
          this.hastop=true;
        },
        showMenu:function(){
          this.aside_w="65px";
        },
        onselect:function(k){
          if(k=="login"){
            console.log(391);
             this.showLogin();
          }
          if(k=="exit"){
             this.hintLogin.close();
          }
        },
        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);
              // 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){
          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);
              self.showLogin();
              return null;
            }else{
              return r.data?r.data:null;
            }
          });
        },
      },
    });
  });


});
