import { defineNuxtPlugin } from '#app'
import axios from 'axios'
import { getToken } from '@/store/useCookieStore'

export default defineNuxtPlugin(nuxtApp => {
    let Url = {
        //正式环境
        webUrl: 'https://flzxw.bjzxtw.org.cn', //接口地址
        CwebUrl: 'nw.china-village.com.cn' //页面地址
        //pre环境
        // webUrl: 'http://apipre1.bjzxtw.org.cn:29501', //pre接口地址
        // CwebUrl: 'pre.china-village.com.cn' //页面地址
    }

    const service = axios.create({
        baseURL: Url.webUrl
    });

    // 请求拦截器
    service.interceptors.request.use(config => {
        // console.log("请求拦截器",config);
        // 从cookie中获取数据
        const token = getToken()
        // const token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJwaHBlcjY2Ni9qd3QiLCJ1aWQiOjY0OCwidXNlcl9uYW1lIjoiMTM5MzA4OTg4ODgiLCJtb2JpbGUiOiIiLCJlbWFpbCI6IiIsImxldmVsX2lkIjowLCJ0eXBlX2lkIjoxMDAwMCwiand0X3NjZW5lIjoiZGVmYXVsdCIsImp0aSI6ImRlZmF1bHRfNjdmMzlmNWUzZjY2MjMuODM0ODQ2NTciLCJpYXQiOjE3NDQwMTkyOTQsIm5iZiI6MTc0NDAxOTI5NCwiZXhwIjoxNzQ0MTA1Njk0fQ.rzEcEy8hNn43P3bE3PTOS4nGeG_Zg1mmac40VNjx6mU"
        if (token) {
            config.headers.token = token;
        }
        config.headers.userurl = Url.CwebUrl;
        return config;
    }, error => {
        console.log(error)
        return Promise.reject(error);
    });

    // 响应拦截器
    service.interceptors.response.use(response => {
        if (response.status >= 200 && response.status <= 210) {
            return response.data;
        } else if (response.status == 404) {
            console.error(response.data.errmsg);
        } else {

        }
    },
        error => {
            // console.log(1);
            console.log('err' + error);
        })

    return {
        provide: {
            axios: service
        }
    }
});

