import Vue from 'vue'
import App from './App.vue'
import axios from 'axios'
import {router} from './router'
import store from './store/store'
import filters from './filters'
import directive from './directive'
import md5 from 'js-md5'
import {services as Services} from './api/index'
import Util from './util/index'
import Vconsole from 'vconsole'

//本地环境开启提示信息
Vue.config.productionTip = false;
const env = process.env.NODE_ENV;
if (env != 'production') {
  let vConsole = new Vconsole()
}

//css全局加载
import 'vant/lib/index.css';
import '@/assets/css/global.min.css'

//过滤器遍历
Object.keys(filters).forEach(key => Vue.filter(key, filters[key]));

//自定义指令
Vue.use(directive);

//设置请求头
var csrf = Util.getCookie('Yo4teW_csrf') || ''; //解决接口返回系统错误问题
Vue.prototype.$http = axios;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
axios.defaults.withCredentials = true;
axios.interceptors.request.use(function (config) {
  if (config.method == 'post') {
    if (config.data) {
      if (config.data.indexOf("&pf=2") == -1) {
        config.data += "&pf=" + window.lxpf + '&csrf=' + csrf;
      }
    } else {
      config.data = "pf=" + window.lxpf + '&csrf=' + csrf;
    }
  } else if (config.method == 'get') {
    let paramsArr = Object.keys(config.params);
    if (paramsArr.length) {
      if (paramsArr.indexOf('pf') == -1) {
        config.params = {
          pf: window.lxpf,
          csrf: csrf,
          ...config.params
        }
      }
    } else {
      config.params = {
        pf: window.lxpf,
        csrf: csrf
      }
    }
  }
  return config;
}, function (error) {
  return Promise.reject(error);
});


//本地初始化uid
var Yo4teW_gid = Util.getCookie('Yo4teW_gid');
var timestmp = new Date().getTime()+Math.random();
if (Yo4teW_gid == null) {
  // var mdStr = md5(timestmp);
  // Util.setCookie('Yo4teW_gid', mdStr, 1, window.cookieHostname);
}

//微信授权
var params = {
  urlhash: window.location.hash
};
params = Util.getParams(params);
Services.wxaccess(params).then((res) => {
  let data = res.data;
  if (data.err_code == 0 && data.data) {
    window.location.href = data.data;
  }
});

//路由页面回跳处理  mate里面参数 back:true 开启登录态回跳
router.beforeEach((to, from, next) => {
  const title = to.meta && to.meta.title;
  if (title) {
    document.title = title;
  }
  //页面回跳
  var backurl_g = to.meta.back || "";
  if (backurl_g) {
    var loginpta = Util.isLogin() ? true : false;
    if (!loginpta) {
      window.location.href = '/v3/login?referer=' + encodeURIComponent(window.location.href);
    } else {
      next();
    }
  } else {
    next();
  }
});

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