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) {
        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;
      },
      isBackToList: state => {
        return state.isBackToList;
      },
    }),
    methods: {
      getUrl(md) {
        return "web/" + this.ctlName + "/" + md;
      },
    }
  });

  var routes = [];
  var codepaths = {};
  var self = this;
  axios.get("/web/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;
      if (!d.data.data.bizs[k].isDynamicRoute) {//如果不忽略静态路由
        var tmp = null;
        tmp = {
          "path": pathTmp, "components": {
            "default": componentFactory(d.data.data.bizs[k].comname)
          },
        };
        routes.push(tmp);
      }
      codepaths[pathTmp] = codepath;//暂存每个叶子节点对应的codepath
    });
    //元数据分析时会为每个叶子节点动态生成codepath,按照code生成从根开始的路径
    d.data.data.ps.forEach(p => {
      if (p.code) {
        var tmpRoute = {
          "path": "/products/" + p.code + "/:id", "components": {
            "default": componentFactory(p.code)
          }
        };
        routes.push(tmpRoute);
      }
    });
    var router = new VueRouter({
      routes: routes,
    });
    const store = new Vuex.Store({
      state: {
        isBackToList: false,
        count: 1,
        products: d.data.data.ps,
        currentCodePath: "",
        currentUser: null,
        curSelRow: {},
        header_height: "200",
        socketClient: null,
        logoUrl: "",
        appimgUrl: "",
        currentChatTo: "",
        channelCode: "",
        itemCode: "",
        queryParam: "",
        queryParams: {},
        channelOrderNum: "",
        openid: "",
        env: "",
        mobile: "",
        username: "",
        appCode: "",
        timestamp: "",
        needId: ""
      },
      mutations: {
        increment(state) {
          state.count++
        },
      }
    });
    router.beforeEach((to, from, next) => {
      console.log("enter before...........................");
      //设置当前访问的叶子节点的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);
        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 () {
        return {
          aside_w: "0px",
          showType: 0,
          header_h: 40,
          hastop: true,
          catas: [
          ],
          logins: [
          ],
          hintLogin: null,
          //currentUser:null,
          loading: false,
          menu_h: 0,
          collapse: true,
          isToggle: false,
          items: [
            { code: "zero", left: "/imgs/i22.png", right: "/imgs/rebot.png" },
            { code: "one", left: "/imgs/i21.png", right: "/imgs/rebot.png" },
            { code: "two", left: "/imgs/i2.png", right: "/imgs/rebot.png" },
          ],
          currentPos: {},
          onlines: 0,
          openid: "",
          channelCode: "",
          itemCode: "",
          channelOrderNum: "",
          username: "",
        };
      },
      computed: Vuex.mapState({
        currentCodePath: state => {
          return state.currentCodePath;
        },
        currentUser: state => {
          return state.currentUser;
        },
        logoUrl: state => {
          return state.logoUrl;
        },
        appimgUrl: state => {
          return state.appimgUrl;
        },
      }),
      created() {

      },
      updated() {
        /*var $workbench=$(this.$refs.workbench.$el);
        if(!this.currentPos[this.currentCodePath]){
          $workbench.scrollTop(0);
        }else{
          this.$nextTick(()=>{
              $workbench.scrollTop(this.currentPos[this.currentCodePath]);
          });

        }*/
      },
      mounted() {
        var env = window.location.search.substr(1).match(new RegExp("(^|&)" + "env" + "=([^&]*)(&|$)", "i"));
        if (env != null) {
          this.env = unescape(env[2]);
          this.$store.state.env = unescape(env[2]);
        }
        var showtype = window.location.search.substr(1).match(new RegExp("(^|&)" + "showtype" + "=([^&]*)(&|$)", "i"));
        if (showtype != null) {
          this.showType = unescape(showtype[2]);
        }
        var queryParam = window.location.search.substr(1).match(new RegExp("(^|&)" + "queryParam" + "=([^&]*)(&|$)", "i"));
        if (queryParam != null) {
          this.$store.state.queryParam = unescape(queryParam[2]);
        }
        var queryTmId = window.location.search.substr(1).match(new RegExp("(^|&)" + "queryTmId" + "=([^&]*)(&|$)", "i"));
        if (queryTmId != null) {
          this.$store.state.queryTmId = unescape(queryTmId[2]);
        }        
        var channelOrderNum = window.location.search.substr(1).match(new RegExp("(^|&)" + "channelOrderNum" + "=([^&]*)(&|$)", "i"));
        if (channelOrderNum != null) {
          this.$store.state.channelOrderNum = unescape(channelOrderNum[2]);
          this.channelOrderNum = unescape(channelOrderNum[2]);
        }
        var itemCode = window.location.search.substr(1).match(new RegExp("(^|&)" + "itemCode" + "=([^&]*)(&|$)", "i"));
        if (itemCode != null) {
          this.$store.state.itemCode = unescape(itemCode[2]);
          this.itemCode = unescape(itemCode[2]);
        }
        var mobile = window.location.search.substr(1).match(new RegExp("(^|&)" + "mobile" + "=([^&]*)(&|$)", "i"));
        if (mobile != null) {
          this.mobile = unescape(mobile[2]);
        }
        var username = window.location.search.substr(1).match(new RegExp("(^|&)" + "username" + "=([^&]*)(&|$)", "i"));
        if (username != null) {
          this.username = decodeURIComponent(username[2]);
          this.$store.state.username = this.username;
        }
        var channelCode = window.location.search.substr(1).match(new RegExp("(^|&)" + "channelCode" + "=([^&]*)(&|$)", "i"));
        if (channelCode != null) {
          this.$store.state.channelCode = unescape(channelCode[2]);
          this.channelCode = unescape(channelCode[2]);
        } else {
          this.header_h = 0;
          $("#loading").fadeOut();
          this.$message.warning("传递参数channelcode错误");
          this.$router.push("/");
          return false;
        }
        var openid = window.location.search.substr(1).match(new RegExp("(^|&)" + "openid" + "=([^&]*)(&|$)", "i"));

        if (openid != null) {
          this.$store.state.openid = unescape(openid[2]);
          this.openid = unescape(openid[2]);
        } else {
          this.header_h = 0;
          $("#loading").fadeOut();
          this.$message.warning("传递参数openid错误");
          this.$router.push("/");
          return false;
        }
        var timestamp = window.location.search.substr(1).match(new RegExp("(^|&)" + "timestamp" + "=([^&]*)(&|$)", "i"));
        if (timestamp != null) {
          this.timestamp = unescape(timestamp[2]);
        }
        var appCode = window.location.search.substr(1).match(new RegExp("(^|&)" + "appCode" + "=([^&]*)(&|$)", "i"));
        if (appCode != null) {
          this.appCode = unescape(appCode[2]);
        }
        var needId = window.location.search.substr(1).match(new RegExp("(^|&)" + "needId" + "=([^&]*)(&|$)", "i"));
        if (needId != null) {
          this.$store.state.needId = unescape(needId[2]);
          this.needId = unescape(needId[2]);
        }
        var sign = window.location.search.substr(1).match(new RegExp("(^|&)" + "sign" + "=([^&]*)(&|$)", "i"));
        if (sign != null) {
          this.sign = unescape(sign[2]);
        }
        this.checkIncomingParams();
        if (this.showType == 0) {
          this.header_h = 0;
        }
        /*var $workbench=$(this.$refs.workbench.$el);
        var winHeight=$(window).height();
        var ch=winHeight-this.header_h;
        this.$store.state.header_height=this.header_h;
        //this.header_h=winHeight;
        $workbench.height(ch);
        $(window).resize(()=>{
          var ch=$(window).height()-this.header_h;
          $workbench.height(ch);
        });*/
        var $header = $(this.$refs.inmain.$el);
        setTimeout(function () {
          $("#loading").fadeOut();
          if (self.currentUser) {
            self.minHeader();
          }
          $header.removeClass("inheader");
        }, 1500);
        /*$workbench.scroll(()=>{
          this.currentPos[this.currentCodePath]=$workbench.scrollTop();
          if(this.currentPos[this.currentCodePath]>564){
            $header.hide(100);
          }else{
            $header.show(100);
          }
        });*/
      },
      methods: {
        localdata(key, item) {
          if (item) {
            localStorage.setItem(key, JSON.stringify(item));
            var strobj = localStorage.getItem(key);
          } else {
            var strobj = localStorage.getItem(key);
            if (strobj) {
              return JSON.parse(strobj);
            } else {
              return null;
            }

          }
        },
        handleCommand: function (command) {
          if (command && command == "tm") {
            this.myTm();
          }
          if (command && command == "order") {
            this.myOrder();
          }
          if (command && command == "tmSubmitInfo") {
            this.tmSubmit();
          }
          if (command && command == "softwarecrsubmit") {
            this.softwarecrsubmit();
          }
          if (command && command == "workcrsubmit") {
            this.workcrsubmit();
          }
          if (command && command == "mySoftwarecrsubmit") {
            this.mySoftwarecrsubmit();
          }
          if (command && command == "myWorkcrsubmit") {
            this.myWorkcrsubmit();
          }
        },
        toMain: function () {
          if (this.openid && this.channelCode) {
            window.location.href = "https://boss.gongsibao.com/autosubmithtml5?params=" + this.channelCode + '&' + this.openid;

          }
        },
        softwarecrsubmit: function () {
          if (this.openid && this.channelCode) {
            this.$router.push("/softwarecrsubmit");
          }
        },
        workcrsubmit: function () {
          if (this.openid && this.channelCode) {
            this.$router.push("/workcrsubmit");
          }
        },
        mySoftwarecrsubmit: function () {
          if (this.openid && this.channelCode) {
            this.$router.push("/autosoftwarecrsubmit");
          }
        },
        myWorkcrsubmit: function () {
          if (this.openid && this.channelCode) {
            this.$router.push("/aotuworkcrsubmit");
          }
        },
        myTm: function () {
          if (this.openid && this.channelCode) {
            this.$router.push("/autosubmittminside");
          }
        },
        tmSubmit: function () {
          if (this.openid && this.channelCode) {
            this.$router.push("/automatictmsubmitinside");
          }
        },
        myOrder: function () {
          if (this.openid && this.channelCode) {
            this.$router.push("/autosubmitorder");
          }
        },
        aboutus: function () {
          this.$router.push("/sysmag/articledetail/1");
        },
        onlinechange: function (n) {
          this.onlines = n;
        },
        showMask() {
          var self = this;
          setTimeout((function () {
            self.loading = true;
          }), 10);
        },
        hideMask() {
          var self = this;
          setTimeout((function () {
            self.loading = false;
          }), 500);
        },
        checkIncomingParams: function () {
          var self = this;
          var obj = { openid: this.openid, channelCode: this.channelCode };
          if (this.itemCode) {
            obj["itemCode"] = this.itemCode;
          }
          if (this.mobile) {
            obj["mobile"] = this.mobile;
          }
          if (this.username) {
            obj["username"] = this.username;
          }
          if (this.appCode) {
            obj["appCode"] = this.appCode;
          }
          if (this.timestamp) {
            obj["timestamp"] = this.timestamp;
          }
          if (this.channelOrderNum) {
            obj["channelOrderNum"] = this.channelOrderNum;
          }
          if (this.sign) {
            obj["sign"] = this.sign;
          }
          if (this.env) {
            obj["env"] = this.env;
          }
          if (this.needId) {
            obj["needId"] = this.needId;
          }
          this.postReq("/web/userCtl/checkUserInfo", obj).then(function (d) {
            // debugger
            if (d && d.status >= 0) {
              self.$store.state.currentUser = d.data;
            } else {
              self.header_h = 0;
              $("#loading").fadeOut();
              self.$store.state.currentUser = {};
              if (d) {
                self.$message({
                  message: d.msg,
                  type: 'warning'
                });
              } else {
                self.$message({
                  message: "用户为空",
                  type: 'warning'
                });
              }
              /*self.$router.push("/");*/
            }
          });
        },
        onclick: function () {
          if (this.aside_w == "65px") {
            this.aside_w = "0px";
          } else {
            this.aside_w = "65px";
          }
        },
        hideMenu: function () {
          this.aside_w = "0px";
        },
        hideTop: function () {
          this.header_h = 0;
          this.hastop = false;
        },
        showTop: function () {
          this.header_h = 40;
          this.hastop = true;
        },
        showMenu: function () {
          this.aside_w = "65px";
        },
        onMenuSelect: function (index) {
          var self = this;
          if (index == "exit") {
            this.onlines = 0;
            this.minHeader();
            this.getReq("/web/userCtl/exit", null).then(function (r) {
              self.$store.state.currentUser = null;
              //清空session
              //self.showLogin();
              //self.$router.push("/");
              window.location.reload();
            });

          }
          if (index == "home") {
            this.$router.push("/");
            return;
          }
          if (index == "fillmoney") {
            this.$refs.payselect.show();
          }
          if (index == "fillpersoninfo") {
            self.$router.push("/products/finishpersoninfo/");
            return;
          }

          if (index == "toggleHeader") {
            this.minHeader();
          } else {
            this.$router.push(index);
          }

        },
        minHeader: function () {
          if (!this.isToggle) {
            this.header_h = 40;
            this.$store.state.header_height = this.header_h;

            $(window).trigger("resize");
            this.isToggle = true;
          } else {
            this.header_h = 40;
            this.$store.state.header_height = this.header_h;
            $(window).trigger("resize");
            this.isToggle = false;
          }
        },
        hideHeader: function () {
          if (!this.isToggle) {
            this.minHeader();
          }
        },
        handleClick(tab, e) {
          //console.log(tab,e);
        },
        formatItem: function (t, label) {
          if (t) {
            if (!label && t.src) {//表示当前是image元素
              if (this.currentUser) {
                return this.currentUser.imgUrl;
              }
              return t.src;
            } else {
              if (t.code == "smallmoney") {
                return label;
              }
              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.hideMenu();
              self.$message({
                message: '超时，请重新登录',
                type: 'warning'
              });

              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.hideMenu();
              self.$message({
                message: '超时，请重新登录',
                type: 'warning'
              });
              return null;
            } else {
              return r.data ? r.data : null;
            }
          });
        },
      },
    });
  });


});
