function getQueryStringMap() {
  //取得查询字符串并去掉开头的问号
  var str = (location.search.length > 0 ? location.search.substring(1) : "");
  var args = {};//保存数据的对象
  items = str.length ? str.split('&') : [];//取得每一项
  var item = null;
  var name = null;
  var value = null;
  for (var i = 0; i < items.length; i++) {
    item = items[i].split('=');
    name = decodeURIComponent(item[0]);
    value = decodeURIComponent(item[1]);
    if (name.length) {
      args[name] = value;
    }
  }
  return args;
}
var queryMap = getQueryStringMap();//解析当前的查询字符串
function addCSS(csspath) {
  var link = document.createElement('link');
  link.type = 'text/css';
  link.rel = 'stylesheet';
  link.href = csspath;
  document.getElementsByTagName("head")[0].appendChild(link);
}
var currentTheme = (queryMap["paramtheme"] && queryMap["paramtheme"] != "default") ? queryMap["paramtheme"] : "";
axios.get("/vue/comp/base").then(function (res) {
  $.base64.utf8encode = true;
  if (res.data) {
    res.data.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, { "headers": { "theme": currentTheme } }).then(function (res) {
        console.log(compath);
        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;
  Vue.mixin({
    props: ["modelName"],
    computed: Vuex.mapState({
      currentUser: state => {
        return state.currentUser;
      },
      currentWxUser: state => {
        return state.currentWxUser;
      },
      currentCompany: state => {
        return state.currentCompany;
      },
      pfooterinfo: state => {
        return state.pfooterinfo;
      },
      codePath: state => {
        return state.currentCodePath;
      },
      ctlName: function () {
        return this.modelName + "Ctl";
      },
      header_height: state => {
        return state.header_height;
      },
      socketClient: state => {
        return state.socketClient;
      },
      istabclick: state => {
        return state.istabclick;
      },
    }),
    methods: {
      getUrl(md) {
        return "web/" + this.ctlName + "/" + md;
      },
    }
  });

  var routes = [];
  var codepaths = {};
  var mapTile = {};
  var mapRouterEntry = {};
  var isp = 0;
  var global_rsconfig = null;
  axios.get("/web/metaCtl/getRouteConfigWithoutProduct").then(d => {
    isp = d.data.data.isp;
    Object.keys(d.data.data.bizs).map((k) => {
      if (k.indexOf("mobile") >= 0) {
        //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["default"] = componentFactory(d.data.data.bizs[k].comname);
          mapTile[pathTmp] = d.data.data.bizs[k].title;
          if (pathTmp == "/mobilehome") {
            tmp.path = "/";
          }
          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: {
        popupsCode: null,
        count: 1,
        products: d.data.data.ps,
        currentCodePath: "",
        istabclick: false,
        currentUser: null,
        currentWxUser: null,
        currentCompany: null,
        userInfo: null,
        curSelRow: {},
        header_height: "200",
        socketClient: null,
        logoUrl: "",
        appimgUrl: "",
        currentChatTo: "",
        pfooterinfo: null,
      },

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

      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();




    });
    var app = new Vue({
      el: "#app",
      router: router,
      store: store,
      data: function () {
        return {
          selected: '1',
          headerRowType: false,
          pDataKey: 0,
          pTowDataKey: null,
          companys: [],
          catas: [

          ],
          loading: false,
          items: [
          ],
          isShowMenu: "true",
          currentCompany: null,
          bankAccount: null,
          wxJpg: '/imgs/wxJpg.jpg',
          isfront: true,
          stageType: true,
          themename: "",
          showWxrm: false,
          showPhoneNum: false,
          mitems: [
            // code里的值控制活动时的样式..
            // { "code": "waitsign", "text": "神盾", "icon": "fa fa-clock-o" },
            { "code": "mobilehome", "text": "首页", "icon": "mintui mintui-home" },
            { "code": "mobiledeal", "text": "交易", "icon": "mintui mintui-jiaoyi" },
            { "code": "mobilemy", "text": "我的", "icon": "mintui mintui-wode" },
          ],
          openid: null,
        };
      },
      created() {
        /**是否微信登录 */
        // var arr = location.href.split('?');
        // if(arr && arr.length>1){
        //   var arr2 = arr[1].split('=');
        // }
        // let url = location.href.split('?')[1].split('=')[1];
        // let urlLength = url.length - 2;
        // if(url){
        //   this.openid = url.substr(0, urlLength);
        // }
        // console.log(url, urlLength, this.openid, "/ccccccccccccccccccccccccccccccccccccccc");
        var href = location.href;
        if (href.indexOf("openid=") >= 0) {
          var reg = new RegExp("(^)openid=([^&]*)(&|$)");
          var r = window.location.search.substr(1).match(reg);
          if (r != null) {
            this.openid = r[2];
          }
        }

        // this.checkAndLogin();
      },
      updated() {

      },
      computed: {

      },
      mounted() {
        //　mobile默认路由


      },
      methods: {
        // 用户是否登录过
        async  checkAndLogin() {
          await this.getReq("/wxop/empowerWxop/checkAndLogin2", { openid: this.openid }).then((r) => {
            console.log(r, 'zzzzzzzzzzzzzzz');
            if (r && r.code == 1) {
              if (r.user) {
                localStorage.gsbUser = JSON.stringify(r.user) || "";
              } else {
                localStorage.gsbUser = "";
              }
              if (r.wxuser) {
                localStorage.gsbWxUser = JSON.stringify(r.wxuser) || "";
              } else {
                localStorage.gsbWxUser = "";
              }
              if (r.company) {
                localStorage.gsbCompany = JSON.stringify(r.company) || "";
              } else {
                localStorage.gsbCompany = "";
              }
            }
          })
          await this.getOauthUrl();

          /*微信登录接口 */

        },
        // 微信授权
        getOauthUrl() {
          if (!localStorage.gsbUser || localStorage.gsbUser == 'null') {
            this.getReq("/wxop/empowerWxop/getOauthLink", { callbackpage: 'mobilemy' }).then((res) => {
              if (res.code == '1') {
                location.href = res.data;
              }
            });
          }
        },

        contextCompany() {
          if (localStorage.gsbCompany && localStorage.gsbCompany != "") {
            let gsbCompany = JSON.parse(localStorage.gsbCompany);
            return gsbCompany;
          }

        },
        // footer导航
        menuclick(code) {
          // 路由默认首页显示页面
          if (code == 'mobilemy') {
            /*路由拦截  */
            if (!localStorage.gsbWxUser || localStorage.gsbWxUser == "null") {
              this.checkAndLogin();
              return
            } else {
              /*判断用户手机是否绑定 */
              if (!localStorage.gsbUser || localStorage.gsbUser == 'null') {
                this.$router.push({ path: "/mobilelog", query: {} });
                return
              }
              this.$router.push('/' + code);
            }
          };

          if (code == 'mobilehome') {
            this.$router.push("/");
            return
          };
          this.$router.push('/' + code);

        },
        showmenu() {
          this.$refs.bottommenu.showmenu();
        },
        hidemenu() {
          this.$refs.bottommenu.hidemenu();
        },
        titleModify(title) {
          let mobileTitle = document.getElementsByTagName('title')[0];
          mobileTitle.innerText = title;
        },
        getReq(path, data) {
          var self = this;
          return new Promise(function (resv, reject) {
            // self.contextCompany() ? self.contextCompany().id : ""
            axios.get(path, { params: data, "headers": { "theme": currentTheme, "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.$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(path, data) {
          var self = this;
          return axios.post(path, data, { "headers": { "theme": currentTheme, '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.$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;
            }
          });
        },
      },
    });
  });
});
  // Vue.$messagebox = Vue.prototype.$messagebox = MessageBox;   alert confirm prompt

  // Vue.$toast = Vue.prototype.$toast = Toast;        提示框

  // Vue.$indicator = Vue.prototype.$indicator = Indicator;   loading  [open] [close]