import axios from 'axios'
import { Message } from 'view-design'
import router from '@/router/index'
import config from '@/store/module/config'
import { app } from '@/boot-app.js'


let refreshing = false
let isProduction = process.env.NODE_ENV == 'development' ? false : true
axios.defaults.timeout = 30000 // 设置超时时长
// axios.defaults.baseURL = isProduction ? '' : 'https://localhost:5001'
axios.defaults.baseURL = '' 


// http request 拦截器
axios.interceptors.request.use(    
    async (config) => {

        // 呼叫API先偵測是否超過一小時，有則回到登入頁
        let webEndTime = localStorage.getItem('webEndTime')
        let access_token = localStorage.getItem('access_token')
        if(isProduction && access_token && webEndTime){
            let time_now = new Date().getTime()
            if(time_now > webEndTime){
                let login_schoolCode = localStorage.getItem('login_schoolCode')
                let srvAdr = localStorage.getItem('srvAdr')
                localStorage.clear()
                localStorage.setItem('srvAdr', srvAdr)
                localStorage.setItem('login_schoolCode', login_schoolCode)
                window.location.href = window.location.origin + '/login'
            }
        } 

        // if (config.url != 'https://api2.teammodel.cn/oauth2/v2.1/token') {
        let flag = checkToken()
        if (flag) {
            if (!refreshing) {
                if (localStorage.getItem('access_token')) {
                    await refreshToken()
                }
            }
        }
        // }
        // if (localStorage.getItem('auth_token')) {
        //     config.headers = {
        //         'X-Auth-IdToken': localStorage.getItem('auth_token')
        //     }
        // }
        config.data = JSON.stringify(config.data)
        if (localStorage.getItem('access_token')) {
            config.headers = {
                'Content-Type': 'application/json',
                'Authorization': 'Bearer ' + localStorage.getItem('access_token'),
                'lang': localStorage.getItem('local')
            }
        } else {
            config.headers = {
                'Content-Type': 'application/json',
                'Authorization': ''
            }
        }
        if (localStorage.getItem('auth_token')) {
            config.headers['X-Auth-AuthToken'] = localStorage.getItem('auth_token')
            
        }
        
        return config
    },
    error => {
        return Promise.reject(error)
    }
)

// http response 拦截器
axios.interceptors.response.use(
    response => {
        if (response.data.errCode === 2) {
            router.push({
                path: '/login',
                querry: { redirect: router.currentRoute.fullPath }// 从哪个页面跳转
            })
        }

        // API 呼叫完成後以現在的時間向後加一小時
        if(isProduction){
            let endTime = (new Date().getTime() + (1 * 60 * 60 * 1000))
            localStorage.setItem('webEndTime', endTime)
        }

        return response
    },
    error => {
        if (error.response && error.response.status === 401) {
            localStorage.clear()
            window.location.href = window.location.origin + '/login'
            Message.error(app.$t('http.error401'))
        } else if (error.response.status === 500) {
            Message.error(app.$t('http.error500'))
        } else if (error.response.status === 404) {
            Message.error(app.$t('http.error404'))
        } else{
			Message.error(app.$t('http.error'))
		}
        return Promise.reject(error)
    }
)

/**检测token是否快过期 */
function checkToken() {
    if(!localStorage.getItem('expires_in') || localStorage.getItem('expires_in') == undefined) return false

    var nowTime = new Date();
    var offset = nowTime.getTimezoneOffset() / 60
    let cT = Date.parse(nowTime)
    let eT = Date.parse(localStorage.getItem('expires_in'))
    let oT = 0
    let btw = eT - oT - cT
    if (btw > 10 * 60 * 1000) {
        return false
    } else {
        return true
    }

}

/**刷新token */
async function refreshToken() {
    refreshing = true
    let srvAdr = localStorage.getItem('srvAdr')
    let url = config.state[srvAdr].coreAPIUrl

    await axios.post(url + '/oauth2/token', {
        "grant_type": "refresh_token",
        'client_id': config.state[srvAdr].clientID,
        "access_token": localStorage.getItem('access_token')
    }).then(
        res => {
            localStorage.setItem("access_token", res.data.access_token)
            localStorage.setItem("expires_in", res.data.expires_in)
            refreshing = false
        },
        err => {
            refreshing = false
        }
    )
}

/**
 * 封装get方法
 * @param url
 * @param data
 * @returns {Promise}
 */

export function fetch(url, params) {
    let data = {}
    data.method = url
    data.params = params
    data.lang = localStorage.getItem('local')
    return new Promise((resolve, reject) => {
        axios.get(url, data)
            .then(response => {
                resolve(response.data)
                //  this.$Message.success('数据访问成功！');
            })
            .catch(err => {
                reject(err)
                Message.error('数据访问错误！')
            })
    })
}

/**
 * 封装post请求
 * @param url
 * @param data
 * @returns {Promise}
 */

export function post(url, params) {
    //params['id_token'] = localStorage.getItem('id_token')
    let data = {}
    data.method = url
    data.params = params
    data.lang = localStorage.getItem('local')
    return new Promise((resolve, reject) => {
        axios.post(url, params)
            .then(response => {
                if (response) {
                    resolve(response.data)
                }
            }, err => {
                reject(err)
            })
    })
}

/**
 * 封装post请求
 * @param url
 * @param data
 * @returns {Promise}
 */

export function corePost(url, params) {
    return new Promise((resolve, reject) => {
        axios.post(url, params).then(response => {
            resolve(response.data)
        }
        , err => {
            reject(err.response)
            Message.error('数据访问错误！')
        })
    })
}
