//axios.get("/vue/comp/base").then(function(res){

basecomp.forEach(function (comp) {
  try {
    var obj = eval("(" + comp + ")");
    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) {
      console.log(compath);
      // var obj=eval("("+res.data+")");
      var obj = eval("(" + unescape(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;
const store = new Vuex.Store({
  state: {
    currentCodePath: "",
    currentUser: null,
    curSelRow: {},
  },
});
Vue.mixin({
  props: ["modelName"],
  computed: Vuex.mapState({
    currentUser: state => {
      return state.currentUser;
    },
    codePath: state => {
      return state.currentCodePath;
    },
    ctlName: function () {
      return this.modelName + "Ctl";
    },
  }),

});
var routes = [];
var codepaths = {};
axios.get("/web/common/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;
    var tmp = {
      "path": pathTmp, "components": {
        "default": componentFactory(d.data.data.bizs[k].comname)
      },
    };
    routes.push(tmp);
    codepaths[pathTmp] = codepath;//暂存每个叶子节点对应的codepath
  });
  console.log(routes);
  var router = new VueRouter({
    routes: routes,
  });

  router.beforeEach((to, from, next) => {
    next();
  });
  Vue.use(window['vue-cropper']);
  var app = new Vue({
    el: "#app",
    router: router,
    store: store,
    data: function () {
      return {
        // 请求地址
        host: ``,
        // 请求头携带参数
        globelHeader: {},
        // 通用接口参数
        commonParams: {
          "actionProcess": "",
          "sign": "2FviZ9PGws8Pt1fBhq0t90mjUvI",
          "actionBody": {},
          "actionType": "",
          "requrl": '',
        },
        loading: true,
        logins: [],
        editableTabs2: [
          {
            title: '首页',
            name: '/',
          }
        ],
        editableTabsValue2: '/',
        loadingHome: false,
        headerRowType: false,
        popupsHeight: null,
        popupslineHeight: null,
        popupsType: false,
        popupsDataList: [],
        pDataKey: 0,
        pTowDataKey: null,
        popupsData: [],
        // 
        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,
        qrcodeurl: "",
        pfooterinfo: null,
        serviceqq: null,
        servicetel: null,
        wxJpg: '/imgs/wxJpg.jpg',
        homeobj: null,
        isfront: true,
        stageType: true,
        isleyu: true,
        isphone: false,
        istop: false,
        iswx: false,
        themename: "",
        showWxrm: false,
        showPhoneNum: false,
        rsData: [],
        channelPath: "",
        channelUserId:"",
      };
    },
    created() {
      $(window).resize(() => {
        $("#app").css("min-height", $(window).height());
      });
      $("#app").css("visibility", 'visible');
      this.loading = false;
    },
    updated() {

    },
    mounted() {
      var self = this;
      if (!this.currentUser) {
        this.logins.push({ "icon": "el-icon-location-outline", "title": "登录", "type": "text", key: "login", "isOnGrid": true });
        this.logins.push({ "icon": "el-icon-edit-outline", "title": "注册", "type": "text", key: "register", "isOnGrid": true });
      } else {
        this.logins.push({ "icon": "el-icon-arrow-right", "title": "退出", "type": "text", key: "exit", "isOnGrid": true });
      }
      this.checkLogin();
    },
    methods: {
      // 返回当前接入渠道标识
      getChannelPath() {
        var from = this.$route.path;
        var path = from.match(/\/(\S*)\//)[1];
        this.$root.channelPath = path;
        return path;
      },

      // 处理参数方法
      copyParams(actionBody, actionType, url, isUser = "no",isDecryptUser = "no") {
        var data = this.commonParams;
        data.actionProcess = this.$root.getChannelPath();
        data.actionType = actionType;
        data.actionBody = actionBody || {};
        data.requrl = this.host + url;
        data.isUser = isUser;
        data.isDecryptUser = isDecryptUser;
        let currentDate = Math.floor(new Date().getTime() / 1000);
        data.actionBody.timeStamp = currentDate;
        data.actionBody.channelUserId = this.$root.channelUserId;
        var newObj = JSON.parse(JSON.stringify(data));
        return newObj;
      },

      handleOpen(key, keyPath) {
        console.log(key, keyPath);
      },
      handleClose(key, keyPath) {
        console.log(key, keyPath);
      },
      hidetabs: function () {
        $(".el-tabs__nav-scroll").hide();
        $(".el-tabs--border-card > .el-tabs__header").css("border-bottom", "none");
      },
      showtopmenu() {
        console.log('检索');
        this.isfront = true;
        var test = window.location.hash;
        console.log("nnnnnnnnnnnnnnnnnnnnnnnnn===============", test);
        if (test.indexOf('moreservice') == '-1' && test != "#/") {
          this.popupsType = false;
          $(".spechorizotal .nav_color").css("color", "black");
          $(".spechorizotal .nav_color:hover").css("color", "#2692FF");
        } else {
          this.popupsType = true;

        }

        // setTimeout(()=>{
        //   this.$refs.topmenu.fetchMetaData(()=>{
        //     $("#servicecat").mouseenter(()=>{    
        //       // var leftNum = $("#header_row")[0].offsetLeft - 10;
        //       // console.log(leftNum,'kanzhenliaaaaaaaaaaaaaaaaaaaaaa');
        //       // $('.popups').css("left", leftNum + 'px');
        //       // $('.popups').fadeIn(200);
        //     });
        //     // $(".popups").mouseleave(()=>{
        //     //   $('.popups').fadeOut(200);
        //     // });
        //   });
        // },300);

      },
      getUrl(md) {
        return "web/" + this.ctlName + "/" + md;
      },
      async bizadmin() {
        location.href = "/admin";
      },
      async settingclick() {
        var d = await this.$root.postReq("/web/auth/userCtl/navSysSetting", {});
        location.href = d.data.jumpUrl;
      },
      async exitclick() {
        var d = await this.$root.postReq("/web/auth/userCtl/exit", {});
        location.reload();

      },
      async checkLogin() {
        var d = await this.$root.postReq("/web/auth/userCtl/checkLogin", {});
        if (d && d.status == 0 && d.data) {
          this.$store.state.currentUser = d.data;
        } else {
          //alert("no login");
        }
      },
      onselect(code) {
        if (code == "login") {
          location.href = appinfo.oauthlogin;
        }
        if (code == "register") {
          location.href = appinfo.oauthreg;
        }
      },
      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;
          }
        }
      },
      // 
      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;
        }
      },
      tabclick: function (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();
          this.hidetabs();
          this.isShowMenu = false;
        }
        if (tab.name == "home") {
          this.$router.push("/");
          this.hidetabs();
          this.isShowMenu = false;
        } 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);
          }
        }
      },
      pushx: function (to) {
        console.log(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 });
          }
        });

      },
      getReq(path, data) {
        var self = this;
        return axios.get(path, { params: data, "headers": { "codepath": this.codePath } }).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'
            });
            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.codePath } }).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'
            });
            self.showLogin();
            return null;
          } else {
            return r.data ? r.data : null;
          }
        });
      },
    },
  });
});
//});
