

axios.get("/vue/comp/base").then(function (res) {
  $.base64.utf8encode = true;

  if (res.data) {
    res.data.forEach(function (comp) {
      try {
        console.log("...................................comp....................");
        console.log(comp);
        var objfun = eval("(" + comp + ")");
        var obj = objfun();
        Vue.component(obj.vname, obj);
      } catch (e) {
        console.log(e);
      }
    });
  }

  console.log("load base component finished...");

  function buildPromise(compath) {
    return Promise.resolve(new Promise(function (resolve, reject) {
      //异步加载组件
      axios.get(compath).then(function (res) {
        var objfunc = eval("(" + res.data + ")");
        var obj = objfunc();
        resolve(obj);
      })["catch"](function (reason) {
        console.log(reason);
      });
    }));
  }

  function componentFactory(comname) {
    var compath = "/vue/comp/" + comname;

    var tmpFunc = function tmpFunc() {
      return buildPromise(compath);
    };

    return tmpFunc;
  }

  window.componentFactory = componentFactory;
  Vue.mixin({
    props: ["modelName"],
    computed: Vuex.mapState({
      currentUser: function currentUser(state) {
        return state.currentUser;
      },
      currentCompany: function currentCompany(state) {
        return state.currentCompany;
      },
      pfooterinfo: function pfooterinfo(state) {
        return state.pfooterinfo;
      },
      codePath: function codePath(state) {
        return state.currentCodePath;
      },
      ctlName: function ctlName() {
        return this.modelName + "Ctl";
      },
      header_height: function header_height(state) {
        return state.header_height;
      },
      socketClient: function socketClient(state) {
        return state.socketClient;
      },
      istabclick: function istabclick(state) {
        return state.istabclick;
      }
    }),
    methods: {
      getUrl: function getUrl(md) {
        return "web/" + this.ctlName + "/" + md;
      }
    }
  });
  var routes = [];
  var codepaths = {};
  var mapTile = {};
  var mapRouterEntry = {};
  console.log("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx=======================");
  axios.get("/web/metaCtl/getRouteConfigWithoutProduct").then(function (d) {
    console.log("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx=======================");
    console.log(d.data.data.bizs);
    Object.keys(d.data.data.bizs).map(function (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;
    var store = new Vuex.Store({
      state: {
        count: 1,
        products: d.data.data.ps,
        currentCodePath: "",
        istabclick: false,
        currentUser: null,
        currentCompany: null,
        curSelRow: {},
        header_height: "200",
        socketClient: null,
        logoUrl: "",
        appimgUrl: "",
        currentChatTo: "",
        pfooterinfo: null
      },
      mutations: {
        increment: function increment(state) {
          state.count++;
        }
      }
    });

    function headtransparent() {
      $("#header").addClass("headtransparent"); // $("#leftmenudiv").addClass("menutransparent");

      $(".spechorizotal .nav_color").css("color", "white");
      $("#header").css("background-color", "transparent");
      $("#welcome").css("color", "white");
      $("#exitbtn").css("color", "white");
      $("#adminbtn").css("color", "white");
      $("#adminbtn").css("display", "display");
      $("#loginbtn").css("color", "white");
      $("#appname").css("color", "white");
    }

    function headnotransparent() {
      setTimeout(function () {
        $(".spechorizotal .nav_color").css("color", "black");
        $(".spechorizotal .nav_color:hover").css("color", "#2692FF");
        $("#header").removeClass("headtransparent");
        $("#header").css("background-color", "white");
        $("#welcome").css("color", "#fff");
        $("#exitbtn").css("color", "#fff");
        $("#adminbtn").css("color", "#fff"); // $("#adminbtn").css("display", "none");

        $("#loginbtn").css("color", "#2692FF");
        $("#appname").css("color", "#2692FF");
      }, 1500);
    }

    router.beforeEach(function (to, from, next) {
      console.log("enter before...........................");
      console.log(to); //设置当前访问的叶子节点的codepath
      //对于静态路由按照路由条目，获取codepath
      //对于工具产品，按照去掉最后一个数字后的路径去获取codepath,要求
      //配置工具类产品的path时，路径要按照products/code(组件名字来设置)
      //--可以添加静态路由，再次映射到产品，比如实现平台功能

      var keyCodePath = to.path;
      console.log(keyCodePath);

      if (keyCodePath == "/" || keyCodePath.indexOf("login") > 0 || keyCodePath.indexOf("more") > 0 || keyCodePath.indexOf("about") > 0) {
        headtransparent();
      } else {
        headnotransparent();
      }

      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();
    });
    Vue.use(window['vue-cropper']);
    var app = new Vue({
      el: "#app",
      router: router,
      store: store,
      data: function data() {
        return {
          switchcompany: null,
          companys: [],
          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",
          currentCompany: null,
          bankAccount: null,
          footerInfo: null,
          pfooterinfo: null,
          serviceqq: null,
          servicetel: null,
          homeobj: null,
          isfront: true
        };
      },
      created: function created() {
        var _this = this;

        this.refreshLoginState(function () {
          _this.initIndexPage();
        });
      },
      updated: function updated() {},
      mounted: function mounted() {
        var sself = this; //获取被授权的公司列表

        this.postReq("/web/companyCtl/refQuery", {
          fields: ["id", "name"],
          datapriv: true
        }).then(function (d) {
          if (d && d.data) {
            d.data.forEach(function (r) {
              sself.companys.push({
                label: r.name,
                value: r.id
              });
            });
          }
        });

        if (this.$refs.topmenu) {
          console.log("xxxxxxxxxxxxxxxxxxxxxxxxxx=====");
          this.$refs.topmenu.fetchMetaData();
        }

        function initMainHeight() {
          var appheight = $("#app").height();
          var headheight = 60;
          var footerheight = 140;
          var minMainHeight = appheight - headheight - footerheight;
          console.log("minMainHeightxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
          console.log(minMainHeight);
          $("#stage").css("min-height", minMainHeight + "px");
        }

        ;
        $(window).resize(function () {
          initMainHeight();
        });
        initMainHeight();
        this.hidetabs();
        localStorage.removeItem("afterLogin");

        if (window.history && window.history.pushState) {
          window.addEventListener('popstate', this.goBack, false);
        }

        this.isShowMenu = false;
        setTimeout(function () {
          $("#app").css("visibility", "visible");
          $("#footer").css("visibility", "visible");
        }, 1000);
      },
      methods: {
        initIndexPage: function initIndexPage() {
          var url = location.href;
          console.log("00000000000000000000000000000000");
          console.log(url);

          if (url.indexOf("bycdetailtm?sbzch") > 0) {
            var obj1 = url.split("bycdetailtm?sbzch=")[1];
            var obj2 = obj1.split("&gjfl=");
            this.pushx({
              title: "",
              name: "/bycdetailtm",
              params: {
                sbzch: obj2[0],
                gjfl: obj2[1]
              }
            });
            headnotransparent();
          } else if (url.indexOf("bycquerytm?tmmonitzcr") > 0) {
            var obj1 = url.split("bycquerytm?tmmonitzcr=")[1];
            var obj1 = decodeURI(obj1);
            this.pushx({
              title: "",
              name: "/bycquerytm",
              params: {
                tmmonitzcr: obj1
              }
            });
            headnotransparent();
          } else if (url.indexOf("bycquerytm") > 0) {
            this.pushx({
              title: "",
              name: "/bycquerytm"
            });
            headnotransparent();
          } else if (url.indexOf("bycnoticedetailtm?name") > 0) {
            var obj1 = url.split("bycnoticedetailtm?name=")[1];
            var obj2 = obj1.split("&imgurl=");
            var na = decodeURI(obj2[0]);
            var url = decodeURI(obj2[1]);
            console.log(url);
            this.pushx({
              title: "",
              name: "/bycnoticedetailtm",
              params: {
                name: na,
                imgurl: url
              }
            });
            headnotransparent();
          } else if (url.indexOf("bytmmonitlistdetails?code=") > 0) {
            var obj1 = url.split("bytmmonitlistdetails?code=")[1];
            this.pushx({
              title: "",
              name: "/bytmmonitlistdetails",
              params: {
                code: obj1
              }
            });
            headnotransparent();
          } else if (url.indexOf("bytmmonitagency?agency_name=") > 0) {
            var obj1 = url.split("bytmmonitagency?agency_name=")[1];
            var obj1 = decodeURI(obj1);
            this.pushx({
              title: "",
              name: "/bytmmonitagency",
              params: {
                agency_name: obj1
              }
            });
          } else if (url.indexOf("bycncldetail") > 0) {
            this.pushx({
              title: "商标尼斯查询",
              name: "/bycncldetail"
            });
          } else if (url.indexOf("bycnoticetm") > 0) {
            this.pushx({
              title: "商标公告查询",
              name: "/bycnoticetm"
            });
          } else if (url.indexOf("bycnoticeindex") > 0) {
            var obj1 = url.split("bycnoticeindex?noticetype=")[1];
            var obj2 = obj1.split("&noticenumber=");
            var noticetype = decodeURI(obj2[0]);
            var noticenumber = decodeURI(obj2[1]);
            this.pushx({
              title: "商标公告查询",
              name: "/bycnoticeindex",
              params: {
                noticetype: noticetype,
                noticenumber: noticenumber
              }
            });
          } else if (url.indexOf("selftmreg") > 0) {
            this.$root.pushx({
              title: "自主商标注册",
              name: "/selftmreg",
              params: {
                itemCode: "zzsbzc"
              }
            });
          } else if (url.indexOf("bytmmonitlist") > 0) {
            this.pushx({
              title: "监控列表",
              name: "/bytmmonitlist"
            });
            headnotransparent();
          } else if (url.indexOf("bytmmonitdynamics") > 0) {
            this.pushx({
              title: "",
              name: "/bytmmonitdynamics"
            });
            headnotransparent();
          } else if (url.indexOf("bytmmonit") > 0) {
            this.pushx({
              title: "商标监控",
              name: "/bytmmonit"
            });
            headnotransparent();
          } else {
            //检查lastaccess
            var to = this.localdata("lastaccess");

            if (to && to.name.indexOf("roleview") >= 0) {
              this.isfront = false;
            }

            if (to && to.name.indexOf("login") < 0 && this.currentUser) {
              this.pushx(to);
            } else {
              if (this.currentUser) {
                this.$root.pushx({
                  "title": "每日概览",
                  "name": "/roleview"
                });
              } else {
                this.$router.push("/");
              }
            }
          }
        },
        contextCompany: function contextCompany() {
          if (this.switchcompany) {
            return this.switchcompany;
          } else {
            return this.currentCompany;
          }
        },
        channelchange: function channelchange(v) {
          var _this2 = this;

          /*获取当前公司信息，更新当前公司和当前银行*/
          if (v) {
            this.postReq("/web/companyCtl/getInitCompanyInfo", {
              id: v
            }).then(function (d) {
              if (d && d.status == 0) {
                // this.currentCompany = d.data.company;
                // this.$store.state.currentCompany = d.data.company;
                _this2.switchcompany = d.data.company;
                _this2.footerInfo = d.data.footerinfo;

                _this2.homeobj.initMounted();

                _this2.homeobj.initCreated();
              }
            });
          } else {
            this.switchcompany = null;
            this.footerInfo = this.pfooterinfo;
            this.homeobj.initMounted();
            this.homeobj.initCreated();
          }

          if (this.$refs.topmenu) {
            console.log("xxxxxxxxxxxxxxxxxxxxxxxxxx=====");
            this.$refs.topmenu.fetchMetaData();
          }
        },
        mnufunc: function mnufunc(item) {
          if (this.contextCompany() && this.contextCompany().id != 1) {
            if (item.code == "siteapply") {
              return false;
            } else {
              return true;
            }
          }

          return true;
        },
        goBack: function goBack() {
          this.pushx({
            title: "首页",
            name: "/"
          });
        },
        backhome: function backhome() {
          this.pushx({
            title: "首页",
            name: "/"
          });
          this.showtopmenu();
        },
        goadmin: function goadmin() {
          this.isfront = false;
          this.pushx({
            title: "每日概览",
            name: "/roleview"
          });
        },
        aboutus: function aboutus() {
          console.log("---------------------------------------");
          this.pushx({
            title: "关于我们",
            name: "/aboutus"
          });
        },
        showtabs: function showtabs() {
          $(".maintab .el-tabs__nav-scroll").show();
          $(".maintab  .el-tabs--border-card > .el-tabs__header").css("border-bottom", "solid 1px #eee");
        },
        hidetabs: function hidetabs() {
          $(".el-tabs__nav-scroll").hide();
          $(".el-tabs--border-card > .el-tabs__header").css("border-bottom", "none");
        },
        localdata: function 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;
            }
          }
        },
        pushx: function pushx(to) {
          var _this3 = this;

          var exittabs = this.editableTabs2.filter(function (tab) {
            return tab.name == to.name;
          }); //缓存记录最后一次的点击

          this.localdata("lastaccess", to); //记录当前to到内存,key是路由路径

          this.localdata(to.name, to);

          if (exittabs.length > 0) {
            this.editableTabsValue2 = to.name;
            this.$nextTick(function () {
              // this.$router.push(to.name);
              if (to.params) {
                _this3.$router.push({
                  path: to.name,
                  query: to.params
                });
              } else {
                _this3.$router.push({
                  path: to.name
                });
              }
            });
            return;
          }

          this.editableTabs2.push({
            title: to.title,
            name: to.name
          });
          this.editableTabsValue2 = to.name;
          this.$nextTick(function () {
            //this.$router.push(to.name);
            if (to.params) {
              _this3.$router.push({
                path: to.name,
                query: to.params
              });
            } else {
              _this3.$router.push({
                path: to.name
              });
            }
          });
        },
        showtopmenu: function showtopmenu() {
          var _this4 = this;

          this.isfront = true;
          setTimeout(function () {
            _this4.$refs.topmenu.fetchMetaData();
          }, 100);
        },
        tabclick: function tabclick(tab) {
          console.log(tab.name);
          console.log("..................................................");
          console.log(this.currentCodePath);
          this.editableTabsValue2 = tab.name; //点击页签时，先获取以前的缓存to

          var tovalue = this.localdata(tab.name); //点击页签时，设置一个全局的环境变量宣称当前的操作为点击页签

          this.$store.state.istabclick = true;

          if (tab.name == "/") {
            this.showtopmenu();
          }

          if (tab.name == "home") {
            this.$router.push("/");
          } else {
            console.log("================mmmmmmmmmmmmmmmmmmmmmmmmmmmmm===============");
            console.log(JSON.stringify(this.editableTabs2));
            console.log(tab.name);

            if (tovalue) {
              if (tovalue.params) {
                this.$router.push({
                  path: tovalue.name,
                  query: tovalue.params
                });
              } else {
                this.$router.push({
                  path: tovalue.name
                });
              }
            } else {
              this.$router.push(tab.name);
            }
          }
        },
        // addTab(to){
        //   this.editableTabs2.push({
        //     title: to.title,
        //     name:  to.name,
        //   });
        //   this.editableTabsValue2 =  to.name;
        // },
        removetab: function removetab(targetName) {
          console.log("removeTab");

          if (targetName != "/home" || targetName != "/") {
            var tabs = this.editableTabs2;
            var activeName = this.editableTabsValue2;

            if (activeName === targetName) {
              tabs.forEach(function (tab, index) {
                console.log();

                if (tab.name === targetName) {
                  var nextTab = tabs[index + 1] || tabs[index - 1];

                  if (nextTab) {
                    activeName = nextTab.name;
                  }
                }
              });
            }

            this.editableTabsValue2 = activeName;
            this.editableTabs2 = tabs.filter(function (tab) {
              return tab.name !== targetName;
            });
            this.tabclick({
              name: activeName
            });
          } else {
            return false;
          }
        },
        showMask: function showMask() {
          var self = this;
          setTimeout(function () {
            self.loading = true;
          }, 10);
        },
        hideMask: function hideMask() {
          var self = this;
          setTimeout(function () {
            self.loading = false;
          }, 10);
        },
        refreshLoginState: function refreshLoginState(cbk) {
          var self = this; //检查登录状态

          self.checkLogin(function () {
            if (cbk) {
              cbk();
            }

            $("#leftmenudiv").addClass("menutransparent"); //setTimeout(() => {
            //$("#leftmenudiv").addClass("menutransparent");
            // if (self.$refs.leftmenu) {
            //   self.$refs.leftmenu.fetchMetaData();
            // }
            // if (self.$refs.topmenu) {
            //   self.$refs.topmenu.fetchMetaData();
            // }
            // }, 100);
          });
        },
        checkLogin: function checkLogin(cbk) {
          var self = this;
          self.postReq("/web/userCtl/checkLogin", {}).then(function (d) {
            console.log("------checkLogin------");
            console.log(d.data);

            if (d && d.status == 0 && d.data.status != -99) {
              //修改样式header
              self.$store.state.currentUser = d.data;
              self.currentUser = d.data;

              if (d.data.company) {
                self.currentCompany = d.data.company;
                self.$store.state.currentCompany = d.data.company;
                self.bankAccount = d.data.bankAccount;
                self.footerInfo = d.data.footerinfo;
                self.pfooterinfo = d.data.footerinfo;
                ;
                self.$store.state.pfooterinfo = self.footerInfo;
                self.serviceqq = "http://wpa.qq.com/msgrd?v=3&uin=" + self.currentCompany.serviceqq + "&site=qq&menu=yes";

                if (self.footerInfo) {
                  self.servicetel = self.footerInfo.serviceTel;
                } else {
                  self.servicetel = "请完善客服电话";
                }

                $("#idtitle").text(self.currentCompany.sitename);
              }

              if (cbk) {
                cbk(d.data);
              }
            } else {
              if (d && d.data && d.data.company) {
                self.$store.state.currentUser = null;
                self.currentUser = null;
                self.currentCompany = d.data.company;
                self.footerInfo = d.data.footerinfo;
                self.pfooterinfo = d.data.footerinfo;
                self.$store.state.pfooterinfo = d.data.footerinfo;
                self.serviceqq = "http://wpa.qq.com/msgrd?v=3&uin=" + self.currentCompany.serviceqq + "&site=qq&menu=yes";

                if (self.footerInfo) {
                  self.servicetel = self.footerInfo.serviceTel;
                } else {
                  self.servicetel = "请完善客服电话";
                }

                $("#idtitle").text(self.currentCompany.sitename);
              }

              if (d.data.isJump == 1) {
                self.$message({
                  type: 'error',
                  message: '您访问的地址未申请站点或还在审核中，请申请站点或耐心等待.',
                  delay: 5000
                });
              }

              if (cbk) {
                cbk(null);
              }
            }
          });
        },
        showLogin: function showLogin() {},
        hideLogin: function hideLogin() {},
        onselect: function onselect(k) {
          console.log(k);
          var self = this;

          if (k == "register") {
            this.pushx({
              title: "注册",
              name: "/register"
            });
          }

          if (k == "login") {
            this.pushx({
              title: "登录",
              name: "/login"
            });
          }

          if (k == "roleview") {
            this.pushx({
              title: "概况",
              name: "/roleview"
            });
          }

          if (k == "exit") {
            this.getReq("/web/userCtl/exit", null).then(function (r) {
              self.$store.state.currentUser = null;
              self.$nextTick(function () {
                window.location.reload();
              });
            });
          }
        },
        onMenuSelect: function onMenuSelect(index) {
          var self = this;
          console.log("main.........." + index);
          console.log("dddddddddddddddddddxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");

          if (index == "/") {
            if (this.homeobj && this.currentCompany.id == 1) {
              this.homeobj.a = false;
            }

            if (this.homeobj && this.currentCompany.id != 1) {
              this.homeobj.moreservice("ip");
            }
          }

          if (index == "home") {
            this.editableTabsValue2 = "/";
            this.$router.push("/"); //this.$router.push({path:"/",query:{"from":"1"}});
          } else {
            var title = this.$router.mapTile[index]; // var to=index.substring(1);

            this.pushx({
              title: title,
              name: index
            });
          }
        },
        formatItem: function formatItem(t, label) {
          if (t) {
            if (!label && t.src) {
              //表示当前是image元素
              if (this.currentUser) {
                return this.currentUser.imgUrl;
              }

              return t.src;
            } else {
              return label;
            }
          }
        },
        getReq: function getReq(path, data) {
          var self = this;
          return new Promise(function (resv, reject) {
            axios.get(path, {
              params: data,
              "headers": {
                "codepath": self.codePath,
                "companyid": self.contextCompany() ? self.contextCompany().id : ""
              }
            }).then(function (r) {
              if (r && r.data && r.data.status == -99) {
                self.$store.state.currentUser = null;
                self.hideMask(); // self.$message({
                //   type: 'error',
                //   message: '请检查权限.'
                // });

                resv(null);
              } else {
                if (r.data && r.data.bizmsg && r.data.bizmsg != "empty") {
                  self.$message({
                    message: r.data.bizmsg,
                    type: 'warning'
                  });
                }

                if (r.data.status < 0) {
                  self.$message({
                    type: 'error',
                    message: r.data.msg
                  });
                }

                resv(r.data ? r.data : null);
              }
            })["catch"](function (e) {
              reject(e);
            });
          });
        },
        postReq: function postReq(path, data) {
          var self = this;
          return axios.post(path, data, {
            "headers": {
              'codepath': self.codePath,
              "companyid": self.contextCompany() ? self.contextCompany().id : ""
            }
          }).then(function (r) {
            if (r && r.data && r.data.status == -99) {
              self.$store.state.currentUser = null;
              self.hideMask(); // self.$message({
              //   type: 'error',
              //   message: '请检查权限.'
              // });

              return null;
            } else {
              if (r.data.status < 0) {
                self.$message({
                  type: 'error',
                  message: r.data.msg
                });
              }

              return r.data ? r.data : null;
            }
          });
        }
      }
    });
  });
});