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'
const NO_ACCESS_API = [
    '/core/system-info',
    '/oauth2/login',
    '/oauth2/token',
    '/teacher/init/get-school-list',
    '/student/login',
    '/area/lang'
]
const NO_AUTH_API = [
    '/teacher/init/get-teacher-info',
    '/teacher/init/get-school-info',
    '/stulist/scan-code-join-list'
]

let refreshing = false
// let isProduction = process.env.NODE_ENV == 'development' ? false : true
let isProduction = true //暂时本地和线上都要进行验证，如果验证流程没有问题则用上面的设置线上验证
axios.defaults.timeout = 30000 // 设置超时时长
axios.defaults.baseURL = ''

// http request 拦截器
axios.interceptors.request.use(
    async (config) => {
        /***
         * 登录及登录之前的API 不需要任何检查
         */
        let isNeedAccess = true
        for (let apiUrl of NO_ACCESS_API) {
            if (config.url.includes(apiUrl)) {
                isNeedAccess = false
                break
            }
        }
        if (!isNeedAccess) return config

        /**
         * 登录之后，获取auth_token之前
         * 1、学生端登录没有access_token,不需要验证
         * 2、检查用户操作时间 
         * 3、检查access_token及有效时间
         */
        let webEndTime = localStorage.getItem('webEndTime')
        let time_now = new Date().getTime()
        if (time_now > webEndTime) {
            console.log('长时间未操作，重新登录', config)
            loginOut()
            return
        }
        let access_token = localStorage.getItem('access_token')
        //有access_token才刷新
        if (access_token) {
            //检查access_token有效时间
            let flag = checkToken()
            if (flag && !refreshing) {
                console.log('token即将过期，刷新token')
                await refreshToken()
            }
            config.headers['Authorization'] = 'Bearer ' + localStorage.getItem('access_token')
        }
        //通过验证，设置对应参数
        config.headers['Content-Type'] = 'application/json'
        config.headers['lang'] = localStorage.getItem('local')
        let isNeedAuth = true
        for (let apiUrl of NO_AUTH_API) {
            if (config.url.includes(apiUrl)) {
                console.log('auth_token无效', config)
                isNeedAuth = false
                break
            }
        }
        if (!isNeedAuth) return config

        /**
         * 获取auth_token之后的API
         * 1、检查auth_token是否存在
         */
        let auth_token = localStorage.getItem('auth_token')
        if (!auth_token) {
            console.log('auth_token失败', config)
            loginOut()
            return
        }
        //通过验证设置对应参数
        config.headers['X-Auth-AuthToken'] = 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() + (4 * 60 * 60 * 1000))
        localStorage.setItem('webEndTime', endTime)
        // }

        return response
    },
    error => {
		if(!error.response){
			Message.error(app.$t('http.error'))
		}else 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.error400'))
        }
        return Promise.reject(error)
    }
)

/**检测token是否快过期 */
function checkToken() {
    if (!localStorage.getItem('expires_in')) 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
        }
    )
}

// 超时退出重新登录
function loginOut() {
    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'
}

/**
 * 封装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('数据访问错误！')
            })
    })
}
