import { Http } from '../../lib/http/index';
import UserLogin from '../login';
import urlMap from './urlMap';

function isString (o) {
  // 是否字符串
  return Object.prototype.toString.call(o).slice(8, -1) === 'String';
}

class MyHttp extends Http {
  constructor () {
    super();
    this.init();
    this.urlMap = urlMap;
    this.instance = null;
  }

  static getInstance () {
    if (!this.instance) {
      this.instance = new MyHttp();
    }
    return this.instance;
  }
  init () {
    this.interceptor = {
      before: _config => {
        // 该请求是否需要登录
        if (_config.needLogin) {
          if (!UserLogin.checkIfLogin()) {
            return false;
          }
          let _token = UserLogin.getToken();
          if (_token) {
            _config['header']['token'] = _token;
            _config.url = this.addToken(_config.url, _token);
          } else {
            return false;
          }
        }

        return _config;
      },
      after: res => {
        // TODO 处理如果返回未登录的情况
        let statusCode = res.statusCode;
        if (statusCode === 401) {
          UserLogin.logout();
          UserLogin.showLoginTips();
        }

        if (res.data && res.data.code === 0) {
          if (isString(res.data.msg)) {
            uni.showToast({
              icon: 'none',
              title: (res.data.msg && res.data.msg.toString()),
              duration: 3000
            });
          } else {
            uni.showToast({
              icon: 'none',
              title: '错误'
            });
          }
        }
        return res;
      }
    };
  }
  // 通用的post请求
  post (params) {
    return super.post(params);
  }
  // 通用的get请求
  get (params) {
    return super.get(params);
  }
  addToken (url, token) {
    if (url.indexOf('?') === -1) {
      url = `${url}?token=${token}`;
    } else {
      url = url.replace('?',
        `?token=${token}&`);
    }
    return url;
  }
}

let _myHttp = MyHttp.getInstance();
export default _myHttp;
