/**
 * request 网络请求工具
 * 更详细的 api 文档: https://github.com/umijs/umi-request
 */
import { extend } from 'umi-request';
import { notification, message } from 'antd';
import { getToken, getVersion } from './token';
import {
  queryApiActionPath,
  queryOauthActionPath,
  queryPermActionPath,
  queryDynamicActionPath, queryUiaApi,
} from './queryConfig';
import { openToast } from '../location/Notification';
import { showToast } from '../location/Toast';
import { offline } from '../location/Toast';
import { giveBase16EnCode, requestFileInfo } from '@/webPublic/one_stop_public/Base16';
import objectToFormData from '@/webPublic/zyd_public/utils/object-to-formdata-custom';
import { getUrlInfo } from '@/webPublic/one_stop_public/DetailForAudit/utils';
import { getHeaders, getIsBei_Dian } from '@/webPublic/zyd_public/utils/utils';
import { proxyChangeUrl } from '@/webPublic/zyd_public/request/proxyChangeUrl';
import { getTransformApi } from '@/webPublic/one_stop_public/2022beidianke/localstorageTransform';
import { getVisitorToken } from '@/webPublic/zyd_public/utils/getHeaders';
import { getCacheData, saveCacheData } from '@/webPublic/one_stop_public/utils/apiServiceCache';
import { filterSearchParams } from "@/webPublic/one_stop_public/utils/utils";

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参数字符串
 */
let time = new Date().getTime();

export const qqCw = ({
                       title = '请求错误',
                       msg = '',
                       customErrMsg = '',
                     }) => {
  let nowX = new Date().getTime() - time;
  if (nowX < 3000) {
    return false;
  }
  time = new Date().getTime();
  // 请求错误 增加自定义错误提示信息 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: 'include', // 默认请求是否带上cookie
  //  2023年11月28日 顺哥说的 延职 要传成 include;
  mode: 'cors',
});

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

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

const requestA = (url, data, options = {}) => {
  // window.CONFIG.IS_SAFE = false;
  return giveBase16EnCode(data, url)
    .then((newData) => {
      if (typeof newData === 'object' && newData.url && newData.datas) {
        return requestFileInfo(newData.url, newData.datas);
      }
      return requestOrigin(url, newData, options);
    });
};

export async function request(url, data, options = {}) {
  data = filterSearchParams(data);
  if (localStorage.getItem('errDetail') === '1') { // 调试模式关闭加密
    window.CONFIG.IS_SAFE = false;
    window.CONFIG.IS_BINARY = false;
    window.CONFIG.ALLBIN = false;
    if(typeof data === 'object' && data){
      data.errDetail = true; // 欢哥 2023年3月27日 说的 加了这个参数就能开启调试模式 输出日志
    }
  }
  let cacheData = await getCacheData(url, data); // 读接口缓存
  if(cacheData){
    return cacheData;
  }
  const response = await requestA(url, data, options);
  saveCacheData(url, data, response); // 写接口缓存
  return response;
}



export async function requestOrigin(url, data, options = {
  credentials: 'include',
}){
  let version = getVersion();
  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)
    // GET请求
    return umiRequest(url, {
      data: pp,
      // method: "POST",

      requestType: 'form',
      credentials: 'include',
      ...getHeaders(url),
      ...options,

    })
      .then(response => {
        if (response && response.errMsg) {
          response.errMsg = response.errMsg.slice(0, 50);
        }
        if (response.errCode && response.errCode == '10000') {
          return false;
          // 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 = {
      token: getVisitorToken(), // 部分接口 只需要传入假token 所以这里优先级是 data中的token > getToken;
      ...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();
      }
    }

    // 由于自动添加前缀 这里暂时修改getUrl(url)
    let fetchRequest = url.indexOf('UserApi/login') > -1 ? loginUmiRequest : umiRequest;

    // if (getToken()) {
      options.headers = getHeaders(url).headers;
    // }
    let trueUrl = (options.prefix || '') + url;
    const { transformApi, headersApi } = await getTransformApi(trueUrl);
    if(getIsBei_Dian()){
      if(options.headers){
        options.headers = {
          ...options.headers,
          // apis: headersApi,
        };
      }
    }

    delete options.prefix;
    // POST请求
    return fetchRequest(transformApi, {
      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') {
          return false;
          // 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 && (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 noPrefixRequest = createServerRequest({
  method: 'POST',
  prefix: '',
  credentials: 'include',
  mode: 'cors',
});


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 const getUiaRequest = (data) => { // 2.0的登录接口
  return fetch(queryUiaApi() + '/oauth/token', {
    credentials: 'include',
    mode: 'cors',
    headers: {
      Accept: 'application/json',
      // 'Content-Type': 'multipart/form-data',
    },
    method: 'POST',
    body: objectToFormData(data),
  })
    .then(response => {
      return response.json();
    })
    .then((g) => {
      if (g && g.access_token) {
        g.token = g.access_token;
        return g;
      } else {
        if (g && g.message) {
          message.warn(g.message);
        }
        return false;
      }
    });
};


// export const testGetUiaRequest = (data) => { // 2.0的登录接口
//   return fetch('http://scjoyedu.eicp.net:7180/ocr/api/diff', {
//     credentials: 'omit',
//     mode: 'cors',
//     headers:{
//       Accept: 'application/json',
//       // 'Content-Type': 'multipart/form-data',
//     },
//     method: 'POST',
//     body: objectToFormData({right: '123', left: '456'}),
//   }).then(response => {
//     return response.json();
//   }).then((g) => {
//     if(g && g.access_token){
//       g.token = g.access_token;
//       return g;
//     }else{
//       if(g && g.message){
//         message.warn(g.message);
//       }
//       return false;
//     }
//   })
// }

export default request;
