/**
 * request 网络请求工具
 * 更详细的 api 文档: https://github.com/umijs/umi-request
 */
import { extend } from 'umi-request';
import { notification } from 'antd';
import { getToken } from './token';
import {
  queryApiActionPath,
  queryOauthActionPath,
  queryPermActionPath,
  queryDynamicActionPath,
} from './queryConfig';
import { openToast } from '../location/Notification';
import { showToast } from '../location/Toast';
import { offline } from '../location/Toast';
import { giveBase16EnCode } from "@/webPublic/one_stop_public/Base16";

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

const qqCw = ({ title = '请求错误', msg = '', customErrMsg = '' }) => {
  // 请求错误 增加自定义错误提示信息 customErrMsg 从发起 接口那里自定义
  // 禅道bug 11794
  notification.error({
    message: title,
    description: customErrMsg || msg,
  });
  return undefined;
};

const objectToQuery = function(param, key, encode) {
  if (param == null) return '';
  var paramStr = '';
  var t = typeof param;
  if (t == 'string' || t == 'number' || t == 'boolean') {
    paramStr += '&' + key + '=' + (encode == null || encode ? encodeURIComponent(param) : param);
  } else {
    for (var i in param) {
      var k = key == null ? i : key + (param instanceof Array ? '[' + i + ']' : '.' + i);
      paramStr += objectToQuery(param[i], k, encode);
    }
  }
  return paramStr;
};
/**
 * 异常处理程序
 */
var canReportError = true;
const errorHandler = error => {
  const { response } = error;

  if (response && response.status) {
    const errorText = codeMessage[response.status] || response.statusText;
    qqCw({
      msg: errorText,
    });
    if (response.status === 401) {
      // @HACK
      /* eslint-disable no-underscore-dangle */
      if (window.location.href.indexOf('/portal/previewModule') !== -1) {
        return;
      }
      return window.g_app._store.dispatch({
        type: 'login/loginout',
      });
    }
  } else {
    if (canReportError) {
      notification.error({
        message: `网络故障`,
        description: '请检查网络链接或联系管理员',
      });
      canReportError = false;
    }
  }
};

/**
 * 配置request请求时的默认参数
 */

const umiRequest = extend({
  errorHandler, // 默认错误处理
  credentials: 'omit', // 默认请求是否带上cookie
  mode: 'cors',
});

const loginUmiRequest = extend({
  errorHandler, // 默认错误处理
  credentials: 'include', // 默认请求是否带上cookie
  // mode: 'cors',
});

const getUrl = url => (url.startsWith('/') ? url : '/' + url);

export const request = (url, data, options = {}) => {
    return giveBase16EnCode(data, url).then((newData) => {
      // console.log(newData);
     return requestOrigin(url, newData, options);
    });
}


