import config from '../config/index';
import { ElMessage, ElLoading } from 'element-plus';
let loading = undefined;
const origins = location.href.split('#');

function ajax(longRange) {
  return new Promise((resolve, reject) => {
    var xhttp,
      url = config.base[longRange.base || 'origin'] + longRange.api;
    if (window.XMLHttpRequest) xhttp = new XMLHttpRequest();
    else if (window.ActiveXObject)
      xhttp = new window.ActiveXObject('Microsoft.XMLHTTP');
    var method = (longRange.method || 'GET').toUpperCase();
    if (method === 'GET') url += getdata(longRange.data || {});
    xhttp.open(method, url, true);
    //   添加头部
    var headers = headerFunc(longRange.headers);
    for (const key in headers) {
      if (!Object.hasOwnProperty.call(headers, key)) continue;
      xhttp.setRequestHeader(key, headers[key]);
    }
    // 添加body
    xhttp.send(method !== 'GET' ? bodyFunc(longRange.data) : '');

    xhttp.onreadystatechange = function () {
      if (this.readyState !== 4) return;
      !longRange.noload && loading.close();
      var data = JSON.parse(this.responseText || '{}');
      if (this.status !== 200) {
        // 网络错误
        errorStatus({ ...data, status: this.status });
        return reject({ ...data, status: this.status });
      }

      if (longRange.noJY) return resolve(data);

      if (!longRange.platfrom && data.code !== 0) {
        // 业务错误
        if (data.code === 40001) noLogin();
        errorStatus({ ...data, status: this.status });
        return reject({ ...data, status: this.status });
      }

      const res = longRange.platfrom ? data || {} : data.data;
      return resolve(res);
    };
  });
}

function fetch(longRange) {
  return new Promise((resolve, reject) => {
    const met = (longRange.method || 'GET').toUpperCase();
    const p = {
      method: met,
      //   mode: 'no-cors',
      headers: headerFunc(longRange.headers),
    };
    if (met !== 'GET') p.body = bodyFunc(longRange.data);
    else longRange.api = longRange.api + bodyGetFunc(longRange.data);

    window
      .fetch(config.base[longRange.base || 'origin'] + longRange.api, p)
      .then(res => {
        const json = res.json();
        if (res.status !== 200) {
          // 网络错误
          errorStatus(res);
          return reject(res);
        }
        return json;
      })
      .then(res => {
        !longRange.noload && loading.close();
        if (longRange.noJY) return resolve(res);
        if (!longRange.platfrom && res.code !== 0) {
          // 业务错误
          if (res.code === 40001) noLogin();
          errorStatus(res);
          return reject(res);
        }

        const Data = longRange.platfrom ? res || {} : res.data;
        return resolve(Data);
      });
  });
}

function getdata(data) {
  let text = '';
  for (const key in data) {
    text += key + '=' + data[key] + '&';
  }
  text ? (text = '?' + text) : '';
  text = text.replace(/&$/, '');
  return text;
}

function errorStatus(err) {
  if (err.status && err.status !== 200) {
    return ElMessage({
      type: 'error',
      message: err.error || '请稍后再试！',
    });
  }
  if (err.code !== 0) {
    return ElMessage({
      type: 'error',
      message: err.message || '请稍后再试',
    });
  }
}

/**
 * 未登录跳转
 */
function noLogin(api = '#/login') {
  if (location.replace) location.replace(origins[0] + api);
  else location.href = origins[0] + api;
}

function bodyGetFunc(body = {}) {
  let search = '?';
  for (const key in body) {
    if (!Object.hasOwnProperty.call(body, key)) continue;
    search += key + '=' + body[key] + '&';
  }
  if (search === '?') return '';
  return search;
}

function bodyFunc(body = {}) {
  const bodys = {};
  return JSON.stringify({
    ...bodys,
    ...body,
  });
}

function headerFunc(headers = {}) {
  const head = {
    'Content-Type': 'application/json',
  };
  return {
    ...head,
    ...headers,
  };
}

export default function (longRange) {
  !longRange.noload &&
    (loading = ElLoading.service({
      lock: true,
      text: 'Loading',
      background: 'rgba(0, 0, 0, 0.1)',
    }));
  if (longRange.type !== 'ajax' && window.fetch) return fetch(longRange);
  return ajax(longRange);
}
