import axios from 'axios'
import qs from 'qs'
import util from '@/js/util'
import { TIME_OUT } from '@/config'

// 网络请求前拦截器
axios.interceptors.request.use(resquest => {
    console.log(resquest)
//   if(resquest && resquest.data && typeof (resquest.data) === 'object'){
    // 若每个接口需要添加时间戳时
    // resquest.data.currentDateTime = util.getFormatDate('yyyy-mm-dd hh:mm:ss')
//   }
  return resquest
}, error => {
    console.log(error)
    return Promise.reject(error)
})

// 网络响应后拦截器
axios.interceptors.response.use(response => {
    // console.log(response)
    return response
}, error => {
    console.log(error)
    return Promise.resolve(error.response)
})

// 数据统一处理来自网络及服务器的错误
function checkStatus (response) {
    if (response && response.status === 200 || response && response.status === 304){
        return response.data
    } else {
        return response && response.statusText || '网络错误'
    }
}

// 处理来自程序的异常
function checkCode (response) {
    if (response.status && response.status !== 'ok'){
        response.error = response.error || '出错了！'
    }
    return response
}
// let accessToken = sessionStorage.getItem("accessToken")
let accessToken = "jAf6LV0HJJiIvhgvIHCM2t10GW7lHt5VAUE13pmj2lLEWlzQyNqx9dbVG0aXpTvn"

// export default ({method = 'post', url = '', params = {}}) => {
// 	return new Promise((resolve, reject) => {
// 		axios[method.toLowerCase()](url, params).then(response => {
// 			resolve(response)
// 		}, err => {
// 			reject(err)
// 		}).catch(err => {
// 			reject(err)
// 		})
// 	})
// }
export default {
    post (url, data) {
        if (!accessToken){
            accessToken = sessionStorage.getItem("accessToken");
        }
        const params = {accessToken};
        return axios({
            method:'post',
            // url,
            url: `${url}?${qs.stringify(params)}`,
            // timeout: TIME_OUT,
            data,
            // data: qs.stringify(data),
            headers:{
                'Content-Type': 'application/json',
                // 'Content-Type':'application/x-www-form-urlencoded'
            }
        }).then(checkStatus).then(checkCode)
    },
    get (url, params){
        return axios({
            method: 'get',
            url: `${url}?${qs.stringify(params)}`,
            timeout: TIME_OUT,
            data: params,
            headers:{
                'Content-Type':'text/plain'
            }
        }).then(checkStatus).then(checkCode)
    },
}