export const requestOrigin = (url, data, options = {}) => {
  let version =
    localStorage.getItem('version') && localStorage.getItem('version') !== 'undefined'
      ? JSON.parse(localStorage.getItem('version'))
      : null;

  if (options.method === 'GET') {
    const pp = {
      ...data,
      version_: version,
    };
    for (let i in pp) {
      if (pp[i] == null) {
        delete pp[i];
      } else if (typeof pp[i] == 'string') {
        pp[i] = pp[i].trim();
      }
    }
    if (url.indexOf('?') !== -1) {
      url = url + '&token=' + getToken() + objectToQuery(pp);
    } else {
      url = url + '?token=' + getToken() + objectToQuery(pp);
    }
    // 由于自动添加前缀 这里暂时修改getUrl(url)
    return umiRequest(url, {
      data: pp,
      // method: "POST",

      requestType: 'form',
      ...options,
    })
      .then(response => {
      // console.log(response);
      if(response && response.errMsg){
        response.errMsg = response.errMsg.slice(0,50);
      }
      if (response.errCode && response.errCode == '10000') {
        const ul = window.location.href;
        if (ul.indexOf('timeVersion=') == -1) {
          let x = JSON.parse(response.errMsg);
          let time = +new Date();
          localStorage.setItem('version', JSON.stringify(x.version));

          if (ul.indexOf('/portal/') == -1 && ul.indexOf('/admin/') == -1) {
            sessionStorage.removeItem('cacheMobile');
            showToast('检查到最新版本，即将自动更新，更新完成后请重新操作');

            window.location.href = x.mobileAdress
              ? mobileAdress + '?timeVersion=' + time
              : ul.indexOf('?') > -1
              ? ul + '&timeVersion=' + time
              : ul + '?timeVersion=' + time;
          } else {
            sessionStorage.removeItem('cacheMobile');
            openToast('error', '版本更新', '检查到最新版本，即将自动更新，更新完成后请重新操作');

            window.location.href = x.webAdress
              ? x.webAdress + '?timeVersion=' + time
              : ul.indexOf('?') > -1
              ? ul + '&timeVersion=' + time
              : ul + '?timeVersion=' + time;
          }
          setTimeout(() => location.reload(), 3000);
        }

        return;
      }
      if (window.location.href.indexOf('/mobile') != -1) {
        if (response.errCode || response.errMsg) {
          offline(response.errMsg, 2);
          if (data.callback) data.callback(response);
          return;
        }
      }
      if (!response) return;

      if (response.errCode || response.errMsg) {
        qqCw({
          msg: response.errMsg,
          customErrMsg: pp.customErrMsg,
        });
        return;
      }
      if (response.errcode) {
        qqCw({
          msg: response.errmsg,
          customErrMsg: pp.customErrMsg,
        });
        return;
      }
      canReportError = true;
      return response;
    });
  } else {
    const pp = {
      ...data,
      token: getToken(),
      version_: version,
    };

    for (let i in pp) {
      if (pp[i] == null) {
        delete pp[i];
      } else if (typeof pp[i] == 'string') {
        pp[i] = pp[i].trim();
      }
    }

    // 由于自动添加前缀 这里暂时修改getUrl(url)
    let fetchRequest = url.indexOf('UserApi/login') > -1 ? loginUmiRequest : umiRequest;
    if (
      (window.location.href.indexOf('localhost') > -1 ||
        window.location.href.indexOf('172.32.2') > -1) &&
      url.indexOf('UserApi/login') > -1
    ) {
      // 开发环境直接免密登录 2021年11月25日
      fetchRequest = umiRequest;
      url = '/UserApi/loginByCount';
    }
    return fetchRequest(url, {
      data: pp,
      //    method: "POST",

      requestType: 'form',
      ...options,
    }).then(response => {
      if(response && response.errMsg){
        response.errMsg = response.errMsg.slice(0,30) + '...';
      }
      if (response && response.errCode && response.errCode == '10000') {
        const ul = window.location.href;
        if (ul.indexOf('timeVersion=') == -1) {
          let x = JSON.parse(response.errMsg);
          let time = +new Date();
          localStorage.setItem('version', JSON.stringify(x.version));

          if (ul.indexOf('/portal/') == -1 && ul.indexOf('/admin/') == -1) {
            sessionStorage.removeItem('cacheMobile');
            showToast('检查到最新版本，即将自动更新，更新完成后请重新操作');
            window.location.href = x.mobileAdress
              ? mobileAdress + '?timeVersion=' + time
              : ul.indexOf('?') > -1
              ? ul + '&timeVersion=' + time
              : ul + '?timeVersion=' + time;
          } else {
            sessionStorage.removeItem('cacheMobile');
            openToast('error', '版本更新', '检查到最新版本，即将自动更新，更新完成后请重新操作');

            window.location.href = x.webAdress
              ? x.webAdress + '?timeVersion=' + time
              : ul.indexOf('?') > -1
              ? ul + '&timeVersion=' + time
              : ul + '?timeVersion=' + time;
          }
          setTimeout(() => location.reload(), 3000);
        }
        return;
      }
      if (window.location.href.indexOf('/mobile') != -1) {
        if (response.errCode || response.errMsg) {
          offline(response.errMsg, 2);
          if (data.callback) data.callback(response);
          return;
        }
      }
      if (!response) return;

      if (response.errCode || response.errMsg) {
        qqCw({
          msg: response.errMsg,
          customErrMsg: pp.customErrMsg,
        });
        return;
      }
      if (response.errcode) {
        qqCw({
          msg: response.errmsg,
          customErrMsg: pp.customErrMsg,
        });
        return;
      }
      canReportError = true;
      return response;
    });
  }
};

const setRequestConfig = config => {

  return (url, data, options = {}) => {
    if (Array.isArray(url)) {
      return Promise.all(
        url.map(ags => {
          return request(ags[0], ags[1], Object.assign({}, ags[2], config));
        }),
      );
    }
    return request(url, data, { ...options, ...config });
  };
};

const createServerRequest = (config = {}) => {
  return setRequestConfig(config);
};

export const dynamicRequest = createServerRequest({
  method: 'POST',
  prefix: queryDynamicActionPath(),
});

export const uaaRequest = createServerRequest({
  method: 'POST',
  prefix: queryOauthActionPath(),
});

export const permRequest = createServerRequest({
  method: 'POST',
  prefix: queryPermActionPath(),
});

export const apiRequest = createServerRequest({
  method: 'POST',
  prefix: queryApiActionPath(),
});

export const getRequest = createServerRequest({
  method: 'GET',
  prefix: queryApiActionPath(),
});

export default request;
