import axios from "axios";
import { ElMessageBox, ElMessage } from "element-plus";
import {router} from "@/router";
import { getToken, clearAllCookies, removeToken } from "@/utils/auth";
// vite环境变量
const ENV = import.meta.env

const requestObj = {};
// 添加一个标志位，用于记录是否已经显示了登录过期的消息
let isLoginExpiredMessageShown = false;

const source = axios.CancelToken.source()
const service = axios.create({
  headers: {
    "Content-Type": "application/json",
    "X-Requested-With": "XMLHttpRequest"
  },
  cancelToken: source.token
});

service.interceptors.request.use(
  config => {
    if (getToken("TOKEN")) config.headers["TOKEN"] = getToken("TOKEN");
    let dataBranchFactoryId = getToken("dataBranchFactoryId");
    if (
      dataBranchFactoryId &&
      dataBranchFactoryId != "undefined" &&
      dataBranchFactoryId != ""
    ) {
      let urlString = config.url;
      let str_url = urlString.split("?")[0];
      if (str_url == "/user/captcha" || str_url == "/user/login") {
        config.url = ENV.VITE_APP_BASE_API5 + config.url;
      }  else {
        config.url = ENV.VITE_APP_BASE_API5 + config.url;
  
      }
    } else {
        config.url = ENV.VITE_APP_BASE_API5 + config.url;
    }
    requestObj.url = config.url;
    requestObj.param = config.params;
    return config;
  },

  error => {
    // console.error(`${error.message}`)
    // error.message = `连接错误`;
    return Promise.reject(error);
  }
);

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data;
    if (res.code !== 1) {
      if (res.code === 1001) {
        removeToken("dataBranchFactoryId");
        // 检查是否已经显示过登录过期的消息
        if (!isLoginExpiredMessageShown) {
          ElMessage({
            message: "登录已过期，请重新登录",
            type: "error",
            duration: 2 * 1000
          });
          isLoginExpiredMessageShown = true;
          // 设置一个定时器，在一段时间后重置标志位，以便下次可以再次显示
          setTimeout(() => {
            isLoginExpiredMessageShown = false;
          }, 3000);
        }
        router.push(`login`);
      } else {
        if (!res.success) {
          if (res.code === 9000) {
            if (res.msg.indexOf("新密码输入不符合规则") >= 0) {
              let tmpMsg = res.msg;
              tmpMsg += "<br/> 1、长度8~20";
              tmpMsg += "<br/> 2、必须包含字母（大写或者小写）";
              tmpMsg += "<br/> 3、必须包含数字";
              tmpMsg +=
                "<br/> 4、包含特殊字符 ~!@#$%^&*()[]{}<>?+    不能包含空格";
              tmpMsg += "<br/> 5、只能包含以上特殊字符以及大小字母和数字的密码";
              ElMessage({
                dangerouslyUseHTMLString: true, //重点代码
                message: tmpMsg,
                type: "error",
                duration: 5 * 1000
              });
            }  else {
              const msg = res.message || res.msg || "Error";
              // msg 是否包含英文字符
              if (msg.match(/[a-zA-Z]/)) {
                console.error('错误接口',response);
                console.error('错误信息',msg);
              } else {
                ElMessage({
                  message: res.message || res.msg || "Error",
                  type: "error",
                  duration: 5 * 1000
                });
              }
            }
          }
          else if (
            res.code === 3015 ||
            res.code === 3017 ||
            res.code === 3014 ||
            res.code === 3016 ||
            res.code === 9002
          ) {
            // 数据下沉的状态码不做报错提示
          } else {
            const whiteList = ['exportDeviceAndSignal']
            // 判断是否是下载接口，如果是下载接口，则不进行错误提示
            if (isExportUrl(whiteList, response.config.url)) {
              return res
            }
            requestExceptCap(response.config, response.status);
            const msg = res.message || res.msg || "Error";
             // msg 是否包含英文字符
             if (msg.match(/[a-zA-Z]/)) {
               console.error('错误接口',response);
               console.error('错误信息',msg);
             } else {
             ElMessage({
               message: res.message || res.msg || "Error",
               type: "error",
               duration: 5 * 1000
             });
            }
          }
        }

      }
      return res;
    } else {
      return res;
    }
  },
  error => {
    if (error && error.response) {
      requestExceptCap(error.response.config, error.response.code);
      switch (error.response.code) {
        case 400:
          error.message = "请求错误(400)";
          break;
        case 401:
          error.message = "未授权,请登录(401)";
          break;
        case 403:
          error.message = "拒绝访问(403)";
          break;
        case 404:
          error.message = `请求地址出错: ${error.response.config.url}`;
          break;
        case 405:
          error.message = "请求方法未允许(405)";
          break;
        case 408:
          error.message = "请求超时(408)";
          break;
        case 500:
          error.message = "服务器内部错误(500)";
          break;
        case 501:
          error.message = "服务未实现(501)";
          break;
        case 502:
          error.message = "网络错误(502)";
          break;
        case 503:
          error.message = "服务不可用(503)";
          break;
        case 504:
          error.message = "网络超时(504)";
          break;
        case 505:
          error.message = "HTTP版本不受支持(505)";
          break;
        default:
          error.message = `连接错误: ${error.message}`;
          // console.error(error.message);
          // error.message = `连接错误`;
      }
    } else {
      error.message = "连接到服务器失败，请联系管理员";
    }
    requestExceptCap(error.config);
    // ElMessage({
    //   message: error.message || error.msg,
    //   type: 'error',
    //   duration: 5 * 1000
    // })
    return Promise.reject(error);
  }
);

