import fetch from 'dva/fetch';
import router from 'umi/router';
import moment from 'moment';
import FormdataWrapper from '@/webPublic/zyd_public/utils/object-to-formdata-custom';
import { isJSON, controlNotification, getIsBei_Dian } from '@/webPublic/zyd_public/utils/utils';
import config from '@/config/config';
import apiConfig from './apiSystemConfig';
import { omit } from 'lodash';
import qs  from 'qs';
import { queryIsSafe } from '@/webPublic/one_stop_public/utils/queryConfig';
import { uaaRequest } from '@/webPublic/one_stop_public/utils/request';
import { getToken, setToken, setFetchUrl, getFetchUrl, getType  } from '@/webPublic/one_stop_public/utils/token';

const codeMessage = {
  200: '服务器成功返回请求的数据。',
  201: '新建或修改数据成功。',
  202: '一个请求已经进入后台排队（异步任务）。',
  204: '删除数据成功。',
  400: '发出的请求有错误，服务器没有进行新建或修改数据的操作。',
  401: '登录已过期,请重新登录',
  403: '用户得到授权，但是访问是被禁止的。',
  404: '发出的请求针对的是不存在的记录，服务器没有进行操作。',
  406: '请求的格式不可得。',
  410: '请求的资源被永久删除，且不会再得到的。',
  422: '当创建一个对象时，发生一个验证错误。',
  500: '服务器发生错误，请检查服务器。',
  502: '网关错误。',
  503: '服务不可用，服务器暂时过载或维护。',
  504: '网关超时。',
};

const checkStatus = response => {
  if (response.status !== 401) {
    return response;
  }
  const errortext = codeMessage[response.status] || response.statusText;
  const token = getToken();
  if (token && token !== 'null') {

    controlNotification({
      message: `${response.status === 401 ? '登录过期' : '请求错误'}`,
      description: errortext,
    });
  }
  if (response.status === 401) {
    setToken(null);
    if(window.top != window.self){
      window.top.postMessage("returnLogin", '*'); // Iframe 返回登录页
      return true;
    }
  }
  const error = new Error(errortext);
  error.name = response.status;
  error.response = response;
  throw error;
};

const cachedSave = (response, hashcode) => {
  /**
   * Clone a response data and store it in sessionStorage
   * Does not support data other than json, Cache only json
   */
  const contentType = response.headers.get('Content-Type');
  if (contentType && contentType.match(/application\/json/i)) {
    // All data is saved as text
    response
      .clone()
      .text()
      .then(content => {
        sessionStorage.setItem(hashcode, content);
        sessionStorage.setItem(`${hashcode}:timestamp`, Date.now());
      });
  }
  return response;
};

async function queryDemo() {
  return false;
}

function setFetchInfo(url, options) {
  let session = getFetchUrl();
  if (isJSON(session)) {
    session = JSON.parse(session);
    if (session.url === url && moment().valueOf() - session.time < 500) {
      if (options.body && JSON.stringify(options.body) === session.body) {
        console.log('频繁调用接口: ', url);
        return false;
      }
    }
  }

  return JSON.stringify({
    url,
    time: moment().valueOf(),
    body: options.body ? JSON.stringify(options.body) : '',
  });
}

/**
 * Requests a URL, returning a promise.
 *
 * @param  {string} url       The URL we want to request
 * @param  {object} [options] The options we want to pass to "fetch"
 * @return {object}           An object containing either "data" or "err"
 */
