//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: {},
    reqUrl: "",
    channelName: "",
    reqQuery: "",
  },
});
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) => {
    if (to.path == "/" && location.hostname == "tm.plus.jdcloud.com") {
      router.replace({ path: '/jd/jdtrademark' });
    }
    if (to.path == "/" && location.hostname == "xwzc.xiaowangtech.com") {
      router.replace({ path: '/bw/jdtrademark' });
    }
    if (to.path == "/" && location.hostname == "gs.plus.jdcloud.com") {
      router.replace({ path: '/jd/jdindustry' });
    }
    if (to.path.includes('login')) {
      store.state.reqUrl = from.path;
      store.state.reqQuery = from.query;
      console.log(to, from, store.state.reqUrl);
    }

    next();
  });

  Vue.use(window['vue-cropper']);
  var app = new Vue({
    el: "#app",
    router: router,
    store: store,
    data: function () {
      return {
        // 回调地址
        reqUrl: "",
        // 请求地址
        host: ``,
        // 请求头携带参数
        globelHeader: {},
        // 通用接口参数
        commonParams: {
          "actionProcess": "",
          "sign": "2FviZ9PGws8Pt1fBhq0t90mjUvI",
          "actionBody": {},
          "actionType": "",
          "requrl": '',
        },
        loading: false,
        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: [

        ],
        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: [],
        channelUserId: "",
        channelName: '',
        jdSelfFooterShow: true,
        jdSelfHeaderShow: true,
        commonHeader: true,
        commonFooter: true,
        user_Name: "",
        channelMessage: "",
        isLogin: false,
        logoImg: null,
        homeUrl: "",
        footerText: "",
        superAdmin: null,
        fromListPath: "",
      };
    },
    created() {
      $("#app").css("visibility", 'visible');
      this.loading = false;
      this.channelName = location.hash.split('/')[1];
      this.accessTitle();
    },
    updated() {

    },
    mounted() {

      this.$nextTick(() => {
        this.handleHeader();
      });
      console.log($.fn.jquery, "vvvvvvvvvvvvvvvvv");
      var self = this;
      if ($.cookie('userpin')) {
        this.getUserInfo();
      }
    },
    watch: {
      // 监听路由变化
      $route: {
        handler: function (val, oldVal) {
          console.log("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;;", val, oldVal);
          if (val.path == "/bw/jdindentdetail") {
            this.fromListPath = oldVal.path;
            console.log(this.fromListPath, 'ttttttttttttttttttttttttttttttt');
          };
          if (val.fullPath == "/jd/jdtrademark" && location.hostname == "tm.plus.jdcloud.com") {
            this.jdSelfHeaderShow = true;
            this.jdSelfFooterShow = true;
            this.channelName = location.hash.split('/')[1];
          };
          if (val.fullPath == "/jd/jdindustry" && location.hostname == "gs.plus.jdcloud.com") {
            this.jdSelfHeaderShow = true;
            this.jdSelfFooterShow = true;
            this.channelName = location.hash.split('/')[1];
          };

        },
        // 深度观察监听
        deep: true
      }
    },
    methods: {
      // 获取用户信息
      getUserInfo() {
        var userPin = $.cookie('userpin');
        this.$root.postReq("/web/trademark/tmqueryCtl/getUserByPin", { userpin: userPin }).then((d) => {
          this.$root.loading = false;
          if (d.status == 0) {
            this.$root.user_Name = d.data.userName;
            this.$root.channelUserId = d.data.encryptChannelUserId;
            d.data.isAdmin ? this.superAdmin = true : this.superAdmin = false;
          } else {
            console.log(d.msg);
            this.$message("请重试");
          }
        });
      },
      accessTitle() {
        // 渠道标题
        var title = document.getElementById('idtitle');
        switch (this.channelName) {
          case 'jd':
            title.innerText = "京东云商标注册服务";
            break;
          case 'bw':
            title.innerText = "小望商标注册服务";
            this.logoImg = '/imgs/bwlogo.png';
            this.homeUrl = "/bw/jdtrademark";
            this.footerText = "浙江小望科技有限公司";
            break;
          case '1688':
            title.innerText = "1688商标注册服务";
            break;
          case 'gsbhome':
            title.innerText = "公司宝商标注册服务";
            break;
          default:
            title.innerText = "启服通";
            break;
        }
      },
      goSuperAdmin() {
        this.$router.push({
          path: `/${this.channelName}/OAjdlist`,
          query: {
            channelUserId: this.$root.channelUserId
          }
        })
      },
      myIndent() {
        this.$router.push({
          path: `/${this.channelName}/jdindentlist`,
          query: {
            channelUserId: this.$root.channelUserId
          }
        })
      },
      goHome() {
        this.$router.push(this.homeUrl);
      },
      headerMenu(key) {
        console.log(key);
        switch (key) {
          case 'loginOut':
            this.loginOut();
            break;
          case 'myIndent':
            this.myIndent();
            break;
          case 'goSuperAdmin':
            this.goSuperAdmin();
            break;
          default:
            break;
        }
      },
      loginOut() {
        let _this = this;
        console.log(this.channelName);
        /*
        var url = encodeURIComponent("http://tm.plus.jdcloud.com/#/jd/jdtrademark") ;
        
        */
        /*
         location.href = `http://login.jdcloud.com/logout?callback=http://tm.plus.jdcloud.com/#/jd/jdtrademark`;
         */
        switch (this.channelName) {
          case "jd":
            $.ajax({
              async: true,
              url: "https://login.jdcloud.com/logout",
              type: "GET",
              dataType: "jsonp",
              jsonp: 'callback',
              jsonpCallback: 'handleResponse',
              data: {
              },
              success: function (response, status, xhr) {
                console.log('状态为：' + status + ',状态是：' + xhr.statusText);
                console.log(response);
                if (response.code == 0) {
                  console.log(response);
                  _this.$router.push({ path: `/${_this.$root.channelName}/jdtrademark` });
                }
              }
            });
            break;
          case "bw":
            var userPin = this.$root.copyParams({ "userpin": $.cookie('userpin') }, "logout", "/auth/accessAuth/springBoard");
            this.$root.loading = true;
            this.$root.postReq("/web/trademark/tmqueryCtl/doPost", userPin).then((d) => {
              this.$root.loading = false;
              if (d.status == 0) {
                $.removeCookie("userpin");
                $.removeCookie("userName");
                $.removeCookie("channelUserId");
                this.$root.user_Name = "";
                this.$root.channelUserId = '';
                this.$router.push({
                  path: `/${_this.$root.channelName}/jdtrademark`
                });
                this.$message("您已退出");
              } else {
                console.log(d.msg);
                this.$message("请重试");
              }
            });


            break;
          default:
            break;
        }





      },
      // 返回当前接入渠道标识
      getChannelPath() {
        var from = this.$route.path;
        var path = from.split('/')[1];
        return path;
      },
      // 操作头尾显示隐藏 公共部分
      handleHeader() {
        this.$nextTick(() => {
          let hideHeader = location.hash.split('/')[1];
          switch (hideHeader) {
            case "jd":
              console.log("xxxxxxxxxxxxxxxxxxxx", location.hash.split('/')[1], location);
              var selftmreg = location.hash.includes('/selftmreg');
              var OAjdlist = location.hash.includes('/OAjdlist');
              var jdindentlist = location.hash.includes('/jdindentlist');
              var jdindentdetail = location.hash.includes('/jdindentdetail');
              var OAjddetails = location.hash.includes('/OAjddetails');
              var OAjdcompany = location.hash.includes('/OAjdcompany');
              var companydetail = location.hash.includes('/companydetail');
              // 京东公共尾部隐藏
              if (OAjdlist || selftmreg || jdindentlist || jdindentdetail || OAjddetails || OAjdcompany || companydetail) {
                this.jdSelfFooterShow = false;
              }
              // 京东公共头部隐藏
              if (OAjdlist || jdindentlist || jdindentdetail || OAjddetails || OAjdcompany || companydetail) {
                this.jdSelfHeaderShow = false;
              }
              $(document).ready(function () {
                $('#LRdiv0').hide();
              });
              console.log("bbbbbbbbbbbbbbbbbbbbbbbbb", $('#LRdiv0'));

              break;
            case "bw":
              this.channelMessage = "百望";
              this.jdSelfHeaderShow = false;
              this.jdSelfFooterShow = false;
              break;
            case "gsbhome":
              $(document).ready(function () {
                $('#LRdiv0').hide();
              });
              this.jdSelfHeaderShow = false;
              this.jdSelfFooterShow = false;
              break;
            case "1688":
              $(document).ready(function () {
                $('#LRdiv0').hide();
              });
              this.jdSelfHeaderShow = false;
              this.jdSelfFooterShow = false;
              break;
            default:
              this.jdSelfHeaderShow = false;
              this.jdSelfFooterShow = false;
              break;
          }
        });
      },
      // 处理参数方法
      copyParams(actionBody, actionType, url, isUser = "no", isDecryptUser = "no") {
        var data = this.commonParams;
        data.actionProcess = this.channelName;
        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) {

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

        });
      },
      postReq(path, data) {
        var _this = this;
        return axios.post(path, data, { "headers": { 'codepath': this.codePath } }).then(function (r) {
          if (r.data.status == -99) {
            $.removeCookie("userpin");
            $.removeCookie("userName");
            $.removeCookie("channelUserId");
            _this.$root.user_Name = "";
            _this.$root.channelUserId = '';
          }
          return r.data ? r.data : null;

        });
      },
    },
  });
});
//});
