axios.get("/vue/comp/base").then(function (res) {
  $.base64.utf8encode = true;
  console.log(res);
  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;
      },
    }),
    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;
        //  if(pathTmp=="/"){
        //    tmp={"path":pathTmp,"components":{
        //      "default":componentFactory("autosubmitorder")
        //    },};
        //  }else{
        //    tmp={"path":pathTmp,"components":{
        //      "default":componentFactory(d.data.data.bizs[k].comname)
        //    },};
        //  }
        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: {
        count: 1,
        products: d.data.data.ps,
        currentCodePath: "",
        currentUser: null,
        curSelRow: {},
        header_height: "200",
        socketClient: null,
        logoUrl: "",
        appimgUrl: "",
        currentChatTo: "",
        channelCode: "",
        itemCode: "",
        queryParam: "",
        queryParams: {},
        orderNum: "",
      },
      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",
          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: "",
          appcode: "",
          mess: 0,
          timestamp: 0,
          sign: "",
          baseUrl: "",
          baseparams: "",
        };
      },
      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 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]);
        }
        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 openid = window.location.search.substr(1).match(new RegExp("(^|&)" + "openid" + "=([^&]*)(&|$)", "i"));
        if (openid != null) {
          this.openid = unescape(openid[2]);
        }
        if (!channelcode || !openid) {
          $("#loading").fadeOut();
          this.$message.warning("传递参数传递错误，channelcode、openid必须传递");
          this.$router.push("/");
          return false;
        }
        /*必须参数--结束 */
        var appcode = window.location.search.substr(1).match(new RegExp("(^|&)" + "appcode" + "=([^&]*)(&|$)", "i"));
        if (appcode != null) {
          this.appcode = unescape(appcode[2]);
        }

        var mess = window.location.search.substr(1).match(new RegExp("(^|&)" + "mess" + "=([^&]*)(&|$)", "i"));
        if (mess != null) {
          this.mess = unescape(mess[2]);
        }

        var timestamp = window.location.search.substr(1).match(new RegExp("(^|&)" + "timestamp" + "=([^&]*)(&|$)", "i"));
        if (timestamp != null) {
          this.timestamp = unescape(timestamp[2]);
        }

        var sign = window.location.search.substr(1).match(new RegExp("(^|&)" + "sign" + "=([^&]*)(&|$)", "i"));
        if (sign != null) {
          this.sign = unescape(sign[2]);
        }

        this.baseparams = "channelcode=" + this.channelCode + "&openid=" + this.openid;
        if (this.itemCode) {
          this.baseparams = this.baseparams + "&itemcode=" + this.itemCode;
        }
        if (this.appcode) {
          this.baseparams = this.baseparams + "&appcode=" + this.appcode;
        }
        if (this.mess) {
          this.baseparams = this.baseparams + "&mess=" + this.mess;
        }
        if (this.timestamp) {
          this.baseparams = this.baseparams + "&timestamp=" + this.timestamp;
        }
        if (this.sign) {
          this.baseparams = this.baseparams + "&sign=" + this.sign;
        }
        this.baseUrl = "/automaticsubmit?" + this.baseparams;
        this.checkUserInfo();

        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");
          // if(self.currentUser){
          //   $header.removeClass("inheader");
          // }else{
          //   $header.addClass("inheader");
          // }
          //self.minHeader();
          // if(localStorage.getItem("logoUrl")){
          //   self.$store.state.logoUrl=localStorage.getItem("logoUrl");
          //   self.$store.state.appimgUrl=localStorage.getItem("appimgUrl");
          // }
        }, 1500);
        //this.checkPayState();
        $workbench.scroll(() => {
          this.currentPos[this.currentCodePath] = $workbench.scrollTop();
          if (this.currentPos[this.currentCodePath] > 564) {
            $header.hide(100);
          } else {
            $header.show(100);
          }
        });
      },
      methods: {
        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 = "/autosubmithtml5?" + this.baseparams;
          }
        },
        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("/autosubmittrademark");
          }
        },
        tmSubmit: function () {
          if (this.openid && this.channelCode) {
            this.$router.push("/automaticsubmit");
          }
        },
        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);
        },
        checkUserInfo: function () {
          var self = this;
          var obj = {
            channelCode: this.channelCode, itemCode: this.itemCode, openid: this.openid,
            appcode: this.appcode, mess: this.mess, timestamp: this.timestamp, sign: this.sign
          };
          self.hideTop();
          this.postReq("/web/userCtl/checkUserInfo", obj).then(function (d) {
            if (d && d.status >= 0) {
              if (self.sign && self.appcode) {
                self.showTop();
              }
              self.$store.state.currentUser = d.data;
            } else {
              self.hideTop();
              $("#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") {
            //console.log("xxxxxxxxxxxxxxxxxxxx");
            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;
            //$("#imgapp").attr("style","position:absolute;top:8px;margin-left:-45px;height:35px");
            $(window).trigger("resize");
            this.isToggle = true;
          } else {
            this.header_h = 40;
            this.$store.state.header_height = this.header_h;
            //$("#imgapp").attr("style","position:absolute;top:8px;margin-left:-170px;");
            $(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;
          console.log(path);
          console.log(this.currentCodePath);
          return axios.get(path, { params: data, "headers": { "codepath": this.currentCodePath } }).then(function (r) {
            console.log(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'
              });
              console.log(482);

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


});
