import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken, getRefreshToken } from '@/utils/auth'
import { CodeSr } from '@/api/user'

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'

const service = axios.create({
    // baseURL: '/harmonicWaveApi',//超高压生产嵌入
    // baseURL: '/PMS3/Application/third/aqcp-dnzl/harmonicWaveApi',//河北嵌入
    baseURL: '/api',
    timeout: 150000
})
// service.interceptors.request.use(
//   config => {
//      if(config.url !=='/pqs-oauth2/oauth/token' || config.params.grant_type=='refresh_token'){
//      if (store.getters.token){
//       config.headers['Authorization'] = getToken()
//      }
//    }else{
//       store.dispatch('user/remToken').then(() => {
//       //location.reload()
//     })
//    }
//     return config
//   },
//   error => {
//     return Promise.reject(error)
//   }
// )

//拦截器

service.interceptors.request.use(
    config => {
        // debugger

        if (process.env.VUE_APP_MODE === 'jbqr') {
            config.headers['Authorization'] =
                'bearer ' + JSON.parse(window.localStorage.getItem('adminInfo')).access_token
        } else if (
            process.env.VUE_APP_MODE === 'cgyqr' &&
            store.getters.token &&
            window.sessionStorage.getItem('cntoken')
        ) {
            config.headers['Authorization'] = getToken()
        } else {
            if (store.getters.token && window.sessionStorage.getItem('cntoken')) {
                config.headers['Authorization'] = getToken()

                var userInfo = JSON.parse(
                    decodeURIComponent(
                        escape(atob(getRefreshToken().split('.')[1].replace(/-/g, '+').replace(/_/g, '/')))
                    )
                )

                if (userInfo.exp < Math.floor(Date.now() / 1000)) {
                    Message({ message: '会话已过期，返回登录页请重新认证！', type: 'warning' })
                    store.dispatch('user/resetToken').then(() => {})
                    return
                }

                // console.log('🚀 ~  decodeJwtPayload(getToken());:', decodeJwtPayload(getToken()))
            } else if (config.url === '/pqs-auth/auth/getImgCode') {
                config.headers['Authorization'] = 'Basic bmpjbnRlc3Q6bmpjbnBxcw=='
                //config.headers['Authorization'] ='Basic bmpjbjpuamNucHFz'
            } else {
                config.headers['Authorization'] = 'Basic bmpjbnRlc3Q6bmpjbnBxcw=='
                //config.headers['Authorization'] ='Basic bmpjbjpuamNucHFz'
            }
        }
        // NProgress.done()
        return config
    },
    error => {
        return Promise.reject(error)
    }
)
let refreshing = false, // 正在刷新标识，避免重复刷新
    waitQueue = [] // 请求等待队列
var number = true
service.interceptors.response.use(
    ({ config, data }) => {
        const { code, message } = data
        if (code !== 'A0000') {
            // debugger
            if (code === 'A0202') {
                const refreshToken = getRefreshToken()

                if (!refreshToken) {
                    window.location.href = window.location.origin

                    return
                }
                // access_token过期，尝试续期token
                // debugger
                if (refreshing == false) {
                    refreshing = true // 切换正在刷新标识，其他请求先进请求等待队列中
                    return store
                        .dispatch('user/refreshToken', refreshToken)
                        .then(token => {
                            config.headers['Authorization'] = token
                            config.baseURL = '/api' // 请求重试时，url已包含baseURL
                            waitQueue.forEach(callback => callback(token)) // 已成功刷新token，队列中的所有请求重试
                            waitQueue = []
                            return service(config)
                        })
                        .catch(() => {
                            // token续期失败
                            // MessageBox.confirm(
                            //     '当前页面已失效，请重新认证', '确认退出', {
                            //         confirmButtonText: '重新登录',
                            //         cancelButtonText: '取消',
                            //         type: 'warning',
                            //         showClose: false,
                            //         showCancelButton: false,
                            //         closeOnClickModal: false,
                            //         type: 'warning'
                            //     }).then(() => {
                            store.dispatch('user/resetToken').then(() => {})
                            // })
                        })
                        .finally(() => {
                            refreshing = false
                        })
                } else {
                    // store.dispatch('user/resetToken').then(() => {})
                    return new Promise(resolve => {
                        waitQueue.push(token => {
                            config.headers['Authorization'] = token
                            config.baseURL = '/api'
                            resolve(service(config))
                        })
                    })
                }
            } else if (code === 'A0024' && number) {
                // token被禁止访问，添加到黑名单，跳转至登录页

                // MessageBox.confirm(
                //   '会话已过期，请重新认证', '警告', {
                //     confirmButtonText: '重新登录',
                //     cancelButtonText: '取消',
                //     type: 'warning',
                //     showClose:false,
                //     showCancelButton:false,
                //     closeOnClickModal:false
                //   }).then(() => {
                number = false
                Message({ message: '会话已过期，返回登录页请重新认证！', type: 'warning' })
                store.dispatch('user/resetToken').then(() => {})
                return
                //})
            } else if (code === 'A0024' && !number) {
                number = true
                return
            } else if (code === 'A0101') {
                Message({ message: message, type: 'warning' })
                return data
            } else if (message) {
                Message({ message: message, type: 'warning' })
                if (code === 'A0095' || code === 'A0094' || code === 'A0001') {
                    Message({ message: message, type: 'warning' })
                    return data
                }
                if (code === 'A0101') {
                    //  if(window.sessionStorage.getItem('imgcode')){ window.sessionStorage.removeItem('imgcode')}else{ window.sessionStorage.setItem('imgcode',false) }
                    Message({ message: message, type: 'warning' })
                    return Promise.reject(new Error(message))
                }
                return data
            } else {
                // alert(22222)
                return data
            }
        } else {
            return data
        }
    },
    error => {
        // const {status} = error.response
        // debugger
        // if(status==401){
        //   if (refreshing == false) {
        //     refreshing = true  // 切换正在刷新标识，其他请求先进请求等待队列中
        //     const refreshToken = getRefreshToken()
        //     return store.dispatch('user/refreshToken', refreshToken).then((token) => {
        //       config.headers['Authorization'] = token
        //       config.baseURL = '' // 请求重试时，url已包含baseURL
        //       waitQueue.forEach(callback => callback(token)) // 已成功刷新token，队列中的所有请求重试
        //       waitQueue = []
        //       return service(config)
        //     }).catch(() => {  // token续期失败
        //       MessageBox.confirm(
        //         '当前页面已失效，请重新登录', '确认退出', {
        //           confirmButtonText: '重新登录',
        //           cancelButtonText: '取消',
        //           type: 'warning'
        //         }).then(() => {
        //         store.dispatch('user/resetToken').then(() => {
        //         location.reload()
        //         })
        //       })
        //     }).finally(() => {
        //       refreshing = false
        //     })
        //   } else {
        //     return new Promise((resolve => {
        //       waitQueue.push((token) => {
        //         config.headers['Authorization'] = token
        //         config.baseURL = ''
        //         resolve(service(config))
        //       })
        //     }))
        //   }
        //     refreshing = true  // 切换正在刷新标识，其他请求先进请求等待队列中
        //         const refreshToken = getRefreshToken()
        //         return store.dispatch('user/refreshToken', refreshToken).then((token) => {
        //           config.headers['Authorization'] = token
        //           config.baseURL = '' // 请求重试时，url已包含baseURL
        //           waitQueue.forEach(callback => callback(token)) // 已成功刷新token，队列中的所有请求重试
        //           waitQueue = []
        //           return service(config)
        //   })
        return Promise.reject(error)
        // }
    }
)
export default service
