import axios from 'axios'
// import md5 from 'js-md5'
import { Message } from 'element-plus'
import vue from "vue"
import router from '@/router'
// 请求url
const service = axios.create({
    // baseURL: window.STATIC_CONFIG.proxyUrl, // url = base url + request url
    baseURL: "http://8.142.173.95:9527/api",
    timeout: 15000 // request timeout
})

// 请求前拦截
service.interceptors.request.use(
    config => {
        let user = sessionStorage.getItem("userInfo")
        if (user) {
            user = JSON.parse(user)
            let userToken = user.sessionid
            const now = new Date().getTime()
            const nonce = now + randomString(6)
            let signparam = ''
            let signdata = ''
            const params = config.params
            const data = config.data
            if (data) {
                for (const key in data) {
                    if (data[key] == null) continue
                    const signdataItem = key + '=' + data[key]
                    signdata = signdata + (signdata === '' ? '' : '&') + signdataItem
                }
            }

            if (params) {
                for (const k in params) {
                    if (params[k] == null) continue
                    const signparamItem = k + '=' + params[k]
                    signparam = signparam + (signparam === '' ? '' : '&') + signparamItem
                }
            }
            let signs = signparam + ((signparam === '' || signdata === '') ? '' : '&') + signdata
            signs = signs + (signs === '' ? '' : '&') + 'auth_nonce=' + nonce + '&auth_time=' + now
            signs = signs.split('&').sort().join('&')

            signs = signs.replace(/\+/gi, '%20')
            signs = decodeURIComponent(signs)
            signs = encodeURIComponent(signs)
            // signs = md5(signs)
            // }
            config.headers['Authorization'] = 'Bearer ' + userToken
            config.headers.auth_time = now
            config.headers.auth_nonce = nonce
            config.headers.sign = signs
            config.headers['content-type'] = 'application/x-www-form-urlencoded'
            return config
        } else {
            return config
        }

    },
    error => {
        // do something with request error
        console.log('请求前拦截error=', error) // for debug
        // return Promise.reject(error)
    }
)

// 响应拦截
service.interceptors.response.use(
    response => {
        let res = response.data
        return res
    },
    error => {
        console.log(error,'相应拦截器error');
        if (error.response.status === 401) {
            Message({
                message: "登陆已过期，请重新登录",
                type: "error"
            })
            router.push("/login")
            sessionStorage.removeItem('userInfo')
            sessionStorage.removeItem('userToken')
        }
        // Message({
        //   message: '' + error.response.data.message,
        //   type: 'error',
        //   duration: 3 * 1000,
        //   offset: window.screen.height / 3
        // })
        return Promise.reject(error)
    }
)
const randomString = function (e) {
    e = e || 32
    const t = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'
    const a = t.length
    let n = ''
    for (let i = 0; i < e; i++) n += t.charAt(Math.floor(Math.random() * a))
    return n
}
export default service
