import "babel-polyfill";
import Vue from "vue";
import App from "./App";
import ElementUI from "element-ui";
import VueRouter from "vue-router";
import stores from "./vuex";
import Vuex from "vuex";
import routes from "./routes/routes";

import "font-awesome/css/font-awesome.min.css";
import "@/utils/dialog.js";
import "@/utils/option-scroll.js";
import "@/utils/buttonPermission.js";
import { mixins } from "@/mixins";
Vue.mixin(mixins);

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

import{endCalc,optionTimeCalc,init}from'@/utils/TimeOnPage.js';


import setting from '@/mixins/theme.js'
Vue.prototype.$setting = setting;

//Import Froala Editor
import "froala-editor/js/plugins.pkgd.min.js";
import "froala-editor/js/plugins/quick_insert.min.js";
import "froala-editor/js/plugins/font_size.min.js";
// import 'froala-editor/js/languages/hr.js';
//Import third party plugins
import "froala-editor/js/third_party/embedly.min";
import "froala-editor/js/third_party/font_awesome.min";
import "froala-editor/js/third_party/spell_checker.min";
import "froala-editor/js/third_party/image_tui.min";
//引入中文语言包
require("froala-editor/js/languages/zh_cn");
require("froala-editor/js/languages/hr.js");
require("froala-editor/css/froala_style.min.css");
// Import Froala Editor css files.
import "froala-editor/css/froala_editor.pkgd.min.css";
import "froala-editor/css/plugins/quick_insert.css";

// Import and use Vue Froala lib.
import VueFroala from "vue-froala-wysiwyg";
Vue.use(VueFroala);

/* 请求数据解密 */
import { parseData } from "@/utils/parseData";
Vue.prototype.$parseData = parseData;

/* icon */
import icons from "@/utils/icon.js";
Vue.prototype.$icons = icons;

import Clipboard from "clipboard"; // 复制
Vue.prototype.Clipboard = Clipboard;

/* 全局挂载component */
import "@/utils/registryComponents";

/*  */
import Vue2OrgTree from "vue2-org-tree";
import "./styles/org.scss";

Vue.use(Vue2OrgTree);

/* lodash */
import _ from "lodash";
Vue.prototype._ = _;

/* moment */
import moment from "moment";
moment.locale("zh-cn");
Vue.prototype.$moment = moment;

/* VueClipboard 用于拷贝 */
import VueClipboard from "vue-clipboard2";

Vue.use(VueClipboard);
// 瀑布流
import { VueMasonryPlugin } from "vue-masonry";

Vue.use(VueMasonryPlugin);

import * as permissionBtn from "@/utils/buttonConfig";
Vue.prototype.permissionBtn = permissionBtn

// flat
Array.prototype.flat = function (count) {
  let c = count || 1;
  let len = this.length;
  let exe = [];
  if (this.length == 0) return this;
  while (c--) {
    let _arr = [];
    let flag = false;
    if (exe.length == 0) {
      flag = true;
      for (let i = 0; i < len; i++) {
        if (this[i] instanceof Array) {
          exe.push(...this[i]);
        } else {
          exe.push(this[i]);
        }
      }
    } else {
      for (let i = 0; i < exe.length; i++) {
        if (exe[i] instanceof Array) {
          flag = true;
          _arr.push(...exe[i]);
        } else {
          _arr.push(exe[i]);
        }
      }
      exe = _arr;
    }
    if (!flag && c == Infinity) {
      break;
    }
  }
  return exe;
};
export const router = new VueRouter({
  mode: "history",
  routes,
});

export const store = new Vuex.Store({
  ...stores,
});

//import { getUserUuid } from "./api/api";
router.beforeEach(async(to, from, next) => {
  // 判断本地是否有uuid
  /* const uuid = localStorage.getItem("uuid");
  if (!uuid) {
    getUserUuid().then((res) => {
      if (res.Ret == 200) {
        localStorage.setItem("uuid", res.Data);
      }
    });
  } */

  let auth = localStorage.getItem("auth") || false;
  if (to.path != "/login" && to.path!='/temppage' &&to.path!='/fogetpassword' && !auth) {
    window.location.href =  window.location.origin + '/login';
    return false;
  }

  /* 沙盘详情name添加 */
  if (to.path === "/sandflow") {
    to.matched[1].name =
      to.query.type === "view"
        ? "查看沙盘"
        : to.query.id
        ? "编辑沙盘"
        : "添加沙盘";
  }

  if (to.path === "/analyseVariety") {
    to.matched[1].name = to.query.type === "look" ? "查看品种" : "分析品种";
  }

  if (to.path) {
    //百度统计
    if (window._hmt) {
      window._hmt.push(["_trackPageview", "/#" + to.fullPath]);
    }
    //获取权限按钮
    to.path != "/login"&&to.path!='/temppage'&&await store.dispatch('getPermissionButtons')
    next();
  } else {
    next({ path: "/404" });
  }
});


router.afterEach((to, from, next) => {
  // 改变页面标题
  document.title = to.matched[to.matched.length - 1].name
  ? `${setting.name}-${to.matched[to.matched.length - 1].name}`
  : setting.name;

  window.scrollTo(0, 0);
  if(stores.state.hasTrialUserPermisson){

    sessionStorage.setItem('preTitle',from.name||'')

    if(!stores.state.hasDoPageListening){
      // 初始化需要放在 页面设置标题后，才能拿到正确的标题
      init()
      stores.mutations.SET_PAGE_EVENT_LISTENER(stores.state,true)
    }

    const routerChangeType = sessionStorage.getItem('routerChangeType')
    if(routerChangeType==='popstate'){
      const IsActive = sessionStorage.getItem('IsActive')
      if(IsActive=='1'){
        endCalc('popstate',Number(sessionStorage.getItem('popStayTime')||0))
      }
      optionTimeCalc()
      sessionStorage.removeItem('routerChangeType')
      sessionStorage.removeItem('popStayTime')
    }
  }
});

Vue.config.devtools = true;

new Vue({
  router,
  store,
  render: (h) => h(App),
}).$mount("#app");

router.onError((error) => {
  // 当更新服务器上打包资源时，浏览器不刷新会报错，故当监听到错误刷新浏览器
  window.location.reload();
  // const pattern = /Loading chunk (\d)+ failed/g;
  // const isChunkLoadFailed = error.message.match(pattern);
  // const targetPath = router.history.pending.fullPath;
  // if(isChunkLoadFailed){
  // 		router.replace(targetPath);
  // }
});

/* ie11 router jump */
if (
  "-ms-scroll-limit" in document.documentElement.style &&
  "-ms-ime-align" in document.documentElement.style
) {
  // detect it's IE11
  window.addEventListener(
    "hashchange",
    function (event) {
      var currentPath = window.location.hash.slice(1);
      if (store.state.route.path !== currentPath) {
        router.push(currentPath);
      }
    },
    false
  );
}
