/**
 * Created by jialiu on 17/1/11.
 */
import store from '../store';
import { isWechat, isApp } from './validation.service';
import Cookies from './cookieStorage.service';
import localStorage from './localStorage.service';

export default {
  // token校验，整个流程都是登陆后的
  init: router => {
    router.beforeEach((to, from, next) => {
      // 所有自定义路由字段在此处理
      const { meta } = to;
      isWechat && localStorage.set('vccChannel', '159913');
      meta?.has?.header && store.commit('CHANGE_HEADER', meta.has.header); // 改变header
      const localParams = ['token', 'redirectUrl'];
      const cookieParams = ['h', 'vccToken', 'vccChannel', 'sonVccChannel'];
      // TODO: 类似逻辑可以整合
      localParams.forEach(item => {
        const value = to.query[item];
        if (item === 'token' && value === '') {
          localStorage.remove('token');
        }
        if (value && value !== '{token}' && value !== '{vccToken}') {
          localStorage.set(item, value);
        }
      });
      Cookies.remove('ka');
      Cookies.remove('sonVccChannel');
      cookieParams.forEach(item => {
        const value = to.query[item];
        if (item === 'vccToken' && value === '') {
          Cookies.remove('vccToken');
        }
        if (value && value !== '{vccToken}' && value !== '{token}') {
          Cookies.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();
    });
  }
};
