/* eslint-disable prettier/prettier */
import HttpRequest from '@qg/ui-request';
import { Toast } from '@qg/cherry-ui';

import allCfg from '@/config';
import store from '@/store';
import router from '@/router';
import localStorage from './localStorage.service';
import { getVccChannel, getUid, getTc } from './userInfo.service';
import { getPublicConfig } from '@/customize';
import { isApp, isWxMp, isAndroid } from './validation.service';
import wx from 'weixin-js-sdk';

const http = new HttpRequest(
  {
    tob: {
      response(res) {
        const { data, config } = res;
        const returnRawData = config.rawData;
        if (returnRawData) return [data, null];
        if (data.businessCode === '401' || data.businessCode === '0401') {
          if (isApp) {
            // 羊小咩打开礼品卡禁止弹出请重新打开APP弹窗
            // TODO 目前只对小程序token失效做了处理，app后续按需添加，具体实现方式可参考
            // http://git.quantgroup.cn/ui/quantum-block-h5/blob/master/app/web/component/layout/activity/index.ts#L47
            return;
          }
          if (isWxMp) {
            wx.miniProgram.navigateTo({
              url: `/pages/webview/middleWay?event=getToken&clear=true`
            });
            return;
          }
          const publicConfig = getPublicConfig();
          publicConfig.signOutFn();
          return;
        }
        const success =
          (data.code === '0000' && data.businessCode === '0000') || data.business_code === 0;

        if (success) {
          return [data.data, null];
        }
        const msg = data.msg || '服务异常';
        const hasNoAlert = typeof data?.noAlert !== 'undefined'; // 查看接口返回数据是否存在noAlert
        if (!config.hideToast || (hasNoAlert && !data.noAlert)) {
          Toast(msg);
        }
        let error = new Error(msg);
        error.response = data;
        console.error(error);
        return [null, error];
      },
      request(cfg) {
        const publicConfig = getPublicConfig();

        if (!cfg.hideVccChannel) {
          cfg.headers['vccChannel'] = getVccChannel() || publicConfig.vccChannel || '';
          cfg.headers['sonVccChannel'] = getVccChannel('sonVccChannel') || '';
        }
        cfg.headers['qg-tenant-id'] = store?.getters?.tenantId || 560761;

        if (publicConfig.flw) {
          cfg.headers['uid'] = getUid();
          cfg.headers['tc'] = getTc();
        }

        cfg.headers['version'] = allCfg.VERSION;
        cfg.headers['X-Auth-Token'] = localStorage.get('vccToken') || '';
        let terminal =''
        if (isApp) {
          terminal = isAndroid ? 'ANDROID' : 'IOS';
        } else if (isWxMp) {
          terminal = 'MINI-APP';
        } else {
          terminal = 'H5';
        }
        cfg.headers['x-user-terminal'] = terminal;
        // cfg.headers['x-user-terminal'] = 'IOS';
        // cfg.headers['appchannel'] = 'AppStore';
        // cfg.headers['vccChannel'] = '214'
        cfg.headers = { ...cfg.headers, ...cfg.customHeader };
        return cfg;
      }
    },
    promotion: {
      // 地推工具专用
      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: 'PromotionLogin' });
        }
        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;
        return [null, error];
      },
      request(cfg) {
        if (!cfg.hideVccChannel) {
          cfg.headers['vccChannel'] = getVccChannel() || '';
          cfg.headers['sonVccChannel'] = getVccChannel('sonVccChannel') || '';
        }
        cfg.headers['qg-tenant-id'] = '560867';
        cfg.headers['version'] = allCfg.VERSION;
        cfg.headers['group-push-auth-token'] = localStorage.get('promotionToken') || '';
        cfg.headers['x-user-terminal'] = allCfg.TERMINAL; //H5  MINI-APP
        cfg.headers = { ...cfg.headers, ...cfg.customHeader };
        return cfg;
      }
    }
  },
  {
    strategy: 'tob'
  },

  () => {},
  // eslint-disable-next-line space-before-function-paren
  function(loadingState) {
    store.dispatch('change_loading', loadingState);
  }
).getInstance();

export default http;
