module.exports = {

  run: function (appVue, elId, routes, processNewPath) {

    var CONFIG = window.CONFIG;

    var Vue = require('vue');
    var Vuex = require("vuex");

    var ElementUI = require('element-ui');

    require('normalize.css');
    require('./theme/index.css');
    require("./semantic/dist/components/icon.css");

    var VueRouter = require('vue-router');
    var userUtil = require('user-util-vkm');
    var sso = require("sso-vkm");
    var $ = require("jquery");
    var cookie = require("js-cookie");
    var moment = require("moment");

    Vue.use(VueRouter)
    Vue.use(ElementUI)
    Vue.use(Vuex)

    function isLogin() {
      return CONFIG.sso === true ? ( sso.isLogin() && userUtil.getEntity() != null ) : userUtil.isLogin();
    }

    Vue.directive("auth", function (el, obj) {

      var $el = $(el);
      var authList = $el.data("auth") || $el.data("authname");

      var roleList = $el.data("role");

      ( hasAuth(authList) && hasRole(roleList) ) ? $el.show() : $el.hide();

    });

    function hasRole(roleList) {

      if(roleList && roleList.trim().length > 0)
      {

        roleList = roleList.split(",");

        for(var i = 0, l = roleList.length; i < l; ++ i)
        {
          var role = $.trim(roleList[i]);
          var not = false;

          if(role.indexOf("!") == 0)
          {
            role = role.substr(1);
            not = true;
          }

          if((( userUtil.hasRole(role) ? 1 : -1 ) * ( not ? -1 : 1 )) == 1)
          {
            return true;
          }

        }

        return false;

      }

      return true;

    };

    function hasAuth(authList) {

      if(authList && authList.trim().length > 0)
      {
        authList = authList.split(",");

        for(var i = 0, l = authList.length; i < l; ++ i)
        {
          var auth = $.trim(authList[i]);
          var not = false;

          if(auth.indexOf("!") == 0)
          {
            auth = auth.substr(1);
            not = true;
          }

          if((( userUtil.hasAuth(auth) ? 1 : -1 ) * ( not ? -1 : 1 )) == 1)
          {
            return true;
          }

        }

        return false;

      }

      return true;

    };

    const router = new VueRouter({
      routes,
      mode: 'history',
      saveScrollPosition: true
    });

    function getRoute(to) {

      var path = to.matched.length > 0 ? to.matched[0].path : null;

      for (let route of routes) {

        if (path === route.path) {

          return route;

        }

      }

    };

    router.beforeEach((to, from, next) => {

      if(processNewPath != false && ( to.path != "/new" && to.path.indexOf("/new/") == -1 ))
      {
        //命中路由到老管理端请求，原地刷新由老管理端处理。
        location.href = to.fullPath;
        return;
      }

      var route = getRoute(to) || {};

      //同步老管理端登录状态
      if(route.public != true)
      {
        var userEntity = userUtil.getEntity();

        if(CONFIG.sso != true)
        {

          if(userEntity && userEntity.id && userEntity.token
            && localStorage.getItem("m_token") && localStorage.getItem("m_token").length > 0
            && localStorage.getItem("m_userid") && localStorage.getItem("m_userid").length > 0)
          {
            if(userEntity.id != localStorage.getItem("m_userid") || userEntity.token != localStorage.getItem("m_token"))
            {
              userUtil.logout(false, location.pathname + location.search);
              return;
            }
          }

        }

      }

      switch(to.path)
      {
        case CONFIG.pathPrefix + "/":

          router.replace(CONFIG.pathPrefix + "/home");
          return;

        break;

        case CONFIG.pathPrefix + "/user/login":

          if(isLogin())
          {
            router.replace(CONFIG.pathPrefix + "/home");
            return;
          }

        break;

        default:

          if(isLogin() == false && route.public != true)
          {
            router.replace(CONFIG.pathPrefix + "/user/login?redirect_url=" + encodeURIComponent(to.fullPath));
            return;
          }

          if (to.path) {

            if (route.public != true)
            {

              if(route.hasOwnProperty("auth") && hasAuth(route.auth) == false)
              {
                if(window.app_m)
                {
                  window.app_m.$message({
                    message: "无权限查看此页",
                    type: 'warning'
                  })
                }
                else
                {
                  alert("无权限查看此页");
                }
                return;
              }

            }

          }
      }

      next();
    });

    var waterMarkBase64 = null;

    function initWaterMark(el) {

      if(waterMarkBase64 == null)
      {
        var userEntity = userUtil.getEntity();

        var canvas = $("<canvas></canvas>");
        var canvasDOM = canvas.get(0);

        var ctx = canvasDOM.getContext('2d');
        var fontSize = 12;
        ctx.font = fontSize + 'px sans-serif';
        ctx.textBaseline = 'middle';

        var userMark = userEntity.name + "<" + userEntity.email + ">";

        var textWidth = Math.ceil(ctx.measureText(userMark).width);

        canvasDOM.width = textWidth;
        canvasDOM.height = textWidth;

        ctx.textBaseline = 'middle';
        ctx.translate(canvasDOM.width / 2, canvasDOM.height / 2);
        ctx.rotate(25 * Math.PI / 180);
        ctx.font = fontSize + 'px serif';
        ctx.fillStyle = "rgba(0, 0, 0, 0.2)";
        ctx.fillText(userMark, Math.ceil(ctx.measureText(userMark).width) / 2 * -1, 0);
        waterMarkBase64 = canvasDOM.toDataURL("image/png", 1.0);
      }

      el.css("backgroundImage", "url(" + waterMarkBase64 + ")");

    };

    Vue.mixin({

      beforeCreate: function () {

      },

      watch: {
        $route: {
          handler: function (val) {
            this.vkroute = val;
          },
          immediate: true
        }
      },

      updated() {
        if(isLogin())
        {
          initWaterMark($(this.$el));
        }
      },

      methods: {

        formatDatetime(datetime, format) {
          return moment(datetime).format(format)
        },

        setTitle(title) {

          if(title && title.length > 0)
          {

            if(CONFIG.hasOwnProperty("titleSuffix"))
            {
              title += " - " + CONFIG.titleSuffix;
            }

          }
          else
          {
            if(CONFIG.hasOwnProperty("titleSuffix"))
            {
              title = CONFIG.titleSuffix;
            }
            else
            {
              title + "VIPKID";
            }

          }

          document.title = title;

        },

        setSearch(search) {

          var query = [];

          for(var name in search)
          {
            query.push(encodeURIComponent(name) + "=" + encodeURIComponent(search[name]));
          }

          this.$router.push({
            path: location.pathname + ( query.length > 0 ? ( "?" + query.join("&") ) : ""),
          })

        }
      },

      data() {
        return {
          vkroute: {},
          vkrouter: this.$router
        }
      }

    })

    window.app_m = new Vue({
      router,
      el: elId,
      store: new Vuex.Store({
        state: {
        },
        mutations: {
        }
      }),
      render: h => h(appVue)
    })

  }

}
