import axios from "axios";
import router from "../router/router";
const config = { 
  // proxy: "http://192.168.3.74:9500", // 本地地址
  // proxy: "http://1.15.3.38:19500", // 线上地址
  proxy: "http://101.35.253.12:9440/iot", // 线上地址 新
  // proxy: "http://192.170.1.18:19500", // 华数地址
  // imgUrl: "http://112.17.112.138:19000/images", // 查看服务器图片地址
};
// axios基本配置
const api = axios.create({
  timeout: 30000,
  // withCredentials: true,
});
// 请求开始拦截
api.interceptors.request.use(
  (conf) => {
    return conf;
  },
  (error) => ({ status: 0, msg: error.message })
);
// 请求返回拦截
api.interceptors.response.use(
  (response) => {
    if (
      response.data.code === -1 &&
      response.data.msg === "验签失败，请重新登录"
    ) {
      router.push({ name: "Login" });
      localStorage.clear();
    }
    return Promise.resolve(response).then(checkCode);
  },
  (error) => {
    return Promise.reject(error);
  }
);
// http状态码错误处理
// const checkStatus = (res) => {
//     switch (res.status) {
//         case 401: {        //登录过期
//             console.log('登录过期')
//             break;
//         }
//         default:
//             console.log('服务器存在异常')
//             break;
//     }
// }
// 后台自定义 code错误处理
const checkCode = (res) => {
  console.log('fanhui----------res',res)
  if (res) {
    if (res.data.code === 200 || res.data.status === 100) {
      //code为0成功
      const returnData = {
        code: 200,
        success: true,
        data: res.data.data,
        msg: res.data.message,
      };
      return returnData;
    } else {
      //统一处理错误
      const returnData = {
        success: false,
        code: res.data.code,
        msg: res.data.message || res.data.msg,
      };
      return returnData;
    }
  } else {
    const returnData = {
      success: false,
      code: -1,
      msg: "没有返回值",
    };
    return returnData;
  }
};

// 解析参数
const formatParams = (method = "GET", params) => {
  let token = JSON.parse(localStorage.getItem("accountInfo"));
  //headers配置
  const headers = {
    // "Content-Type": "application/json;charset=utf-8",
    "Authorization": token ? token : '',
  };
  switch (method) {
    case "POST":
      return {
        headers,
        method,
        data: params,
      };
    case "PUT":
      return {
        headers,
        method,
        data: params,
      };
    case "DELETE":
      return {
        headers,
        method,
        data: params,
      };
    case "GET":
      return {
        headers,
        method,
        params,
      };
    default:
      return {
        headers,
        method,
        params,
      };
  }
};

export { api, formatParams, config };
