/**
 * Created by jialiu on 17/1/11.
 */
import store from '../store';
import { isWechat, isApp, isAndroid, isIOS } from './validation.service';
import Cookies from './cookieStorage.service';
import localStorage from './localStorage.service';
import sessionStorage from './sessionStorage.service';
// import { Toast } from '@qg/cherry-ui';

export default {
  // token校验，整个流程都是登陆后的
  init: router => {
    router.beforeEach((to, from, next) => {
      Cookies.set('h', 0);
      const query = JSON.parse(JSON.stringify(to.query));
      if (Object.keys(query).indexOf('vccToken') == -1) {
        to.query.vccToken = sessionStorage.get('vccToken') || '';
      }
      // console.log(to.query, 1);
      // 所有自定义路由字段在此处理
      const { meta } = to;
      isWechat && localStorage.set('vccChannel', '159913');
      isIOS && localStorage.set('vccChannel', '214');
      isAndroid && localStorage.set('vccChannel', '217');
      meta?.has?.header && store.commit('CHANGE_HEADER', meta.has.header); // 改变header
      const localParams = ['redirectUrl', 'h', 'vccToken', 'vccChannel', 'sonVccChannel'];
      // TODO: 类似逻辑可以整合
      localParams.forEach(item => {
        const value = to.query[item];
        if (item === 'vccToken' && value === '') {
          localStorage.remove('vccToken');
          sessionStorage.remove(item);
        }
        if (value && value !== '{token}' && value !== '{vccToken}') {
          localStorage.set(item, value);
          sessionStorage.set(item, value);
        }
      });
      (isWechat || isApp || Cookies.get('h') === '0') && store.commit('CHANGE_HEADER', false); // 改变header
      document.body.className = store.state.pay.header ? 'has-header' : '';
      store.commit('CHANGE_TITLE', meta?.title); // 改变title

      next();
    });
  }
};
