/* eslint-disable prettier/prettier */
/* eslint-disable space-before-function-paren */
/**
 * Created by jialiu on 17/1/11.
 */
import store from '../store';
import { isWechat, isApp, isWxMp } from './validation.service';
import Cookies from './cookieStorage.service';
import localStorage from './localStorage.service';
import { sStorage } from './sessionStorage.service';
import { shouDemo } from '@/config/channel.config';
import { QG_TENANT_ID } from '@/store/type';
import { loadScript } from './utils.service';

//formXcxPage:标识是从小程序跳转过来的;
const localStorageParams = [
  'creditToken',
  'vccToken',
  'vccChannel',
  'sonVccChannel',
  'formXcxPage',
  'orderInfo',
  'uuid',
  'demoPhone',
  'tenantId',
  'token'
];
const cookiesParams = ['h', 'returnUrl', 'source', 'uid', 'agreed', 'tc'];
const sessionParams = [
  'adv_utm_campaign',
  'adv_utm_content',
  'adv_utm_medium',
  'adv_utm_source',
  'adv_utm_term',
  'vccToken'
];

export default {
  // token校验，整个流程都是登陆后的
  init: router => {
    router.beforeEach(async (to, from, next) => {
      try {
        const queryParamsKeys = Object.keys(to.query);
        if (queryParamsKeys.length) {
          for (let i = 0; i < queryParamsKeys.length; i++) {
            if (queryParamsKeys[i].toLowerCase() === 'offlinepath') {
              if (to.query[queryParamsKeys[i]] && to.path != to.query[queryParamsKeys[i]]) {
                const { offlinePath, ...otherQuery } = to.query;
                router.replace({
                  path: offlinePath,
                  query: otherQuery
                });
                return false;
              }
            }
          }
        }
      } catch (err) {
        console.log(err);
      }
      // 所有自定义路由字段在此处理
      const { meta } = to;
      if (meta.cdn) {
        if (Array.isArray(meta.cdn)) {
          for (let i = 0; i < meta.cdn.length; i++) {
            await loadScript(meta.cdn[i].url, meta.cdn[i].globalName);
          }
        } else {
          await loadScript(meta.cdn.url, meta.cdn.globalName);
        }
      }
      if (meta.cdns) {
        for (let i = 0; i < meta.cdns.length; i++) {
          await loadScript(meta.cdns[i]);
        }
      }
      meta?.has?.header && store.commit('CHANGE_HEADER', meta.has.header); // 改变header
      localStorageParams.forEach(item => {
        if (isApp || isWxMp) {
          localStorage.remove(item);
        }
        to.query[item] && localStorage.set(item, to.query[item]);
        if (to.query['token']) {
          localStorage.set('vccToken', to.query['token']);
        }
      });

      cookiesParams.forEach(item => {
        to.query[item] && Cookies.set(item, to.query[item]);
      });
      sessionParams.forEach(item => {
        to.query[item] && sStorage.setItem(item, to.query[item]);
      });
      (isWechat || isApp || Cookies.get('h') === '0') && store.commit('CHANGE_HEADER', false); // 改变header
      document.body.className = store.state.pay.header ? 'has-header' : '';
      document.body.className = store.state.pay.tabBar ? 'has-tab-bar' : '';
      store.commit('CHANGE_TITLE', meta?.title); // 改变title
      const HOME = 0;
      const MEMBER = 1;
      const CART = 2;
      const USER = 3;

      switch (to.name) {
        case 'Home':
          store.commit('CHANGE_TABBAR', true);
          store.commit('CHANGE_ROUTE_IDX', HOME);
          break;
        case 'Member':
          store.commit('CHANGE_TABBAR', true);
          store.commit('CHANGE_ROUTE_IDX', MEMBER);
          break;
        case 'Cart':
          store.commit('CHANGE_TABBAR', true);
          store.commit('CHANGE_ROUTE_IDX', CART);
          break;
        case 'User':
          store.commit('CHANGE_TABBAR', true);
          store.commit('CHANGE_ROUTE_IDX', USER);
          break;
        default:
          store.commit('CHANGE_TABBAR', false);
          break;
      }
      store.commit(QG_TENANT_ID, localStorage.get('tenantId'));
      // 针对安硕渠道的相关配置
      if (to.query['demoPhone'] || localStorage.get('demoPhone')) {
        store.commit('CHANGE_TABBAR', false);
      }
      if (to.query['demoPhone'] && !localStorage.get('vccToken')) {
        shouDemo(next);
      } else {
        next();
      }
    });
  }
};
