
var global_rsconfig=null;
let designSize = 1920;
let html = document.documentElement;
let wW = html.clientWidth;
let rem = wW * 100 / designSize; 
document.documentElement.style.fontSize = rem + 'px';
$(window).resize(function (){
  let designSize = 1920;
  let html = document.documentElement;
  let wW = html.clientWidth;
  let rem = wW * 100 / designSize; 
  document.documentElement.style.fontSize = rem + 'px';
});
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={};
  var mapTile={};
  var mapRouterEntry={};
  console.log("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx=======================");
  axios.get("/web/metaCtl/getRouteConfigWithoutProduct").then(d=>{
    console.log("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx=======================");
    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":{ }};
         var vname=d.data.data.bizs[k].comname;
         //设置要显示的rouer-view的名字
         tmp.components[pathTmp]=componentFactory(d.data.data.bizs[k].comname);
         mapTile[pathTmp]=d.data.data.bizs[k].title;
        //  var tmp={"path":pathTmp,"components":{
        //   "default":componentFactory(d.data.data.bizs[k].comname)
        // },};
         routes.push(tmp);
         mapRouterEntry[pathTmp]=tmp;
       }
       codepaths[pathTmp]=codepath;//暂存每个叶子节点对应的codepath
    });
    //元数据分析时会为每个叶子节点动态生成codepath,按照code生成从根开始的路径
    console.log(JSON.stringify(codepaths));
    var router=new VueRouter({
      routes:routes,
    });
    router.mapTile=mapTile;
    router.mapRouterEntry=mapRouterEntry;
    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...........................");
       //设置当前访问的叶子节点的codepath
       //对于静态路由按照路由条目，获取codepath
       var keyCodePath=to.path;
       console.log(keyCodePath);
       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];
       }
       console.log("store.state.currentCodePath");
       console.log(store.state.currentCodePath);
       next();
    });
    var app = new Vue({
      el:"#app",
      router:router,
      store:store,
      data:function(){
        return {
          typeHome: false,
          loadingHome: false,
          title:"知识产权运营平台",
          catas:[

          ],
          loading:false,
          items:[
          ],
          logins:[
            // {"icon":"fa fa-home","title":"首页","type":"text",key:"login","isOnGrid":true},
            {"icon":"el-icon-arrow-right","title":"专利检索","type":"text",key:"login","isOnGrid":true},
            {"icon":"el-icon-arrow-right","title":"专利分析","type":"text",key:"login","isOnGrid":true},
            {"icon":"el-icon-arrow-right","title":"专利竞争分析","type":"text",key:"login","isOnGrid":true},
          ],
          editableTabs2:[
            {
              title: '首页',
              name: '/',
            }
          ],
          editableTabsValue2:'/',
          isShowMenu:true,
        };
      },
      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(){
        var url = window.location.href;
        var arr1 = url.split("/#");
        var titleValue = "";
        if(url.indexOf("isModifyTitle=1")>=0){
          titleValue = localStorage.getItem("titleValue");
        }else{
          titleValue=this.title;
        }
        if(url.indexOf("isDirectJump=1")>=0 && arr1.length==2){
          this.checkLogin(()=>{
            setTimeout(()=>{
              if(this.$refs.leftmenu){
                this.$refs.leftmenu.fetchMetaData();
              }
              if(this.$refs.topmenu){
                this.$refs.topmenu.fetchMetaData();
              }
            },100);
            $("#app").css("visibility","visible");
            this.isShowMenu=false;
            this.directJump();
            $("#idtitle").text(titleValue);
          });
        }else{
          //检查登录状态
          this.checkLogin(()=>{
            setTimeout(()=>{
              if(this.$refs.leftmenu){
                this.$refs.leftmenu.fetchMetaData();
              }
              if(this.$refs.topmenu){
                this.$refs.topmenu.fetchMetaData();
              }
            },100);
          });
          $("#app").css("visibility","visible");
          this.isShowMenu=false;
          // this.loadingHome = true;
          this.pushx({ name:'/',title:"首页"});
          // setTimeout(()=>{
          //   this.loadingHome = false;
          // },1500);
        }
        this.hidetabs();
      },
      methods:{
        navRoute(v){
          this.typeHome = false;
          if ( v == '区域专利监控') {
            this.loadingHome = true;
            this.pushx({ name:'/regionalpatentmonitoring',title:"hello"});
            setTimeout(()=>{
              this.loadingHome = false;
            },1000);
          }else if ( v == '企业决策') {
            this.pushx({ name:'/businessdecisions'});
          }else if(v== "高级检索"){
            this.pushx({name:"/patentadvancedsearch",title:"高级检索"})
          }else if(v== "智能检索"){
            this.pushx({name:"/patentsimplesearch",title:"智能检索"})
          }else if(v== "专利估价系统"){
            this.loadingHome = true;
            var url = encodeURIComponent("http://gitlab.intelipev.com:9090/");
            this.pushx({name:"/iframehtml",title:"专利估价系统",params:{url:url}});
            setTimeout(()=>{
              this.loadingHome = false;
            },1500);
           
          }else if(v== "智能推送"){
            // window.open("http://58.213.198.76:10012/pmes2/login");
            this.loadingHome = true;
            var url = encodeURIComponent("http://58.213.198.76:10012/pmes2/login");
            this.pushx({name:"/iframehtml",title:"智能推送",params:{url:url}});
            setTimeout(()=>{
              this.loadingHome = false;
            },1500);
          }
        },
        windowOpen(obj){
          // var obj={
          //   url:"http://localhost:3000/#/regionalpatentmonitoring",
          //   title:"windowopen",
          //   params:[]
          // };
          if(!obj){
            this.$message.warning("参数错误");
            return;
          }
          if(!obj.url){
            this.$message.warning("url参数错误");
            return;
          }
          var param="?isDirectJump=1";
          if(obj.title){
            param=param+"&isModifyTitle=1";
            localStorage.setItem("titleValue",obj.title);
          }else{
            localStorage.setItem("titleValue","");
          }
          var params = obj.params;
          for(var i=0;i<params.length;i++){
            if(params[i] && params[i].name && params[i].value){
              param=param+"&"+params[i].name+"="+params[i].value;
            }
          }
          var qurl = obj.url+param;
          window.open(qurl);
        },
        directJump(){
          var url = location.href;
          var params = url.split("/#")[1];
          var arr1 = params.split("?");
          var jumpName = arr1[0];
          var jumpObj = {};
          if(arr1.length==2){
            var arr2 = arr1[1].split("&");
            for(var i=0;i<arr2.length;i++){
              if(arr2[i]){
                var arr3 = arr2[i].split("=");
                var name = arr3[0];
                var value = arr3[1];
                jumpObj[name]=value;
              }
            }
          }
          this.pushx({
            title: "",
            name: jumpName,
            params: jumpObj
          });

        },
        pushx:function(to){
          let exittabs = this.editableTabs2.filter(tab => tab.name == to.name);
          
          if(window.location.href.indexOf("isModifyTitle=1")<0){//若是window.open 打开的页面 则不记录最后一次的点击
           var beforeaccess = this.localdata("lastaccess");
           //缓存记录倒数第二次的点击,目前用于订单修改返回
           this.localdata("beforeaccess",beforeaccess);
           //缓存记录最后一次的点击
           this.localdata("lastaccess",to);
          }
          //记录当前to到内存,key是路由路径
          this.localdata(to.name,to);
          if (exittabs.length > 0) {
            this.editableTabsValue2 = to.name;
            this.$nextTick(() => {
              // this.$router.push(to.name);
              if (to.params) {
                this.$router.push({ path: to.name, query: to.params });
              } else {
                this.$router.push({ path: to.name });
              }

            });
            return;
          }
          this.editableTabs2.push({
            title: to.title,
            name: to.name,
          });
          this.editableTabsValue2 = to.name;
          this.$nextTick(() => {
            //this.$router.push(to.name);
            if (to.params) {
              this.$router.push({ path: to.name, query: to.params });
            } else {
              this.$router.push({ path: to.name });
            }
          });
       
        },
        tabclick:function(tab){
          console.log(tab.name);
          this.editableTabsValue2 =  tab.name;
          if(tab.name=="home"){
            this.$router.push("/");
          }else{
            this.$router.push(tab.name);
          }
          
        },
        removetab:function(targetName){
          console.log("removeTab");
          if(targetName!="/home" || targetName!="/"){
              let tabs = this.editableTabs2;
              let activeName = this.editableTabsValue2;
              if (activeName === targetName) {
                tabs.forEach((tab, index) => {
                  console.log();
                  if (tab.name === targetName) {
                    let nextTab = tabs[index + 1] || tabs[index - 1];
                    if (nextTab) {
                      activeName = nextTab.name;
                    }
                  }
                });
            }
            this.editableTabsValue2 = activeName;
            this.editableTabs2 = tabs.filter(tab => tab.name !== targetName);
            this.tabclick({name:activeName});
          }else{
            return false;
          }
        
        },
        showMask(){
          var self=this;
          setTimeout((function(){
            self.loading=true;
          }),10);
        },
        hideMask(){
          var self=this;
          setTimeout((function(){
            self.loading=false;
          }),500);
        },
        showtabs: function () {
          $(".maintab .el-tabs__nav-scroll").show();
          $(".maintab  .el-tabs--border-card > .el-tabs__header").css("border-bottom", "solid 1px #eee");
        },
        hidetabs: function () {
          $(".el-tabs__nav-scroll").css('display','none');
          $(".el-tabs__nav-scroll").hide();
          $(".el-tabs--border-card > .el-tabs__header").css("border-bottom", "none");
          $('.el-tabs--border-card').css('border','none');
        },
        localdata(key,item){
            if(item){
              localStorage.setItem(key,JSON.stringify(item));
            }else{
              var strobj=localStorage.getItem(key);
              if(strobj){
                return  JSON.parse(strobj);
              }else{
                return null;
              }

            }
        },
        checkLogin:function(cbk){
          var self=this;
          this.getReq("/web/userCtl/checkLogin",{}).then(function(d){
            if(cbk){
              cbk();
            }
            if(d && d.status==0){
              //修改样式header
              self.$store.state.currentUser=d.data;
              console.log(d.data.isAdmin);
            }
          });
        },
        showLogin:function(){

        },
        hideLogin:function(){

        },
        onselect:function(k){
          console.log(k);
          var self=this;
          if(k=="home"){
            this.editableTabsValue2 = "/";
            this.$router.push("/");
          }
          if(k=="register"){
            this.pushx({
              title:"注册",
              name:"/register"
            });
          }
          if(k=="login"){
            this.pushx({
              title:"登录",
              name:"/login"
            });
          }
          if(k=="exit"){
            this.getReq("/web/userCtl/exit",null).then(function(r){
              self.$store.state.currentUser=null;
              self.$nextTick(()=>{
                window.location.reload();
              });
            
            });
          }
        },
        onMenuSelect:function(index){
           var self=this;
           console.log("main.........."+index);
           var title=this.$router.mapTile[index];
          // var to=index.substring(1);
           this.pushx({
            title:title,
            name:index
          });
        },
        formatItem:function(t,label){
           if(t){
             if(!label && t.src){//表示当前是image元素
               if(this.currentUser){
                 return this.currentUser.imgUrl;
               }
               return t.src;
             }else{
               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.$router.push("/");
              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.$router.push("/");
              self.showLogin();
              return null;
            }else{
              return r.data?r.data:null;
            }
          });
        },
      },
    });
  });
});