/**
 * @Description: 接口报错异常捕获
 * @param {Object} capData 报错接口参数
 * @param {string} code 报错编码
 * @return void
 * @author liqiuyu
 * @date 2024/3/11
 */
function requestExceptCap(capData = {}, code = "Network Error") {
  return
  const date = new Date();
  const time = format(date);
  const url = "";
  const link = capData.url;
  let tempData;
  if (!link || link.indexOf("/data/collect") !== -1) {
    return;
  }
  if (capData.method == "post") {
    tempData = capData.data || requestObj.param;
  } else {
    tempData = capData.param || requestObj.param;
  }
  if (typeof tempData == "object") {
    tempData = JSON.stringify(tempData);
  }
  const param = {
    firstLevelCode: "notOpen",
    secondLevelCode: "apiError",
    additionalInfo: {
      code,
      source: "PC",
      mac: "未配置mac信息",
      customerId: getToken("customerId"),
      time: time,
      url: link,
      param: tempData
    }
  };
  service({
    url: "/data/collect",
    data: param,
    method: "post",
    headers: {
      "Content-Type": "application/json"
    }
  })
    .then(res => {})
    .catch(error => {});
}

function format(dataString) {
  //dataString是整数，否则要parseInt转换
  var time = new Date(dataString);
  var year = time.getFullYear();
  var month = time.getMonth() + 1;
  var day = time.getDate();
  var hour = time.getHours();
  var minute = time.getMinutes();
  var second = time.getSeconds();
  return (
    year +
    "-" +
    (month < 10 ? "0" + month : month) +
    "-" +
    (day < 10 ? "0" + day : day) +
    " " +
    (hour < 10 ? "0" + hour : hour) +
    ":" +
    (minute < 10 ? "0" + minute : minute) +
    ":" +
    (second < 10 ? "0" + second : second)
  );
}

// 判断接口链接是否是导出接口
function isExportUrl (whiteList, targetUrl) {
  let result = false;
  for(let i = 0; i < whiteList.length; i++) {
    if(targetUrl.indexOf(whiteList[i]) > -1) {
      result = true;
      break;
    }
  }
  return result;
}
export default service;
