import HttpRequest from '@qg/ui-request';
import { Toast } from '@qg/cherry-ui';
import store from '@/store';
import { appVersion, isApp, isWxMp } from '@/service/validation.service';
import { getVccChannel } from './userInfo.service';
import localStorage from '@/service/localStorage.service';
import sessionStorage from '@/service/sessionStorage.service';
import MpBridge from '@/service/mp';
import Bridge from '@qg/js-bridge';

function getURLSearchParams(json) {
  if (!json) return '';
  const dataArray = Object.keys(json).map(key => {
    if (json[key] === undefined) return '';
    return encodeURIComponent(key) + '=' + encodeURIComponent(json[key]);
  });
  return dataArray.filter(item => item !== undefined && item !== null).join('&');
}

const http = new HttpRequest(
  {
    groupBuy: {
      response(res) {
        const { data, config } = res;
        const returnRawData = config.rawData;
        if (returnRawData) return [data, null];
        // if (data.businessCode === '401' || data.businessCode === '0401') {
        //   // router.push({ name: 'login' });
        //   window.localStorage.removeItem('vccToken');
        //   window.sessionStorage.removeItem('vccToken');
        // }
        const success =
          (data.code === '0000' && data.businessCode === '0000') || data.business_code === 0;
        if (success) {
          return [data.data, null];
        }
        const msg = data.msg || '服务异常';
        if (!config.hideToast || !data.noAlert) {
          Toast(msg);
        }
        let error = new Error(msg);
        error.response = data;
        if (
          error?.response?.businessCode === '6049' ||
          error?.response?.businessCode === '401' ||
          error?.response?.businessCode === '0401'
        ) {
          localStorage.remove('vccToken');
          sessionStorage.remove('vccToken');
          if (isApp) {
            const nativeBridge = new Bridge();
            window.xyqbNativeEvent = function(res) {
              const json = typeof res === 'string' ? JSON.parse(res) : res;
              if (json.event === 'getTokenSuccess') {
                const appData = json.data || {};
                if (appData && appData.token) {
                  localStorage.set('vccToken', appData.token);
                  sessionStorage.set('vccToken', appData.token);
                  setTimeout(() => {
                    window.location.reload();
                  }, 500);
                }
              }
            };
            nativeBridge.getToken();
          }
          if (isWxMp) {
            const nativeBridge = new MpBridge();
            nativeBridge.getToken({
              clear: 1
            });
          }
        }

        console.error(error);
        return [null, error];
      },
      request(cfg) {
        const { method } = cfg;
        cfg.headers['X-Auth-Token'] = localStorage.get('vccToken') || '';
        if (cfg.customHeader) {
          Object.assign(cfg.headers, cfg.customHeader);
        }
        cfg.headers['x-user-terminal'] = isWxMp ? 'MINI-APP' : 'H5';
        cfg.headers['vccChannel'] = getVccChannel();
        cfg.headers['sonVccChannel'] = getVccChannel('sonVccChannel');
        if (method === 'post' && cfg.emulateJSON) {
          cfg.headers['Content-Type'] = 'application/x-www-form-urlencoded';
          cfg.data = getURLSearchParams(cfg.data);
        }
        return cfg;
      }
    }
  },
  {
    strategy: 'groupBuy',
    headers: {
      'x-user-terminal': isWxMp ? 'MINI-APP' : 'H5',
      version: appVersion || '7900'
    }
  },
  function(msg) {
    Toast(msg);
  },
  function(loadingState) {
    store.dispatch('change_loading', loadingState);
  }
).getInstance();
export default http;
