import axios from 'axios'
import store from '@/store'
import router from '@/router'
import sysparam from '@/sysparam/sysparam.js'
import { getToken } from '@/utils/auth'
import codecutil from '@/utils/codec/codecutil'


// 创建一个axios对象
const service = axios.create({
    //baseURL: "http://localhost:9528/pcapi",//本地调试
    baseURL: process.env.VUE_APP_BASE_API, //process表示读取的意思
    // withCredentials: true, // send cookies when cross-domain requests
    timeout: 10000, // 超时时长
    responseType: 'json',
    withCredentials: true
})


//请求拦截器
service.interceptors.request.use(
    config => {
        config.headers['Accept'] = 'application/json'
        config.headers['Content-Type'] = 'application/json;charset=utf-8'

        //若vue中token存在，则在请求头中添加用户token
        if (store.state.user.token) {
            config.headers['token'] = getToken()//获得本地的token
        }

        //组织请求参数加密密钥
        const aesKey = sysparam.copyright + sysparam.app.snCode

        //get请求参数加密
        if (config.params) {
            let params = config.params
            if (params != undefined && params != "") {
                let ciphertext = codecutil.aesEncode(params, aesKey)
                config.params = {}
                config.params = ciphertext
            }
        }

        //post参数加密
        if (config.method === 'post' && config.data != null) {
            let plaintext = JSON.stringify(config.data)
            let ciphertext = codecutil.aesEncode(plaintext, aesKey)
            config.data = {}
            config.data = ciphertext
        }

        return config
    },
    error => {
        return Promise.reject(error)
    }
)

//响应拦截器
service.interceptors.response.use(
    function (response) {//返回成功
        const res = response.data

        //返回成功
        if (res.code == 2000) {
            return res//返回数据
        }
        //token过期
        else if (res.code == 2001) {
            //保存当前登录用ID
            const userId = store.state.user.userInfo.id

            //用户退出登录
            store.dispatch("user/logout")

            console.log(location.hash.substring(1))
            console.log(userId)

            //跳转到登录页面
            router.push({
                path: "/login",
                query: {
                    return_url: location.hash.substring(1),//当前页面
                    id: userId//当前用户ID
                },
            })

            //return Promise.reject(new Error(res.msg))//返回错误对象
        }
        //其他错误
        else {
            const error = new Error(res.msg || '未知错误')
            return Promise.reject(error)//返回错误对象
        }
    },
    function (error) {//返回失败
        return Promise.reject(error)
    }
)

export default service
