
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 {
          navarr:[
              { 
                  name:'首页'
              },{
                  name:'智能检索',
                  obj:['专利检索','高级检索']
              },{
                  name:'智能分析'
              },{
                  name:'IP智慧城市',
                  obj:['产业创新监测','创新人才发现','IP创新管理']
              },{
                  name:'智能估价'
              },{
                  name:'创新资源共享'
              },{
                name:'智能分类'
              },{
                name:'智能采集'
              }
          ],
          // {
          //   name:'企业级服务',
          //   obj:['IP智慧管理','智能估价']
          // } 
          // {
          //   name:'政府级服务',
          //   obj:['IP智慧城市','产业创新监测系统']
          // }{ name:'专利分析',
          //   obj:['申请人分析','发明人分析','区域分析','技术结构分布分析','趋势分析','法律状态分析','代理人/机构分析','专利竞争分析','相似专利分析','专利引文组合分析','专利同族组合分析','专利质押分析','专利诉讼分析']
          //   },
          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(){
        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);
            // $("#app").css("visibility","visible");
            // this.isShowMenu=false;
            // // this.$router.push("/");
            // var lastaccess = this.localdata("lastaccess");
            // if(lastaccess){
            //   this.loadingHome = true;
            //   this.pushx(lastaccess);
            //   setTimeout(()=>{
            //     this.loadingHome = false;
            //   },1000);
            // }else{
            //   this.$router.push("/");
            // }
          });
        }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.$router.push("/");
            // var lastaccess = this.localdata("lastaccess");
            // if(lastaccess){
            //   this.loadingHome = true;
            //   this.pushx(lastaccess);
            //   setTimeout(()=>{
            //     this.loadingHome = false;
            //   },1000);
            // }else{
            //   this.$router.push("/");
            // }
          });
          $("#app").css("visibility","visible");
          this.isShowMenu=false;

          this.$router.push("/");
        }
      },
      updated(){

      },
      mounted(){
        this.hidetabs();
      },
      methods:{
        NavIndexRoute(v){
          console.log(v);
          if (v == '首页') {
            this.pushx({ name:'/',title:"首页"});
            this.loadingHome = false;
          }else if ( v == 'IP智慧城市') {
            this.typeHome = false;
            this.loadingHome = true;
            this.pushx({ name:'/regionalpatentmonitoring',title:"IP智慧城市"});
            setTimeout(()=>{
              this.loadingHome = false;
            },1000);
          }else if ( v == 'IP创新管理') {
            this.typeHome = false;
            this.pushx({ name:'/businessdecisions'});
          }else if(v== "高级检索"){
            this.typeHome = false;
            this.pushx({name:"/patentadvancedsearch",title:"高级检索"})
          }else if(v== "专利检索"){
            this.typeHome = false;
            this.pushx({name:"/patentsimplesearch",title:"专利检索"})
          }else if(v== "智能检索"){
            this.typeHome = false;
            this.pushx({name:"/patentsimplesearch",title:"智能检索"})
          }else if(v== "智能分析"){
            this.typeHome = false;
            this.pushx({name:"/patentanalysis",title:"智能分析"})
          }else if(v== "智能估价"){
            this.typeHome = false;
            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== "创新人才发现"){
            this.typeHome = false;
            // window.open("https://gct.aminer.cn/");
            this.loadingHome = true;
            var url = encodeURIComponent("https://gct.aminer.cn/");
            this.pushx({name:"/iframehtml",title:"智能推送",params:{url:url}});
            setTimeout(()=>{
              this.loadingHome = false;
            },1500);
          }else if(v== "知识产权运营"){
            // window.open("https://www.cnuip.com/");
            this.typeHome = false;
            this.loadingHome = true;
            var url = encodeURIComponent("https://www.cnuip.com/");
            this.pushx({name:"/iframehtml",title:"智能推送",params:{url:url}});
            setTimeout(()=>{
              this.loadingHome = false;
            },1500);
          }else if(v== "智能采集"){
            // window.open("http://47.104.94.221:8001/wiki");
            this.typeHome = false;
            this.loadingHome = true;
            var url = encodeURIComponent("http://47.104.94.221:8001/wiki");
            this.pushx({name:"/iframehtml",title:"智能推送",params:{url:url}});
            setTimeout(()=>{
              this.loadingHome = false;
            },1500);
          }else if(v== "创新资源共享"){
            this.typeHome = false;
            this.loadingHome = true;
            var url = encodeURIComponent("http://47.104.94.221:8080/swagger-ui.html");
            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;
              self.navarr.push({
                name:'API查询'
              });
              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;
            }
          });
        },
      },
    });
  });
});
