import { extend } from 'umi-request';
import { ElMessage, ElNotification } from 'element-plus';
const envMode=process.env.NODE_ENV;
const baseUrl = envMode == "development" ? "/mes" : "";
const codeMessage = {
  302: '重定向。',
  400: '发出的请求有错误，服务器没有进行新建或修改数据的操作。',
  401: '用户没有权限（令牌、用户名、密码错误）。',
  403: '用户没有得到授权，无法访问当前资源。',
  404: '发出的请求针对的是不存在的记录，服务器没有进行操作。',
  406: '请求的格式不可得。',
  410: '请求的资源被永久删除，且不会再得到的。',
  422: '当创建一个对象时，发生一个验证错误。',
  500: '服务器发生错误，请检查服务器。',
  502: '网关错误。',
  503: '服务不可用，服务器暂时过载或维护。',
  504: '网关超时。',
};

//清除所有cookie
function clearCookie() {
  var cookies = document.cookie.split(";");
  // 遍历所有的cookie并删除它们
  for (var i = 0; i < cookies.length; i++) {
    var cookie = cookies[i];
    var eqPos = cookie.indexOf("=");
    var name = eqPos > -1 ? cookie.substring(0, eqPos) : cookie;
    document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT";
  }
}

/**
 * 退出登录，并且将当前的 url 保存
 */
const loginOut = () => {
  // getFetch({ url: "/logout", params: {} }).then(res => {
  //   window.location.href = res?.logoutRedirectUrl;
  //   localStorage.clear();
  // })
};

const request = extend({
  credentials: 'include', // 默认请求是否带上cookie
});
// request拦截器, 改变url 或 options.
request.interceptors.request.use(async (url, options) => {
  let token = localStorage.getItem('TOKENES') ?? "", headers = {};
  if (envMode == "development" && url.indexOf("mesc") == -1 && token) {
    headers = options.type == 'form' ? {
      Authorization: "Bearer " + token
    } : {
      'Content-Type': 'application/json',
      Accept: 'application/json',
      Authorization: "Bearer " + token
    }
  } else {
    headers = options.type == 'form' ? {} : {
      'Content-Type': 'application/json',
      Accept: 'application/json'
    }
  }
  return {
    url: url.indexOf("mesc") > -1 ? envMode == "development" ? url : url.slice(4) : baseUrl + url,
    options: { ...options, headers: headers },
  };
});

// response拦截器, 处理response 错误提示&&权限拦截
request.interceptors.response.use(async (response, options) => {
  var reg = new RegExp(".*idp.*nangaoyun.com.*");
  if (response && response.status) {
    const errorText = codeMessage[response.status] || response.statusText;
    const { status, url } = response;
    if (response?.url.indexOf('api/user_token') == -1 && Object.keys(codeMessage).indexOf(String(response.status)) > -1) {
      ElNotification({
        message: errorText,
        type: 'error',
      });
    }
    if (status == "401") {
      clearCookie();
    }
    if (status == "401" || status == "302") {
      // loginOut();
      window.location.href = "/";
    }
    if (reg.exec(url) && reg.exec(url)?.length > 0 && status == 200) {
      window.location.href = url;
    }
  } else if (!response) {
    if (response?.url.indexOf('api/user_token') == -1) {
      ElNotification({
        title: '网络异常',
        message: '您的网络发生异常，无法连接服务器',
        type: 'error',
      });
    }
  }
  try {
    if (options.responseType == 'blob') {
      //下载blob
      const data = await response.clone().blob();
      if (data.type == 'application/octet-stream') {
        const a = document.createElement('a');
        a.style.display = 'none';
        let temp = response.headers.get('Content-Disposition').split(';')[1].split('=')[1] || '';
        let fileDefaultName = decodeURI(temp);
        let pathname = localStorage.getItem('curinf')
          ? JSON.parse(localStorage.getItem('curinf'))
          : {};
        if (fileDefaultName.indexOf('.png') != -1) {
          const blob = new Blob([data], {
            type: 'image/png',
          });
          let blobUrls = window.URL.createObjectURL(blob);
          a.href = blobUrls;
          a.target = '_black';
          a.click();
          a.remove();
        } else {
          let blobUrl = window.URL.createObjectURL(data);
          a.download = fileDefaultName || pathname.cname + '.xls';
          a.href = blobUrl;
          a.click();
          a.remove();
        }
      } else {
        const data = await response?.clone()?.json();
        // 详情返回的response处理
        if (data?.code != '0000') {
          ElMessage.closeAll();
          data?.msg && ElMessage({
            message: data?.msg,
            type: 'warning',
          })
        }
      }
    } else {
      const data = await response.clone().json();
      // 详情返回的response处理
      if (data?.code != "0000") {
        ElMessage.closeAll();
        data?.msg && ElMessage({
          message: data?.msg,
          type: 'warning'
        });
      }
      if (data.code == "0001") {
        loginOut();
      }
    }
  } catch (error) {

  }


  return response;
});


export default request;
