import axios from "axios";
import { Message, Loading } from "element-ui";
import { setToken, getToken, removeToken } from "@/utils/Auth";
import router from "@/router";
import qs from "qs";
import config from "@/utils/config";


let loading; //定义loading变量

//弹窗loading
function startLoading() {
  //使用Element loading-start 方法  
  loading = Loading.service({
    target: document.querySelector(".loadingtext"),
    lock: true,
    fullscreen: false,
    text: "加载中……",
    background: "rgba(0,0,0,0)",
  });
}
//关闭loading
function endLoading() {
  //使用Element loading-close 方法
  loading.close();
}

//开始loading计数
let needLoadingRequestCount = 0;
export function showFullScreenLoading() {
  if (needLoadingRequestCount === 0) {
    startLoading();
  }
  needLoadingRequestCount++;
}

//结束loading计数
export function tryHideFullScreenLoading() {
  if (needLoadingRequestCount <= 0) return;
  needLoadingRequestCount--;
  if (needLoadingRequestCount === 0) {
    endLoading();
  }
}

//接口请求判断拦截
// 创建axios实例---axios请求接口封装拦截
// 实例对象
const service = axios.create({
  // baseURL: config.BASE_API+'/v3', // api的base_url
  baseURL: '/v3', // api的base_url
  // timeout: 30000, // 请求超时时间
  headers: {
    // "Content-Type":"application/x-www-form-urlencoded;charset=utf-8",
    "Content-Type":"application/json"
  },
});
service.defaults.withCredentials = true; //跨域请求设置 axios代码中配置withCredentials为true以便可以携带cookie,false代表不携带cookie

// request请求拦截器---接口拦截器
service.interceptors.request.use(
  (config) => {
    // console.log("==========")
    // console.log(config);
    if(config.url.indexOf("ComServiceApi")>-1){//保险列表接口调用公共服务代理ComServiceApi前缀
      config.baseURL=""
      config.headers["access_token"]=localStorage.getItem("accessToken") //公共服务使用access_token
    }
    if(config.url.indexOf("obpm")>-1){//保险列表接口调用公共服务代理ComServiceApi前缀
      config.baseURL=""
    }
    // console.log(config);
    // console.log(router.currentRoute.query.token)
    if (localStorage.getItem("token")||router.currentRoute.query.token) {
      if(router.currentRoute.query.token){
        config.headers["Authorization"] ="Bearer "+router.currentRoute.query.token; // 让每个请求携带自定义token 请根据实际情况自行修改
      }else{
        config.headers["Authorization"] ="Bearer "+localStorage.getItem("token"); // 让每个请求携带自定义token 请根据实际情况自行修改
      }
      config.headers["accessToken"]=localStorage.getItem("accessToken")//v5使用accessToken
      config.headers["userV5Token"]=localStorage.getItem("userV5Token")||"1"
    }
    // config.method === 'post'? config.data = qs.stringify({...config.data}): config.params = {...config.params}
    /* 判断method是否为post，为post则对参数进行序列化，不为post择不进行序列化 */
    //responseType: 'blob'  导出
    //upload_type: true    上传
    if (config.data && !config.upload_type) {
      // config.data = qs.stringify(config.data); //转为formdata数据格式
    }
    
    //路由--请求接口判断loading  /HomePage路由  /cost/addUseUser.do定时查询在线用户信息 /billDetail不加载loading,其他加载loading
    if(!config.hideLoading){
        showFullScreenLoading(); //全屏加载loading
    }
    
    return config;
  },
  (error) => {
    // Do something with request error
    //console.log(error) // for debug
    return Promise.reject(error);
  }
);

// respone返回拦截器
service.interceptors.response.use(
  (response) => {  
    // console.log(response)
    /**
     * returnStatus为0是有异常，未传入参数；为1 表示成功；为2 用户未登录
     */
    const res = response.data;
    if (res) {
      //x_token如有值，取最新
      // setToken(res); //每次请求接口都重设x_token
    }
    //  console.log(res)
    if (res.status == 500) {
      //请求500
      if (res.httpStatus) {        
        Message({
          message: "系统服务器错误,请联系管理员",
          type: "error",
          duration: 2 * 1000,
        });
      }
    }

    if (res.status == 200) {
      //请求200
      if (res.httpStatus) {
        // console.log(response.config.method)
        // console.log(response.config.url)
        if(response.config.method!=="get"){
          if(response.config.url.indexOf("search")==-1||response.config.url.indexOf("Export")==-1){ //API路径包含这些字段不提示语
          }else{
            Message({
              message: "操作成功",
              type: "success",
              duration: 2 * 1000,
            });
         }
       }      
      }
    }

    else{  
      if(res.message){ 
        Message({
          message: res.message,
          type: "error",
          duration: 2 * 1000,
        });     
      } 
    }

    tryHideFullScreenLoading(); //全屏隐藏加载loading
    return res;
  },
  (error) => {
    // console.log(error.response)
    tryHideFullScreenLoading(); //全屏隐藏加载loading
    if (error && (error.response.status === 405)) {//405表示 not allowed
      // 抛出数据到then      
      Message({
        dangerouslyUseHTMLString: true, //将dangerouslyUseHTMLString属性设置为 true，message 就会被当作 HTML 片段处理
        message: error.response.data.message,
        type: "warning",
        duration: 2 * 1000,
      });
      return Promise.resolve(error.response.data)
    }else if (error && (error.response.status === 404)) {//405表示 not allowed
      // 抛出数据到then      
      Message({
        dangerouslyUseHTMLString: true, //将dangerouslyUseHTMLString属性设置为 true，message 就会被当作 HTML 片段处理
        message: error.response.data.message ||'无请求数据',
        type: "error",
        duration: 2 * 1000,
      });
      return Promise.reject(error.response.data)
    }else{
      // 抛出数据到catch
      console.log('400', error.response)
      if (error.response.data.code != 1000600 && error.response.data.code != 1000601 && error.response.data.code != 1000602) {
        Message({
          dangerouslyUseHTMLString: true, //将dangerouslyUseHTMLString属性设置为 true，message 就会被当作 HTML 片段处理
          message: error.response.data.message,
          type: "error",
          duration: 2 * 1000,
        });
      }
      return Promise.reject(error.response.data)
    }

  }
);
export default service;
