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 'element-ui/lib/theme-chalk/index.css';
import {mixins} from '@/mixins';  //引入混合
Vue.mixin(mixins);  //使用混合

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

//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';
// froala-editor 预览时的样式，如需使用在展示富文本的节点上加上 .fr-view 的类
import 'froala-editor/css/froala_style.min.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;

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'
// 公共样式
import './styles/index.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);

// 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
});

// 菜单mock
// import meundata from '@/assets/json/meundata.json';
// let data = JSON.stringify(meundata);
import {getUserUuid} from "./api/api";
router.beforeEach((to, from, next) => {
	// 判断本地是否有uuid
    const uuid=localStorage.getItem('uuid')
    if(!uuid){
      getUserUuid().then(res=>{
        if(res.Ret==200){
          localStorage.setItem('uuid',res.Data)
        }
      })
    }
	// let rddp_user_name=http.getCookie('rddp_user_name') || false;
	// let rddp_admin_access_token=http.getCookie('rddp_admin_access_token') || false;
	let auth = localStorage.getItem('auth') || false;
	if( to.path!='/login'&&to.path!='/temppage'&&(!auth)){
		window.location.href=process.env.Login;
		return false;
	}
	//面包屑
	if(to.meta.pathFrom && 
		['/customList','/customSearch','/approvalList','/potentialList','/pickList','/contractapprovallist','/contractmanagelist',
			'/expiringlist','/incrementalist','/stocklist','/chartJurisdiction','/readClassify','/contractlist','/incomelist','/newCustomlist',
		'/contractCustomlist'].includes(from.path)) {
		to.meta.pathFrom =  from.path.replace('/','')
		to.meta.pathName =  from.path == '/readClassify' ? '图库阅读统计' : from.name 
	} 
	if(to.path=='/customDetail'){
		if(from.matched[0]){
			to.matched[0].name=from.matched[0].name
		}
	}

	// 续约审批审批和补充协议审批
	if(to.path=='/approvalUpdate'&&to.query.ApplyMethod==6){
		to.matched[1].name='补充协议'
	}

	/* 沙盘详情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' ? '查看品种' : '分析品种';
	}

	/* 图库阅读统计 修改下级name */
	if(to.path === '/readClassify') {
		to.matched[1].name = to.query.name;
	}

	/* ETA试用 修改面包屑 */
	if(to.path==='/etaAddApproval'){
		to.matched[1].name = sessionStorage.getItem('applyInfo')?'重新申请':'新增申请'
	}
	/* 全量客户列表 修改面包屑 */
	if(to.path==='/customDetail'&&to.query.IsFullCompany==1){
		to.meta.pathName = '全量客户列表'
		to.meta.pathFrom = 'customAllList'
	}
	
	if( to.path ){
		 //百度统计
		if (window._hmt) {
			window._hmt.push(['_trackPageview', '/#' + to.fullPath])
		}
		next();
	}else{
		next({ path:'/404' });
	}
});

router.afterEach((to,from,next) => {
	// 改变页面标题
	document.title = to.matched[to.matched.length-1].name ?
									`弘则-${to.matched[to.matched.length-1].name}`:'弘则管理后台'
	window.scrollTo(0,0);
	// 或
	// window.scroll(0, 0);
 });

 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)
 }