import axios from "axios";
import qs from 'qs'
import { Toast } from 'vant'

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  headers: {
    Accept: 'application/json'
  },
  timeout: 10000
})
const urlParams = new URLSearchParams(window.location.search);
let token = urlParams.get('token');
if( token ) {
  localStorage.setItem('token', token);
} else {
  localStorage.setItem('token', '');
}
service.interceptors.request.use(
    config => {
      let reqUrl=config.url
        // console.log('config',config)
      config.data = config.contentType ? config.data : qs.stringify(config.data)
      if (config.testFlag) {
        config.data = qs.stringify(config.data, {arrayFormat: 'indices', allowDots: true})
      }
      config.headers['Content-Type'] = config.contentType || 'application/x-www-form-urlencoded'
      let token = localStorage.getItem('token');
      // let token='eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJBTkNIQU5HIiwidXNlcklkIjo0NTY3MSwibmFtZSI6IuWuieeVhSIsInVzZXJOYW1lIjoiQU5DSEFORyIsInN1cHBsaWVySWQiOjExMjgsImlzWmQiOjAsImV4cCI6MTc1NTQyMjUyNX0.xzDZhaANJFnbeViIHJA0SEtOyTv7Ja3rKmXqRKRuFkc'
      // let token='eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJTSEhQWEIiLCJ1c2VySWQiOjU0NzI2LCJuYW1lIjoiI-a1i-ivleWwj-eZveeZvSIsInVzZXJOYW1lIjoiU0hIUFhCIiwic3VwcGxpZXJJZCI6MTAwMDE2NSwiZXhwIjoxNzQ0NTEwNzkwfQ.JPk0OA7slYJN3FIi_uhW4Y0CiWRvl6R1dK8MRTbyhD8'
      //  if(!(reqUrl=='/supplier/supplierTraining/trainingTask' || reqUrl=='/supplier/supplierTraining/normalList' || reqUrl=='/supplier/supplierTraining/trainingList')){
        if ((reqUrl=='/supplier/supplierTraining/trainingList' || reqUrl=='/supplier/supplierTraining/normalList') && config?.params?.type==1){
            console.log('司机app使用该请求不挂token')
        } else {
            if(token) {
                config.headers['Authorization'] = `${token}`;
                config.headers['token'] = `${token}`;
            }
        }

       // }
      return config
    },
    error => {
      return Promise.reject(error)
    }
)

service.interceptors.response.use(
    response => {
        console.log('response', response.data)
      const res = response.data
      if ( res.code === 401 || res.code === 400  || res.code == 500) {
          Toast(res.msg || 'Error')
          return Promise.reject(res.msg)
      } else {
          return res
      }
    },
    error => {
        if(error.message != 'Network Error'){
            Toast(error.message)
        }
      return Promise.reject(error)
    }
)
export default service