export default function request(
  url,
  options = {},
) {

  if (url && url.indexOf('/CmsApi/') > -1 && queryIsSafe() && url.indexOf('/CmsApi/getExportInfo') <= -1) {
    url = url.replace(config.httpServer, '');
    return uaaRequest(url, options.body);
  }
  if(process.env.NODE_ENV === 'development' && getIsBei_Dian()){
    url = url.replace('https://yx.bpi.edu.cn/produce', 'http://localhost:8010/produce');
  }

  let sessionFetch = setFetchInfo(url, options);
  if (!sessionFetch) {
    return queryDemo();
  } else {
    setFetchUrl(sessionFetch);
  }
  let defaultToken = getToken();
  const token = defaultToken !== null && defaultToken !== 'null' ? defaultToken : '';
  if(url.indexOf('oauthPub=true') <= -1 && url.indexOf('uia/logout') <= -1){
    if(url.indexOf('?') > -1){
      url = url + '&token=' +  (process.env.NODE_ENV === 'development' ? token : '');
    }else{
      url = url + '?token=' +  (process.env.NODE_ENV === 'development' ? token : '');
    }
  }

  if (options.time) {
    const time = new Date().getTime();
    if (url.indexOf('?') === -1) {
      url = url + '?time=' + time;
    } else {
      url = url + '&time=' + time;
    }
  }

  const defaultOptions = {
    credentials: 'omit',
    // credentials: 'include',
    mode: 'cors',
  };
  let newOptions = { ...defaultOptions, ...options };
  if (newOptions.method === 'POST' ||
    newOptions.method === 'PUT' ||
    newOptions.method === 'DELETE') {
    if (!(newOptions.body instanceof FormData)) {
      newOptions.headers = {
        Accept: 'application/json',
        ...newOptions.headers,
        Authorization: `bearer ${token}`,
      };
      newOptions.body = FormdataWrapper(newOptions.body);
    } else {
      // newOptions.body is FormData
      newOptions.headers = {
        Accept: 'application/json',
        'Content-Type': 'multipart/form-data',
        ...newOptions.headers,
        Authorization: `bearer ${token}`,
      };
    }
  }
  if (newOptions.method === 'GET') {
    url = url + '&' + qs.stringify(newOptions.body || {});
    newOptions = omit(newOptions, 'body');
  }

  if(!token || token === 'null' || url.indexOf('uia/logout') > -1){
    delete newOptions.headers.Authorization;
  }

  // console.log({
  //   url,
  //   newOptions,
  // })

  return fetch(url, newOptions)
    .then(checkStatus)
    //.then(response => cachedSave(response, hashcode))
    .then(response => {
      if (response.status !== 200) {
        return response.text();
      }
      return response.json();
    })
    .then(response => {
      if (typeof response == 'string') {
        try {
          const xxx = JSON.parse(response);
          if(xxx.status === 404){
            controlNotification({
              message: '接口异常',
            });
            return null;
          }
          if (xxx.errMsg || xxx.message) {
            controlNotification({
              //message: '',
              message: xxx.errMsg || xxx.message,
            });
            return null;
          }
          return xxx;
        } catch (e) {
          return response;
        }
      }
      return response;
    })
    .catch(e => {

      const status = e.name;
      if (status === 401) {

        if(window.top != window.self){
          window.top.postMessage("returnLogin", '*'); // Iframe 返回登录页
          return true;
        }
        // @HACK
        /* eslint-disable no-underscore-dangle */
        window.g_app._store.dispatch({
          type: 'login/logout',
        });
        return false;
      }
      // environment should not be used
      if (status === 403) {
        router.push('/exception/403');
        return false;
      }
      if (status <= 504 && status >= 500) {
        router.push('/exception/500');
        return false;
      }
      if (status >= 404 && status < 422) {
        router.push('/exception/404');
      }



      let systemName = '学工系统';
      let type = getType();
      if (url.indexOf('/v1/api/zydxgWeb/') > -1 && type) {
        let reg = new RegExp('/', 'g');
        type = type && type.replace(reg, '');
        systemName = config.systems[type] && config.systems[type].name || systemName;
      } else {
        let findApiConfig = apiConfig.find((x) => {
          return url.indexOf(x.path) > -1;
        });
        systemName = findApiConfig && findApiConfig.name || '系统';
      }

      if(!window.navigator.onLine){
        return   controlNotification({
          message: '网络故障',
          description: `${systemName}无法连接到网络,请稍后再试`,
        });
      }
      controlNotification({
        message: '网络故障',
        description: `${systemName}无法连接到服务器,请稍后再试`,
      });
      if(window.top != window.self){
        window.top.postMessage("returnLogin", '*'); // Iframe 返回登录页
        return true;
      }
      return;
    });
}
